branch_name
stringclasses
22 values
content
stringlengths
18
81.8M
directory_id
stringlengths
40
40
languages
sequence
num_files
int64
1
7.38k
repo_language
stringlengths
1
23
repo_name
stringlengths
7
101
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>import './style.less' import '../lib/flexible' // import axios from 'axios' console.log('hello worldbbbb') <file_sep>import '../lib/reset.less' import './style.css' import '../lib/flexible' console.log('hello world1213')
52a5756b072183465cd6365b1da9c34866aa701c
[ "JavaScript" ]
2
JavaScript
vison123/webpack-activity-pages
a4da68a8300e5834646a078c5bfa0b9389a7abf6
f7b4424e46b07082d60dc07d55019c97774c8dca
refs/heads/master
<file_sep>#Thu Jul 25 09:24:19 EDT 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.12.0.v20190605-1800
3cc809884bcbaee996990f2c4166d93105a9ee56
[ "INI" ]
1
INI
wahula4/bikes
29c8871593cafb101d7f5fa1661daebd81f031af
ba788cb9c4a3dda4eb50a91739d0ea3306e08413
refs/heads/master
<file_sep>$(document).ready(function () { let movies = ['finding nemo', 'toy story ', 'alien', 'predator']; let apiKey = "<KEY>"; function getGifs(movie) { let queryUrl = "http://api.giphy.com/v1/gifs/search?q=" + movie + "&api_key=" + apiKey + "&limit=10"; $.ajax({ url: queryUrl, method: "GET" }).then(function (response) { for (let i = 0; i < response.data.length; i++) { console.log(i) console.log(response.data[i]) let giphy = $('<div>'); let rating = $('<p>').text(response.data[i].rating); let title = $('<h3>').text(response.data[i].title); let image = $("<img>").attr("src", response.data[i].images.fixed_height_still.url); image.attr("dataImage", response.data[i].images.fixed_height_still.url); image.attr("dataAnimate", response.data[i].images.fixed_height.url); image.attr("dataCurrent", "static"); image.addClass('giphyImage'); giphy.append(rating, title, image); giphy.addClass("giphy"); rating.addClass('rating'); title.addClass('title'); $('#gifWrapper').append(giphy); } console.log(response.data) for (let i = 0; i < response.data.length; i++) { console.log("hit") } }) } function renderedButton() { for (let i = 0; i < movies.length; i++) { let button = $('<button>'); button.addClass("movieButton").text(movies[i]); $('#buttonWrapper').append(button); } } $(document).on("click", ".giphyImage", function () { if ($(this).attr("dataCurrent") === "static") { $(this).attr("src", $(this).attr('dataAnimate')) $(this).attr('dataCurrent', "animate"); } else { $(this).attr("src", $(this).attr('dataImage')) $(this).attr('dataCurrent', "static"); } }) $(document).on("click", "#buttonView", function () { var a = $("<button>"); a.addClass("movie-btn"); a.attr("data-name"); var ourtextinput = $('#exampleInputPassword1').val() a.text(ourtextinput); //buttonview.text(movies[i]) $("#buttonWrapper").append(a); console.log(this) getGifs(ourtextinput); }) $(document).on('click', '.movieButton', function () { let movieName = $(this).text(); getGifs(movieName); }); renderedButton(); }) //this is a collection of gifs //when the user clicks on a button it will pull 10 gifs from an api and display them on the window. // when they click on the gif will start moving. the gif will display the rating of the gif as well. It will also // create a new button so someone else can click or add to the list. //======================================================================================================== // things i need // need a couple of array's they will need to be strings of topics that I like. // going to need some for loops to run through the array // will need buttons in html so that the user can click on what they like. // Need to add a form to the page that takes the value from a user input box and adds it to the topics array. // The entire app needs to be mobile responsive. // if possible add additional apis.
3a71f05b1a8a83e48739d14946fe4cd0501b5dae
[ "JavaScript" ]
1
JavaScript
Gonzalon3140/Giphy_app
ef249135fe8ab5643ae9fb2272e2903a61c40d85
1ab052a3189893ad8833748f6e0d7cb599027db2
refs/heads/master
<repo_name>tscibilia/ProvisioningVMs<file_sep>/README.md [![License](https://img.shields.io/github/license/mashape/apistatus.svg)](https://choosealicense.com/licenses/mit/) # ProvisioningVMs Bash scripts to (ideally) provision a VM for "automated-ish" deployment ## Usage 1. Find the provisioning file you desire (they're each pretty descriptive with version numbers and Linux kernels). 2. Use a wget command in your terminal window similar to this one: `wget https://raw.githubusercontent.com/tscibilia/ProvisioningVMs/master/Graylog2-OneNode-Ubuntu1604.sh` 3. Make the bash script you downloaded executable similar to this: `chmod +x Graylog2-OneNode-Ubuntu1604.sh` 4. Run the script as root: `./Graylog2-OneNode-Ubuntu1604.sh` ## License _ProvisioningVMs_ is released under the [MIT License](LICENSE). <file_sep>/ApacheGuacamole-Ubuntu1604.sh #!/bin/bash # Script logic from https://github.com/MysticRyuujin/guac-install/blob/master/guac-install.sh # Graphic from https://sourceforge.net/projects/guacamoleinstallscript/ # Version numbers of Guacamole and MySQL Connector/J to download VERSION="0.9.13" MCJVERSION="5.1.43" Black=`tput setaf 0` #${Black} Red=`tput setaf 1` #${Red} Green=`tput setaf 2` #${Green} Yellow=`tput setaf 3` #${Yellow} Blue=`tput setaf 4` #${Blue} Magenta=`tput setaf 5` #${Magenta} Cyan=`tput setaf 6` #${Cyan} White=`tput setaf 7` #${White} Bold=`tput bold` #${Bold} Rev=`tput smso` #${Rev} Reset=`tput sgr0` #${Reset} Bold=`tput bold` #${Bold} clear echo -e " ${Yellow}'.' ${Green}'.:///:-.....' ${Yellow}-yyys/- ${Green}.://///++++++++++++++/- ${Yellow}.yhhhhhys/' ${Green}'.:++++++++++++++++++++++: ${Yellow}'yhhhhhhhhy- ${White}.+y' ${Green}'://++++++++++++++++++++++++' ${Yellow}':yhhhhyo:' ${White}-yNd. ${Green}'/+++++++++++++++++++++++++++//' ${Yellow}.+yo:' ${White}':: ${White}oNMh' ${Green}./++++++++++++++++++++++++++++++/:' '''' ${White}'mMh. ${White}-MMM: ${Green}/+++++++++++++++++++++++++++++++++-.:/+: ${White}yMMs ${White}-MMMs ${Green}./++++++++++++++++++++++++++++++++++++/' ${White}.mMMy ${White}'NMMMy. ${Green}'-/+++++++++++++++++++++++++++++++/:. ${White}:dMMMo ${White}+MMMMNy:' ${Green}'.:///++++++++++++++++++++//:-.' ${White}./hMMMMN' ${White}-MMMMMMMmy+-.${Green}''''.---::::::::::--..''''${White}.:ohNMMMMMMy ${White}sNMMMMMMMMMmdhs+/:${Green}--..........--${White}:/oyhmNMMMMMMMMMd- ${White}.+dNMMMMMMMMMMMMMMNNmmmmmmmNNNMMMMMMMMMMMMMMmy:' ${White}./sdNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNmho:' ${White}' .:+shmmNNMMMMMMMMMMMMMMMMNNmdyo/-' ${White}.o:. '.-::/+ossssssso++/:-.' '-/' ${White}.ymh+-.' ''./ydy. ${White}/dMMNdyo/-.'''' ''''.-:+shmMNh: ${White}:yNMMMMMMNmdhhyyyyyyyhhdmNNMMMMMNy: ${White}':sdNNMMMMMMMMMMMMMMMMMMMNNds:' ${White}'-/+syhdmNNNNNNmdhyo/-' " echo -e " Installation Menu\n ${Bold}Guacamole Remote Desktop Gateway ${VERSION}\n" && tput sgr0 echo # Grab a password for MySQL Root read -s -p "Enter the password that will be used for MySQL Root: " mysqlrootpassword echo debconf-set-selections <<< "mysql-server mysql-server/root_password password $mysqlrootpassword" debconf-set-selections <<< "mysql-server mysql-server/root_password_again password $mysqlrootpassword" # Grab a password for Guacamole database user account read -s -p "Enter the password that will be used for the Guacamole database: " guacdbuserpassword echo # Update apt so we can search apt-cache for newest tomcat version supported apt update # tomcat8 is newest, tomcat7 and tomcat6 should work too if [ $(apt-cache search "^tomcat8$" | wc -l) -gt 0 ]; then TOMCAT="tomcat8" elif [ $(apt-cache search "^tomcat7$" | wc -l) -gt 0 ]; then TOMCAT="tomcat7" else TOMCAT="tomcat6" fi # If you want to force a specific tomcat install and not go with the newest just set it here and uncomment: #TOMCAT="" # Ubuntu and Debian have different names of the libjpeg-turbo library for some reason... if [ `egrep -c "ID=ubuntu" /etc/os-release` -gt 0 ] then JPEGTURBO="libjpeg-turbo8-dev" else JPEGTURBO="libjpeg62-turbo-dev" fi # Ubuntu 16.10 has a different name for libpng12-dev for some reason... if [ `egrep -c 'VERSION="16.10' /etc/os-release` -gt 0 ] then LIBPNG="libpng-dev" else LIBPNG="libpng12-dev" fi # Install features apt -y install build-essential libcairo2-dev ${JPEGTURBO} ${LIBPNG} libossp-uuid-dev libavcodec-dev libavutil-dev \ libswscale-dev libfreerdp-dev libpango1.0-dev libssh2-1-dev libtelnet-dev libvncserver-dev libpulse-dev libssl-dev \ libvorbis-dev libwebp-dev mysql-server mysql-client mysql-common mysql-utilities ${TOMCAT} freerdp ghostscript jq wget curl dpkg-dev # If apt fails to run completely the rest of this isn't going to work... if [ $? != 0 ]; then echo "apt failed to install all required dependencies" exit fi # Get build-folder BUILD_FOLDER=$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) SERVER=$(curl -s 'https://www.apache.org/dyn/closer.cgi?as_json=1' | jq --raw-output '.preferred|rtrimstr("/")') # Add GUACAMOLE_HOME to $TOMCAT ENV echo "" >> /etc/default/${TOMCAT} echo "# GUACAMOLE ENV VARIABLE" >> /etc/default/${TOMCAT} echo "GUACAMOLE_HOME=/etc/guacamole" >> /etc/default/${TOMCAT} # Download Guacamole files wget ${SERVER}/incubator/guacamole/${VERSION}-incubating/source/guacamole-server-${VERSION}-incubating.tar.gz wget ${SERVER}/incubator/guacamole/${VERSION}-incubating/binary/guacamole-${VERSION}-incubating.war wget ${SERVER}/incubator/guacamole/${VERSION}-incubating/binary/guacamole-auth-jdbc-${VERSION}-incubating.tar.gz wget https://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-${MCJVERSION}.tar.gz # Extract Guacamole files tar -xzf guacamole-server-${VERSION}-incubating.tar.gz tar -xzf guacamole-auth-jdbc-${VERSION}-incubating.tar.gz tar -xzf mysql-connector-java-${MCJVERSION}.tar.gz # Make directories mkdir -p /etc/guacamole/lib mkdir -p /etc/guacamole/extensions # Install guacd cd guacamole-server-${VERSION}-incubating ./configure --with-init-dir=/etc/init.d make make install ldconfig systemctl enable guacd cd .. # Move files to correct locations mv guacamole-${VERSION}-incubating.war /etc/guacamole/guacamole.war ln -s /etc/guacamole/guacamole.war /var/lib/${TOMCAT}/webapps/ ln -s /usr/local/lib/freerdp/guac*.so /usr/lib/${BUILD_FOLDER}/freerdp/ cp mysql-connector-java-${MCJVERSION}/mysql-connector-java-${MCJVERSION}-bin.jar /etc/guacamole/lib/ cp guacamole-auth-jdbc-${VERSION}-incubating/mysql/guacamole-auth-jdbc-mysql-${VERSION}-incubating.jar /etc/guacamole/extensions/ # Configure guacamole.properties echo "mysql-hostname: localhost" >> /etc/guacamole/guacamole.properties echo "mysql-port: 3306" >> /etc/guacamole/guacamole.properties echo "mysql-database: guacamole_db" >> /etc/guacamole/guacamole.properties echo "mysql-username: guacamole_user" >> /etc/guacamole/guacamole.properties echo "mysql-password: <PASSWORD>" >> /etc/guacamole/guacamole.properties rm -rf /usr/share/${TOMCAT}/.guacamole ln -s /etc/guacamole /usr/share/${TOMCAT}/.guacamole # restart tomcat service ${TOMCAT} restart # Create guacamole_db and grant guacamole_user permissions to it # SQL code SQLCODE=" create database guacamole_db; create user 'guacamole_user'@'localhost' identified by \"$<PASSWORD>password\"; GRANT SELECT,INSERT,UPDATE,DELETE ON guacamole_db.* TO 'guacamole_user'@'localhost'; flush privileges;" # Execute SQL code echo $SQLCODE | mysql -u root -p$mysqlrootpassword # Add Guacamole schema to newly created database cat guacamole-auth-jdbc-${VERSION}-incubating/mysql/schema/*.sql | mysql -u root -p$mysqlrootpassword guacamole_db # Cleanup rm -rf guacamole-* rm -rf mysql-connector-java-${MCJVERSION}* <file_sep>/Graylog2-OneNode-Ubuntu1604.sh #!/bin/bash #Concept taken from fodor.xyz #Install from Graylog Docs http://docs.graylog.org/en/2.3/pages/installation/os/ubuntu.html #Approx. 12 min. install based on AWS EC2 t2.micro https://aws.amazon.com/ec2/instance-types/ #Prerequisites apt update && sudo apt upgrade -y apt -y install apt-transport-https openjdk-8-jre-headless uuid-runtime pwgen #MongoDB (version included in 16.04 LTS) apt -y install mongodb-server #Elasticsearch 5.x wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | apt-key add - echo "deb https://artifacts.elastic.co/packages/5.x/apt stable main" | tee -a /etc/apt/sources.list.d/elastic-5.x.list apt update && apt -y install elasticsearch #Elasticsearch config sed -i -e 's/#cluster.name: my-application$/cluster.name: graylog/g' /etc/elasticsearch/elasticsearch.yml systemctl daemon-reload systemctl enable elasticsearch.service systemctl restart elasticsearch.service #Graylog 2.3.x wget https://packages.graylog2.org/repo/packages/graylog-2.3-repository_latest.deb dpkg -i graylog-2.3-repository_latest.deb apt update && apt -y install graylog-server #Graylog config IPV4=$(hostname -i) sed -i -e "s/rest_listen_uri = http:\/\/127.0.0.1:9000\//rest_listen_uri = http:\/\/$IPV4:9000\//g" /etc/graylog/server/server.conf sed -i -e "s/#web_listen_uri = http:\/\/127.0.0.1:9000\//web_listen_uri = http:\/\/$IPV4:9000\//g" /etc/graylog/server/server.conf SECRET=$(pwgen -s 96 1) sed -i -e 's/password_secret =.*/password_secret = '$<PASSWORD>'/' /etc/graylog/server/server.conf echo echo -n "Enter a password for graylog admin [ENTER]: " read ADMIN_PASSWORD PASSWORD=$(echo -n $ADMIN_PASSWORD | sha256sum | awk '{print $1}') sed -i -e 's/root_password_sha2 =.*/root_password_sha2 = '$<PASSWORD>'/' /etc/graylog/server/server.conf #Cleanup & Startup systemctl daemon-reload systemctl enable graylog-server.service systemctl start graylog-server.service #Final output confirmation echo echo "#######################################" echo "# Congrats the installation is finished" echo "# You should be able to view the app at" echo "#" echo "# http://$IPV4:9000" echo "# username: admin" echo "# password: <PASSWORD>" echo "#" echo "# If you want to change the URL, please" echo "# read the docs http://docs.graylog.org" echo "#######################################"
c3f037939c72e4402863e7d0ffaeb504e1d01574
[ "Markdown", "Shell" ]
3
Markdown
tscibilia/ProvisioningVMs
abbda1cb934b80811b98a6c09d66069d077e2266
1007ae44e9abd4c8fda7b16db464164004a53b82
refs/heads/main
<file_sep><!DOCTYPE html> <html> <head> </head> <div class="container"> <h1>Information</h1> </div> <body> <div> <hr> <h2>Form</h2> <?php echo "<h2>Hello, this is my first attempt at php.</h2>"; $firstVar = 27; $secondVar = 30; $thirdVar = $firstVar + $secondVar; echo $thirdVar; ?> <a href = "/math">Math Link </a> </div> </body> </html><file_sep> <!DOCTYPE html> <html> <head> <title> MAths</title> <!-- <link rel="stylesheet" type="text/css" href="resources/css/style.css"> --> <link href="{{asset('/css/style.css') }}" rel="stylesheet" type="text/css" > <h1>Input two numbers whose product is between 0 and 100 </h1> <br> <br> <hr> </head> <body> <form> <br> First Number: <input type = "number" name = "num1" placeholder = "First Number"> Second Number: <input type = "number" name = "num2" placeholder = "Second Number"> <button type = "submit" name = "submit" value = "submit"> Enter </button> </form> <?php if(isset($_GET['submit'])) { $result1 = $_GET['num1']; $result2 = $_GET['num2']; $total = intval($result1) + intval($result2); if($total > 100 || $total < 0){ echo "Please enter numbers that when combined are between 0 - 100 "; }else if (empty ($_GET['num1']) || empty ($_GET['num2']) ) { echo "Please input TWO numbers."; }else{ echo "Result: ".$total; } } ?> </body> </html>
a8b37b2cb1d7839eb4baf949b71f3775794691f4
[ "Blade" ]
2
Blade
w-Talbot/wtAppFirstTest
bfae29f02650d2d05727e16bfcadd4cf1ccd2b2b
5367d10992dc2ed96b782b752207512ba820d225
refs/heads/master
<repo_name>ckxsuper/HelloWorld<file_sep>/README.md # HelloWorld test Commit Linux edit
fe0bad8c3732e1ea6caee3917927d51fd7a5fd70
[ "Markdown" ]
1
Markdown
ckxsuper/HelloWorld
a0b515d013c318a9ef9671962d773580146c8e6a
5ec833b32a6c24b5ba25e4b3f0629cc0ae334699
refs/heads/master
<file_sep># theHashingProject Creating a hash of any given password and associating each password to a given user **TO RUN IT:** ```bash slimkaki@root $ gcc hash.c -o hash slimkaki@root $ ./hash -u `<USERNAME>` -p `<PASSWORD>` ``` *Possible arguments:* `-u <USERNAME>`: Username; `-p <PASSWORD>`: Password; `--login`: Try to login in the account with the given password; `-h` or `-help`: Gives help; **TODO:** - Clean the code; <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <unistd.h> #include <sys/types.h> #include "cores.h" typedef struct { char *username; char *hashpwd; } credentials; int encryptPWD(char myString[], int size) { int hash = 0; int aux; for (int i = 0; i < size; i++) { int x = (int) myString[i]; aux = 1; x = x * 85432100 * (i + 1); for (int j = 512; j > 1; j /= 2) { hash = hash + (aux*x)%j; aux *= -1; } hash *= 100000001; } return hash; } int isTheFileEmpty(FILE *fp) { fseek(fp, 0, SEEK_END); if (ftell(fp) == 0) { return 1; } return 0; } int checkIfUserExists(FILE *fp, char *user) { char line[256]; char needle[256]; sprintf(needle, "username: %s", user); while (fgets(line, sizeof(line), fp)) { if (strstr(line, needle) != NULL) { return 1; } } return 0; } int checkPassword(FILE *fp, credentials *user) { int c = 0; char line[256]; char needle[256]; sprintf(needle, "username: %s", user->username); while (fgets(line, sizeof(line), fp)) { if (c) { sprintf(needle, "password: %s", user->hashpwd); if (strstr(line, needle) != NULL) { return 1; } } if (strstr(line, needle) != NULL) { c++; } } return 0; } int main(int argc, char *argv[]) { /* Arguments: -u <USERNAME>: Username to be signed in; -p <PASSWORD>: Password to respectively username; --login: Check if given password is correct to that username; -h or -help: Gives help to the user; */ FILE *fp; if ((fp = fopen("./data/login.txt", "r+")) == NULL) { fprintf(stderr, "Error trying to create login data file\n"); exit(1); } int filho; int login = 0; char *myUSER; char *myPWD; if (argc <= 2) { if (argc == 1) { boldRed(); fprintf(stdout, "No argumments were passed\n"); reset(); } else { if (strstr(argv[1], "-h") || strstr(argv[1], "-help")) { magenta(); printf("Possible arguments:\n"); cyan(); printf("\t-u <USERNAME>: Username to be signed in;\n\t-p <PASSWORD>: Password to respectively username;\n\t--login: Check if given password is correct to that username;\n\t-h or -help: Gives help to the user;\n"); reset(); exit(0); } } exit(1); } else { for (int i = 1; i < argc; i++) { if (strstr(argv[i], "-u")) { i++; myUSER = argv[i]; } if (strstr(argv[i], "-p")) { i++; myPWD = argv[i]; } if (strstr(argv[i], "--login")) { login++; } } if (myUSER == NULL) { boldRed(); fprintf(stdout, "Need a username to continue...\n"); reset(); exit(1); } else { credentials *newUser = malloc(sizeof(credentials)); newUser->username = myUSER; if (login) { int checkSIZE = strlen(myPWD); int checkHash = encryptPWD(myPWD, checkSIZE); char hexHash[16]; sprintf(hexHash, "%x", checkHash); newUser->hashpwd = hexHash; if (checkPassword(fp, newUser)) { boldGreen(); fprintf(stdout, "Access granted!\n"); reset(); exit(0); } } if (checkIfUserExists(fp, newUser->username)) { boldYellow(); fprintf(stdout, "User already exists...\n"); reset(); exit(1); } char hexHash[16]; char theNewUser[256]; if ((filho = fork()) == 0) { int mySIZE = strlen(myPWD); int hash = encryptPWD(myPWD, mySIZE); sprintf(hexHash, "%x", hash); newUser->hashpwd = hexHash; if (isTheFileEmpty(fp)) { sprintf(theNewUser, "{\n\tusername: %s,\n\tpassword: %s\n}", newUser->username, newUser->hashpwd); } else { sprintf(theNewUser, ",\n{\n\tusername: %s,\n\tpassword: %s\n}", newUser->username, newUser->hashpwd); } int nbytes = strlen(theNewUser); fwrite(theNewUser, nbytes, 1, fp); } else { wait(&filho); free(newUser); } } } fclose(fp); return 0; }
ca26a8bcfccf7582e892aa6e778651b2e2d16294
[ "Markdown", "C" ]
2
Markdown
slimkaki/theHashingProject
4814ca4fab2be61e31003fdbe194ae73c82507b5
ec631b4cb04f2fa39fbcdc9e89caf7cfd1b0a7ef
refs/heads/master
<file_sep># Generated by Django 3.0.3 on 2020-02-18 14:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auth_my', '0002_auto_20200218_1725'), ] operations = [ migrations.AlterField( model_name='notes', name='date', field=models.DateTimeField(), ), migrations.AlterField( model_name='notifications', name='date', field=models.DateTimeField(), ), ] <file_sep>from django.apps import AppConfig class SwitchNotesConfig(AppConfig): name = 'switch_notifications' <file_sep>from django.contrib import admin # Register your models here. from .models import Users, Notes, Notifications admin.site.register(Users) admin.site.register(Notes) admin.site.register(Notifications) <file_sep>from django.shortcuts import render from rest_framework.response import Response from rest_framework.views import APIView # Create your views here. from auth_my.models import Users from web_helper.common import get_response_error_auth, get_response_success, get_response_error def check_auth(login, password_hash): user = Users.objects.filter(login=login, password_hash=password_hash) if user: return True else: return False class UserView(APIView): def post(self, request): try: user_data = request.data login = user_data["login"] password_hash = user_data["password_hash"] if not check_auth(login, password_hash): return get_response_error_auth() body = { "auth": "True" } return get_response_success(body) except Exception as s: print("auth_service error: " + s) return get_response_error() <file_sep>from django.shortcuts import render # Create your views here. from rest_framework.views import APIView import datetime from auth_my.models import Users, Notes,Notifications from auth_my.views import check_auth from web_helper.common import get_response_error_auth, get_response_success, get_response_error class UserView(APIView): def post(self, request): try: user_data = request.data login = user_data["login"] password_hash = user_data["password_hash"] notes = user_data["notes"] answer = [] if not check_auth(login, password_hash): return get_response_error_auth() user = Users.objects.filter(login=login, password_hash=password_hash) user = user[0] copy_notes = notes for note in notes: date = note["date"] note_server = Notifications.objects.filter(user_id=user.id, date=date) if not note_server: note.update({"status": "delete"}) answer.append(note) note_server = Notifications.objects.filter(user_id=user.id) for note in note_server: date = note.date text = note.text searchDict = { "date":date.isoformat()[:-6]+"Z", "text":text } if not searchDict in notes: answer.append({ "date":date, "text":text, "status": "add" }) body = { "answer":answer } return get_response_success(body) except Exception: print("auth_service error: ") return get_response_error() <file_sep>from django.db import models # Create your models here. class Users(models.Model): login = models.CharField(max_length=36, unique=True) password_hash = models.CharField(max_length=50) class Notes(models.Model): user_id = models.ForeignKey('Users', related_name='users_to_notes', on_delete=models.CASCADE) date = models.DateTimeField() text = models.TextField() class Notifications(models.Model): user_id = models.ForeignKey('Users', related_name='users_to', on_delete=models.CASCADE) date = models.DateTimeField() text = models.TextField() <file_sep>from django.shortcuts import render # Create your views here. from django.shortcuts import render # Create your views here. from rest_framework.views import APIView import datetime from auth_my.models import Users, Notes, Notifications from auth_my.views import check_auth from web_helper.common import get_response_error_auth, get_response_success, get_response_error class UserView(APIView): def post(self, request): try: user_data = request.data login = user_data["login"] password_hash = user_data["password_hash"] note = user_data["note"] status = user_data["status"] if not check_auth(login, password_hash): return get_response_error_auth() user = Users.objects.filter(login=login, password_hash=password_hash) user = user[0] if status == "add": Notifications.objects.create(user_id=user, text=note["text"], date=note["date"]) elif status == "change": note_c = Notifications.objects.filter(user_id=user, date=note["date"]) note_c = note_c[0] note_c.text = note["text"] note_c.save() elif status == "delete": note_c = Notifications.objects.filter(user_id=user, date=note["date"]) note_c = note_c[0] note_c.delete() body = { "answer": "success" } return get_response_success(body) except Exception: print("auth_service error: ") return get_response_error() <file_sep>from rest_framework.response import Response def get_response_error(): body = { "errorType": "Что то пошло не так" } return setup_cors_response_headers(Response(body, status=500, content_type="application/json")) def get_response_error_auth(): body = { "errorType": "Не авторизован" } return setup_cors_response_headers(Response(body, status=401, content_type="application/json")) def get_response_success(body): return setup_cors_response_headers(Response(body, status=200, content_type="application/json")) def setup_cors_response_headers(res): res["Access-Control-Allow-Origin"] = "http://127.0.0.1:1329" res["Access-Control-Allow-Methods"] = "GET,POST,PUT,DELETE,OPTIONS" res["Access-Control-Allow-Headers"] = \ "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" res["Access-Control-Allow-Credentials"] = "true" return res <file_sep># Generated by Django 3.0.3 on 2020-02-18 14:25 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auth_my', '0001_initial'), ] operations = [ migrations.AlterField( model_name='notes', name='user_id', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='users_to_notes', to='auth_my.Users'), ), migrations.AlterField( model_name='notifications', name='user_id', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='users_to', to='auth_my.Users'), ), ] <file_sep>from django.apps import AppConfig class ChangeNotesConfig(AppConfig): name = 'change_notes'
999d2f1fea7b11be8ef23d58349addd686de2e8a
[ "Python" ]
10
Python
KirillSemennikov2803/web_helper
82fcc45b9e5a47aca7c35ed896e2a1f1954a9443
e91503fb4f787a3aa884b22e730d35ac11fd7dfd
refs/heads/master
<repo_name>mikesaraus/MiVPN<file_sep>/README.md # MiVPN This is weird , a i call it VPN lol. What is Does is to change your local IPv4 address and with random IP. <file_sep>/MiVPN.vb Imports System.IO Public Class MiVPN Dim first As Boolean = True Dim intRandomNumber As Integer = 250 Dim posX As Integer Dim posY As Integer Dim drag As Boolean Dim CustomToolTip As System.Windows.Forms.ToolTip = New System.Windows.Forms.ToolTip() Private Sub Enable_Click(sender As System.Object, e As System.EventArgs) Handles Enable.Click newIP() Enable.Visible = False Fresh.Visible = True AnimateWin() End Sub Private Sub Btn_Exit_Click(sender As System.Object, e As System.EventArgs) Handles Btn_Exit.Click StopNexit() End Sub Private Sub Animation_DoubleClick(sender As Object, e As System.EventArgs) Handles Animation.DoubleClick If Animation.Dock = DockStyle.Fill Then Animation.Dock = DockStyle.None Else Animation.Dock = DockStyle.Fill End If Me.TopMost = True End Sub Private Sub Animation_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Animation.MouseDown If e.Button = MouseButtons.Left Then drag = True posX = Cursor.Position.X - Me.Left posY = Cursor.Position.Y - Me.Top End If If e.Button = MouseButtons.Right Then 'MsgBox("Right Button Clicked") AnimateWin() End If End Sub Private Sub Animation_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Animation.MouseMove If drag Then Me.Top = Cursor.Position.Y - posY Me.Left = Cursor.Position.X - posX End If End Sub Private Sub Animation_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Animation.MouseUp drag = False End Sub Private Sub MiVPN_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing StopNexit() End Sub Private Sub MiVPN_Load(sender As Object, e As System.EventArgs) Handles Me.Load Me.TopMost = True Dim x As Integer Dim y As Integer x = Screen.PrimaryScreen.WorkingArea.Width y = Screen.PrimaryScreen.WorkingArea.Height - Me.Height Do Until x = Screen.PrimaryScreen.WorkingArea.Width - Me.Width x = x - 1 Me.Location = New Point(x, y) Loop End Sub Public Sub newIP() intRandomNumber = GetRandom(1, 255) Try Label1.Text = "Connected to server: " & intRandomNumber Process.Start("CMD", "/C netsh interface ipv4 set address name=2 source=static address=192.168.1." & intRandomNumber & " mask=255.255.255.0 gateway=192.168.1.1") 'Process.Start("CMD", "/C netsh interface ipv4 set address name=2 source=dhcp") Catch ex As Exception MsgBox("Error!") End Try Animation.Enabled = True End Sub Public Sub StopNexit() Try Process.Start("CMD", "/C netsh interface ipv4 set address name=2 source=static address=192.168.1.0 mask=255.0.0.0") Catch ex As Exception MsgBox("Error!") End Try Environment.Exit(1) End Sub Public Function GetRandom(ByVal min As Integer, ByVal max As Integer) As Integer Static staticRandomGenerator As New System.Random max += 1 Return staticRandomGenerator.Next(If(min > max, max, min), If(min > max, min, max)) End Function Private Sub Fresh_Click(sender As System.Object, e As System.EventArgs) Handles Fresh.Click newIP() End Sub Private Sub Btn_Minimize_Click(sender As System.Object, e As System.EventArgs) Handles Btn_Minimize.Click Me.ShowInTaskbar = False Me.WindowState = FormWindowState.Minimized End Sub Private Sub Fresh_MouseHover(sender As Object, e As System.EventArgs) Handles Fresh.MouseHover CustomToolTip.SetToolTip(Fresh, "Refresh") End Sub Public Sub AnimateWin() Dim x As Integer Dim y As Integer x = Screen.PrimaryScreen.WorkingArea.Width y = Screen.PrimaryScreen.WorkingArea.Height - Me.Height Do Until x = Screen.PrimaryScreen.WorkingArea.Width - Me.Width + 40 x = x - 1 Me.Location = New Point(x, y) Loop End Sub End Class
27e4785afc43e205ddf6d8ba75e59d52c15ad834
[ "Markdown", "Visual Basic .NET" ]
2
Markdown
mikesaraus/MiVPN
2d9efc2bc131acd212f803827b7b9d493acc939a
6c1de9d5303181db854522d8f5dc07be7c37fbdc
refs/heads/master
<file_sep><?php namespace M\Initializer; class Database extends \M\Initializer { public function init() { if(!empty(getenv('MYSQL_DSN'))) { $c = [ 'dsn' => getenv('MYSQL_DSN') ]; } else { $c = [ 'user' => getenv('MYSQL_USER'), 'pass' => getenv('<PASSWORD>'), 'host' => getenv('MYSQL_HOST'), 'database' => getenv('MYSQL_DATABASE') ]; } new \M\Orm($c); } } <file_sep><?php namespace M; use PHPUnit\Framework\TestCase; abstract class TestHelper extends \PHPUnit\Framework\TestCase { public function isClassLoaded(string $class) : bool { return in_array($class, $this->getLoadedClasses()); } public function isNamespaceLoaded(string $namespace) : bool { $cs = $this->getLoadedClasses(); foreach($cs as $c) { if(strpos($c, $namespace) !== false) { return true; } } return false; } public function getLoadedClasses() : array { return array_filter( get_declared_classes(), function($className) { return !call_user_func( array(new \ReflectionClass($className), 'isInternal') ); } ); } }<file_sep><?php class User extends \M\Orm { }<file_sep><?php final class OrmTest extends \M\TestHelper { public function setUp() : void { (new \M\Orm()) ->create() ->database('orm_test') ->exec(); (new \M\Orm(['database' => 'orm_test'])) ->create() ->table('user') ->columns( ['id', 'int', 20, 'primary'], ['name', 'varchar', 255] ) ->exec(); \M\Orm::query("INSERT INTO user (id, name) VALUES(1, 'Test 1')"); \M\Orm::query("INSERT INTO user (id, name) VALUES(2, 'Test 2')"); } public function tearDown() : void { (new \M\Orm()) ->drop() ->database('orm_test') ->exec(); } public function testConstruct() { $this->assertInstanceOf(\M\Orm::class, new \M\Orm()); } public function testConstructWithWrongCredentials($config=[]) { $this->expectException(\M\OrmConnectionException::class); new \M\Orm([ 'username' => 'non-existing-user', 'password' => '<PASSWORD>' ]); } public function testConstructWithNonExistingDatabase() { $this->expectException(\M\OrmConnectionException::class); new \M\Orm([ 'database' => 'non-existing-database' ]); } public function testSetColumnValue() { $o = new \M\Orm(); $o->name = 'value'; $this->assertEquals($o->name, 'value'); } public function testGetColumnValue() { $o = new \M\Orm(); $o->name = 'value'; $this->assertEquals($o->name, 'value'); } public function testCallingSelectMethod() { $o = new \M\Orm(); $o->select('value'); $this->assertEquals($o->getComponents(), ['select' => ['value']]); } public function testCallingBuildQuery() { $r = (new \M\Orm()) ->select('name') ->from('user') ->build(); $this->assertEquals( $r, 'SELECT name FROM `user`' ); } public function testBuildingUnknownComponent() { $this->expectException(\M\OrmBuilderComponentNotImplementedException::class); (new \M\Orm()) ->nonExistingComponent('name') ->build(); } public function testManualWrittenQuery() { $r = \M\Orm::query('SELECT * FROM user WHERE id = :id LIMIT 1', [ 'id' => 1 ]); $this->assertTrue(is_array($r)); $this->assertCount(1, $r); } public function testExecutingAQuery() { $r = (new \M\Orm()) ->exec( 'SELECT * FROM user WHERE id = :id LIMIT 1', ['id' => 1] ); $this->assertTrue(is_array($r)); $this->assertCount(1, $r); } public function testFindAllRecords() { $r = (new \M\Orm())->from('user')->find(); $this->assertTrue(is_array($r)); $this->assertCount(2, $r); } public function testFindOneRecord() { $r = (new \M\Orm())->from('user')->findOne(); $this->assertInstanceOf(User::class, $r); } public function testUpdatingRecordsWhileCallingSave() { $u = new User(); $u->id = 1; $u->name = '<NAME>'; $u->save(); $r = (new \M\Orm()) ->from('user') ->where([ 'id' => $u->id ]) ->findOne(); $this->assertEquals( $u->name, $r->name ); } public function testSaveUpdateFailedSoSkipToInsert() { $u = new User(); $u->id = 3; $u->name = 'Test 3'; $u->save(); $r = (new \M\Orm()) ->from('user') ->where([ 'id' => $u->id ]) ->findOne(); $this->assertEquals( $u->name, $r->name ); } public function testSaveInsertWithoutPrimaryKey() { $u = new User(); $u->name = '<NAME>'; $u->save(); $r = (new \M\Orm()) ->from('user') ->where([ 'name' => $u->name ]) ->findOne(); $this->assertEquals( $u->name, $r->name ); } public function testDeletingARecord() { $r = (new \M\Orm())->from('user')->find(); $this->assertCount(2, $r); $r = (new \M\Orm()) ->from('user') ->where([ 'id' => 1 ]) ->remove(); $r = (new \M\Orm()) ->from('user') ->where([ 'id' => 1 ]) ->findOne(); $this->assertFalse($r); $r = (new \M\Orm())->from('user')->find(); $this->assertCount(1, $r); } }<file_sep><?php namespace M\Controller; class Homepage extends \M\Controller { use HomepageDecorator; public static $path = '/'; } <file_sep><?php namespace M\Orm\Builder; class Select extends \M\Orm\Builder { public static function parse(\M\Orm $orm, array $args) { if(empty($args[0])) { $args[0] = '*'; } return 'SELECT '. $args[0]; } }<file_sep><?php namespace M\Initializer; class Session extends \M\Initializer { public function init() { session_start(); // @TODO set session timeout and lifetime } } <file_sep><?php require './vendor/autoload.php'; require 'test/support/TestHelper.php'; require 'test/support/Model/User.php';<file_sep><?php namespace M\Initializer; class Error extends \M\Initializer { public function init() { $dsn = getenv('SENTRY_DSN', ''); if(!empty($dsn)) { \Sentry\init([ 'dsn' => $dsn, 'environment' => getenv('APP_ENV'), ]); } } } <file_sep># Magic Framework - it's a kinda magic ## Getting started For now we have two flavours for you how to set up a new project. We have the quick start way with a repository template or the manual way, please not that the manual way does not include examples. ### Quick start @TODO Create a new repository based on our github.com repository template. ### Install with composer @TODO If you haven't done so already, add the Magic Framework package to your composer.json file. You can do it manually or use the command below. composer require m4lloc/magic-framework After that you can create a index.php file with the following content. <?php require_once 'vendor/autoload.php'; $app = new \M\App(); $app->run(); ### Manually start a new project @TODO First create a `composer.json` file and copy/paste the json below. After that run `composer install`. { "repositories": [{ "type": "git", "url": "https://github.com/m4lloc/magic-framework.git" }], "require": { "m4lloc/magic-framework": "dev-master" } } Since we are talking about starting a new clean project we can now run the command below to create all the files we need. vendor/bin/m init # Decorator pattern For some standard objects in the Magic Framework, you can use the decorator pattern to overwrite some methods within these objects. A good example is overwriting the Homepage controller `M\Controller\Homepage` to implement your own homepage functionalities. All you need to do for this to work is to create a new file with the example contents below and place it in the corresponding directory. So to overwrite the homepage controller we will create the file `src/App/Controller/HomepageDecorator.php` and copy/paste the code example from below. <?php namespace M\Controller; trait HomepageDecorator { } # Adding a new controller When you want to add a new controller to your project, you need to create a new file in the `src/App/Controller` directory. Let's create a `Browse` controller to browse through some site content, for example. Create the file `src/App/Controller/Browse.php` and copy/paste the following contents in the file. <?php namespace M\Controller; class Browse extends \M\Controller { } It will automatically generate the routings for you to use, you just need to create a template file. Now we are going to create a new file in the `src/App/View/Controller` directory. The file structure is the same as for the controllers, except we have added the `/View` part and the name of the controller is now a directory. Let's create the template file `src/App/View/Controller/Browse/Index.tpl`, it's for the `index` action. If you want you can copy/paste the example template below or just write your own HTML. <h1>Hello, world!</h1> <p>This is where you can browse our content.</p> # Possible improvements * php-http/client-common suggests installing php-http/logger-plugin (PSR-3 Logger plugin) * php-http/client-common suggests installing php-http/cache-plugin (PSR-6 Cache plugin) * php-http/client-common suggests installing php-http/stopwatch-plugin (Symfony Stopwatch plugin) * phpunit/phpunit suggests installing phpunit/php-invoker (^2.0.0) * add the possiblility to run `composer require m4lloc/magic-framework` <file_sep><?php namespace M; class App { public static $VENDOR_DIR = '.'; public function __construct() { self::$VENDOR_DIR = dirname(__FILE__, 5); } public function run() { $this->environment(); $this->initializers(); $this->routes(); $this->dispatcher(); } private function environment() { $dotenv = \Dotenv\Dotenv::create(getcwd() .'/..'); $dotenv->load(); } private function initializers() { $init = new Initializer; $init->load(); } private function routes() { $router = new Router; $router->load(); } private function dispatcher() { $dispatcher = new Dispatcher; $dispatcher->load(); } } <file_sep><?php namespace M\Initializer; class Https extends \M\Initializer { public static $before = 'error'; public function init() { if($this->shouldRedirect()) { $this->setHeaderLocation(); $this->terminate(); } } private function shouldRedirect() : bool { $redirect_envs = ['production', 'test']; if(!isset($_SERVER['HTTPS']) && in_array(getenv('APP_ENV'), $redirect_envs)) { return true; } return false; } private function setHeaderLocation() : void { header('Location: https://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], true, 301); } private function terminate() : void { if(getenv('APP_ENV') != 'test') { exit; } } } <file_sep><?php class ErrorTest extends \M\TestHelper { public function testWhenDsnIsGivenEnableSentry() { putenv('SENTRY_DSN=https://key@sentry.io/project'); $i = new \M\Initializer\Error(); $i->init(); $this->assertTrue($this->isSentryEnabled(), 'Sentry is not loaded while it should have been'); } public function testWhenDsnIsEmptyDoNotEnableSentry() { putenv('SENTRY_DSN='); $i = new \M\Initializer\Error(); $i->init(); $this->assertFalse($this->isSentryEnabled(), 'Sentry is loaded even when the DSN is empty'); } private function isSentryEnabled() : bool { if($this->isClassLoaded('Sentry\Client')) { return true; } return false; } } <file_sep><?php namespace M\Initializer; class Autoload extends \M\Initializer { public function init() { $paths = array_filter([ get_include_path(), realpath('../src/App'), realpath(dirname(__FILE__, 2)), realpath('../src/Lib'), realpath(dirname(__FILE__, 3) .'/Lib'), ]); set_include_path(implode(PATH_SEPARATOR, $paths)); $this->registerAutoloader(); $this->registerDecoraterLoader(); } private function registerAutoloader() { spl_autoload_register(function($namespaced_class) { if(class_exists($namespaced_class)) { return true; } $path = realpath(\M\App::$VENDOR_DIR .'/../src/App/'. substr(str_replace('\\', '/', $namespaced_class), 2) .'.php'); if(file_exists($path)) { require $path; } }, true, true); } private function registerDecoraterLoader() { spl_autoload_register(function($namespaced_trait) { if(trait_exists($namespaced_trait)) { return true; } if(substr($namespaced_trait, -9) != 'Decorator') { return false; } if(strpos($namespaced_trait, '\\')) { $namespace = explode('\\', strrev($namespaced_trait), 2); $namespace = strrev($namespace[1]); if(!empty($namespace)) { $namespace_create = 'namespace '. $namespace .'; '; $trait = str_replace($namespace .'\\', '', $namespaced_trait); } } $trait_path = str_replace('\\', '/', str_replace('M\\', '', $namespace)) .'/'. $trait .'.php'; $paths = explode(PATH_SEPARATOR, get_include_path()); foreach($paths as $path) { if(file_exists($path .'/'. $trait_path)) { require $trait_path; return trait_exists($namespaced_trait); } } eval($namespace_create .'trait '. $trait .' { }'); }, true, true); } } <file_sep><?php namespace M\Orm\Builder; class Set extends \M\Orm\Builder { public static function parse(\M\Orm $orm, array $args) { $args = (sizeof($args) == 1) ? $args[0] : $args ; $columns = []; foreach($args as $column => $value){ $columns[] = '`'. $column .'` = :'. $column; } return 'SET '. implode(', ', $columns); } }<file_sep><?php namespace M; class View { private $smarty = null; private static $instance = null; public function __set(string $name, $value) { $this->$name = $value; $this->assign($name, $this->$name); } public function &__get($name) { return $this->$name; } public function __construct() { if(null === $this->smarty) { $this->smarty = new \Smarty(); } } public static function instance() : \M\View { if(!isset(self::$instance)) { self::$instance = new self(); } return self::$instance; } public static function addTemplateDir(string $path) { return self::instance()->smarty->addTemplateDir($path); } public static function addTemplateDirs(array $paths) { return self::instance()->smarty->addTemplateDir($paths); } public static function setCompileDir(string $path) { return self::instance()->smarty->setCompileDir($path); } public static function assign(string $name, $value) { return self::instance()->smarty->assign($name, $value); } public static function assigned(string $name) { return self::instance()->smarty->getTemplateVars($name); } public static function fetch(string $tpl) { return self::instance()->smarty->fetch($tpl .'.tpl'); } public static function display(string $tpl) { return self::instance()->smarty->display($tpl .'.tpl'); } } <file_sep><?php namespace M\Orm\Builder; class Orwhere extends \M\Orm\Builder { protected static $delimiter = ' OR '; }<file_sep><?php namespace M\Orm\Builder; class Where extends \M\Orm\Builder { protected static $delimiter = ' AND '; public static function parse(\M\Orm $orm, array $args) { $where = []; switch(gettype($args[0])) { case 'array': foreach($args[0] as $name => $value) { $orm->{$name} = $value; $where[] = '`'. $name .'` = :'. $name; } break; case 'string': $where[] = $args[0]; break; } return 'WHERE '. implode(self::$delimiter, $where); } }<file_sep><?php namespace M; abstract class Controller { public function before() { } public function after() { } public function index() { return false; } public function show(array $params = []) { return false; } public function edit(array $params = []) { return false; } public function update(array $params = []) { } public function __xhr() { return false; } public function __post() { return false; } public function __set(string $name, $value=null) { return View::assign($name, $value); } public function __get(string $name) { return View::assigned($name); } } <file_sep><?php namespace M; class Initializer { public static $before = ''; private $initializers = []; public function init() { // @TODO throw exception trigger_error('Every initializer should implement it\'s own init method' , E_USER_WARNING); } public function load() { $this->retrieve(); $this->require_files(); $this->sort(); $this->run(); } private function retrieve() { $this->initializers = glob('{./src/App/Initializer/*.php,'. App::$VENDOR_DIR .'/../App/Initializer/*.php,'. App::$VENDOR_DIR .'/*/*/src/App/Initializer/*.php}', GLOB_BRACE); } private function require_files() { $initializers = []; foreach($this->initializers as $initializer_file) { if(file_exists($initializer_file)) { require_once $initializer_file; $class_name = '\\M\\Initializer\\'. basename($initializer_file, '.php'); if(class_exists($class_name)) { $initializers[] = $class_name; } } } $this->initializers = $initializers; } private function sort() { $inits_by_order = []; foreach($this->initializers as $key => $initializer) { $before = (property_exists($initializer, 'before')) ?? $initializer::$before; $index = array_search($before, array_keys($inits_by_order)); $inits_by_order[$initializer] = $key-(int) $index; } asort($inits_by_order); $this->initializers = array_keys($inits_by_order); } private function run() { foreach($this->initializers as $initializer) { $init = new $initializer; $init->init(); } } } <file_sep><?php namespace M; class Dispatcher { private $route; private $class; private $method; private $params = []; public function load() { $this->determine_route(); $this->determine_controller(); $this->invoke(); $this->render(); } private function determine_route() { $dispatcher = \FastRoute\simpleDispatcher(function(\FastRoute\RouteCollector $r) { foreach(\M\Router::$routes as $route) { $r->addRoute($route['method'], $route['route_pattern'], $route['handler']); } }); // Strip query string (?foo=bar) and decode URI $uri = $_SERVER['REQUEST_URI']; if(false !== $pos = strpos($uri, '?')) { $uri = substr($uri, 0, $pos); } $uri = rawurldecode($uri); $this->route = $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], $uri); } private function determine_controller() { switch($this->route[0]) { case \FastRoute\Dispatcher::NOT_FOUND: $this->class = '\\M\\Controller\\PageNotFound'; break; case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED: $this->class = '\\M\\Controller\\MethodNotAllowed'; $params = ['allowed_methods' => $this->route[1]]; echo 'METHOD_NOT_ALLOWED'. PHP_EOL; $c = new \M\Controller\MethodNotAllowed(); $c->index(); break; case \FastRoute\Dispatcher::FOUND: list($this->class, $this->method) = explode('::', $this->route[1]); $this->params = $this->route[2]; break; default: $this->class = '\\M\\Controller\\NoRouteFound'; } if(!isset($this->method) || empty($this->method)) { $this->method = 'index'; } } private function invoke() { $controller = new $this->class; $controller->before(); $controller->{$this->method}($this->params); $controller->after(); } private function render() { $basename = explode('\\', $this->class); $basename = end($basename); $controller = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $basename)); View::assign('params', $this->params); View::assign('body', View::fetch('Controller/'. $controller .'/'. ucfirst($this->method))); View::display('Main'); } } <file_sep><?php // clearstatcache(); // // require_once( 'smarty/Smarty.class.php' ); // // view::set_template_dir( '../view' ); // view::set_compile_dir( '../tmp/compile' ); // @TODO set up view initializer <file_sep><?php namespace M\Initializer; class View extends \M\Initializer { public function init() { clearstatcache(); // @TODO is this one still required? \M\View::addTemplateDirs([ '../src/App/View', // '../vendor/m4lloc/magic-framework/src/App/View', ]); \M\View::setCompileDir('/tmp/magic/compile'); } } <file_sep><?php namespace M\Orm\Builder; class Delete extends \M\Orm\Builder { public static function parse(\M\Orm $orm, array $args) { return 'DELETE'; } }<file_sep><?php namespace M; class Router { public static $routes = []; private $route_files = []; public function load() { $this->retrieve(); $this->require_files(); $this->defaults(); } public static function draw($method, $route_pattern, $handler) { $route = [ 'method' => $method, 'route_pattern' => $route_pattern, 'handler' => $handler ]; if(!self::exists($route)) { self::$routes[] = $route; } } public static function get(string $route_pattern, string $handler) : void { self::draw('GET', $route_pattern, $handler); } public static function post(string $route_pattern, string $handler) : void { self::draw('POST', $route_pattern, $handler); } public static function getDeclaredRoutes() : array { return self::$routes; } private function retrieve() { $this->route_files = glob('{'. App::$VENDOR_DIR .'/../src/App/Routes.php,'. App::$VENDOR_DIR .'/*/*/src/App/Routes.php}', GLOB_BRACE); } private static function exists($route) { return in_array($route, self::$routes); } private function require_files() { foreach($this->route_files as $routes) { if(file_exists($routes)) { require_once $routes; } } } private function defaults() : void { $controllers = glob('{'. App::$VENDOR_DIR .'/../src/App/Controller/*.php,'. App::$VENDOR_DIR .'/*/*/src/App/Controller/*.php}', GLOB_BRACE); foreach($controllers as $controller) { if(substr($controller, -13) == 'Decorator.php') { continue; } $controller = '\\M\\Controller\\'. basename($controller, '.php'); $path = $this->getPathForController($controller); self::get($path, $controller .'::index'); self::get($path .'/{id:\d+}', $controller .'::show'); self::post($path .'/{id:\d+}', $controller .'::update'); } } private function getPathForController(string $controller) : string { list(, , , $path) = explode('\\', $controller); if(property_exists($controller, 'path')) { $path = $controller::$path; } return '/'. rtrim(strtolower($path), '/'); } } <file_sep><?php namespace M\Orm\Builder; class Columns extends \M\Orm\Builder { public static function parse(\M\Orm $orm, array $args) { $args = (sizeof($args) == 1) ? $args[0] : $args ; $columns = []; foreach($args as $column){ if(isset($column[3]) && $column[3] == 'primary') { $columns[] = '`'. $column[0] .'` '. $column[1] .'('. $column[2] .') NOT NULL AUTO_INCREMENT'; $columns[] = 'PRIMARY KEY ('. $column[0] .')'; continue; } $columns[] = '`'. $column[0] .'` '. $column[1] .'('. $column[2] .')'; } return '('. implode(', ', $columns) .')'; } }<file_sep><?php namespace M\Orm\Builder; class Values extends \M\Orm\Builder { public static function parse(\M\Orm $orm, array $args) { $columns = array_keys($args[0]); return '('. implode(', ', $columns) .') VALUES(:'. implode(', :', $columns) .')'; } }<file_sep><?php class HttpsTest extends \M\TestHelper { public function testRedirectToHttpsWhenHttpIsUsed() { $this->assertFalse($this->isLocationHeaderSet(), 'It seems the HTTPS location header redirect is already set'); $i = new \M\Initializer\Https(); $i->init(); $this->assertTrue($this->isLocationHeaderSet(), 'Failed to set the HTTPS location header redirect'); } private function isLocationHeaderSet() : bool { $h = xdebug_get_headers(); if(in_array('Location: https://localhost/test', $h)) { return true; } return false; } } <file_sep><?php namespace M\Orm\Builder; class Andwhere extends \M\Orm\Builder\Where { }
2937bf4d4c0a121cc9f4103d388129f0f9467407
[ "Markdown", "PHP" ]
29
Markdown
m4lloc/magic-framework
6b593a8d957ebc49154cc7cbfbe4f8061d02fce1
e7c3b16591cd9dba96e0175e6ba6f6119bc4af09
refs/heads/master
<file_sep>//unchecked exception - at run time package com.lti.demos; public class Exception1 { public static void main(String[] args) { int k=1000; try { int i=0; int j=500/i; System.out.println("j "+j); } catch(ArithmeticException e) { System.out.println("Cant be divided by 0"); //System.out.println(e.getMessage()); e.printStackTrace(); } System.out.println("k "+k); } } <file_sep>//heterogenous data package com.lti.lists; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class list1 { public static void main(String[] args) { List myList = new ArrayList(); myList.add("Anu"); myList.add(170801008); myList.add(100.99); myList.add("japs"); myList.add(null); myList.add("Anu"); // dup allowed , order maintained System.out.println(myList); myList.remove(2); //110.99 (using index) System.out.println(myList); myList.remove(null); myList.remove("Anu"); //only 1st name will be removed System.out.println(myList); } } <file_sep>//wrapper class //convert primitive to non primitive datatype //autoboxing package com.lti.lists; import java.util.ArrayList; import java.util.List; public class list3 { public static void main(String[] args) { int no=100; Integer iobj=new Integer(no); //wrapper class int i=iobj.intValue(); List myList = new ArrayList(); myList.add("Anu"); myList.add(170801008); myList.add(100.99); myList.add(iobj); //autoboxing myList.add("japs"); myList.add(null); myList.add("Anu"); System.out.println(myList); } } <file_sep>package com.lti.demos; import java.util.Scanner; public class Details { public static void main(String[] args) { String name; float sal; Scanner in =new Scanner(System.in); System.out.println("Enter the name"); name=in.next(); System.out.println("Enter the salary"); sal=in.nextFloat(); System.out.println("Ur name is " + name ); System.out.println("The salary entered is "+ sal); in.close(); } } <file_sep>//generics //define the specific datatype package com.lti.lists; import java.util.ArrayList; import java.util.List; public class list4 { public static void main(String[] args) { int no=100; Integer iobj=new Integer(no); //wrapper class int i=iobj.intValue(); List<String> myList = new ArrayList(); myList.add("Anu"); myList.add("japs"); myList.add(null); myList.add("Aji"); System.out.println(myList); } } <file_sep>//multiple catch() package com.lti.demos; public class Exception3 { public static void main(String[] args) { int x=15,y=5,a=5,z; int arr[] = {10,5}; try { //int b = arr[1]/5; int b = arr[7]/5; z = 500/10; //exception System.out.println("z:" + z); //System.out.println(" This will not be Executed if error occurs"); } catch(ArithmeticException e) { System.out.println(" number cant be divided by 0"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("array going out of index"); } catch(Exception e) { System.out.println("Exception throwed"); } } } <file_sep>//lambdas implement function interfaces by own //implement annonymous classes //wrks with streams package com.lti.lambdademo; public class TestStream { public static void main(String[] args) { //interface usage for finding largest no //MaxFinderImpl mf1=new MaxFinderImpl(); //double max=mf1.maximum(10,20); //System.out.println(max); //doing without MaxFinderImpl.java MaxFinder mf=(num1,num2)-> num1>num2 ? num1:num2; double max=mf.maximum(1000, 600); System.out.println(max); } } <file_sep>//finally block usage package com.lti.demos; public class Exception5 { public static void main(String[] args) { int arr[] = {10,5}; int a = 5; try { arr[0]=100; int b = arr[0]/10; int c = arr[0]/0; System.out.println(c); } catch(ArrayIndexOutOfBoundsException | ArithmeticException e) { System.out.println(e.getMessage()); } finally { System.out.println("Finally executed"); } } } <file_sep>package com.lti.demos; import java.util.Scanner; public class Add { public static void main(String[] args) { int x=0,y = 0,add=0; Scanner in = new Scanner(System.in); System.out.println("enter the 1st number"); x=in.nextInt(); System.out.println("enter the 2nd number"); y=in.nextInt(); add=x+y; System.out.println("The added result is " +add); in.close(); } } <file_sep>package com.lti.stringmethods; public class StringCompare { public static void main(String[] args) { String s1="Hi "; String s2="I am Anu"; String s4 = "Hi "; //equal hashcode as s1 String s3=new String("Hi"); System.out.println(s1.hashCode()); System.out.println(s2.hashCode()); System.out.println(s3.hashCode()); System.out.println(s4.hashCode()); System.out.println("************88"); System.out.println(s1==s2); //false System.out.println(s1==s3); System.out.println(s1==s3); //false System.out.println("**** equals() *****"); System.out.println(s1.equals(s4)); System.out.println(s1.equals(s3)); } } <file_sep>//usage of static variables package com.lti.demos; class Fb { int userId; static int no=0; Fb(int userId) { this.userId= userId; } @Override public String toString() { return "Fb [userId=" + userId + ", no=" + no + "]"; } void showLikes() { no++; System.out.println(no); } } public class Static_FB { public static void main(String[] args) { Fb usr1=new Fb(101); //System.out.println(usr1); usr1.showLikes(); Fb usr2=new Fb(102); usr2.showLikes(); } } <file_sep>//accessing student.java and book.java package com.lti.lists; import java.util.ArrayList; import java.util.List; public class list5 { public static void main(String[] args) { //generics List<Student> myList=new ArrayList<Student>(); //only stud can be done not the book Student s1=new Student(101,"Anu",1000); Student s2=new Student(102,"Aji",1000); Student s3=new Student(103,"Asu",1000); Book b1=new Book(1111,"Java",2000); myList.add(s1); myList.add(s2); myList.add(s3); // myList.add(b1); myList.add(s2); //System.out.println(myList); myList.remove(s2); //System.out.println(myList); /* * for (Student s:myList) { System.out.println(s); } */ for(Student s:myList) { if(s.getStuName()=="Anu") { System.out.println(s); } } } } <file_sep>package com.lti.methods; import java.util.Scanner; public class Excel { public int Sum(int num1,int num2) { int add=num1+num2; return add; } } <file_sep>//user defined exception package com.lti.demos; class MyOwnException extends Exception{ @Override public String getMessage() { System.out.println("Please enter number within range"); return super.getMessage(); } } public class Exception7 { public static void main(String[] args) { int n1=100; int n2=10; int res=0; try { res = calcDiv(n1,n2); System.out.println(res); } catch(MyOwnException e) { System.out.println("Please check n2 value, might be zero"); } System.out.println("Program continues"); } public static int calcDiv(int num1, int num2) throws MyOwnException { if(num2 == 0) { throw new MyOwnException(); //new Object gets created by JVM of user-defined class } else { return num1/num2; } } } <file_sep>//calling the procedure package com.lti.jdbcdemos; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Scanner; public class CallableStmt { public static void main(String[] args) throws SQLException { String url = "jdbc:oracle:thin:@localhost:1521/XE"; // orcl or XE or OSE Connection conn=DriverManager.getConnection(url,"HR","hr"); Scanner in=new Scanner(System.in); CallableStatement cstmt=null; if (conn != null) { System.out.println("Connected"); } try { cstmt =conn.prepareCall("{ call getProductName(?,?)}"); //input parameters of procedure //cstmt.setInt(1, 1111); //user input System.out.println("Enter the prod id"); cstmt.setInt(1, in.nextInt()); //output paramater of procedure //output is strin so varchar is used cstmt.registerOutParameter(2,java.sql.Types.VARCHAR); //executing cstmt.executeUpdate(); //printing the output String prdName=cstmt.getNString(2); System.out.println(prdName); } catch(SQLException e) { System.out.println(e.getMessage()); } finally { conn.close(); } } } <file_sep>//linked list //list iterator package com.lti.lists; import java.util.LinkedList; import java.util.ListIterator; public class list7 { public static void main(String[] args) { LinkedList<String> lst=new LinkedList<>(); lst.add("J"); lst.add("A"); lst.add("P"); lst.add("P"); lst.add("Y"); System.out.println(lst); lst.addFirst("HI"); System.out.println(lst); //works only with linked list ListIterator itr=lst.listIterator(); while(itr.hasNext()) { System.out.println(itr.next()); } while(itr.hasPrevious()) { System.out.println(itr.previous()); } } } <file_sep>package com.lti.entity; public class Employee { private int empId; private String empName; private float empSal; private String companyName; public Employee() { super(); } public Employee(int empId, String empName, float empSal) { super(); this.empId = empId; this.empName = empName; this.empSal = empSal; this.companyName="LTI"; } public float Tot_sal() { float hra=1000.00f; float ta=2000.00f; float tax= empSal* 0.10f; float tSal=empSal + hra+ta-tax; //System.out.println("Ttal Salary : "+tSal); return (float)tSal; } @Override public String toString() { return "Employee [empId=" + empId + ", empName=" + empName + ", empSal=" + empSal + ", companyName=" + companyName + "]"; } } <file_sep>package com.lti.lists; public class Book { private int bookId; private String bookName; private double cost; public Book() { super(); } public Book(int bookId, String bookName, double cost) { super(); this.bookId = bookId; this.bookName = bookName; this.cost = cost; } public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public double getCost() { return cost; } public void setCost(double cost) { this.cost = cost; } @Override public String toString() { return "Book \n[bookId=" + bookId + ", bookName=" + bookName + ", cost=" + cost + "]"; } } <file_sep>package com.lti.entity; //ms office has abstract class for save as //wrd , excel,ppt will implement and wrk on it public class PermEmpImpl implements IPerson{ private int permEmpId; private double basicSal; public PermEmpImpl() { super(); } public PermEmpImpl(int permEmpId, double basicSal) { super(); this.permEmpId = permEmpId; this.basicSal = basicSal; } public int getPermEmpId() { return permEmpId; } public void setPermEmpId(int permEmpId) { this.permEmpId = permEmpId; } public double getBasicSal() { return basicSal; } public void setBasicSal(double basicSal) { this.basicSal = basicSal; } @Override public void calc() { double tSal=basicSal + 500; System.out.println("perm emp sal " + tSal); } @Override public String toString() { return "PermEmpImpl [permEmpId=" + permEmpId + ", basicSal=" + basicSal + "]"; } } <file_sep>package com.lti.entity; public class Employee extends Person { double basicSal; public Employee() { super(); } public Employee(int pId, String pName) { super(pId, pName); } public Employee(int pId, String pName, double basicSal) { super(pId, pName); this.basicSal = basicSal; } public double getBasicSal() { return basicSal; } public void setBasicSal(double basicSal) { this.basicSal = basicSal; } public void calc() { //accessing the method of parent class //super.calc(); double tSal=(double) (basicSal+500); System.out.println("employee - cal() method" + tSal); } @Override public String toString() { return "Employee [ pId "+pId+ "name "+pName+ "basicSal" + basicSal + "]"; } } <file_sep>package com.lti.demos; public class TypeCasting { public static void main(String[] args) { int x=10; int y=3; int res=x/y; System.out.println(res); float res1=x/y; System.out.println(res1); float res2=(float)x/y; System.out.println(res2); } } <file_sep>package com.lti.service; import com.lti.entity.StudDetails; public class Info { public void Display(StudDetails s) { System.out.println("Displayed "+ s); } public void Display(StudDetails s[]) { for(int i=0;i<2;i++) { System.out.println(s[i]); } } } <file_sep>package com.lti.demos; public class IfElse { public static void main(String[] args) { int num1=10; /*if (x<=5) { System.out.println("less thn 5"+x); } else { System.out.println("greater thn 5"); System.out.println(x); }*/ if (num1==10) System.out.println("its 10"); else System.out.println("not 10"); } } <file_sep>//accessing student.java and book.java //iterator is used to print all the array list //iterator is fail fast behaviour package com.lti.lists; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class list6 { public static void main(String[] args) { List myList=new ArrayList(); //only stud can be done not the book Student s1=new Student(101,"Anu",1000); Student s2=new Student(102,"Aji",1000); Student s3=new Student(103,"Asu",1000); Book b1=new Book(1111,"Java",2000); myList.add(s1); myList.add(s2); myList.add(s3); myList.add(b1); myList.add(s2); //System.out.println(myList); myList.remove(s2); //for each loop //rarely used for(Object o:myList) { System.out.println(o); } //commonly used is iterator //cursors in collections (fast) //used for all collections Iterator itr=myList.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } } } <file_sep>//updating the recrd by getting it from the user package com.lti.jdbcdemos; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; public class UpdateRecrd { public static void main(String[] args) throws SQLException { String url = "jdbc:oracle:thin:@localhost:1521/XE"; // orcl or XE or OSE Connection conn=DriverManager.getConnection(url,"HR","hr"); Scanner in=new Scanner(System.in); if (conn != null) { System.out.println("Connected"); } try { //? is a placeholder PreparedStatement pstmt = conn.prepareStatement("update Products set PRDCOST=? where PRDID=?"); System.out.println("Enter the prod id "); pstmt.setInt(2, in.nextInt()); System.out.println("Enter the cost "); pstmt.setFloat(1, in.nextFloat()); int rec=pstmt.executeUpdate(); System.out.println("recrds updated "+rec); } catch(SQLException e) { System.out.println(e.getMessage()); } finally { conn.close(); } } } <file_sep>package com.lti.jdbcdemos; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; public class InsertRecrd { public static void main(String[] args) throws SQLException { String url = "jdbc:oracle:thin:@localhost:1521/XE"; // orcl or XE or OSE Connection conn=DriverManager.getConnection(url,"HR","hr"); try { Statement stmt = conn.createStatement(); int i =stmt.executeUpdate("insert into PRODUCTS values(104,'Pen',500)"); System.out.println("no of recrds added "+i); } catch(SQLException e) { System.out.println(e.getMessage()); } finally { conn.close(); } } } <file_sep>package com.lti.demos; class FaceBook { int userId; int no = 0; static int like=0; FaceBook(int userId) { this.userId = userId; } static void likes() { like++; System.out.println(" likes " + like); } @Override public String toString() { return "FaceBook [userId=" + userId + ", no=" + no + "]"; } void showLikes() { no++; System.out.println("no : " +no); } } public class FaceBookUserApp { public static void main(String[] args) { Math.sqrt(25); FaceBook user1= new FaceBook(101); System.out.println(user1); user1.showLikes(); FaceBook.likes(); FaceBook user2= new FaceBook(102); System.out.println(user2); user2.showLikes(); FaceBook.likes(); FaceBook user3= new FaceBook(102); System.out.println(user3); user3.showLikes(); FaceBook.likes(); } }<file_sep>package com.lti.lists; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class list2 { public static void main(String[] args) { List myList=new ArrayList(); myList.add("Anu"); myList.add("Aji"); myList.add("Tilak"); myList.add("Asu"); myList.add(null); myList.add("Anu"); System.out.println(myList); System.out.println(myList.get(2)); myList.remove(4); System.out.println(myList); myList.remove("Anu"); //only 1st occurance is removed System.out.println(myList); //sorting Collections.sort(myList); System.out.println(myList); } } <file_sep>package com.lti.demos; import java.util.Scanner; public class Arrays { public static void main(String[] args) { int n=0; System.out.println("enter the number length "); Scanner in = new Scanner(System.in); n=in.nextInt(); int marks[]=new int[10]; for(int i=0;i<n;i++) { System.out.println("enter the marks "); marks[i]=in.nextInt(); } for(int i=0;i<n;i++) { System.out.println(marks[i]); } } } <file_sep>//strings are immutable //string buffer - drawback: //thread safe / synchronized package com.lti.stringmethods; public class StringImmutable { public static void main(String[] args) { String s1="Hi "; //String s1=new String("hi"); String s2="<NAME>"; //concatenation String s3=s1+s2; System.out.println(s3); System.out.println(s1+s2); s1.concat(s2); System.out.println(s1);// immutable so value of s1 will not chmage even of u concat String s4=s1.concat(s2); System.out.println(s4); System.out.println("****************"); //string buffer System.out.println("String buffer"); StringBuffer sb=new StringBuffer("Hi "); sb.append("Im Anu"); System.out.println(sb); System.out.println("****************"); System.out.println("String builder"); StringBuilder sb1=new StringBuilder("Hi "); sb1.append("Im Anu"); System.out.println(sb1); System.out.println("****************"); } } <file_sep>//if its execute() we have to use boolean package com.lti.jdbcdemos; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class ExcuteCmd { public static void main(String[] args) throws SQLException { String url = "jdbc:oracle:thin:@localhost:1521/XE"; // orcl or XE or OSE Connection conn=DriverManager.getConnection(url,"HR","hr"); try { Statement stmt = conn.createStatement(); Boolean i =stmt.execute("insert into PRODUCTS values(1114,'Pencil',900)"); System.out.println("no of recrds added "+i); } catch(SQLException e) { System.out.println(e.getMessage()); } finally { conn.close(); } } } <file_sep>package com.lti.user; import java.sql.SQLException; import java.util.Scanner; import com.lti.entity.AddComponents; import com.lti.service.ServiceLayer; public class UserApp { public static void main(String[] args) throws SQLException { AddComponents ac = new AddComponents(); ServiceLayer ml= new ServiceLayer(); Scanner sc = new Scanner(System.in); int res = ml.emptyOrNot(ac.getConn1()); if (res == 0) { System.out.println("Enter 1 to load data from a CSV file into a database"); int loadData = sc.nextInt(); final String link = "complaints.csv"; ac.readAndAdd(link); } System.out.println("Database already contains records"); int option=0; do { System.out.println("1. Display all records based on year\n" + "2.Display by bank\n" + "3.Display complaints based on the complaint id provided by the user\n" + "4.Display number of days took by the Bank to close the complaint\n" + "5.Display all the complaints closed/closed with explanation\n" + "6.Display all the complaints which received a timely response\n" + "7.Take input from user for storing new complaints\n" +"8.Exit"); System.out.println("Enter an option from menu"); option = sc.nextInt(); switch (option) { case 1:System.out.println("Enter year"); String year=sc.next(); ml.displayByYear(year); break; case 2:System.out.println("Enter bankname"); String bankname=sc.next(); ml.displayBybank(bankname); break; case 3:System.out.println("cusid?"); String custid=sc.next(); ml.displayBycustid(custid); break; case 4:System.out.println("custid"); String custid1=sc.next(); int diff=ml.getDayscount(custid1); System.out.println(diff+" this is the difference"); break; case 5:ml.ccExplaination(); break; case 6:ml.timelyResponse(); break; case 7:System.out.println("Enter all details"); String[]arr=new String[14]; for(int i=0;i<14;i++) { arr[i]=sc.next(); } int res11=ml.insertRecord(arr); System.out.println(res11); break; } }while(option!=8); } } <file_sep>package com.lti.user; import java.util.Scanner; import com.lti.entity.StudDetails; import com.lti.service.Info; public class Stud { public static void main(String[] args) { StudDetails s1=new StudDetails(100,"Anu",50000); Info info = new Info(); info.Display(s1); StudDetails[] stuArr=new StudDetails[2]; Scanner in = new Scanner(System.in); for(int i=0;i<2;i++) { //alternate to write in single line //stuArr[i]=new StudDetails(in.nextInt(),in.nextLine(),in.nextInt()); System.out.println("enter the details "); stuArr[i]=new StudDetails(); stuArr[i].setStudId(in.nextInt()); stuArr[i].setStudName(in.next()); stuArr[i].setStudFees(in.nextInt()); } info.Display(stuArr); /*StudDetails stud1=new StudDetails(); * System.out.println(stud1); * * StudDetails stud2=new StudDetails(111,"Anu",20000.00f); * System.out.println(stud2); * * StudDetails stud3=new StudDetails(); stud3.setStudId(101); * stud3.setStudName("Aji"); stud3.setStudFees(200000.05f); * System.out.println(stud3.getStudId()); System.out.println(stud3); */ } } <file_sep>//details on how to get the dataset info //get the db used info package com.lti.jdbcdemos; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; public class MetaData { public static void main(String[] args) throws SQLException { String url = "jdbc:oracle:thin:@localhost:1521/XE"; // orcl or XE or OSE Connection conn=DriverManager.getConnection(url,"HR","hr"); Scanner in=new Scanner(System.in); if (conn != null) { System.out.println("Connected"); } Statement stmt=null; try { stmt = conn.createStatement(); String query = "select * from Products"; ResultSet rs = stmt.executeQuery(query); //methods used ResultSetMetaData rsmd = rs.getMetaData(); System.out.println("no of columns in the table= "+ rsmd.getColumnCount()); System.out.println("Name of the first column "+ rsmd.getColumnName(1)); System.out.println("Type of the second column "+ rsmd.getColumnTypeName(2)); System.out.println("No of characters in 3rd column "+ rsmd.getColumnDisplaySize(2)); //database info DatabaseMetaData dma = conn.getMetaData(); System.out.println("\n connected to "+ dma.getURL()); System.out.println(" driver "+ dma.getDriverName()); System.out.println(" version "+ dma.getDatabaseProductName()); System.out.println(" version "+ dma.getUserName()); } catch(SQLException e) { System.out.println(e.getMessage()); } finally { conn.close(); } } }
6a136ccfdae81ca50475ae3f4d63479a767ba98b
[ "Java" ]
34
Java
anobhama/Java---Eclipse
f13c1c611209c98dcf48d8688da3509459d1fa88
a1ee8102b598074ba8cdd2ed5e114369269cb94f
refs/heads/master
<file_sep>using Lean.Touch; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class InputManager : MonoBehaviour { private static InputManager _instance; public static event Action<float> MoveLeft = delegate { }; public static event Action<float> MoveRight = delegate { }; public static event Action Shoot = delegate { }; public static event Action Jump = delegate { }; public LeanScreenDepth ScreenDepth; private bool _prevFrameTouchEnabled = false; private bool _currentFrameTouchEnabled = false; private void Awake() { if (_instance == null) _instance = this; } protected virtual void LateUpdate() { var fingers = LeanTouch.GetFingers(false, false, 1); if (fingers.Count >= 1) { _currentFrameTouchEnabled = true; var lastScreenPoint = LeanGesture.GetLastScreenCenter(fingers); var screenPoint = LeanGesture.GetScreenCenter(fingers); var worldDelta = lastScreenPoint - screenPoint; if (worldDelta.x > 0) { MoveLeft(Mathf.Abs(worldDelta.x)); } else if (worldDelta.x < 0) { MoveRight(Mathf.Abs(worldDelta.x)); } Shoot(); } else _currentFrameTouchEnabled = false; if (_prevFrameTouchEnabled && !_currentFrameTouchEnabled && GameManager.GameStarted) { Jump(); } if (!_prevFrameTouchEnabled && !_currentFrameTouchEnabled && !GameManager.GameStarted) { GameManager.GameStarted = true; } if (!_prevFrameTouchEnabled && _currentFrameTouchEnabled && !GameManager.GameStarted) { return; //if (!GameManager.GameStarted) GameManager.GameStarted = true; } _prevFrameTouchEnabled = _currentFrameTouchEnabled; } } <file_sep>using UnityEngine; using UnityEngine.SceneManagement; public class PlayerControl : MonoBehaviour { [SerializeField] private GameObject _bulletPrefab; [SerializeField] private Transform _bulletSpawnPoint; private float _shootTimerCurrentValue = 0f; private bool _shootLocked = false; private Rigidbody2D _rigidbody2D; public Rigidbody2D RigidBody2D { get { if (!_rigidbody2D) _rigidbody2D = GetComponent<Rigidbody2D>(); return _rigidbody2D; } } private BoxCollider2D _playerCollider; public BoxCollider2D PlayerCollider { get { if (!_playerCollider) _playerCollider = GetComponent<BoxCollider2D>(); return _playerCollider; } } private void OnEnable() { InputManager.MoveLeft += MoveLeft; InputManager.MoveRight += MoveRight; InputManager.Shoot += Shoot; InputManager.Jump += Jump; } private void OnDisable() { InputManager.MoveLeft -= MoveLeft; InputManager.MoveRight -= MoveRight; InputManager.Shoot -= Shoot; InputManager.Jump -= Jump; } private void Update() { if (_shootLocked) { if (_shootTimerCurrentValue <= 1f / GameManager.FireRate) { _shootTimerCurrentValue += Time.deltaTime; } else { _shootLocked = false; _shootTimerCurrentValue = 0; } } } private void LateUpdate() { var playerPosition = transform.position; var downScreenBorderYCoord = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 0)).y; var upScreenBorderYCoord = Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height, 0)).y; playerPosition.y = Mathf.Clamp(playerPosition.y, downScreenBorderYCoord + PlayerCollider.size.y / 2, upScreenBorderYCoord - PlayerCollider.size.y / 2); transform.position = playerPosition; } private void MoveRight(float value) { var playerPosition = transform.position; playerPosition.x += value * GameManager.MoveSpeed * Time.deltaTime; var leftScreenBorderXCoord = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 0)).x; var rightScreenBorderXCoord = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0, 0)).x; playerPosition.x = Mathf.Clamp(playerPosition.x, leftScreenBorderXCoord + PlayerCollider.size.x / 2, rightScreenBorderXCoord - PlayerCollider.size.x / 2); transform.position = playerPosition; } private void MoveLeft(float value) { var playerPosition = transform.position; playerPosition.x -= value * GameManager.MoveSpeed * Time.deltaTime; var leftScreenBorderXCoord = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 0)).x; var rightScreenBorderXCoord = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0, 0)).x; playerPosition.x = Mathf.Clamp(playerPosition.x, leftScreenBorderXCoord + PlayerCollider.size.x / 2, rightScreenBorderXCoord - PlayerCollider.size.x / 2); transform.position = playerPosition; } private void Shoot() { if (_shootLocked) return; _shootLocked = true; var instRocket = Instantiate(_bulletPrefab, transform); instRocket.transform.localPosition = _bulletSpawnPoint.localPosition; instRocket.transform.localRotation = _bulletSpawnPoint.localRotation; instRocket.transform.parent = null; var rocketComponent = instRocket.GetComponent<Bullet>(); rocketComponent.Launch(); } private void Jump() { RigidBody2D.AddForce(Vector2.up * 400); } public void Die() { GameManager.GameStarted = false; SceneManager.LoadScene(0); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class FloorsManager : MonoBehaviour { [SerializeField] private GameObject _floorPrefab; [SerializeField] private Floor _firstFloor; private List<Floor> _floors = new List<Floor>(); private void Awake() { _floors.Add(_firstFloor); var prevFloorPosition = _firstFloor.transform.position; while (_floors.Count < 5) { var newFloor = Instantiate(_floorPrefab, prevFloorPosition + Vector3.up * 2.5f, Quaternion.identity).GetComponent<Floor>(); _floors.Add(newFloor); prevFloorPosition = newFloor.transform.position; newFloor.GenerateEnemies(); } } private void Update() { for (int i = 0; i < _floors.Count; i++) { if (_floors[i].CanBeDestroyed) { Destroy(_floors[i]); _floors.RemoveAt(i); break; } } var prevFloorPosition = _floors[_floors.Count - 1].transform.position; while (_floors.Count < 5) { var newFloor = Instantiate(_floorPrefab, prevFloorPosition + Vector3.up * 2.5f, Quaternion.identity).GetComponent<Floor>(); _floors.Add(newFloor); prevFloorPosition = newFloor.transform.position; newFloor.GenerateEnemies(); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { private static GameManager _instance; [SerializeField] private PlayerControl _playerControl; public static PlayerControl PlayerControl { get { return _instance._playerControl; } } [SerializeField] private float _moveSpeed; public static float MoveSpeed { get { return _instance._moveSpeed; } private set { _instance._moveSpeed = value; } } [SerializeField] private float _fireSpeed = 10f; public static float FireSpeed { get { return _instance._fireSpeed; } set { _instance._fireSpeed = value; } } [SerializeField] private float _fireDamage = 5f; public static float FireDamage { get { return _instance._fireDamage; } set { _instance._fireDamage = value; } } [SerializeField] private float _fireRate = 2f; public static float FireRate { get { return _instance._fireRate; } set { _instance._fireRate = value; } } [SerializeField] private float _enemyHealth = 20f; public static float EnemyHealth { get { return _instance._enemyHealth; } set { _instance._enemyHealth = value; } } [SerializeField] private float _floorsSpeed = 0.5f; public static float FloorsSpeed { get { return _instance._floorsSpeed; } private set { _instance._floorsSpeed = value; } } public static bool GameStarted = false; private void Awake() { if (_instance == null) _instance = this; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { private float _selfDestructTimerCurrentValue = 0f; private float _selfDestructTimerDefaultValue = 10f; private bool _launched = false; private void Update() { if (_selfDestructTimerCurrentValue <= _selfDestructTimerDefaultValue) _selfDestructTimerCurrentValue += Time.deltaTime; else Destroy(gameObject); if (_launched) { transform.position += transform.up * GameManager.FireSpeed * Time.deltaTime; } } public void Launch() { _launched = true; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Floor : MonoBehaviour { private BoxCollider2D[] _boxColliders2D; public BoxCollider2D[] BoxColliders2D { get { if (_boxColliders2D == null) { _boxColliders2D = GetComponentsInChildren<BoxCollider2D>(); } return _boxColliders2D; } } private bool _becameGround = false; public bool CanBeDestroyed { private set; get; } [SerializeField] private GameObject _enemyPrefab; private void Awake() { var holesCount = Random.Range(0, 3); var holes = new int[holesCount]; for (int i = 0; i < holesCount; i++) { holes[i] = Random.Range(0, BoxColliders2D.Length); BoxColliders2D[i].GetComponent<SpriteRenderer>().enabled = false; } foreach (var col in BoxColliders2D) { col.isTrigger = true; } } private void Update() { if (transform.position.y < GameManager.PlayerControl.transform.position.y - GameManager.PlayerControl.PlayerCollider.size.y/2 && !_becameGround) { var jumpInHole = false; foreach (var boxCollider2D in BoxColliders2D) { if (GameManager.PlayerControl.transform.position.x > boxCollider2D.transform.position.x - boxCollider2D.size.x/2 && GameManager.PlayerControl.transform.position.x < boxCollider2D.transform.position.x + boxCollider2D.size.x/2) { if (!boxCollider2D.GetComponent<SpriteRenderer>().enabled) { jumpInHole = true; break; } } } if (!jumpInHole) { _becameGround = true; foreach (var col in BoxColliders2D) { col.isTrigger = false; col.GetComponent<SpriteRenderer>().enabled = true; } ScoreManager.Score += 1; } } else if (transform.position.y > GameManager.PlayerControl.transform.position.y + GameManager.PlayerControl.PlayerCollider.size.y / 2 && _becameGround) { _becameGround = false; foreach (var col in BoxColliders2D) { col.isTrigger = true; } } transform.position += GameManager.FloorsSpeed * Vector3.down * Time.deltaTime; CanBeDestroyed = transform.position.y < -5; } public void GenerateEnemies() { var enemiesCount = Random.Range(1, 3); var occupiedFloorParts = new List<int>(); for (int i = 0; i < enemiesCount; i++) { var randomFloorPartIndex = Random.Range(0, BoxColliders2D.Length); while (!BoxColliders2D[randomFloorPartIndex].GetComponent<SpriteRenderer>().enabled || occupiedFloorParts.Contains(randomFloorPartIndex)) { randomFloorPartIndex++; if (randomFloorPartIndex >= BoxColliders2D.Length) { randomFloorPartIndex = 0; } } var enemy = Instantiate(_enemyPrefab, new Vector3(BoxColliders2D[randomFloorPartIndex].transform.position.x, transform.position.y), Quaternion.identity); enemy.transform.position += Vector3.up * enemy.GetComponent<Enemy>().EnemyCollider.size.y / 2; enemy.transform.parent = transform; occupiedFloorParts.Add(randomFloorPartIndex); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { private BoxCollider2D _enemyCollider; public BoxCollider2D EnemyCollider { get { if (!_enemyCollider) _enemyCollider = GetComponent<BoxCollider2D>(); return _enemyCollider; } } public float EnemyCurrentHealth { get; private set; } [SerializeField] private Transform _healthBar; public Transform HealthBar { get { return _healthBar; } } private void Awake() { EnemyCurrentHealth = GameManager.EnemyHealth; } private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Player")) { GameManager.PlayerControl.Die(); } if (other.gameObject.CompareTag("Bullet")) { EnemyCurrentHealth -= GameManager.FireDamage; Destroy(other.gameObject); } } private void Update() { var healthBarScale = HealthBar.localScale; healthBarScale.x = 0.4f * EnemyCurrentHealth / GameManager.EnemyHealth; HealthBar.localScale = healthBarScale; if (EnemyCurrentHealth <= 0) { ScoreManager.Score += 5; Destroy(gameObject); } } } <file_sep>using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; public class ScoreManager : MonoBehaviour { private static ScoreManager _instance; [SerializeField] private TextMeshProUGUI _scoreLabel; private int _score; public static int Score { get { return _instance._score; } set { _instance._score = value; } } private void Awake() { if (_instance == null) _instance = this; } private void Update() { _scoreLabel.text = string.Format("Score: {0}", Score); } }
66e2ac8b0c1df9a6304feb56a31635e318f4ebea
[ "C#" ]
8
C#
hickoma/jumpshooter
32b5e89cce306d39c9b186ac4654dc32e2084588
780655039ece550220bfce72802d18269c4dc211
refs/heads/master
<repo_name>SantiOnAndroid/Sandvitx-club-app<file_sep>/app/src/main/java/cat/ioc/sandwich_club_app/utils/ParseSandvitxJson.java package cat.ioc.sandwich_club_app.utils; import android.text.TextUtils; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import cat.ioc.sandwich_club_app.model.Sandvitx; public class ParseSandvitxJson { private static final String TAG=ParseSandvitxJson.class.getSimpleName(); /**Strings per la clau associada amb el Json * */ private static final String KEY_NAME="name"; private static final String KEY_MAIN_NAME="mainName"; private static final String KEY_ALSO_KNOWN_AS="alsoKnownAs"; private static final String KEY_PLACE_OF_ORIGIN="placeOfOrigin"; private static final String KEY_DESCRIPTION ="description"; private static final String KEY_IMAGE = "image"; private static final String KEY_INGREDIENTS = "ingredients"; /** * Retorna a {@link Sandvitx} Object que pot ser utilitzat per a emplenar la UI parsejant el Json */ public static Sandvitx parseSandvitxJson(String json){ //Si el String de JSON es buit o null, llavors retorna if(TextUtils.isEmpty(json)) return null; //Intenta parsejar el JSON string. Si hi ha algun problema amb com es formatejat //Una JSONException es llençada try { //crea un JSONObject del JSON string JSONObject baseJson=new JSONObject(json) ; //Pren el JSONObject associada amb la clau anomenada nom JSONObject name=baseJson.getJSONObject(KEY_NAME); //per a un nom donat, pren el valor fro amb clau anomenada "nomPrincipal" String mainName=name.getString(KEY_MAIN_NAME); //per a un nom donat, extrau el JSOnArray associat amb tambeconegutCom JSONArray tambeConegutArray=name.getJSONArray(KEY_ALSO_KNOWN_AS); //Crea un arraylist buit List<String> tambeConegutCom=new ArrayList<>(); //si el JSONArray no es buit ,afageix cada element dins el JSONArray dins el ArrayList if(tambeConegutArray.length()!=0){ for(int i=0;i<tambeConegutArray.length();i++){ tambeConegutCom.add(tambeConegutArray.get(i).toString()); } }else{ tambeConegutCom=null; } //pren el valor per a la clau "llocOrigen" String llocOrigen=baseJson.getString(KEY_PLACE_OF_ORIGIN); if(llocOrigen.isEmpty())llocOrigen=null; //pren el valor per a la clau imatge String imageUrl=baseJson.getString(KEY_IMAGE); //pren el valor per la clau desciption String descripcio=baseJson.getString(KEY_DESCRIPTION); //pren el JSONArray associat amb la clau ingredients JSONArray ingredientsArray=baseJson.getJSONArray(KEY_INGREDIENTS); List<String> ingredients=new ArrayList<>(); //Si el JSONArray no es buit , cada elemnt dins el JSON Array cap el Arraylist if(ingredientsArray.length()!=0){ for(int j=0;j<ingredientsArray.length();j++){ ingredients.add(ingredientsArray.get(j).toString()); } }else ingredients = null; return new Sandvitx(mainName,tambeConegutCom,llocOrigen,descripcio,imageUrl,ingredients); } catch (JSONException e) { Log.e(TAG,"Problemes parsing el JSON",e); return null; } } }
9272a7ad54503c2d4653a160ff1d29535f8ff1a4
[ "Java" ]
1
Java
SantiOnAndroid/Sandvitx-club-app
d02ed407bb90fe7bb9b52c64b5b98dc342b42b0d
d4a7cb101259872b969888509c19e0a161744153
refs/heads/master
<file_sep>'use strict'; const path = require('path'); const COLLECTION_NAME = "migrations"; const CONFIG_CONNECTION = "db.connectionString"; const MIGRATIONS_DIR = "./migrations"; class ArgsManager { constructor(args, config, processPath) { this.args = args; this.config = config; this.processPath = processPath; } static removeQuotes(string) { return string.replace(/"/g, '').replace(/'/g, ''); } /** * look up the argument in the argument list * @param argName {string} the name of the argument * @returns {boolean} true of argument found, false otherwise */ findArg(argName) { let found = false; for (let i = 0; i < this.args.length; i++) { if (this.args[i].includes("=")) { //if --blala=pathto format found = this.args[i].includes(argName) || found; } else { found = this.args[i].trim() === argName || found; } } return found; } findKey(argName) { for (let i = 0; i < this.args.length; i++) { if (this.args[i].includes("=") && this.args[i].includes(argName)) { let arg = this.args[i].replace(argName + "=", ""); return ArgsManager.removeQuotes(arg); } else if (this.args[i] === argName) { if (i + 1 === this.args.length) { return undefined; } else { if (this.args[i + 1].includes('--')) { return undefined; } return ArgsManager.removeQuotes(this.args[i + 1]); } } } } getConnectionString() { let configArg = this.findKey("--configConnection"), connectionString; if (configArg) { connectionString = this.config.get(configArg); } else { connectionString = this.config.get(CONFIG_CONNECTION); } return connectionString; } migrationsFilesPath() { let migrationsArg = this.findKey("--migrationsDir"); if (migrationsArg) { return path.resolve(this.processPath, migrationsArg); } return path.resolve(this.processPath, MIGRATIONS_DIR); } getCollectionName() { let collectionArg = this.findKey("--collection"); if (collectionArg) { return collectionArg } return COLLECTION_NAME; } } module.exports = ArgsManager;<file_sep>const fs = require('fs'), path = require('path'); function getRandomIntInclusive(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } function copyFile(source, target) { return new Promise(function (resolve, reject) { let rd = fs.createReadStream(source); rd.on('error', rejectCleanup); let wr = fs.createWriteStream(target); wr.on('error', rejectCleanup); function rejectCleanup(err) { rd.destroy(); wr.end(); reject(err); } wr.on('finish', resolve); rd.pipe(wr); }); } class Migration { constructor(name, path, applied) { if (!name || (!path && !applied)) { throw ('PARSERROR') } this.name = name; this.path = path; this.applied = applied; if (this.path) { this.file = require(this.path); } } async up() { let randomColour = getRandomIntInclusive(32, 36); console.time(`${this.name}`); console.log(`\x1b[${randomColour}m up migration ${this.name} started\x1b[0m`); let result = await this.file.up(); console.timeEnd(`${this.name}`); console.log(`\x1b[${randomColour}m up migration ${this.name} finished\x1b[0m`); return result; } async down() { let randomColour = getRandomIntInclusive(32, 36); console.time(`${this.name}`); console.log(`\x1b[${randomColour}m down migration ${this.name} started\x1b[0m`); let result = await this.file.down(); console.timeEnd(`${this.name}`); console.log(`\x1b[${randomColour}m down migration ${this.name} finished\x1b[0m`); return result; } get isApplied() { return !!this.applied; } get timeStamp() { let regex = /^[0-9]+(?!-)/; return +regex.exec(this.name)[0]; } static getMigrationsFromFolder(argsManager) { try { let migrationDir = argsManager.migrationsFilesPath(), files = fs.readdirSync(migrationDir); return files.map(file => { let fullPath = path.resolve(migrationDir, file); return new Migration(file, fullPath) }); } catch (err) { if (err.code === 'ENOENT') { throw ('it looks like migration folder could not be found. Please use --migrationsDir option and "help" for mode details') } else { throw (err) } } } isEqual(to) { return this.timeStamp === to.timeStamp && this.name === to.name; } static compare(a, b) { if (a.timeStamp < b.timeStamp) { return -1; } if (a.timeStamp > b.timeStamp) { return 1; } return 0; } static sortMigrationsArray(array) { return array.sort(Migration.compare) } /** * produce descend on migrations set down to name (inclusively) * @param migrations {Array<Migration>} array of migrations * @param downToName {string} name of the migration to descent there * @returns {Array<Migration>} array of migration to be downgraded */ static descentMigrations(migrations, downToName) { let result = [], found = Migration.findMigrationInSet(migrations, downToName); if (downToName === undefined) { found = { index: 0 } } if (!found) { throw ({ message: `provided migration name ${downToName} could not be found` }) } for (let i = migrations.length - 1; i >= found.index; i--) { result.push(migrations[i]); } return result; } /** * produce ascent on migration up to the specific name (inclusively) * @param migrations {Array<Migration>} array of migrations * @param upToName {string} name of the migration to descent there * @returns {Array<Migration>} array of migration to be applied */ static ascentMigrations(migrations, upToName) { let result = [], found = Migration.findMigrationInSet(migrations, upToName); if (upToName === undefined) { found = { index: migrations.length - 1 }; } if (!found) { throw ({ message: `provided migration name ${upToName} could not be found` }) } for (let i = 0; i <= found.index; i++) { result.push(migrations[i]); } return result; } static findMigrationInSet(set, migration) { for (let i = 0; i < set.length; i++) { if (typeof migration === 'string') { if (set[i].name === migration) { return { index: i, migration: set[i] } } } else if (migration instanceof Migration) { if (set[i].isEqual(migration)) { return { index: i, migration: set[i] } } } } } static intersectMigrationsSets(a, b) { let result = []; for (let migration of a) { if (Migration.findMigrationInSet(b, migration)) { result.push(migration); } } return result; } static subtractMigrationsSets(minuend, deduction) { let result = []; for (let migration of minuend) { let contains = false; for (let toFind of deduction) { if (toFind.isEqual(migration)) { contains = true; break; } } if (!contains) { result.push(migration); } } return Migration.sortMigrationsArray(result); } static createMigration(argsManager) { let name = argsManager.findKey("create", ""), file = '' + Date.now(), templatePath = path.resolve(__dirname, './migration-template.js'); if (name !== undefined) { file += '-' + name; } file += '.js'; if (!fs.existsSync(argsManager.migrationsFilesPath())) { fs.mkdirSync(argsManager.migrationsFilesPath()); } try { let filePath = path.resolve(argsManager.migrationsFilesPath(), file); return copyFile(templatePath, filePath) .then(result => { console.log(`file ${file} successfully created`); return result; }) } catch (err) { console.error(`could not create ${file}:`, JSON.stringify(err, null, 2)); } } } module.exports = Migration;<file_sep>#! /usr/bin/env node const path = require('path'), ArgsManager = require('./args-manager'), Database = require('./database'), Migration = require('./migration'), {askQuestion} = require('./utils'); const CONFIG_DIR = "./config"; process.env.NODE_CONFIG_DIR = path.resolve(process.cwd(), CONFIG_DIR); let config = require('config'); let argsManager = new ArgsManager(process.argv, config, process.cwd()); function askAboutConnection() { return askQuestion(`with current working environment will be used \x1b[32m${argsManager.getConnectionString()}\x1b[0m are you agree with that?`, argsManager); } function showRaggedMigrations(dbMigrations, dirMigrations) { const dbDifference = Migration.subtractMigrationsSets(dbMigrations, dirMigrations); if (dbDifference.length) { console.log(`\x1b[41m>>> THE FOLLOWING ${dbDifference.length} MIGRATIONS ARE IN THE DATABASE BUT NOT IN LOCAL FILES <<<\x1b[0m`); let counter = 1; for (let migration of dbDifference) { console.log(`\x1b[47m${counter++}: ${migration.name}\x1b[0m`); } console.log(); return true; } return false; } async function up(until) { let db = new Database(argsManager), dbMigrations = await db.fetchAppliedMigrations(), dirMigrations = Migration.getMigrationsFromFolder(argsManager), needApply = Migration.ascentMigrations(dirMigrations, until), set = Migration.subtractMigrationsSets(needApply, dbMigrations); showRaggedMigrations(dbMigrations, dirMigrations); await db.upMigrations(set); } async function down(until) { let db = new Database(argsManager), dbMigrations = await db.fetchAppliedMigrations(), dirMigrations = Migration.getMigrationsFromFolder(argsManager); if (showRaggedMigrations(dbMigrations, dirMigrations) && !argsManager.findArg("--force")) { console.log(`\x1b[47m migration roll back is not possible, use --force option to skip that migrations\x1b[0m`); process.exit(1); } let intersection = Migration.intersectMigrationsSets(dirMigrations, dbMigrations), needMisapply = Migration.descentMigrations(intersection, until); await db.downMigrations(needMisapply); } async function listPending() { let db = new Database(argsManager), dbMigrations = await db.fetchAppliedMigrations(), dirMigrations = Migration.getMigrationsFromFolder(argsManager), applicable = Migration.subtractMigrationsSets(dirMigrations, dbMigrations); showRaggedMigrations(dbMigrations, dirMigrations); if (applicable.length) { console.log(`The following ${applicable.length} migrations could be applied:`) } else { console.log("There are no migrations to be applied") } let counter = 0; for (let migration of applicable) { console.log(`${++counter}: ${migration.name}`) } } async function listApplied() { let db = new Database(argsManager), dbMigrations = await db.fetchAppliedMigrations(), dirMigrations = Migration.getMigrationsFromFolder(argsManager); showRaggedMigrations(dbMigrations, dirMigrations); if (dbMigrations.length) { console.log(`The following ${dbMigrations.length} already applied on the database:`) } else { console.log("There are no applied migrations") } let counter = 0; for (let migration of dbMigrations) { console.log(`${++counter}: ${migration.name}`) } } if (argsManager.findArg("up")) { askAboutConnection() .then(() => up(argsManager.findKey("up"))) .then(() => process.exit(0)) .catch(err => { console.log(err); process.exit(1); }) } else if (argsManager.findArg("down")) { askAboutConnection() .then(() => down(argsManager.findKey("down"))) .then(() => process.exit(0)) .catch(err => { console.log(err); process.exit(1); }) } else if (argsManager.findArg("create")) { Migration.createMigration(argsManager) .then(() => process.exit(0)); } else if (argsManager.findArg("pending")) { listPending() .then(() => process.exit(0)) .catch(err => { console.error(err); process.exit(1); }) } else if (argsManager.findArg("applied")) { listApplied() .then(() => process.exit(0)) .catch(err => { console.error(err); process.exit(1); }) } else if (argsManager.findArg("help")) { console.log(` usage: migrate [keys] arguments [param] arguments: create [name] \t creates new migration, and the name of the migration [optional] (optional) up [name] \t migrates from current position up to migration name [optional] (INCLUSIVELY) down [name] \t downgrades database from current position down to migration name [optional] (INCLUSIVELY) applied \t show currently applied migrations pending \t list migration that could be applied help \t\t show this help message keys: --migrationsDir='./new-migration' \t\t absolute or relative path to the migrations dir. By default './migrations' --collection='db-migrations' \t\t\t the name of the collection to persist in the database. By default 'migrations' --configConnection='database.connectionString' \t the name of the property of the 'config' module to be used as connection string. By default 'db.connectionString' --force \t\t\t\t\t ignore migration that has no related files in case of down way --silence \t\t\t\t\t do not ask at all. Be really carefull with that key! Use it on your own risk. `); process.exit(0); } else { console.log("Unknown argument type. Please use 'help' argument to find out how to use."); process.exit(0); } <file_sep>const MongoClient = require('mongodb').MongoClient, Migration = require('./migration'), {askQuestion} = require('./utils'); class Database { constructor(argsManager) { this.argsManager = argsManager; this.collectionName = this.argsManager.getCollectionName() } getConnection() { let connectionString = this.argsManager.getConnectionString(); return this.mongoConnect(connectionString); } mongoConnect(uri) { return new Promise((resolve, reject) => { return MongoClient.connect(uri, function (err, db) { if (err) { return reject(err); } else { return resolve(db) } }) }) } async cleanUpMigrationsCollection() { let db = await this.getConnection(); return db.collection(this.collectionName) .deleteMany({}) } async fixMigrationsCollection() { let message = `it looks like you ${this.collectionName} collection is damaged. \x1b[32mWould you like to fix it?\x1b[0m`; await askQuestion(message, this.argsManager); await this.cleanUpMigrationsCollection(); let migrations = Migration.getMigrationsFromFolder(this.argsManager); for (let migration of migrations) { try { await askQuestion(`is that migration: \x1b[33m${migration.name}\x1b[0m already applied?`, this.argsManager); await this._writeDownMigration(migration); } catch (err) { //TODO: make common-error module to throw and handle appropriate errors if (err === 'declined by user') { continue; } else { throw err; } } } } async fetchAppliedMigrations() { let db = await this.getConnection(); let result = await db.collection(this.collectionName) .find({}) .toArray() .then(migrations => { try { return migrations .map(migration => new Migration(migration.name, undefined, migration.applied)) } catch (err) { if (err === 'PARSERROR') { //TODO: error... return this.fixMigrationsCollection() .then(() => this.fetchAppliedMigrations()) } else { throw err; } } } ); db.close(); return result; } /** * make a note in database that specified migration applied * @param migration {Migration} * @returns {Promise.<void>} */ async _writeDownMigration(migration) { let db = await this.getConnection(); return db.collection(this.collectionName) .updateOne({ name: migration.name }, { name: migration.name, applied: new Date() }, { upsert: true }) } async _cleanUpMigration(migration) { let db = await this.getConnection(); return db.collection(this.collectionName) .deleteMany({ name: migration.name }) } async upMigrations(migrations) { return this._applyMigrations(migrations, "up"); } async downMigrations(migrations) { return this._applyMigrations(migrations, "down"); } async _applyMigrations(migrations, method) { for (let migration of migrations) { try { await migration[method]() } catch (err) { throw ( `during ${method} migration [${migration.name}] an error occurred: ${JSON.stringify(err, null, 2)} migration process interrupted` ); } try { switch (method) { case "up": await this._writeDownMigration(migration); break; case "down": await this._cleanUpMigration(migration); break; } } catch (err) { throw ( `migration ${this.collectionName} ${method} successfully, but an error occurred during persisting migration in [${migration.name}] collection: ${JSON.stringify(err, null, 2)} migration process interrupted` ); } } } } module.exports = Database; <file_sep>module.exports.up = () => { return new Promise((resolve, reject) => { resolve(); }) }; module.exports.down = () => { return new Promise((resolve, reject) => { resolve(); }) }; <file_sep># Migration CLI for mongodb [![NPM](https://nodei.co/npm/devhouse-migrate.svg?downloads=true&downloadRank=true)](https://www.npmjs.com/package/devhouse-migrate)&nbsp;&nbsp; ``` npm install -g devhouse-migrate ``` This module requires `nodejs 8`. All migrations staged in database in `migrations` collection by default (you can change that, see _usage_). The form of the stored database object: ``` { "_id" : ObjectId("5988679406f2faeaab6a3b2a"), "name" : "1484640085344-addCurrentOrderProcessIdToUsers.js", "applied" : ISODate("2017-08-07T13:13:56.835Z") } ``` The connection string is retrieved from `config` module. By default `db.connectionString` property is taken. The module expects to have configuration files in `./config` directory ## Usage In order to show usage type ``` migrate help ``` ``` usage: migrate [keys] arguments [param] arguments: create [name] creates new migration, and the name of the migration [optional] (optional) up [name] migrates from current position up to migration name [optional] (INCLUSIVELY) down [name] downgrades database from current position down to migration name [optional] (INCLUSIVELY) applied show currently applied migrations pending list migration that could be applied help show this help message keys: --migrationsDir='./new-migration' absolute or relative path to the migrations dir. By default './migrations' --collection='db-migrations' the name of the collection to persist in the database. By default 'migrations' --configConnection='database.connectionString' the name of the property of the 'config' module to be used as connection string. By default 'db.connectionString' --force ignore migration that has no related files in case of down way --silence do not ask at all ``` ## Examples ----- If you want to show all migration to be applied type ``` migrate pending ``` This will returns the full list of migration to apply ``` The following 6 migrations could be applied: 1: 1484640085344-addCurrentOrderProcessIdToUsers.js 2: 1485165880117-UpdatePropertyBankInfoSchema.js 3: 1497443127517-UpdateUsersBirthdays.js 4: 1497531877195-SetFromAmbitaMark.js 5: 1499927755913-SetFromAmbitaForApartmentOwnersAndUsers.js ``` ----- In order apply all migration ``` migration up ``` Migrate to specific migration. This will migrate to provided migration **inclusively** ``` migration up 1497531877195-SetFromAmbitaMark.js ``` ---- In order to show currently applied migrations ``` migrate applied ``` this will return ``` The following 7 already applied on the database: 1: 1497443127600-SuperMigration.js 2: 1484640085344-addCurrentOrderProcessIdToUsers.js 3: 1485165880117-UpdatePropertyBankInfoSchema.js 4: 1497443127517-UpdateUsersBirthdays.js 5: 1497531877195-SetFromAmbitaMark.js 6: 1499927755913-SetFromAmbitaForApartmentOwnersAndUsers.js ``` ---- In order to downgrade to specific migration use ``` migrate down 1497443127517-UpdateUsersBirthdays.js ``` And that will downgrate from migration #6 down to #4 **inclusively** ----- In some cases you might noticed the following warning ``` THE FOLLOWING 1 MIGRATIONS ARE IN THE DATABASE BUT NOT IN LOCAL FILES <<< 1: 1497443127600-SuperMigration.js ``` That means that you cannot downgrade without `--force` option, that will ignore that migration --- In case of `up` and `down` migrations you will be asked to approve connection string ``` with current working environment will be used mongodb://localhost/mongomigrate are you agree with that? [y/n]: y ``` choose `y` or `n` in order to accept/decline If you don't want to see such messages and reply always `yes` use `--silence` key. ---- In order to create migration use. The name is optional. ``` migrate create MyNewMigration ``` This will generate file in you `migrations` (or `--migrationsDir`) folder file ``` file 1502115579733-MyNewMigration.js successfully created ``` ---- When something wroing with your `--collection`, you will be asked to fix it. Just reply `yes` and `no` to question: ``` it looks like you migrations collection is damaged. Would you like to fix it? [y/n]: y is that migration: 1484640085344-addCurrentOrderProcessIdToUsers.js already applied? [y/n]: y is that migration: 1485165880117-UpdatePropertyBankInfoSchema.js already applied? [y/n]: n is that migration: 1497443127517-UpdateUsersBirthdays.js already applied? [y/n]: y is that migration: 1497531877195-SetFromAmbitaMark.js already applied? [y/n]: n is that migration: 1499927755913-SetFromAmbitaForApartmentOwnersAndUsers.js already applied? [y/n]: y is that migration: 1502110122262-newmigra.js already applied? [y/n]: y is that migration: 1502115579733-MyNewMigration.js already applied? [y/n]: n ``` ---- For futher details see ``` migrate help ```
e73f0ca0ecef6cca9b072ab267e491c95a561ced
[ "Markdown", "JavaScript" ]
6
Markdown
devhousellc/mongodb-migrate
7b4ba469f2e046abd0f34c9bd0bebbd15282b846
36b666bb6a7f1b7ae12395ac06a6fd1787469ad1
refs/heads/master
<file_sep># CrazyStoneJ.github.io my main page
220797bc27d86c17b1a0f4c3708db25d55c1dff8
[ "Markdown" ]
1
Markdown
CrazyStoneJ/CrazyStoneJ.github.io
d6a17478f8de7ac7b0433be630837140dba12b7f
cce3353ca46d94dcae495065e52c774fd6052bcc
refs/heads/master
<file_sep>// // StardustCrossView.m // StardustCrossView // // Created by <NAME> on 06/16/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <CoreGraphics/CoreGraphics.h> #import "StardustCrossView.h" #import "StardustCrossManager.h" #import "StardustMenuContent.h" @interface StardustCrossView () @property(nonatomic, retain) StardustCrossManager *manager; @end @implementation StardustCrossView - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { _autoFallingStar = YES; _manager = [[StardustCrossManager alloc] init]; _manager.view = self; [self setAlpha:0.3f]; } return self; } /** * 初期座標はfallingStar時に決定される */ - (void)fallingStars { [self.manager fallingStars]; } - (NSString *)addMenuWithImage:(UIImage *)image text:(NSString *)text onClick:(dispatch_block_t)click { StardustMenuContent *content = [self.manager addMenuWithImage:image text:text onClick:click]; if (!content.tag) { return nil; } return content.tag; } - (void)removeMenuWithTag:(NSString *)tag { [self.manager removeMenuWithTag:tag]; } - (NSString *)addMenuChildWithImage:(UIImage *)image text:(NSString *)text onClick:(dispatch_block_t)click tag:(NSString *)tag { return [self.manager addMenuChildWithTag:tag image:image text:text onClick:click]; } - (void)removeMenuChildWithTag:(NSString *)tag { [self.manager removeMenuChildWithTag:tag]; } #pragma mark - touchEvent static CGPoint clickPos; - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *touch in touches) { clickPos = [touch locationInView:self]; break; } } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *touch in touches){ CGPoint pt = [touch locationInView:self]; [self.manager dragMovingView:pt.y origin:clickPos.y]; break; } } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *touch in touches){ CGPoint pt = [touch locationInView:self]; [self.manager dragMovingEnd:pt]; break; } } @end <file_sep>// // Created by <NAME> on 2013/06/16. // Copyright (c) 2013 ___FULLUSERNAME___. All rights reserved. // // To change the template use AppCode | Preferences | File Templates. // #import <UIKit/UIKit.h> #import <CoreGraphics/CoreGraphics.h> #import "StardustCrossManager.h" #import "StardustCrossHorizontalView.h" @interface StardustCrossManager () @property dispatch_semaphore_t sem; @property BOOL infinityMode; @property BOOL subMode; @property (retain) StardustCrossHorizontalView *viewHorizontal; @end @implementation StardustCrossManager - (id)init { if (self = [super init]) { _head = [[StardustMenuContent alloc] init]; _head.next = nil; _sem = dispatch_semaphore_create(1); _viewHorizontal = [[StardustCrossHorizontalView alloc] init]; } return self; } static int originViewingIdx = 0; - (BOOL)fallingStars { dispatch_semaphore_wait(self.sem, DISPATCH_TIME_FOREVER); StardustMenuContent *cur = self.head; __block NSUInteger order = 0; originViewingIdx = 0; while (cur.next) { cur = cur.next; //if (!cur.fallen) { if (1) { [UIView animateWithDuration:1.0f animations:^{ [cur.label setText:[NSString stringWithFormat:@"%d", order]]; CGRect frame = [self landingRect:cur order:order]; [cur.view setFrame:frame]; } completion:^(BOOL finished) { //枠外なら消す if ([self outOfScape:cur.view.frame]) { // [cur.view removeFromSuperview]; } }]; cur.fallen = YES; } order++; } if (order >= 6) { self.infinityMode = YES; } if (self.count == 6) { //余分に一つずつ前後のものを表示するため、リストに追加.無限モードにおいて常にViewは8必要。 //後 cur.next = [StardustMenuContent stardustCrossContentWithImage:nil text:nil onClick:nil]; CGRect frame = cur.view.frame; frame.origin.y = frame.origin.y + 80; [cur.next.view setFrame:frame]; [cur.next.label setText:[NSString stringWithFormat:@"%d", order - self.count]]; [self.view addSubview:cur.next.view]; //前 cur = cur.next; cur.next = [StardustMenuContent stardustCrossContentWithImage:nil text:nil onClick:nil]; frame = self.head.next.view.frame; frame.origin.y = frame.origin.y - 80; [cur.next.view setFrame:frame]; [cur.next.label setText:[NSString stringWithFormat:@"%d", order - 1]]; [self.view addSubview:cur.next.view]; } dispatch_semaphore_signal(self.sem); return self.infinityMode; } - (BOOL)outOfScape:(CGRect)frame { if (frame.origin.y > 560.0f || frame.origin.y < -80.0f) { return YES; } return NO; } - (void)dealloc { } - (CGRect)landingRect:(StardustMenuContent *)content order:(NSUInteger)order { CGFloat originUnitHeight = 480 / 6; CGFloat originY = originUnitHeight * order; return CGRectMake(0, originY, 100, 70); } - (CGRect)objectivePoint:(StardustMenuContent *)content order:(NSUInteger)order moveType:(SDMoveType)moveType { CGFloat originUnitHeight = 480 / 6; CGFloat originY; if (!self.infinityMode) { if (moveType == SDMoveToDowner) { originY = originUnitHeight * order; return CGRectMake(0, originY, 100, 70); } else if (moveType == SDMoveToUpper) { CGFloat adjust = 480 - originUnitHeight * self.count; originY = originUnitHeight * order + adjust; return CGRectMake(0, originY, 100, 70); } } return content.view.frame; } - (StardustMenuContent *)tail { dispatch_semaphore_wait(self.sem, DISPATCH_TIME_FOREVER); StardustMenuContent *cur = self.head; while (cur.next) { cur = cur.next; } dispatch_semaphore_signal(self.sem); return cur; } static BOOL dragNow = NO; - (void)changeUpDownView:(StardustMenuContent *)cur order:(NSUInteger)order { if (cur.view.frame.origin.y < -80.0f && order >= originViewingIdx) { originViewingIdx = (originViewingIdx + 1) % self.count; CGRect frame = cur.view.frame; frame.origin.y = frame.origin.y + self.count * 80.0f; [cur.view setFrame:frame]; } else if (cur.view.frame.origin.y > self.count * 80.0f - 80.0f) { if (--originViewingIdx < 0) { originViewingIdx = self.count - 1; } CGRect frame = cur.view.frame; frame.origin.y = frame.origin.y - self.count * 80.0f; [cur.view setFrame:frame]; } } static SDMoveType touchEndMoveToUpper = SDMoveNeutral; - (void)dragMovingView:(CGFloat)touchMoveY origin:(CGFloat)touchBeganY { CGFloat distance = touchMoveY - touchBeganY; static CGFloat beforeDistance = 0; if(self.subMode){ return; } CGRect frame; NSInteger order = 0; dispatch_semaphore_wait(self.sem, DISPATCH_TIME_FOREVER); StardustMenuContent *cur = self.head; while (cur.next) { cur = cur.next; frame = cur.view.frame; frame.origin.y = frame.origin.y + distance - (dragNow ? beforeDistance : 0); [cur.view setFrame:frame]; if (self.infinityMode) { if ([self outOfScape:cur.view.frame]) { [self changeUpDownView:cur order:order]; } } order++; } dragNow = YES; if (distance > beforeDistance) { touchEndMoveToUpper = SDMoveToDowner; } else if (distance > beforeDistance) { touchEndMoveToUpper = SDMoveToUpper; } else { touchEndMoveToUpper = SDMoveNeutral; } beforeDistance = distance; dispatch_semaphore_signal(self.sem); } static NSInteger parentOrder = 0; - (void)dragMovingEnd:(CGPoint)touchPoint { SDMoveType moveType = SDMoveNeutral; if(self.subMode){ [self closeSubMenus]; return; } StardustMenuContent *tail = self.tail; dispatch_semaphore_wait(self.sem, DISPATCH_TIME_FOREVER); StardustMenuContent *cur = self.head; __block NSUInteger order = 0; if (self.head.next && !self.infinityMode) { if (self.head.next.view.frame.origin.y < 0) { moveType = SDMoveToDowner; } else if (tail.view.frame.origin.y > (480 - 70)) { moveType = SDMoveToUpper; } } while (cur.next) { cur = cur.next; if (!cur.fallen && !self.infinityMode) { [UIView animateWithDuration:0.3f animations:^{ CGRect frame = [self objectivePoint:cur order:order moveType:moveType]; [cur.view setFrame:frame]; } completion:^(BOOL finished) { //枠外なら消す if ([self outOfScape:cur.view.frame]) { [cur.view removeFromSuperview]; } }]; } else if (self.infinityMode) { //慣性を実装+枠外なら消す __block CGRect frame = cur.view.frame; if (!dragNow) { /* タップ時処理 */ if (CGRectContainsPoint(cur.view.frame, touchPoint)) { /* サブメニューがあれば開く */ if (cur.head.next) { [self openSubMenus:cur]; parentOrder = order; } /* クリックハンドラ実行 */ dispatch_async(dispatch_get_main_queue(), ^{ if (cur.onClick) { cur.onClick(); } }); break; } continue; } [UIView animateWithDuration:0.1f animations:^{ if (touchEndMoveToUpper == SDMoveToUpper) { frame.origin.y = frame.origin.y - 30.0f; [cur.view setFrame:frame]; } else if (touchEndMoveToUpper == SDMoveToDowner) { frame.origin.y = frame.origin.y + 30.0f; [cur.view setFrame:frame]; } } completion:^(BOOL finished) { if ([self outOfScape:cur.view.frame]) { [self changeUpDownView:cur order:order]; } }]; } order++; } dispatch_semaphore_signal(self.sem); dragNow = NO; } #ifdef NEVER - (CGRect)subbingRect:(StardustMenuContent *)content order:(NSUInteger)order { CGFloat scale = 5; CGFloat originUnitHeight = 480 / (6 * scale); /*1/5の大きさになる*/ CGFloat originY = originUnitHeight * order; return CGRectMake(-50, originY, 100 / scale, 70 / scale); } #endif - (CGRect)subbingRect:(StardustMenuContent *)content order:(NSUInteger)order { CGRect frame = content.view.frame; frame.origin.x = frame.origin.x - 50; return frame; } - (CGRect)mainingRect:(StardustMenuContent *)content order:(NSUInteger)order { CGRect frame = content.view.frame; frame.origin.x = frame.origin.x + 50; return frame; } - (void)openSubMenus:(StardustMenuContent *)content { __block NSUInteger order = 0; CGRect frame = content.view.frame; [self.viewHorizontal setFrame:CGRectMake(0, frame.origin.y, 320.0f, 70.0f)]; [self.view addSubview:self.viewHorizontal]; [self.viewHorizontal openMenus:content]; StardustMenuContent *cur = self.head; order = 0; while (cur.next) { cur = cur.next; [UIView animateWithDuration:0.3f animations:^{ CGRect frame = [self subbingRect:cur order:order]; [cur.view setFrame:frame]; } completion:^(BOOL finished) { }]; order++; } self.subMode = YES; } - (void)closeSubMenus { self.subMode = NO; StardustMenuContent *cur = self.head; __block NSUInteger order = 0; while (cur.next) { cur = cur.next; if(order == parentOrder){ [self.viewHorizontal closeMenus:cur]; } [UIView animateWithDuration:0.3f animations:^{ CGRect frame = [self mainingRect:cur order:order]; [cur.view setFrame:frame]; } completion:^(BOOL finished) { [self.viewHorizontal removeFromSuperview]; }]; order++; } } - (StardustMenuContent *)addMenuWithImage:(UIImage *)image text:(NSString *)text onClick:(dispatch_block_t)click { StardustMenuContent *addition; addition = [StardustMenuContent stardustCrossContentWithImage:image text:text onClick:click]; if (!addition) { return nil; } [self tail].next = addition; self.count++; CGFloat x = rand() % (320 - 300); CGFloat y = rand() % (480 - 300); CGFloat width = rand() % 200; CGFloat height = width * 0.6; CGRect frame = CGRectMake(x, y, width, height); NSLog(@"addMenuWithImage: %f,%f,%f,%f", x, y, width, height); [addition.view setBackgroundColor:[UIColor blueColor]]; [addition.view setFrame:frame]; [self.view addSubview:addition.view]; return addition; } - (void)removeMenuWithTag:(NSString *)tag { } - (NSString *)addMenuChildWithTag:(NSString *)tag image:(UIImage *)image text:(NSString *)text onClick:(dispatch_block_t)click { dispatch_semaphore_wait(self.sem, DISPATCH_TIME_FOREVER); StardustMenuContent *cur = self.head; StardustMenuContent *child = nil; while (cur.next) { cur = cur.next; if ([cur.tag isEqualToString:tag]) { child = [cur tail]; child.next = [StardustMenuContent stardustCrossContentWithImage:image text:text onClick:click]; child.countChild++; break; } } dispatch_semaphore_signal(self.sem); return child ? child.next.tag : nil; } - (void)removeMenuChildWithTag:(NSString *)tag { } @end<file_sep>// // Created by <NAME> on 2013/06/16. // Copyright (c) 2013 ___FULLUSERNAME___. All rights reserved. // // To change the template use AppCode | Preferences | File Templates. // #import "StardustCrossController.h" @implementation StardustCrossController { } @end<file_sep>// // Created by <NAME> on 2013/06/16. // Copyright (c) 2013 ___FULLUSERNAME___. All rights reserved. // // To change the template use AppCode | Preferences | File Templates. // #import <Foundation/Foundation.h> #import "StardustCrossView.h" #import "StardustMenuContent.h" @interface StardustCrossManager : NSObject @property (retain) StardustMenuContent *head; @property (retain) StardustCrossView *view; @property NSInteger count; typedef NS_ENUM(NSUInteger, SDMoveType) { SDMoveToUpper=1, SDMoveToDowner, SDMoveNeutral, }; - (StardustMenuContent *)tail; - (id)init ; - (BOOL)fallingStars; - (void)dragMovingView:(CGFloat)touchMoveY origin:(CGFloat)touchBeganY; - (void)dragMovingEnd:(CGPoint)touchPoint; - (StardustMenuContent *)addMenuWithImage:(UIImage *)image text:(NSString *)text onClick:(dispatch_block_t)click; - (void)removeMenuWithTag:(NSString *)tag; - (NSString *)addMenuChildWithTag:(NSString *)tag image:(UIImage *)image text:(NSString *)text onClick:(dispatch_block_t)click; - (void)removeMenuChildWithTag:(NSString *)tag; @end<file_sep>// // Created by <NAME> on 2013/06/17. // Copyright (c) 2013 ___FULLUSERNAME___. All rights reserved. // // To change the template use AppCode | Preferences | File Templates. // #import <UIKit/UIKit.h> #import "StardustMenuContent.h" #import "StardustHash.h" @interface StardustMenuContent () @property dispatch_semaphore_t sem; @end @implementation StardustMenuContent + (StardustMenuContent *)stardustCrossContentWithImage:(UIImage *)image text:(NSString *)text onClick:(dispatch_block_t)click{ StardustMenuContent *content = [[StardustMenuContent alloc] init]; content.view = [[UIView alloc] init]; content.view.backgroundColor = [UIColor blueColor]; content.caption = text; content.onClick = click; content.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 30)]; [content.view addSubview:content.label]; content.tag = [StardustHash hash]; content.fallen = NO; content.head = [[StardustMenuContent alloc] init]; return content; } - (id)init{ if(self = [super init]){ _sem = dispatch_semaphore_create(1); } return self; } - (StardustMenuContent *)tail { dispatch_semaphore_wait(self.sem, DISPATCH_TIME_FOREVER); StardustMenuContent *cur = self.head; while (cur.next) { cur = cur.next; } dispatch_semaphore_signal(self.sem); return cur; } @end<file_sep>// // Created by <NAME> on 2013/06/24. // Copyright (c) 2013 ___FULLUSERNAME___. All rights reserved. // // To change the template use AppCode | Preferences | File Templates. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "StardustMenuContent.h" @interface StardustCrossHorizontalView : UIView - (void)openMenus:(StardustMenuContent *)content; - (void)closeMenus:(StardustMenuContent *)content; @end<file_sep>// // StardustCrossViewTests.m // StardustCrossViewTests // // Created by <NAME> on 06/16/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import "StardustCrossViewTests.h" @implementation StardustCrossViewTests - (void)setUp { [super setUp]; // Set-up code here. } - (void)tearDown { // Tear-down code here. [super tearDown]; } - (void)testExample { STFail(@"Unit tests are not implemented yet in StardustCrossViewTests"); } @end <file_sep>// // ViewController.m // StardustCrossViewSample // // Created by <NAME> 06/17/13. // Copyright (c) 2013 com.regaria. All rights reserved. // #import "ViewController.h" #import <StardustCrossView/StardustCrossView.h> @interface ViewController () @property StardustCrossView *stardustView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)viewWillAppear:(BOOL)animated { StardustCrossView *view = [[StardustCrossView alloc] initWithFrame:CGRectMake(50, 0, 100, 480)]; self.stardustView = view; // view.backgroundColor = [UIColor redColor]; [self.view addSubview:view]; dispatch_block_t block = ^{ NSLog(@"Now clicked."); }; NSString *tagMenu0 =[view addMenuWithImage:nil text:@"text1" onClick:block]; [view addMenuChildWithImage:nil text:@"sub1" onClick:block tag:tagMenu0]; [view addMenuChildWithImage:nil text:@"sub1" onClick:block tag:tagMenu0]; [view addMenuChildWithImage:nil text:@"sub1" onClick:block tag:tagMenu0]; [view addMenuWithImage:nil text:@"text1" onClick:nil]; [view addMenuWithImage:nil text:@"text1" onClick:nil]; [view addMenuWithImage:nil text:@"text1" onClick:nil]; [view addMenuWithImage:nil text:@"text1" onClick:nil]; [view addMenuWithImage:nil text:@"text1" onClick:nil]; [view addMenuWithImage:nil text:@"text1" onClick:nil]; [view addMenuWithImage:nil text:@"text1" onClick:nil]; [view fallingStars]; UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button setFrame:CGRectMake(200, 0, 100, 50)]; [button setTitle:@"addMenu" forState:UIControlStateNormal]; [button addTarget:self action:@selector(pushAddMenuButton:) forControlEvents:UIControlEventTouchDown]; [self.view addSubview:button]; UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button2 setFrame:CGRectMake(200, 50, 100, 50)]; [button2 setTitle:@"falling" forState:UIControlStateNormal]; [button2 addTarget:self action:@selector(pushFallingStar:) forControlEvents:UIControlEventTouchDown]; [self.view addSubview:button2]; } - (void)pushAddMenuButton:(id)sender{ [self.stardustView addMenuWithImage:nil text:@"text1" onClick:nil]; } - (void)pushFallingStar:(id)sender{ [self.stardustView fallingStars]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end<file_sep>// // Created by <NAME> on 2013/06/24. // Copyright (c) 2013 ___FULLUSERNAME___. All rights reserved. // // To change the template use AppCode | Preferences | File Templates. // #import "StardustCrossHorizontalView.h" @implementation StardustCrossHorizontalView - (void)openMenus:(StardustMenuContent *)content { StardustMenuContent *child = content.head; CGRect frame = content.view.frame; NSUInteger order = 0; while (child.next) { child = child.next; frame.origin.y = 0; [child.view setFrame:frame]; [self addSubview:child.view]; [UIView animateWithDuration:0.3f animations:^{ CGRect subViewFrame = frame; subViewFrame.origin.x = order * 120 + frame.origin.x; [child.view setFrame:subViewFrame]; } completion:^(BOOL finished) { }]; order++; } } - (void)closeMenus:(StardustMenuContent *)content { CGRect frame = content.view.frame; NSUInteger order = 0; StardustMenuContent *child = content.head; while (child.next) { child = child.next; [UIView animateWithDuration:0.3f animations:^{ CGRect subViewFrame = frame; subViewFrame.origin.x = 0; subViewFrame.origin.y = 0; [child.view setFrame:subViewFrame]; } completion:^(BOOL finished) { [child.view removeFromSuperview]; }]; order++; } } @end<file_sep>#include <stdio.h> unsigned rotate(unsigned l) { return (l << 1 | (l >> 32 - 1 )& 0x1); } unsigned hash(unsigned char *hoge) { unsigned hash = 0; while(*hoge != '\0'){ hash = rotate(hash) ^ *(hoge++); } return hash; } int main (int argc , char **argv){ printf("%d", hash(argv[1])); } <file_sep>// // Created by <NAME> on 2013/06/17. // Copyright (c) 2013 ___FULLUSERNAME___. All rights reserved. // // To change the template use AppCode | Preferences | File Templates. // #import <Foundation/Foundation.h> @interface StardustMenuContent : NSObject @property(retain) StardustMenuContent *next; @property(retain) StardustMenuContent *head; /* For child menu */ @property(atomic, assign) NSUInteger countChild; @property(retain) NSString *tag; @property(retain) UIView *view; @property(retain) UILabel *label; @property(assign) BOOL fallen; @property(retain) NSString *caption; @property(copy) dispatch_block_t onClick; + (StardustMenuContent *)stardustCrossContentWithImage:(UIImage *)image text:(NSString *)text onClick:(dispatch_block_t)click; - (StardustMenuContent *)tail; @end<file_sep>// // StardustCrossView.h // StardustCrossView // // Created by <NAME> on 06/16/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface StardustCrossView : UIView @property (nonatomic, assign) BOOL autoFallingStar; /** * Initializes instance. * @param frame The CGRect. * @return The `StardustCrossView` instance. */ - (id)initWithFrame:(CGRect)frame; /** * Performs animation falling stars. */ - (void)fallingStars; /** * Adds a menu. * @param image The image in menu if `text` is nil. * @param text The text in menu if `image` is nil. * @param click The handler on click. * @return The menu `tag`. */ - (NSString *)addMenuWithImage:(UIImage *)image text:(NSString *)text onClick:(dispatch_block_t)click; /** * Removes a menu. * @param tag The tag of target menu. */ - (void)removeMenuWithTag:(NSString *)tag; /** * Adds a child menu. * @param image The image in menu if `text` is nil. * @param text The text in menu if `image` is nil. * @param click The handler on click. * @param tag The tag of the parent menu. * @return The menu `tag`. */ - (NSString *)addMenuChildWithImage:(UIImage *)image text:(NSString *)text onClick:(dispatch_block_t)click tag:(NSString *)tag; /** * Removes a menu. * @param tag The tag of target menu. */ - (void)removeMenuChildWithTag:(NSString *)tag; @end <file_sep>// // StardustCrossViewTests.h // StardustCrossViewTests // // Created by <NAME> on 06/16/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <SenTestingKit/SenTestingKit.h> @interface StardustCrossViewTests : SenTestCase @end
7279f105d2b2fb8fed68c88f1ec056a44b3a87db
[ "C", "Objective-C" ]
13
C
adachic/StardustCrossView
5fe0a995f613a7a50352b47265c35f8edd39759f
38f337adf0869a9d1012d4661378d46e80f06d60
refs/heads/main
<file_sep>h1{ text-align:center; color:#ffffff; text-transform:uppercase; } header{ background: url('http://intro-webdesign.com/CSS/assignment-2/images/flywheel.jpg' ) } nav a{ display:inline-block; width:15%; padding:2%; border-radius:10%; margin-left:4%; font-size:150%; text-decoration:none; color:#ffa500; text-align:center; background-color: rgba(1,1,1,0.5) } .active{ background-color:#ffffff; color:#0000ff; } header{ padding:2%; } img{ width:60%; margin:17%; display:block; border: solid 2px; } .left{ display:block; background-color:#3cb371; float:left; width:20%; } .right{ display:inline-block; width:75%; margin:1%; } th{ background-image:-webkit-linear-gradient(#006600,#00cc00); background-image:-moz-linear-gradient(top,#006600,#00cc00); background-image:-o-linear-gradient(top,#006600,#00cc00); background-image:linear-gradient(#006600,#00cc00); line-height:30px; padding:2%; } table{ width:75%; margin:2% 10%; color:#ffffff; font-family:courier,arial,helvetica; border:3px solid #000000; border-radius:2% 2% 0% 0%; border-width: thin medium thick; text-shadow: 2px 2px #ff0000; } table th:first-child{ text-align:left; } tr{ background-color:rgb(0,102,0,.6); line-height:30px; } td{ padding:2%; text-align:center; width:0%; color:#000000; } tr td:first-child{ text-align:left; } tr:hover{ background-color:rgb(0,204,0,1); }
2eeb7825e93e9e4aabd4fdc73c3cb81760106206
[ "CSS" ]
1
CSS
Mihir008/Web-Components
cf60f7d29422069cac6faa7e10c28a2bda4d26f1
614a6bf1ec0de1a9ccd6ba61cafedb4e927cc888
refs/heads/main
<repo_name>senaKash/TestMe-<file_sep>/README.md # TestMe- Скачиваешь, разархивируешь, !!!устанавливаешь питон!!! рапускаешь exe и радуешься
bb7f18b25109dfaadb69d09e82bd36cf464625c7
[ "Markdown" ]
1
Markdown
senaKash/TestMe-
b0c9223a5fbe66f904986980987b257b69bab68c
6e1578752386da791f05548005472334062809f8
refs/heads/main
<file_sep># Predict Hotel Rating from reviews ![NUX_Octodex](https://user-images.githubusercontent.com/64835443/137617657-bdc4dcdf-617c-4b0c-a811-02891277be27.gif) - Steps followed in this notebook - Data Cleaning - Tokenization - Visualization - Word Cloud Generation - Classification ## Observations - Some reviews had 0 rating and some had rating above 5, so I filtered out those reviews. - Since the main idea of analysis had to be depended on the review I tokenized them in three categories : - The original unaltered review - Limited review filtered to have no stopwords - review that only contains the adjectives of the review - It was observed that the reviews were only about hotels in the US but the reviews were also in languages other than english, so i visualized the location of the reviews. ![newplot](https://user-images.githubusercontent.com/64835443/137616502-29c34db6-bad6-4eaa-a465-f1a68b2cd054.png) - Plotting the reviews on the globe ![globe](https://user-images.githubusercontent.com/64835443/137616646-896d2035-54cc-4192-b1b4-1c41d9cafbea.png) - Generating Word Cloud ![word_cloud](https://user-images.githubusercontent.com/64835443/137616836-ae2e1801-bee5-47a9-9310-e19d2b68c910.png) - By plotting a graph for review length, we can observe that the reviews are fairly short and appear to have a bit of a bimodal distribution. - Accuracy check on classifications found that : - Original review text seemed to be best at classifying the reviews. - Linear svc and naive bayes are both comfortably better than chance at predicting the rating of the hotel review - After plotting the confusion matrix it was found that the fact that there are many more 4,5 star ratings than any other rating, which means the classifier is going to be trained to be much better at identifying these high ratings. But even with this issue, the classifier was mainly confusing rating that were next to each other (e.g. confusing a 4 for a 5), which is understandable given how free text reviews don't always match perfectly with a star rating. Overall, the results are fairly good for such a small data set and considering that I did not do any feature selection or even much tuning of the classifier itself.
71a6aabd78271a9a9cdacd517cb007c07bdfe49e
[ "Markdown" ]
1
Markdown
dikshanasa/Predict_Hotel_rating_from_reviews
e9f315c38d4c8e993b4f556c0627339649e60a0d
745111f6020cc2a5a66530fa017f417ebb598e18
refs/heads/master
<file_sep>trigger: tags: include: - v* branches: include: - develop - release* paths: exclude: - README.md pr: none variables: ref: $(Build.SourceBranch) buildTag: $(Build.BuildId) repository: 'focal-freedom-236620/proxy' jobs: - job: Build_x86 pool: vmImage: 'Ubuntu-16.04' variables: imageTag: steps: - script: | if [[ $(ref) == refs/tags* ]]; then TAG=$(echo $(ref) | sed "s|refs/tags/v||g") echo "##vso[task.setvariable variable=imageTag]$TAG" else LATESTTAG=$(git tag | tail -1) LATESTVERS=${LATESTTAG#?} if [ -z "$LATESTVERS" ]; then LATESTVERS=0.0.0; fi echo "##vso[task.setvariable variable=imageTag]$LATESTVERS-b$(buildTag)" fi displayName: 'Set image tag' - script: | echo $(imageTag) displayName: 'Check image tag' - template: pipeline.yaml parameters: arch: 'X86' repository: $(repository) imageTag: $(imageTag) - job: Build_ARM pool: 'RPi' variables: imageTag: steps: - script: | if [[ $(ref) == refs/tags* ]]; then TAG=$(echo $(ref) | sed "s|refs/tags/v||g") echo "##vso[task.setvariable variable=imageTag]$TAG" else LATESTTAG=$(git tag | tail -1) LATESTVERS=${LATESTTAG#?} if [ -z "$LATESTVERS" ]; then LATESTVERS=0.0.0; fi echo "##vso[task.setvariable variable=imageTag]$LATESTVERS-b$(buildTag)" fi displayName: 'Set image tag' - script: | echo $(imageTag) displayName: 'Check image tag' - template: pipeline.yaml parameters: arch: 'ARM' repository: $(repository)-arm imageTag: $(imageTag) <file_sep>'use strict'; var bridges = require('./bridges.js'); function bridge_addr(config) { var parts = config.split(':'); if (parts.length == 2) { return { protocol: parts[0].toLowerCase(), addr: parts[1] }; } else { return undefined; } } function bridge_type(source_protocol, target_protocol) { return source_protocol + "_to_" + target_protocol; } function bridge_config(config) { var parts = config.split('=>'); if (parts.length == 2) { var source = bridge_addr(parts[0]); var target = bridge_addr(parts[1]); if (source === undefined || target === undefined) { return undefined; } else { return { type: bridge_type(source.protocol, target.protocol), source: source.addr, target: target.addr }; } } else { return undefined; } } function Proxy(config, bridgehost, ioFogOptions) { console.log("Proxying %s", config); var bridgeconfig = bridge_config(config); if (bridgeconfig) { switch (bridgeconfig.type) { case "amqp_to_http": return bridges.amqp_to_http(bridgeconfig.source, bridgehost, bridgeconfig.target, ioFogOptions); case "amqp_to_http2": return bridges.amqp_to_http2(bridgeconfig.source, bridgehost, bridgeconfig.target, ioFogOptions); case "amqp_to_tcp": return bridges.amqp_to_tcp(bridgeconfig.source, bridgehost, bridgeconfig.target, ioFogOptions); case "http_to_amqp": return bridges.http_to_amqp(bridgeconfig.source, bridgeconfig.target, ioFogOptions); case "http2_to_amqp": return bridges.http2_to_amqp(bridgeconfig.source, bridgeconfig.target, ioFogOptions); case "tcp_to_amqp": return bridges.tcp_to_amqp(bridgeconfig.source, bridgeconfig.target, ioFogOptions); } } console.error("Unrecognised bridge type: %s", bridgeconfig.type); } module.exports.proxy = function (config, bridgehost, ioFogOptions) { return new Proxy(config, bridgehost, ioFogOptions) }<file_sep>parameters: - name: 'arch' type: string default: X86 - name: 'repository' type: string - name: 'imageTag' type: string steps: - script: | echo "gcr.io/${{ parameters.repository }}:${{ parameters.imageTag }}" > ${{ parameters.arch }}_DOCKER_IMAGE echo "gcr.io/${{ parameters.repository }}:${{ parameters.imageTag }}" displayName: 'Save Docker image name and tag to ${{ parameters.arch }}_DOCKER_IMAGE into artifacts' - task: CopyFiles@2 inputs: SourceFolder: $(System.DefaultWorkingDirectory) TargetFolder: $(Build.ArtifactStagingDirectory) Contents: | ${{ parameters.arch }}_DOCKER_IMAGE OverWrite: true displayName: 'artefacts to publish' - task: Docker@2 displayName: 'build and push docker image' inputs: containerRegistry: 'Edgeworx GCP' repository: ${{ parameters.repository }} command: 'buildAndPush' Dockerfile: 'Dockerfile.iofog' tags: | $(Build.SourceBranchName) ${{ parameters.imageTag }} - task: PublishBuildArtifacts@1 inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)' ArtifactName: ${{ parameters.arch }} displayName: 'publish artifacts'
aa7c45eb6f299df908e818e76b11bd37baae1185
[ "JavaScript", "YAML" ]
3
JavaScript
eclipse-iofog/skupper-proxy
6118b873201283c01275bfb4458baeed19239ae3
bdedd691fe0f84877136fe486e9b77c4bc92a22c
refs/heads/master
<file_sep># AngularJS Samples for AngularJS practice.
b76608c70c9340cc939ca8d6d3c4573bb2177a17
[ "Markdown" ]
1
Markdown
BabulalS-Optimus/AngularJS
7eb9931f6f548220e015e04181f946e2321b8077
6a9bf07b4c2ccff5d3ab6f4067f1b59f8b6b1d94
refs/heads/master
<repo_name>alvisisme/android-openssl<file_sep>/build.sh #!/bin/bash OPENSSL_VERSION=1.0.2g CWD=$PWD mkdir -p $CWD/build cd $CWD/build if [ ! -f openssl-$OPENSSL_VERSION.tar.gz ];then wget https://openssl.org/source/openssl-$OPENSSL_VERSION.tar.gz fi if [ -d openssl-$OPENSSL_VERSION.tar.gz ];then rm -rf openssl-$OPENSSL_VERSION.tar.gz fi tar xf openssl-$OPENSSL_VERSION.tar.gz cd openssl-$OPENSSL_VERSION ./Configure android --prefix=$CWD/build no--shared no-ssl2 no-ssl3 no-hw no-asm no-unit-test make depend make make install_sw cd $CWD<file_sep>/README.md # openssl-for-android [![Build Status](https://img.shields.io/travis/com/alvisisme/android-openssl?style=flat-square)](https://travis-ci.com/alvisisme/android-openssl) 编译openssl至android平台arm64-v8a架构。 本工程仅编译openssl静态库。 ## 目录 - [背景](#背景) - [安装](#安装) - [用法](#用法) - [维护人员](#维护人员) - [贡献参与](#贡献参与) - [许可](#许可) - [参考引用](#参考引用) ## 背景 编译环境 * ubuntu18.04 * android-ndk-r13b * openssl-1.0.2g ## 安装 将**dist**目录下对应头文件和库文件引入。 ## 用法 推荐使用 docker 和 docker-compose 进行编译 ```bash docker-compose up --build ``` 编译后的文件位于 **build/lib** 目录下 ## 维护人员 [@Alvis Zhao](https://github.com/alvisisme) ## 贡献参与 欢迎提交PR。 ## 许可 © 2020 <NAME> ## 参考资料 * [wiki.openssl.org](https://wiki.openssl.org/index.php/Android) * [Adding OpenSSL Support for Android](http://doc.qt.io/qt-5/opensslsupport.html) <file_sep>/docker-compose.yml version: '2' services: openssl-for-android: build: . image: openssl-for-android-arm64-v8a volumes: - ./build:/build
9d78a41f5fcc658cfcf31f28c5f7bda115b10052
[ "Markdown", "Shell", "YAML" ]
3
Markdown
alvisisme/android-openssl
e693591c53c3c755afb3c0f87d4595d99da94874
0bf30a0874d88441eb31b7481058fec2d8184176
refs/heads/master
<file_sep># explore_california First upload of explore_california from terminal Link: https://hemanth22.github.io/explore_california/
7cbea3542e14cf2c26f38eb7a199b85a09fc9258
[ "Markdown" ]
1
Markdown
hemanth22/explore_california
a8feeb072507dadd6bf8183403279d40322a5bab
9fd69ee9ee3f13a3e8aa7362e261577b614cd16a
refs/heads/main
<file_sep># website1 This website is created using HTML, CSS and Bootstrap.It is fully responsive.
0e0d69c555b266c06be6d12ff79edabe30a8e638
[ "Markdown" ]
1
Markdown
aalokagrawal/website1
08879080b4fbe2c7237486e7b4bcb53de2d0e127
a62245dea8f5a1329caf832cc9bf61dd64baae20
refs/heads/master
<file_sep>.text-center { text-align: center; } @media only screen and (max-width: 992px) { .container { padding: 1rem; } }
fa304b2cf6ccb5f7817e960dd0a31a8480867f8d
[ "CSS" ]
1
CSS
VictorUvarov/mitmanz.github.io
1069a79b46d724aaa4678251c14a34a57a979b05
73a74f0bf357f3c0e628606a50598a868086c5d8
refs/heads/main
<file_sep>@echo off cls python %~dp0src/main.py <file_sep># Boot Program <file_sep>bits 64 global main main: xor rax, rax ret <file_sep>document.addEventListener("DOMContentLoaded",()=>{ // },false); <file_sep>#!/bin/bash echo off clear python build.py "$@" <file_sep>import os import subprocess import sys import zipfile if (os.path.exists("build")): dl=[] for r,ndl,fl in os.walk("build"): dl=[os.path.join(r,k) for k in ndl]+dl for f in fl: os.remove(os.path.join(r,f)) for k in dl: os.rmdir(k) else: os.mkdir("build") jfl=[] ml=[] for r,_,fl in os.walk("src"): r=r.replace("\\","/").strip("/")+"/" for f in fl: if (f[-5:]==".java"): jfl.append(r+f) if (f[-4:]==".jar"): ml.append(r+f) if (subprocess.run(["javac","-encoding","utf8","-cp",os.path.pathsep.join(ml),"-d","build"]+jfl).returncode!=0): sys.exit(1) with zipfile.ZipFile("build/$$$NAME$$$.jar","w") as zf: print("Writing: META-INF/MANIFEST.MF") zf.write("manifest.mf",arcname="META-INF/MANIFEST.MF") for r,_,fl in os.walk("build"): r=r.replace("\\","/").strip("/")+"/" for f in fl: if (f[-6:]==".class"): print(f"Writing: {(r+f)[6:]}") zf.write(r+f,arcname=(r+f)[6:]) for k in ml: with zipfile.ZipFile(k,"r") as jf: for e in jf.namelist(): if (e[-1] not in "\\/" and e.lower()[:8]!="meta-inf"): print(f"Writing: {e}") zf.writestr(e,jf.read(e)) if ("--run" in sys.argv): subprocess.run(["java","-Dfile.encoding=UTF8","-jar","build/$$$NAME$$$.jar"]) <file_sep># $$$PRETTY_TITLE$$$ <file_sep>#include <$$$NAME$$$.h> int main(int argc,const char** argv){ (void)argc; (void)argv; return 0; } <file_sep>#include <$$$NAME$$$.h> <file_sep>queries: - include: "*" - exclude: cpp/poorly-documented-function - exclude: cpp/short-global-name - exclude: cpp/use-of-goto - exclude: py/empty-except - exclude: py/redundant-global-declaration extraction: cpp: prepare: packages: - python3.8 index: build_command: - python3.8 build.py python: python_setup: version: 3 <file_sep>#ifndef __$$$UPPERCASE_NAME$$$_H__ #define __$$$UPPERCASE_NAME$$$_H__ 1 // #endif
7bfcdb29aa038add5f1f10a037c92322a7f5efc9
[ "Shell", "C", "Markdown", "Assembly", "Batchfile", "YAML", "JavaScript", "Python", "C++" ]
11
Shell
Krzem5/Boot_Program
0f4686e106e3cc3b4af31fc05b66e2114e54a34e
6c8494facdf27aee4a39a8d825ca9a017c85ca43
refs/heads/master
<file_sep>EI_VSN = 3.11.3 ERL_INTERFACE_VSN = $(EI_VSN) <file_sep>ELDAP_VSN = 1.2.7 <file_sep>SSL_VSN = 9.2.3 <file_sep>PUBLIC_KEY_VSN = 1.6.6 <file_sep>STDLIB_VSN = 3.8.2
edb3a424223d98ac150b44a425a4cf4dd3353a64
[ "Makefile" ]
5
Makefile
hygonsoc/otp
b4592035dd987e3a615c1219a47988ed51e8e6e5
adf031d8b750580ad9cfe8285583eed149d55ed7
refs/heads/master
<file_sep>## vdom ```js npm install npm run compile ``` open index.html<file_sep>const CREATE = 'CREATE' const REMOVE = 'REMOVE' const REPLACE = 'REPLACE' const UPDATE = 'UPDATE' const SET_PROP = 'SET_PROP' const REMOVE_PROP = 'REMOVE PROP' //// DIFF function changed(node1, node2) { } function diffProps(newNode, oldNode) { } function diffChildren(newNode, oldNode) { } function diff(newNode, oldNode) { //@ } //// PATCH function createElement(node) { //@ if (typeof node === 'string') { return document.createTextNode(node) } const el = document.createElement(node.type) setProps(el, node.props) node.children .map(createElement) .forEach(el.appendChild.bind(el)) return el } function setProp(target, name, value) { //@ } function setProps(target, props) { } function removeProp(target, name, value) { //@ } function patchProps(parent, patches) { } function patch(parent, patches, index = 0) { //@ } //// My Application function flatten(arr) { return [].concat.apply([], arr) } function h(type, props, ...children) { props = props || {} return { type, props, children: flatten(children) } } function view(count) { //@ return <ul id="cool" className="foo"> <li className="test">text 1</li> <li>text 2</li> </ul> } function tick(el, count) { } function render(el) { el.appendChild(createElement(view(0))) }
a6e62cf2336d44ecc36aaa105d6c131b0f638f04
[ "Markdown", "JavaScript" ]
2
Markdown
ranrantu/vdom
359c85d789a78b27e57e38d328f422acc3c29fd7
10a9889581a3480c097ed1d675f72974cd82d499
refs/heads/main
<repo_name>chernyshevdv/pypatch3<file_sep>/api/deployment/Dockerfile FROM python:3.8-slim WORKDIR /code COPY ../requirements.txt . RUN apt-get install sqlite3 RUN pip install -r requirements.txt COPY deployment.py . COPY deployment.sql . RUN sqlite3 pypach.sqlite < deployment.sql CMD ["python","deployment.py"]<file_sep>/api/deployment/deployment.sql CREATE TABLE deployment ( id INTEGER PRIMARY KEY, title TEXT UNIQUE, excel_columns TEXT, excel_header_row INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE cycle ( id INTEGER PRIMARY KEY, deployment_id INTEGER NOT NULL, title TEXT NOT NULL, started DATETIME, rag char, status_update TEXT, is_active BOOLEAN, excel_columns TEXT, excel_header_row INTEGER, FOREIGN KEY (deployment_id) REFERENCES deployment(id) ON DELETE CASCADE ); CREATE TABLE report ( id INTEGER PRIMARY KEY, cycle_id INTEGER NOT NULL, udpated DATETIME NOT NULL, show_in_history TEXT(3) NOT NULL DEFAULT 'yes', FOREIGN KEY (cycle_id) REFERENCES cycle (id) ON DELETE CASCADE );<file_sep>/api/deployment/deployment.py import sqlite3 from flask import Flask, json, jsonify, redirect, g deployment = Flask(__name__) def get_db(): """ Opens DB connection if it's not open yet """ if not hasattr(g, 'db_conn'): g.db_conn = sqlite3.connect("pypatch.sqlite") g.db_conn.row_factory = sqlite3.Row return g.db_conn @deployment.route('/deployment/<id>', methods=['GET']) def read(id): m_sql = "SELECT * FROM deployment WHERE id=:id" m_rs = get_db().execute(m_sql, {"id": id}).fetchone() if m_rs is None: return jsonify(success=False, error=f"Deployment {id} is not found"), 404 else: return jsonify(dict(m_rs)) @deployment.route('/deployment/<title>', methods=['PUT']) def create(title): m_sql = "INSERT INTO deployment (title) VALUES (:title)" conn = get_db() conn.execute(m_sql, {"title": title}) conn.commit() m_rs = conn.execute("SELECT id FROM deployment WHERE title=:title", {"title": title}).fetchone() if m_rs is None: return jsonify(success=False, error=f"User {title} has not been created") else: m_id = m_rs[0] return redirect(f"/deployment/{m_id}") if __name__ == "__main__": deployment.run(host="0.0.0.0") <file_sep>/README.md # pypatch3 ## application architecture ![architecture](images/pypatch3_architecture.png) ## Design decisions - User authentication (authN) and authorization (authZ) is performed in web frontend. API services are auth-free. - Due to the decision above, API should not be exposed outside container network - Maria DB with MyISAM engine is to be used as datasource, as it's an open source product. Previous version (pypatch2) utilized SQLite as datasource, but with introduction of microservices, we need a server to serve concurrent connections. - Every module in API has its own directory to contain its own `Dockerfile` - `venv` dir resides in `pypatch3` dir, launch `vscode` there. ## Directory structure ``` pypatch3 +- api +- deployment -- Dockerfile +- user -- Dockerfile +- web -- Dockerfile +- venv -- docker-compose.yml -- requirements.txt ``` ## API modules ### ad ### user Manages users and logins, provides both authN and authZ. The following endpoints are available: - `/user/authn/<login>` GET gets {password} in JSON parameter and returns True if the user exists - `/user/authz/<login>/<group>` GET returns True if the user with `login` is a member of the `group` - `/user/<login>` GET returns a JSON representation of a user - `/user/<login>` POST updates a user info in DB. - `/user/<login>` DELETE deletes a user - `/user/<login>` PUT creates a new user getting user info from JSON submitted as a parameter. Returns an error if such user exists already - `/user/register` POST gets {login, email, password} parameters, checks if such "login-email" pair exists in `user` table, on success it creates a correspondent login record (unauthorized yet) and stores a hash of the password. - `/user/approve` POST gets {login, authz_login} parameters, checks if authz_login is a member of "login_approvers" group and records "approved_by" field ### deployment Manages deployments, cycles, and reports. Handles upload of excel and CSV data into the database. ### asset Manages assets and asset reports. Handles upload of excel and CSV data into the database. ### reporting ### kpi
b79df349d95c09f9066fe51537b7f1b0e8df3e3b
[ "Markdown", "SQL", "Dockerfile", "Python" ]
4
Markdown
chernyshevdv/pypatch3
1a423dfa1ccee7393b992f71fd9a1c50fbf35ba4
eabd1c3c1388667e7fa28057bc976e99d08fc6f8
refs/heads/master
<repo_name>Jslota25/random-password-generator<file_sep>/script.js // Assignment Code var generateBtn = document.querySelector("#generate"); // Write password to the #password input function writePassword() { var password = generatePassword(); var passwordText = document.querySelector("#password"); passwordText.value = password; } // Add event listener to generate button generateBtn.addEventListener("click", writePassword); //Initial Prompt function generatePassword() { var length = "How many characters do you want your password to be? (Must be between 8 and 128."; var lengthValue; while (true) { lengthValue = parseInt(prompt(length)); if (lengthValue >= 8 && lengthValue <= 128) { break; } { alert ("You must choose a password length between 8 and 128 characters"); lengthValue = prompt(length); } } //Password character criteria var lower = confirm("Do you want lower case letters?"); var upper = confirm("Do you want upper case letters?"); var number = confirm("Do you want numbers?"); var special = confirm("Do you want special characters?"); var lowerChar = "abcdefghijklmnopqrstuvwxyz"; var upperChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var numberChar = "0123456789"; var specChar = "!@#$%^&*()"; var pwChar = []; //If statements for password character criteria if (lower) { for(var i = 0; i < lowerChar.length; i++) { pwChar.push(lowerChar.charAt(i)); } } if (upper) { for(var i = 0; i < upperChar.length; i++) { pwChar.push(upperChar.charAt(i)); } } if (number) { for(var i = 0; i < numberChar.length; i++) { pwChar.push(numberChar.charAt(i)); } } if (special) { for(var i = 0; i < specChar.length; i++) { pwChar.push(specChar.charAt(i)); } } console.log(pwChar); //Generate and print password var password = ""; while(password.length < lengthValue) { password += pwChar[Math.floor(Math.random() * pwChar.length)]; } console.log(password); return password; } <file_sep>/README.md # Random Password Generator Random Password Generator Javacript HW Assignment # Contributors @Jslota25 # Tech HTML, CSS, Javascript # About This is a program that generates a random password with certain characters based on criteria asked within prompts and confirm statements. # Link <a href ="https://jslota25.github.io/random-password-generator">jslota25.github.io/random-password-generator</a> # Contact Email: <a href="mailto:<EMAIL>"><EMAIL></a> <br> Github: <a href="https://github.com/Jslota25">github.com/Jslota25</a> <br> LinkedIn: <a href="https://www.linkedin.com/in/john-slota-83b432165/">linkedin.com/in/john-slota83b432165</a>
1bf21abcb8d39b39819c8537453aeb92d057c83d
[ "Markdown", "JavaScript" ]
2
Markdown
Jslota25/random-password-generator
d88e1861f89902bf91275768f8c55ac1feb17757
21a8709a391185844c5f11b2c666be27f1a1ef10
refs/heads/master
<repo_name>ytjd926/common<file_sep>/app/build.gradle apply plugin: 'com.android.library' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode rootProject.ext.versionCode versionName rootProject.ext.versionName javaCompileOptions { annotationProcessorOptions { includeCompileClasspath = true } } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile "com.android.support:appcompat-v7:${supportVersion}" compile "com.android.support:design:${supportVersion}" compile "com.android.support:support-v4:${supportVersion}" compile 'com.android.volley:volley:1.1.0' compile 'com.koushikdutta.async:androidasync:2.2.1' // Retrofit + RxJava + OkHttp // Start compile 'com.squareup.retrofit2:retrofit:2.3.0'//retrofit compile 'com.squareup.okhttp3:logging-interceptor:3.4.1' // OkHttp日志输出 //下面两个是RxJava 和RxAndroid compile 'io.reactivex.rxjava2:rxjava:2.1.9' compile 'io.reactivex.rxjava2:rxandroid:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.3.0'//转换器,请求结果转换成Model compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'//配合Rxjava 使用 // End compile 'com.github.bumptech.glide:glide:4.1.1' annotationProcessor 'com.github.bumptech.glide:compiler:4.1.1' compile 'com.j256.ormlite:ormlite-core:4.48' compile 'com.j256.ormlite:ormlite-android:4.48' compile 'com.jakewharton:butterknife:7.0.1' compile 'com.google.code.gson:gson:2.8.1' compile 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.34' compile 'com.github.devlight.navigationtabstrip:navigationtabstrip:1.0.4' compile 'com.flyco.tablayout:FlycoTabLayout_Lib:2.1.2@aar' compile 'com.github.PhilJay:MPAndroidChart:v3.0.3' compile 'me.iwf.photopicker:PhotoPicker:0.9.12@aar' compile 'com.github.yalantis:ucrop:2.2.1-native' compile 'top.zibin:Luban:1.1.3' implementation('com.werb.permissionschecker:permissionschecker:0.0.1-beta2', { exclude group: 'com.android.support' }) compile 'cn.bingoogolapple:bga-qrcode-zbar:1.2.1' compile 'cn.bingoogolapple:bga-qrcode-zxing:1.2.1' compile project(':serialport') } <file_sep>/app/src/main/java/com/tangjd/common/widget/RvBase.java package com.tangjd.common.widget; import android.content.Context; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.tangjd.common.R; import java.util.ArrayList; import java.util.List; /** * Created by tangjd on 2016/9/23. */ public abstract class RvBase<T> extends RecyclerView { public View mLoadingView, mEmptyView, mErrorView; public RvBase(Context context) { this(context, null); } public RvBase(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public RvBase(Context context, @Nullable AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER); } public void init(Context context) { setLayoutManager(customSetLayoutManager(context)); mAdapter = instanceCustomAdapter(); setAdapter(mAdapter); mLoadingView = LayoutInflater.from(context).inflate(R.layout.rv_loading_layout, this, false); mEmptyView = LayoutInflater.from(context).inflate(R.layout.rv_empty_data_layout, this, false); mErrorView = LayoutInflater.from(context).inflate(R.layout.rv_error_layout, this, false); } public void setEmptyViewText(String content, boolean withRetryTip) { setEmptyViewText(content, withRetryTip, 0); } public void setEmptyViewText(String content, boolean withRetryTip, int drawableTopResId) { if (withRetryTip) { content = content + "\n点击屏幕重试"; } TextView textView = ((TextView) mEmptyView.findViewById(R.id.tv_msg)); if (textView != null) { textView.setText(content); if (drawableTopResId != 0) { textView.setCompoundDrawablesWithIntrinsicBounds(0, drawableTopResId, 0, 0); textView.setCompoundDrawablePadding(30); } } } public void setLoadingViewText(String content) { if (!TextUtils.isEmpty(content)) { TextView textView = ((TextView) mLoadingView.findViewById(R.id.tv_msg)); if (textView != null) { textView.setText(content); } } } public void setErrorViewText(String content, boolean withRetryTip) { if (withRetryTip) { content = content + "\n点击屏幕重试"; } TextView textView = ((TextView) mErrorView.findViewById(R.id.tv_msg)); if (textView != null) { textView.setText(content); } } public BaseQuickAdapter<T, BaseViewHolder> instanceCustomAdapter() { return new CustomAdapter(customSetItemLayoutId()); } public abstract LayoutManager customSetLayoutManager(Context context); public abstract int customSetItemLayoutId(); public abstract void customConvert(BaseViewHolder holder, T bean); public void setData(List<T> data) { mAdapter.setNewData(data); if (data == null || data.size() == 0) { showEmptyView(); } } public void addData(T bean) { List<T> newData = new ArrayList<>(); newData.add(bean); addData(newData); } public void addData(List<T> data) { mAdapter.addData(data); } public BaseQuickAdapter<T, BaseViewHolder> mAdapter; public class CustomAdapter extends BaseQuickAdapter<T, BaseViewHolder> { public CustomAdapter(int resId) { super(resId, null); } @Override protected void convert(BaseViewHolder baseViewHolder, T t) { customConvert(baseViewHolder, t); } } public void showLoadingView() { mAdapter.setEmptyView(mLoadingView); } public void showEmptyView() { mAdapter.setEmptyView(mEmptyView); } // public void showErrorView() { // mAdapter.setEmptyView(mErrorView); // } public void showLoadingView(String content) { setLoadingViewText(content); mAdapter.setEmptyView(mLoadingView); } public void showEmptyView(String content, boolean withRetryTip) { setEmptyViewText(content, withRetryTip); mAdapter.setEmptyView(mEmptyView); } public void showErrorView(String content, boolean withRetryTip) { setErrorViewText(content, withRetryTip); mAdapter.setEmptyView(mErrorView); } public void clearEmptyView() { mAdapter.setEmptyView(new View(getContext())); } public void setOnEmptyViewClickListener(OnClickListener listener) { mEmptyView.setOnClickListener(listener); mErrorView.setOnClickListener(listener); } public void onGetDataSuccess(List<T> beans) { setData(beans); if (beans == null) { // showErrorView("数据出错", true); showEmptyView(); } else if (beans.size() == 0) { showEmptyView(); } else { clearEmptyView(); } } public void onGetDataSuccess(boolean hasMore, List<T> beans) { setHasMore(hasMore); onGetDataSuccess(beans); } public void onGetDataSuccess(boolean hasMore, List<T> beans, BaseQuickAdapter.RequestLoadMoreListener loadMoreListener) { setHasMore(hasMore); onGetDataSuccess(beans); if (hasMore) { mAdapter.setOnLoadMoreListener(loadMoreListener); } } public void onGetDataFail(String content, boolean withRetryTip) { showErrorView(content, withRetryTip); } public void onLoadMoreSuccess(List<T> beans) { if (beans == null) { mAdapter.loadMoreFail(); } else if (beans.size() == 0) { mAdapter.loadMoreEnd(); } else { addData(beans); mAdapter.loadMoreComplete(); } } public void onLoadMoreSuccess(boolean hasMore, List<T> beans) { setHasMore(hasMore); onLoadMoreSuccess(beans); } public void onLoadMoreFail() { mAdapter.loadMoreFail(); } public void onLoadMoreFail(String error) { mAdapter.loadMoreFail(); Toast.makeText(getContext(), error + "", Toast.LENGTH_LONG).show(); } public void setHasMore(boolean hasMore) { if (hasMore) { mAdapter.loadMoreEnd(false); } else { mAdapter.loadMoreEnd(true); } } } <file_sep>/app/src/main/java/com/tangjd/common/helper/BleSignInHelper.java //package com.tangjd.common.helper; // //import android.annotation.TargetApi; //import android.app.Activity; //import android.bluetooth.BluetoothAdapter; //import android.bluetooth.BluetoothDevice; //import android.bluetooth.BluetoothManager; //import android.content.Context; //import android.content.Intent; //import android.content.pm.PackageManager; //import android.os.Build; //import android.os.Bundle; //import android.os.Handler; //import android.util.Log; // //import com.tangjd.common.abs.BaseActivity; //import com.tangjd.common.abs.PermissionManager; //import com.tangjd.common.utils.StringUtil; // ///** // * Created by tangjd on 2016/9/26. // */ // //@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) //public class BleSignInHelper extends BaseActivity { // private BluetoothAdapter mBluetoothAdapter; // private boolean mSigningIn; // private Handler mHandler = new Handler(); // public static int RSSI_ULTIMATE_VALUE = -40; // public static final int REQUEST_CODE_ENABLE_BT = 1000; // // // Device scan callback. // private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { // @Override // public void onLeScan(final BluetoothDevice device, final int rssi, byte[] data) { // if (rssi < RSSI_ULTIMATE_VALUE) { // return; // } // Log.e("TTT", "----------Rssi:" + rssi + " " + device.getAddress() + " " + device.getName()); // String filterMac = getFilterMac(); // if (!StringUtil.isEmpty(filterMac) && !device.getAddress().equalsIgnoreCase(filterMac)) { // return; // } // if (!isSigningIn()) { // setSigningIn(true); // BtBean bean = new BtBean(); // bean.mDeviceName = device.getName(); // bean.mMajor = (data[25] << 8 & 65280) + (data[26] & 255); // bean.mMinor = (data[27] << 8 & 65280) + (data[28] & 255); // bean.mMac = device.getAddress(); // bean.mRssi = rssi; // Log.e("TTT", "Rssi:" + rssi + " | " + bean.mDeviceName + " | " + bean.mMac + " | " + bean.mMajor + " | " + bean.mMinor); // mBluetoothAdapter.stopLeScan(this); // processLogin(device, bean); // } // } // }; // // public String getFilterMac() { // return null; // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // // Use this check to determine whether BLE is supported on the device. Then you can // // selectively disable BLE-related features. // if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { // showTipDialog("此设备不支持BLE", false, null); // return; // } // // // Initializes a Bluetooth adapter. For API level 18 and above, get a reference to // // BluetoothAdapter through BluetoothManager. // final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); // mBluetoothAdapter = bluetoothManager.getAdapter(); // // // Checks if Bluetooth is supported on the device. // if (mBluetoothAdapter == null) { // showTipDialog("此设备不支持蓝牙", false, null); // return; // } // } // // @Override // protected void onResume() { // super.onResume(); // mHandler.postDelayed(new Runnable() { // @Override // public void run() { // PermissionManager.mayRequestAccessFineLocation(BleSignInHelper.this); // // Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled, // // fire an intent to display a dialog asking the user to grant permission to enable it. // if (!mBluetoothAdapter.isEnabled()) { // if (!mBluetoothAdapter.isEnabled()) { // Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // startActivityForResult(enableBtIntent, REQUEST_CODE_ENABLE_BT); // } // } // if (!isSigningIn()) { // mBluetoothAdapter.startLeScan(mLeScanCallback); // } // } // }, 1000); // } // // @Override // protected void onPause() { // super.onPause(); // mBluetoothAdapter.stopLeScan(mLeScanCallback); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // // User chose not to enable Bluetooth. // if (requestCode == REQUEST_CODE_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) { // showTipDialog("蓝牙已被禁止打开"); // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // public void processLogin(BluetoothDevice bluetoothDevice, BtBean bean) { // } // // public void setSigningIn(boolean signingIn) { // mSigningIn = signingIn; // } // // private boolean isSigningIn() { // return mSigningIn; // } // // public void restartScan() { // mHandler.postDelayed(new Runnable() { // @Override // public void run() { // setSigningIn(false); // mBluetoothAdapter.startLeScan(mLeScanCallback); // } // }, 500); // } // // public class BtBean { // public String mDeviceName; // public int mMajor; // public int mMinor; // public String mMac; // public int mRssi; // } //} <file_sep>/app/src/main/java/com/tangjd/rs485/util/ByteUtil.java package com.tangjd.rs485.util; public class ByteUtil { public static String bytes2HexStr(byte[] src) { StringBuilder builder = new StringBuilder(); if (src == null || src.length <= 0) { return ""; } char[] buffer = new char[2]; for (int i = 0; i < src.length; i++) { buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16); buffer[1] = Character.forDigit(src[i] & 0x0F, 16); builder.append(buffer); } return builder.toString().toUpperCase(); } public static String bytes2HexStr(byte[] src, int dec, int length) { byte[] temp = new byte[length]; System.arraycopy(src, dec, temp, 0, length); return bytes2HexStr(temp); } } <file_sep>/app/src/main/java/com/tangjd/common/widget/IdentifyView.java package com.tangjd.common.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import com.tangjd.common.R; import com.tangjd.common.utils.DisplayUtils; /** * 验证码控件 */ public class IdentifyView extends View { private String mVerifyCode = null; private Paint mPaint = new Paint(); private final int mPointNum; private final int mLineNum; private final int mTextLength; private final float mTextSize; private final int mTextColor; private final int mBgColor; public IdentifyView(Context context) { this(context, null); } public IdentifyView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public IdentifyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IdentifyView); // 获取随机点的个数 mPointNum = a.getInteger(R.styleable.IdentifyView_identify_point_num, 100); // 获取随机线的条数 mLineNum = a.getInteger(R.styleable.IdentifyView_identify_line_num, 5); // 获取验证码长度 mTextLength = a.getInteger(R.styleable.IdentifyView_identify_text_length, 4); // 获取验证码字体大小 mTextSize = a.getDimension(R.styleable.IdentifyView_identify_text_size, DisplayUtils.spToPx(16, context)); // 获取验证码字体颜色 mTextColor = a.getColor(R.styleable.IdentifyView_identify_text_color, Color.BLACK); // 获取背景颜色 mBgColor = a.getColor(R.styleable.IdentifyView_identify_bg_color, Color.WHITE); a.recycle(); mPaint.setAntiAlias(true); mPaint.setTextSize(mTextSize); mPaint.setStrokeWidth(3); mPaint.setColor(mTextColor); mVerifyCode = makeVerifyCode(); } @Override public void onDraw(Canvas canvas) { // 生成验证码 // 设置二维码背景色 canvas.drawColor(mBgColor); final int height = getHeight(); // 获得CheckView控件的高度 final int width = getWidth(); // 获得CheckView控件的宽度 int dx = width / mTextLength / 2; char[] checkNum = mVerifyCode.toCharArray(); for (int i = 0; i < mTextLength; i++) { // 绘制验证控件上的文本 canvas.drawText("" + checkNum[i], dx, getPosition(height), mPaint); dx += width / (mTextLength + 1); } int[] line; for (int i = 0; i < mLineNum; i++) { // 划线 line = getLine(height, width); canvas.drawLine(line[0], line[1], line[2], line[3], mPaint); } // 绘制小圆点 int[] point; for (int i = 0; i < mPointNum; i++) { // 画点 point = getPoint(height, width); canvas.drawCircle(point[0], point[1], 1, mPaint); } } /** * 生成新的验证码 */ public void updateVerifyCode() { mVerifyCode = makeVerifyCode(); invalidate(); } public String getVerifyCode() { return mVerifyCode; } /** * Make new random verify code * * @return new verify code */ private String makeVerifyCode() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < mTextLength; i++) { int temp = (int) (Math.random() * 10); sb.append(temp); } return sb.toString(); } /** * 验证码绘制的y点,保证绘制的视图内 * * @param height IdentifyView的高度 */ private int getPosition(int height) { int position = (int) (Math.random() * height); if (position < mTextSize) { position += mTextSize; } if (position > height) { position = height; } return position; } /** * 随机产生划线的起始点坐标和结束点坐标 * * @param height 控件的高 * @param width 控件的宽 * @return 起始点坐标和结束点坐标 */ public static int[] getLine(int height, int width) { int[] tempCheckNum = {0, 0, 0, 0}; for (int i = 0; i < 4; i += 2) { tempCheckNum[i] = (int) (Math.random() * width); tempCheckNum[i + 1] = (int) (Math.random() * height); } return tempCheckNum; } /** * 随机产生点的圆心点坐标 * * @param height 控件的高 * @param width 控件的宽 */ public static int[] getPoint(int height, int width) { int[] tempCheckNum = {0, 0, 0, 0}; tempCheckNum[0] = (int) (Math.random() * width); tempCheckNum[1] = (int) (Math.random() * height); return tempCheckNum; } } <file_sep>/app/src/main/java/com/tangjd/common/helper/BleScanHelper.java /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tangjd.common.helper; import android.Manifest; import android.annotation.TargetApi; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanResult; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.tangjd.common.abs.BaseActivity; import java.util.List; /** * Activity for scanning and displaying available Bluetooth LE devices. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public abstract class BleScanHelper extends BaseActivity { private BluetoothAdapter mBluetoothAdapter; private boolean mScanning; private Handler mBackHandler; private HandlerThread mBackThread; private static final int REQUEST_ENABLE_BT = 1; private ConnectState mState = ConnectState.STATE_NONE; // private static final int SCAN_PERIOD = 20 * 1000; // private static final int SCAN_INTERVAL = 2 * 1000; public enum ConnectState { STATE_NONE("无连接"), // we're doing nothing STATE_LISTEN("监听中"), // now listening for incoming connections STATE_CONNECTING("连接中"), // now initiating an outgoing connection STATE_CONNECTED("已连接"), // now connected to a remote device STATE_DISCONNECTED("已断开"), STATE_CONNECTION_FAILED("连接失败"); // now connected to a remote device public String mDesc; ConnectState(String desc) { mDesc = desc; } } public void setState(ConnectState state) { mState = state; if (state == ConnectState.STATE_NONE || state == ConnectState.STATE_LISTEN || state == ConnectState.STATE_CONNECTION_FAILED || state == ConnectState.STATE_DISCONNECTED) { scanLeDevice(true); } else if (state == ConnectState.STATE_CONNECTING || state == ConnectState.STATE_CONNECTED) { scanLeDevice(false); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBackThread = new HandlerThread("BleScanResultThread"); mBackThread.start(); mBackHandler = new Handler(mBackThread.getLooper()); // Use this check to determine whether BLE is supported on the device. Then you can // selectively disable BLE-related features. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { showTipDialog("此设备不支持BLE", false, null); return; } // // Initializes a Bluetooth adapter. For API level 18 and above, get a reference to // // BluetoothAdapter through BluetoothManager. // final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); // if (bluetoothManager == null) { // showTipDialog("此设备不支持蓝牙", false, null); // return; // } // mBluetoothAdapter = bluetoothManager.getAdapter(); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // Checks if Bluetooth is supported on the device. if (mBluetoothAdapter == null) { showTipDialog("此设备不支持蓝牙", false, null); return; } mFilterDeviceNameContains = getFilterDeviceName(); mFilterRssi = getFilterRssi(); mayRequestPermission(new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN }, new PermissionRequestCallback() { @Override public void onSuccess() { if (mBluetoothAdapter.enable()) { scanLeDevice(true); } else { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } }); } @Override protected void onDestroy() { super.onDestroy(); scanLeDevice(false); } // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case R.id.menu_scan: // mLeDeviceListAdapter.clear(); // scanLeDevice(true); // break; // case R.id.menu_stop: // scanLeDevice(false); // break; // } // return true; // } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == RESULT_CANCELED) { Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_SHORT).show(); } else if (resultCode == RESULT_OK) { scanLeDevice(true); } } } // @Override // protected void onListItemClick(ListView l, View v, int position, long id) { // final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position).mLeDevices; // if (device == null) return; // final Intent intent = new Intent(this, DeviceControlActivity.class); // intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName()); // intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress()); // if (mScanning) { // mBluetoothAdapter.stopLeScan(mLeScanCallback); // mScanning = false; // } // startActivity(intent); // } // private Handler mHandler = new Handler(); // private Runnable mScanPeriodRunnable = new Runnable() { // @Override // public void run() { // scanLeDevice(false); // try { // Thread.sleep(SCAN_INTERVAL); // } catch (InterruptedException e) { // e.printStackTrace(); // } // scanLeDevice(true); // } // }; public void scanLeDevice(final boolean enable) { if (mScanning && enable) { return; } if (!mScanning && !enable) { return; } if (enable) { // mHandler.removeCallbacks(mScanPeriodRunnable); // mHandler.postDelayed(mScanPeriodRunnable, SCAN_PERIOD); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { mScanning = true; mBluetoothAdapter.startLeScan(mLeScanCallback); } else { mScanning = true; mBluetoothAdapter.getBluetoothLeScanner().startScan(mScanCallback); } } else { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { mScanning = false; mBluetoothAdapter.stopLeScan(mLeScanCallback); } else { mScanning = false; mBluetoothAdapter.getBluetoothLeScanner().stopScan(mScanCallback); } } invalidateOptionsMenu(); } private ScanCallback mScanCallback = new ScanCallback() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onScanResult(int callbackType, final ScanResult result) { super.onScanResult(callbackType, result); mBackHandler.post(new Runnable() { @Override public void run() { boolean filterRssi = (mFilterRssi != 0); boolean filterDeviceName = (!TextUtils.isEmpty(mFilterDeviceNameContains)); boolean filterRssiMatch = false; if (filterRssi) { filterRssiMatch = (result.getRssi() > mFilterRssi); } boolean filterDeviceNameMatch = false; if (filterDeviceName) { filterDeviceNameMatch = ((!TextUtils.isEmpty(result.getDevice().getName())) && (result.getDevice().getName().toLowerCase().contains(mFilterDeviceNameContains.toLowerCase()))); } if ((filterRssi && (!filterRssiMatch)) || (filterDeviceName && (!filterDeviceNameMatch))) { return; } parse(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes()); } }); } @Override public void onBatchScanResults(List<ScanResult> results) { super.onBatchScanResults(results); } @Override public void onScanFailed(int errorCode) { super.onScanFailed(errorCode); } }; // Device scan callback. private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) { mBackHandler.post(new Runnable() { @Override public void run() { boolean filterRssi = (mFilterRssi != 0); boolean filterDeviceName = (!TextUtils.isEmpty(mFilterDeviceNameContains)); boolean filterRssiMatch = false; if (filterRssi) { filterRssiMatch = (rssi > mFilterRssi); } boolean filterDeviceNameMatch = false; if (filterDeviceName) { filterDeviceNameMatch = ((!TextUtils.isEmpty(device.getName())) && (device.getName().toLowerCase().contains(mFilterDeviceNameContains.toLowerCase()))); } if ((filterRssi && (!filterRssiMatch)) || (filterDeviceName && (!filterDeviceNameMatch))) { return; } parse(device, rssi, scanRecord); } }); } }; private void parse(final BluetoothDevice device, final int rssi, final byte[] scanRecord) { runOnUiThread(new Runnable() { @Override public void run() { Log.e("TTTTTT", "----------Rssi:" + rssi + " " + device.getAddress() + " " + device.getName() + " " + ((scanRecord[27] << 8 & 65280) + (scanRecord[28] & 255))); processLogin(device, rssi, scanRecord, (scanRecord[25] << 8 & 65280) + (scanRecord[26] & 255), (scanRecord[27] << 8 & 65280) + (scanRecord[28] & 255)); } }); } public String mFilterDeviceNameContains; public int mFilterRssi; public abstract String getFilterDeviceName(); public abstract int getFilterRssi(); public abstract void processLogin(BluetoothDevice device, int rssi, byte[] scanRecord, int major, int minor); }<file_sep>/app/src/main/java/com/tangjd/common/abs/JsonApiBaseBackUp.java //package com.tangjd.common.abs; // //import android.text.TextUtils; // //import com.android.volley.AuthFailureError; //import com.android.volley.Request; //import com.android.volley.Response; //import com.android.volley.VolleyError; //import com.android.volley.toolbox.JsonObjectRequest; //import com.tangjd.common.manager.VolleyManager; //import com.tangjd.common.utils.Log; // //import org.json.JSONObject; // //import java.io.UnsupportedEncodingException; //import java.net.URLEncoder; //import java.util.Map; // ///** // * Created by tangjd on 2016/8/8. // */ //public class JsonApiBaseBackUp { // public static final String TAG = "Api"; // // public static Request doGetRequest(String url, OnJsonResponseListener listener) { // return doGetRequest(url, null, null, listener); // } // // public static Request doGetRequest(String url, Map<String, String> params, OnJsonResponseListener listener) { // return doGetRequest(url, params, null, listener); // } // // public static Request doGetRequest(String url, Map<String, String> params, Map<String, String> headers, OnJsonResponseListener listener) { // if (params != null && params.size() != 0) { // String paramsStr = ""; // for (Map.Entry<String, String> entry : params.entrySet()) { // try { // paramsStr = paramsStr + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8") + "&"; // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // } // paramsStr = paramsStr.substring(0, paramsStr.length() - 1); // url = url + "?" + paramsStr; // } // return doRequest(Request.Method.GET, url, null, headers, listener); // } // // public static Request doPostRequest(String url, JSONObject params, OnJsonResponseListener listener) { // return doRequest(Request.Method.POST, url, params, listener); // } // // public static Request doPostRequest(String url, JSONObject params, Map<String, String> headers, OnJsonResponseListener listener) { // return doRequest(Request.Method.POST, url, params, headers, listener); // } // // private static Request doRequest(int method, final String url, final JSONObject params, final OnJsonResponseListener listener) { // return doRequest(method, url, params, null, listener); // } // // public static Request doRequest(int method, final String url, final JSONObject params, final Map<String, String> headers, final OnJsonResponseListener listener) { // if (TextUtils.isEmpty(url)) { // return null; // } // JsonObjectRequest request = new JsonObjectRequest(method, url, params, new Response.Listener<JSONObject>() { // @Override // public void onResponse(JSONObject response) { // Log.w(TAG, "----------------"); // Log.i(TAG, url // + "\n headers " + (headers == null ? null : headers.toString()) // + "\n params " + (params == null ? null : params.toString()) // + "\n resp " + response); // Log.w(TAG, "----------------"); // if (listener != null) { // listener.onFinish(true); // listener.onResponse(response); // } // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // Log.w(TAG, "----------------"); // Log.e(TAG, url // + "\n headers " + (headers == null ? null : headers.toString()) // + "\n params " + (params == null ? null : params.toString()) // + "\n error " + error); // if (listener != null) { // listener.onFinish(false); // listener.onError(parseVolleyError(error)); // } // Log.w(TAG, "----------------"); // } // }) { // @Override // public Map<String, String> getHeaders() throws AuthFailureError { // if (headers == null) { // return super.getHeaders(); // } // return headers; // } // }; // VolleyManager.getInstance().getRequestQueue().add(request); // return request; // } // // public interface OnJsonResponseListener { // void onResponse(JSONObject response); // // void onError(String error); // // void onFinish(boolean withoutException); // } // // private static String parseVolleyError(VolleyError error) { // try { // String errorDataStr = new String(error.networkResponse.data); // Log.e(TAG, "errorData " + errorDataStr); // return errorDataStr + " " + error.networkResponse.statusCode; // } catch (Exception e) { // return "连接失败"; // } // } //} <file_sep>/app/src/main/java/com/tangjd/common/mpchart/barchart/BarChartHelper.java package com.tangjd.common.mpchart.barchart; import android.content.Context; import android.graphics.RectF; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.github.mikephil.charting.utils.MPPointF; import com.tangjd.common.R; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; /** * Created by tangjd on 2018/2/2. */ public class BarChartHelper { private Context mContext; private BarChart mChart; private RectF mOnValueSelectedRectF = new RectF(); private int mBarColor; public BarChartHelper(Context context, BarChart barChart) { mContext = context; mChart = barChart; } /** * @param unit 单位 * @param showXAxisLabelCount x坐标label显示的个数,如:共30个柱状图形,可以设置显示10个label等,使显示效果不至于太密集 * @param xAxisLabelFormatter x坐标label需要显示的内容可以自定义, * 回调如下: * public String getFormattedValue(float value, AxisBase axis) { * } * 注意value的起始值为1! */ public void initBarChart(String unit, int showXAxisLabelCount, IAxisValueFormatter xAxisLabelFormatter) { initBarChart(unit, showXAxisLabelCount, mContext.getResources().getColor(R.color.colorPrimary), xAxisLabelFormatter); } /** * @param unit 单位 * @param showXAxisLabelCount x坐标label显示的个数,如:共30个柱状图形,可以设置显示10个label等,使显示效果不至于太密集 * @param barColor 柱状图形的颜色 * @param xAxisLabelFormatter x坐标label需要显示的内容可以自定义, * 回调如下: * public String getFormattedValue(float value, AxisBase axis) { * } * 注意value的起始值为1! */ public void initBarChart(String unit, int showXAxisLabelCount, int barColor, IAxisValueFormatter xAxisLabelFormatter) { mBarColor = barColor; mChart.setNoDataText("没有数据"); mChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { @Override public void onValueSelected(Entry e, Highlight h) { if (e == null) return; RectF bounds = mOnValueSelectedRectF; mChart.getBarBounds((BarEntry) e, bounds); MPPointF position = mChart.getPosition(e, YAxis.AxisDependency.LEFT); MPPointF.recycleInstance(position); } @Override public void onNothingSelected() { } }); mChart.setDrawBarShadow(false); mChart.setDrawValueAboveBar(true); mChart.getDescription().setEnabled(false); // if more than 60 entries are displayed in the chart, no values will be drawn // mChart.setMaxVisibleValueCount(60); // scaling can now only be done on x- and y-axis separately mChart.setPinchZoom(false); mChart.setDoubleTapToZoomEnabled(false); mChart.setDrawGridBackground(false); // mChart.setDrawYLabels(false); XAxis xAxis = mChart.getXAxis(); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); xAxis.setDrawGridLines(false); xAxis.setGranularity(1f); // only intervals of 1 day xAxis.setLabelCount(showXAxisLabelCount); xAxis.setValueFormatter(xAxisLabelFormatter); // x坐标文字旋转-60度 xAxis.setLabelRotationAngle(-60); IAxisValueFormatter custom = new YAxisLabelFormatter(unit); YAxis leftAxis = mChart.getAxisLeft(); // leftAxis.setLabelCount(8, false); leftAxis.setValueFormatter(custom); leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART); leftAxis.setSpaceTop(15f); leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true) leftAxis.setGridLineWidth(0.6f); YAxis rightAxis = mChart.getAxisRight(); rightAxis.setDrawGridLines(false); // rightAxis.setLabelCount(8, false); rightAxis.setValueFormatter(custom); rightAxis.setSpaceTop(15f); rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true) // 不显示rightAxis rightAxis.setEnabled(false); // 图标底部的说明 Legend l = mChart.getLegend(); l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM); l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER); l.setOrientation(Legend.LegendOrientation.HORIZONTAL); l.setDrawInside(false); l.setForm(Legend.LegendForm.CIRCLE); l.setFormSize(9f); l.setTextSize(11f); l.setXEntrySpace(4f); // 不显示Legend l.setEnabled(false); // l.setExtra(ColorTemplate.VORDIPLOM_COLORS, new String[] { "abc", // "def", "ghj", "ikl", "mno" }); // l.setCustom(ColorTemplate.VORDIPLOM_COLORS, new String[] { "abc", // "def", "ghj", "ikl", "mno" }); // 点击柱状图后的PopupView XYMarkerView mv = new XYMarkerView(mContext, xAxisLabelFormatter, unit); mv.setChartView(mChart); // For bounds control mChart.setMarker(mv); // Set the marker to the chart // setData(12, 50); // // // setting data // mSeekBarY.setProgress(50); // mSeekBarX.setProgress(12); // // mSeekBarY.setOnSeekBarChangeListener(this); // mSeekBarX.setOnSeekBarChangeListener(this); // // // mChart.setDrawLegend(false); } /** * SparseArray<ChartBean> key starts from 1 */ public void setData(List<Float> beans) { ArrayList<BarEntry> yValues = new ArrayList<>(); for (int i = 0; i < beans.size(); i++) { yValues.add(new BarEntry(i + 1, beans.get(i) == null ? 0 : beans.get(i))); } BarDataSet set1; if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) { set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0); set1.setValues(yValues); mChart.getData().notifyDataChanged(); mChart.notifyDataSetChanged(); } else { set1 = new BarDataSet(yValues, ""); set1.setDrawIcons(false); set1.setDrawValues(false); set1.setColors(mBarColor); ArrayList<IBarDataSet> dataSets = new ArrayList<>(); dataSets.add(set1); final BarData data = new BarData(dataSets); data.setValueTextSize(10f); data.setBarWidth(0.9f); mChart.setData(data); mChart.invalidate(); } } public class YAxisLabelFormatter implements IAxisValueFormatter { private DecimalFormat mFormat; private String mUnit; public YAxisLabelFormatter(String unit) { mUnit = unit; mFormat = new DecimalFormat("###,###,###,##0.0"); } @Override public String getFormattedValue(float value, AxisBase axis) { return mFormat.format(value) + " " + mUnit; } } // public class DayAxisValueFormatter implements IAxisValueFormatter { // // @Override // public String getFormattedValue(float value, AxisBase axis) { // if (value > 28) { // return ""; // } // return ((int) value) + "日"; // } // } public void setLabelRotationAngle(float angle) { mChart.getXAxis().setLabelRotationAngle(angle); } } <file_sep>/app/src/main/java/com/tangjd/common/abs/BaseFragment.java package com.tangjd.common.abs; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; /** * Author: tangjd * Date: 2017/8/3 */ public abstract class BaseFragment extends Fragment { protected View mLayoutView; protected boolean mDataLoaded = false; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (mLayoutView == null) { mLayoutView = setContentView(inflater, container); ButterKnife.bind(this, mLayoutView); initView(); } else { ViewGroup parent = (ViewGroup) mLayoutView.getParent(); if (parent != null) { parent.removeView(mLayoutView); } } getDataOnCreateView(); return mLayoutView; } protected abstract View setContentView(LayoutInflater inflater, @Nullable ViewGroup container); protected abstract void initView(); public void getDataOnCreateView() { if (!mDataLoaded) { getDataJustOnce(); mDataLoaded = true; } } protected abstract void getDataJustOnce(); } <file_sep>/app/src/main/java/com/tangjd/common/utils/BinaryUtil.java package com.tangjd.common.utils; /** * Author: Administrator * Date: 2018/3/22 */ public class BinaryUtil { /** * 计算byte[]的int型数值 * 如{0xFF, 0xFF, 0xFF, 0xFF} * 11111111 11111111 11111111 11111111 * 其中第一位为符号位:1 = 负数(负数用补码表示),0 = 正数 */ public static int calculate(byte[] data) { int result; String binary = BinaryUtil.hexString2BinaryString(ByteUtil.bytesToHexStringWithoutSpace(data)); if (binary.startsWith("1")) { StringBuilder sb = new StringBuilder("0"); for (int i = 1; i < binary.length(); i++) { if (binary.charAt(i) == '1') { sb.append("0"); } else { sb.append("1"); } } result = (BinaryUtil.binaryString2Int(sb.toString()) + 1) * -1; } else { result = BinaryUtil.binaryString2Int(binary); } return result; } /** * 二进制String转十六进制String * * @param binaryString * @return */ public static String binaryString2HexString(String binaryString) { if (binaryString == null || binaryString.equals("") || binaryString.length() % 8 != 0) return null; StringBuffer tmp = new StringBuffer(); int iTmp = 0; for (int i = 0; i < binaryString.length(); i += 4) { iTmp = 0; for (int j = 0; j < 4; j++) { iTmp += Integer.parseInt(binaryString.substring(i + j, i + j + 1)) << (4 - j - 1); } tmp.append(Integer.toHexString(iTmp)); } return tmp.toString(); } /** * 十六进制String转二进制String */ public static String hexString2BinaryString(String hexString) { if (hexString == null || hexString.length() % 2 != 0) return null; String bString = "", tmp; for (int i = 0; i < hexString.length(); i++) { tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16)); bString += tmp.substring(tmp.length() - 4); } return bString; } /** * 十六进制String转二进制String */ public static String bytes2BinaryString(byte[] bytes) { String hexString = ByteUtil.bytesToHexStringWithoutSpace(bytes); if (hexString == null || hexString.length() % 2 != 0) return null; String bString = "", tmp; for (int i = 0; i < hexString.length(); i++) { tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16)); bString += tmp.substring(tmp.length() - 4); } return bString; } /** * int型数据转十六进制String */ static String int2BinaryString(int integer) { String str = ""; while (integer != 0) { str = integer % 2 + str; integer = integer / 2; } str = "00000000000000000000000000000000" + str; return str.substring(str.length() - 32); } public static int binaryString2Int(String binary) throws NumberFormatException { return Integer.parseInt(binary, 2); } /** * 返回8位二进制1111 1111 */ public static String byte2BinaryString(byte singleByte) { return Integer.toBinaryString(singleByte & 0xFF); } } <file_sep>/app/src/main/java/com/tangjd/common/abs/GsonImpl.java package com.tangjd.common.abs; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** * Author: tangjd * Date: 2017/5/8 */ public class GsonImpl { private static GsonImpl sGsonImpl; private Gson mGson = new Gson(); private GsonImpl() { } public static GsonImpl instance() { if (sGsonImpl == null) { sGsonImpl = new GsonImpl(); } return sGsonImpl; } public String toJson(Object src) { return mGson.toJson(src); } public <T> T toObject(String json, Class<T> claxx) { return mGson.fromJson(json, claxx); } public <T> T toObject(byte[] bytes, Class<T> claxx) { return mGson.fromJson(new String(bytes), claxx); } public <T> List<T> toList(String json, Class<T> claxx) { Type type = new TypeToken<ArrayList<T>>() { }.getType(); List<T> list = mGson.fromJson(json, type); return list; } } <file_sep>/app/src/main/java/com/tangjd/common/retrofit/string/ApiStringBase.java package com.tangjd.common.retrofit.string; import com.tangjd.common.utils.Log; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; /** * Created by tangjd on 2017/11/17. */ public class ApiStringBase { public static final String TAG = "ApiTT"; public static Retrofit getStringRetrofit(String domainName) { //日志显示级别 HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY; //新建log拦截器 HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { Log.i(TAG, message); } }); OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.retryOnConnectionFailure(false); // Default timeout time builder.connectTimeout(10_000, TimeUnit.MILLISECONDS); builder.readTimeout(30_000, TimeUnit.MILLISECONDS); builder.writeTimeout(10_000, TimeUnit.MILLISECONDS); builder.addInterceptor(loggingInterceptor); OkHttpClient okHttpClient = builder.build(); loggingInterceptor.setLevel(level); Retrofit sStringRetrofit = new Retrofit.Builder() .baseUrl(domainName) .addConverterFactory(StringConverterFactory.create()) .client(okHttpClient) .build(); return sStringRetrofit; } public static void enqueue(Call<String> call, final OnStringRespListener listener) { call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { if (listener != null) { listener.onFinish(true); try { listener.onResponse(response.body()); } catch (Exception e) { e.printStackTrace(); listener.onError("数据格式出错"); } } } @Override public void onFailure(Call<String> call, Throwable t) { if (listener != null) { listener.onFinish(false); try { listener.onError("连接失败\n" + t.getMessage()); } catch (Exception e) { e.printStackTrace(); } } } }); } } <file_sep>/app/src/main/java/com/tangjd/common/db/Usage.java //package com.tangjd.common.db; // ///** // * Author: Administrator // * Date: 2017/10/23 // */ // //public class Usage { // // Application中全局public方法 // private BaseDao<TbPatrol, Integer> mPatrolDao; // // public BaseDao getPatrolDao() { // if (mPatrolDao == null) { // mPatrolDao = new BaseDaoImpl<>(TbPatrol.class); // } // return mPatrolDao; // } //} <file_sep>/app/src/main/java/com/tangjd/common/utils/FileUtil.java package com.tangjd.common.utils; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Build.VERSION_CODES; import android.os.Environment; import android.support.v4.content.FileProvider; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class FileUtil { public static void installApk(Context context, File file, String fileProviderAuthority) { if (file != null && file.length() > 0 && file.exists() && file.isFile()) { Intent intent = new Intent(Intent.ACTION_VIEW); Uri data; // 判断版本大于等于7.0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // com.tangjd.common.fileprovider是common中的authorities data = FileUtil.getFileProviderUri(context, file, fileProviderAuthority); // 给目标应用一个临时授权 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { data = Uri.fromFile(file); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } intent.setDataAndType(data, "application/vnd.android.package-archive"); context.startActivity(intent); } } public static Uri getFileProviderUri(Context context, File file, String fileProviderAuthority) { // return FileProvider.getUriForFile(context, "com.tangjd.common.fileprovider", file); return FileProvider.getUriForFile(context, fileProviderAuthority, file); } public static String readFromAssets(Context context, String fileName) { String ret = ""; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { inputStream = context.getResources().getAssets().open(fileName); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); String receiveString = ""; StringBuilder stringBuilder = new StringBuilder(); while ((receiveString = bufferedReader.readLine()) != null) { stringBuilder.append(receiveString); } ret = stringBuilder.toString(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } if (inputStreamReader != null) { inputStreamReader.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return ret; } public static String readFromFile(String filePath) { File file = new File(filePath); if (!file.exists()) { return null; } String ret = ""; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { inputStream = new FileInputStream(file); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); String receiveString = ""; StringBuilder stringBuilder = new StringBuilder(); while ((receiveString = bufferedReader.readLine()) != null) { stringBuilder.append(receiveString); } ret = stringBuilder.toString(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtil.close(bufferedReader, inputStreamReader, inputStream); } return ret; } public static String readFromFile(File file) { if (file == null || !file.exists()) { return null; } String ret = ""; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { inputStream = new FileInputStream(file); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); String receiveString = ""; StringBuilder stringBuilder = new StringBuilder(); while ((receiveString = bufferedReader.readLine()) != null) { stringBuilder.append(receiveString); } ret = stringBuilder.toString(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtil.close(bufferedReader, inputStreamReader, inputStream); } return ret; } public static boolean writeToFile(String filePath, String content, boolean append) { boolean success = false; FileWriter fileWriter = null; try { File file = new File(filePath); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } if (!file.exists()) { file.createNewFile(); } fileWriter = new FileWriter(file, append); fileWriter.write(content); fileWriter.flush(); success = true; } catch (IOException e) { e.printStackTrace(); success = false; } finally { IOUtil.close(fileWriter); } return success; } public static File getCustomDir(Context context, String customDirName) { File file = getFileDir(context, customDirName); return file; } public static File getDownloadDir(Context context) { File file = getFileDir(context, "download"); return file; } private static File getFileDir(Context context, String parentDirName) { if (externalStorageWritable()) { File cacheDirFile = null; if (BuildUtil.hasFroyo()) { cacheDirFile = context.getExternalFilesDir(parentDirName); } if (cacheDirFile != null) { return cacheDirFile; } // Before Froyo we need to construct the external cache dir ourselves final String cacheDir = "/Android/data/" + context.getPackageName() + File.separator + parentDirName + File.separator; return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir); } else { return new File(context.getFilesDir().getAbsolutePath() + File.separator + parentDirName + File.separator); } } /** * Get a usable cache directory (external if available, internal otherwise). */ private static boolean externalStorageWritable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !isExternalStorageRemovable(); } /** * Check if external storage is built-in or removable. * * @return True if external storage is removable (like an SD card), false * otherwise. */ @TargetApi(VERSION_CODES.GINGERBREAD) private static boolean isExternalStorageRemovable() { if (BuildUtil.hasGingerbread()) { return Environment.isExternalStorageRemovable(); } return true; } public static long getExternalCacheSize(Context context) { return folderSize(context.getExternalCacheDir()); } public static void deleteExternalCache(Context context) { deleteDirectory(context.getExternalCacheDir()); } public static void deleteDirectory(File path) { if (path == null) { return; } if (path.exists()) { File[] files = path.listFiles(); if (files == null) { return; } for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } } public static long folderSize(File directory) { long length = 0; if (directory == null || !directory.exists()) { return 0; } File[] files = directory.listFiles(); if (files == null) { return 0; } for (int i = 0; i < files.length; i++) { File file = files[i]; if (file == null) { continue; } if (file.isFile()) { length += file.length(); } else { length += folderSize(file); } } return length; } } <file_sep>/app/src/main/java/com/tangjd/common/qrcode/ActScanZbar.java package com.tangjd.common.qrcode; import android.os.Bundle; import android.os.Vibrator; import android.support.v7.widget.Toolbar; import com.tangjd.common.R; import com.tangjd.common.abs.BaseActivity; import cn.bingoogolapple.qrcode.core.QRCodeView; import cn.bingoogolapple.qrcode.zbar.ZBarView; public abstract class ActScanZbar extends BaseActivity implements QRCodeView.Delegate { private static final String TAG = "TTTTTT"; private QRCodeView mQRCodeView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_scan_zbar_layout); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); mQRCodeView = (ZBarView) findViewById(R.id.zbarview); mQRCodeView.setDelegate(this); setToolbarTitle("扫描"); enableBackFinish(); } @Override protected void onStart() { super.onStart(); mQRCodeView.showScanRect(); mQRCodeView.startSpotDelay(500); } @Override protected void onStop() { mQRCodeView.stopCamera(); super.onStop(); } @Override protected void onDestroy() { mQRCodeView.onDestroy(); super.onDestroy(); } private void vibrate() { Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); vibrator.vibrate(200); } @Override public void onScanQRCodeSuccess(String result) { mQRCodeView.startSpot(); } @Override public void onScanQRCodeOpenCameraError() { showLongToast("打开相机出错"); finish(); } }
759ff2c0812a0b0ac734abf82e32e6bc8986156b
[ "Java", "Gradle" ]
15
Java
ytjd926/common
dc6a28420b943c8636f98a01ec7a91bd1f50f326
49c59462ee5a47fe98db0299fd139597b972faf3
refs/heads/master
<repo_name>triplepoint/pipenv<file_sep>/Pipfile [dev-packages] "flake8" = ">=3.3.0,<4" pytest = "*" mock = "*" sphinx = "<=1.5.5" "-e ." = "*" twine = "*" "sphinx-click" = "*" "pytest-xdist" = "*"
12482ddce0cb457d0b8e7bc390eea9bc551df02d
[ "TOML" ]
1
TOML
triplepoint/pipenv
3248698903d92ea81c617423ec1e28def5ccae2c
11d246a1672d12ef64c0b1520c1eef4458d5745c
refs/heads/main
<repo_name>bhanuvinayes/web_development<file_sep>/README.md # web_development This is for tracking progress of udemy course. :)
246e5e4369372b8a726d388885ccbc14fe769e53
[ "Markdown" ]
1
Markdown
bhanuvinayes/web_development
66e36dcc6bc1b856c81d79cc4c967437ce28c98c
4f26e043f630530e98003f20e93fe3bd6ce7ff4c
refs/heads/master
<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录后台管理系统</title><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link href="/blog/Public/static/icon/favicon.ico" rel="shortcut icon"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/bootstrap-3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/bootstrap-3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/font-awesome-4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/css/bjy.css"> <link rel="stylesheet" type="text/css" href="/blog/Template/default/Home/Public/css/index.css"><link rel="stylesheet" type="text/css" href="/blog/Template/default/Admin/Public/css/login.css" /> </head> <body> <form class="form-group" action="<?php echo U('Admin/Login/login');?>" method="post"> <div id="Login"> <input class="form-control modal-sm" type="password" placeholder="<PASSWORD>" name="ADMIN_PASSWORD" value="<?php echo ($_SESSION['ADMIN_PASSWORD']); ?>"> <input class="form-control modal-sm" type="text" placeholder="验证码" autocomplete="off" name="verify"> <img id="code" class="verify" src="<?php echo U('Admin/Login/showVerify');?>" title="点击更换" > <input class="btn btn-primary submit" type="submit" value="登录"> </div> </form> <script src="/blog/Public/static/js/jquery-2.0.0.min.js"></script> <script> logoutUrl="<?php echo U('Home/User/logout');?>"; </script> <script src="/blog/Public/static/bootstrap-3.3.5/js/bootstrap.min.js"></script> <!--[if lt IE 9]> <script src="/blog/Public/static/js/html5shiv.min.js"></script> <script src="/blog/Public/static/js/respond.min.js"></script> <![endif]--> <script src="/blog/Public/static/pace/pace.min.js"></script> <script src="/blog/Template/default/Home/Public/js/index.js"></script> <!-- 百度页面自动提交开始 --> <script> (function(){ var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })(); </script> <!-- 百度页面自动提交结束 --> <!-- 百度统计开始 --> <!-- 百度统计结束 --> </body> </html> <script type="text/javascript"> // 验证码生成 var captcha_img = $('#code'); var verifyimg = captcha_img.attr("src"); captcha_img.attr('title', '点击刷新'); captcha_img.click(function(){ //如果?第一次出现位置大于0 if( verifyimg.indexOf('?')>0){ $(this).attr("src", verifyimg+'&random='+Math.random()); }else{ $(this).attr("src", verifyimg.replace(/\?.*$/,'')+'?'+Math.random()); } }); </script><file_sep><?php namespace Home\Controller; use Common\Controller\HomeBaseController; class BaiduController extends HomeBaseController { public $api_key = '<KEY>'; public $secret_key = '<KEY>'; /** * [request_post 发送信息] * @param string $url [发送路径] * @param string $param [post参数] */ function request_post($url = '', $param = '') { if (empty($url) || empty($param)) { return false; } $postUrl = $url; $curlPost = $param; $curl = curl_init();//初始化curl curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页 curl_setopt($curl, CURLOPT_HEADER, 0);//设置header curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上 curl_setopt($curl, CURLOPT_POST, 1);//post提交方式 curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //跳过证书检查 $data = curl_exec($curl);//运行curl curl_close($curl); return $data; } //获取token public function get_token(){ $url = 'https://aip.baidubce.com/oauth/2.0/token'; $post_data['grant_type'] = 'client_credentials'; $post_data['client_id'] = $this->api_key; $post_data['client_secret'] = $this->secret_key; $o = ""; foreach ( $post_data as $k => $v ) { $o.= "$k=" . urlencode( $v ). "&" ; } $post_data = substr($o,0,-1); $res = $this->request_post($url, $post_data); $token = json_decode($res,true); $token = $token['access_token']; return $token; } //上传图片 public function face_upload($saveName=''){ $upload = new \Think\Upload();// 实例化上传类 $upload->maxSize = 3145728 ;// 设置附件上传大小 $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 // $root_path=rtrim($_SERVER['SCRIPT_NAME'],'/index.php');//根目录 $upload->rootPath = './Upload/'; // 设置附件上传目录 $upload->savePath = '/image/baidu_AI/'; // 设置附件上传目录 if($saveName){ $upload->saveName = 'face';//固定上传文件名 }else{ $upload->saveName = array('uniqid',''); } $upload->replace = true;//相同文件名是否覆盖 // 上传文件 $info = $upload->upload(); if(!$info) {// 上传错误提示错误信息 $this->error($upload->getError()); }else{// 上传成功 return $info; } } //人脸对比页 public function matching(){ $this->display(); } //人脸对比 public function face_matching() { $token = $this->get_token(); $url = 'https://aip.baidubce.com/rest/2.0/face/v2/match?access_token=' . $token; $info = $this->face_upload();//上传图片 // print_r($info);die; $url1 = './Upload/'.$info['face1']['savepath'].$info['face1']['savename']; $url2 = './Upload/'.$info['face2']['savepath'].$info['face2']['savename']; $img = file_get_contents($url1); $img = base64_encode($img); $img1 = file_get_contents($url2); $img1 = base64_encode($img1); // 上传错误提示错误信息 if(!$img) { echo '图片一上传失败';die; }else if(!$img1){ echo '图片二上传失败';die; } $bodys = array('images' => implode(',', array($img, $img1))); $res = $this->request_post($url, $bodys); echo $res; } //人脸检测页 public function detection(){ $this->display(); } //百度AI人脸检测 public function face_detection(){ $token = $this->get_token(); $url = 'https://aip.baidubce.com/rest/2.0/face/v1/detect?access_token='.$token; $info = $this->face_upload('face');//上传图片 $img_url = './Upload/'.$info['face_detection']['savepath'].$info['face_detection']['savename']; $img = file_get_contents($img_url); $img = base64_encode($img); if(!$img) {// 上传错误提示错误信息 $this->error($upload->getError()); }else{// 上传成功 $bodys = array( 'max_face_num' => 5,//最大识别脸数 'face_fields' => "age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities", 'image' => $img ); $res = $this->request_post($url, $bodys); echo $res; } } } <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文章列表</title> <bootstrapcss/> </head> <body> <table class="table table-bordered table-striped table-hover table-condensed"> <thead> <tr> <th width="3%"> aid </th> <th width="9%"> 所属栏目 </th> <th width="20%"> 标题 </th> <th width="8%"> 作者 </th> <th width="22%"> 标签 </th> <th width="4%"> 原创 </th> <th width="4%"> 显示 </th> <th width="4%"> 置顶 </th> <th width="5%"> 点击数 </th> <th width="13%"> 发布时间 </th> <th width="8%"> 操作 </th> </tr> </thead> <foreach name="data" item="v"> <tr> <td> {$v['aid']} </td> <td> {$v['category']['cname']} </td> <td> <a href="/article/{$v['aid']}" target="_blank">{$v['title']}</a> </td> <td> {$v['author']} </td> <td> <foreach name="v['tag']" item="n"> {$n['tname']}&nbsp;</foreach> </td> <td> <if condition="$v['is_original'] eq 1"> ✔<else/> ✘</if> </td> <td> <if condition="$v['is_show'] eq 1"> ✔<else/> ✘</if> </td> <td> <if condition="$v['is_top'] eq 1"> ✔<else/> ✘</if> </td> <td> {$v['click']} </td> <td> {$v['addtime']} </td> <td> <a href="{:U('Admin/Article/edit',array('aid'=>$v['aid']))}">修改</a> | <a href="javascript:if(confirm('确定要删除吗?')) location='{:U('Admin/Recycle/recycle',array('table_name'=>'Article','id_name'=>'aid','id_number'=>$v['aid']))}'">删除</a> </td> </tr> </foreach> </table> <div style="text-align: center;"> {$page} </div> <bootstrapjs/> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>人脸检测-<?php echo (C("WEB_NAME")); ?></title> <meta name="keywords" content="<?php echo (C("WEB_KEYWORDS")); ?>"/> <meta name="description" content="<?php echo (C("WEB_DESCRIPTION")); ?>"/> <meta http-equiv="Cache-Control" content="no-siteapp"/> <meta name="baidu-site-verification" content="0DW3jOXXNz" /> <meta name="author" content="lizhengmeng,<?php echo (C("ADMIN_EMAIL")); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/bootstrap-3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/bootstrap-3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/font-awesome-4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/css/bjy.css"> <link rel="stylesheet" type="text/css" href="/blog/Template/default/Home/Public/css/index.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/css/animate.css"> <script type="text/javascript" src="/blog/Public/static/games/gobang/js/CookieHandle.js"></script> <script type="text/javascript" src="/blog/Public/static/games/gobang/js/jquery-1.7.2.js"></script> </head> <body> <header id="b-public-nav" class="navbar navbar-inverse navbar-fixed-top"> <!-- 背景动画 --> <!-- <canvas id="c_n9" width="1920" height="990" style="position: fixed; top: 0px; left: 0px; z-index: -1; opacity: 0.5;"></canvas> <script src="/blog/Public/static/js/canvas-nest.min.js"></script> --> <!-- 背景动画 --> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a class="navbar-brand" href="/" onclick="recordId('/',0)"> <div class="hidden-xs b-nav-background"> </div> <ul class="b-logo-code"> <li class="b-lc-start">&lt;?php</li> <li class="b-lc-echo">echo</li> </ul> <p class="b-logo-word"> '爵特猛博客' </p> <p class="b-logo-end"> ;?> </p> </a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav b-nav-parent"> <li class="hidden-xs b-nav-mobile"></li> <li class="b-nav-cname <?php if(($cid) == "index"): ?>b-nav-active<?php endif; ?> " > <a href="/" onclick="recordId('/',0)">首页</a></li> <?php if(is_array($categorys)): foreach($categorys as $key=>$v): ?><li class="b-nav-cname <?php if(($cid) == $v['cid']): ?>b-nav-active<?php endif; ?> "> <a href="<?php echo U('Index/category',array('cid'=>$v['cid']));?>" onclick="return recordId('cid',<?php echo ($v['cid']); ?>)"><?php echo ($v['cname']); ?></a></li><?php endforeach; endif; ?> <li class="b-nav-cname <?php if(($cid) == "chat"): ?>b-nav-active<?php endif; ?> "> <a href="<?php echo U('/chat');?>">随言碎语</a></li> <li class="b-nav-cname <?php if(($cid) == "play"): ?>b-nav-active<?php endif; ?> "> <a href="<?php echo U('/play');?>">小玩意儿</a></li> <!-- <li class="b-nav-cname hidden-sm <?php if(($cid) == "git"): ?>b-nav-active<?php endif; ?> "> <a href="<?php echo U('/git');?>">开源项目</a></li> --> </ul> <ul id="b-login-word" class="nav navbar-nav navbar-right"> <?php if(empty($_SESSION['user']['head_img'])): ?><li class="b-nav-cname b-nav-login"> <div class="hidden-xs b-login-mobile"> </div> <a href="javascript:;" onclick="login()">登录</a></li> <?php else: ?> <li class="b-user-info"> <span> <img class="b-head_img" src="<?php echo ($_SESSION['user']['head_img']); ?>" alt="<?php echo ($_SESSION['user']['nickname']); ?>" title="<?php echo ($_SESSION['user']['nickname']); ?>"/> </span> <span class="b-nickname"><?php echo ($_SESSION['user']['nickname']); ?></span> <span><a href="javascript:;" onclick="logout()">退出</a></span> </li><?php endif; ?> </ul> </div> </div> </header> <div class="b-h-70"> </div> <div id="b-content" class="container"> <div class="row"> <div class="col-xs-12 col-md-12 col-lg-8"> <div class="wrapper"> <div class="chessboard"> <!-- top line --> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top"></div> <div class="chess-top chess-right"></div> <!-- line 1 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- line 2 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- line 3 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- line 4 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- line 5 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- line 6 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- line 7 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- line 8 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- line 9 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- line 10 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- line 11 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- line 12 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- line 13 --> <div class="chess-left"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-middle"></div> <div class="chess-right"></div> <!-- bottom line --> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom"></div> <div class="chess-bottom chess-right"></div> </div> <div class="operating-panel"> <p> <a id="black_btn" class="btn selected" href="#">黑&nbsp;&nbsp;子</a> <a id="white_btn" class="btn" href="#">白&nbsp;&nbsp;子</a> </p> <p> <a id="first_move_btn" class="btn selected" href="#">先&nbsp;&nbsp;手</a> <a id="second_move_btn" class="btn" href="#">后&nbsp;&nbsp;手</a> </p> <a id="replay_btn" class="btn" href="#">开&nbsp;&nbsp;&nbsp;始</a> <p id="result_info">胜率:100%</p> <p id="result_tips"></p> </div> <div style="display: none"> <!-- 图片需合并 减少http请求数 --> <img src="img/black.png" alt="preload" /> <img src="img/white.png" alt="preload" /> <img src="img/hover.png" alt="preload" /> <img src="img/hover_up.png" alt="preload" /> <img src="img/hover_down.png" alt="preload" /> <img src="img/hover_up_left.png" alt="preload" /> <img src="img/hover_up_right.png" alt="preload" /> <img src="img/hover_left.png" alt="preload" /> <img src="img/hover_right.png" alt="preload" /> <img src="img/hover_down_left.png" alt="preload" /> <img src="img/hover_down_right.png" alt="preload" /> <img src="img/black_last.png" alt="preload" /> <img src="img/white_last.png" alt="preload" /> </div> </div> </div> </div> <div class="row"> <footer id="b-foot" class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <ul> <li class="text-center">© 2017-2018 lizhengmeng.club 版权所有 ICP证:桂ICP备17006323号</li> <li class="text-center"> 联系邮箱:<?php echo (C("ADMIN_EMAIL")); ?> <!-- 站长统计开始 --> <script type="text/javascript"> var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://"); document.write(unescape("%3Cspan id='cnzz_stat_icon_1273611319'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s22.cnzz.com/z_stat.php%3Fid%3D1273611319%26show%3Dpic' type='text/javascript'%3E%3C/script%3E")); </script> <!-- 站长统计结束 --> </li> </ul> <div class="b-h-20"> </div> <a class="go-top fa fa-angle-up animated jello" href="javascript:;" onclick="goTop()"></a> </footer> </div> </div> </body> </html> <style> *{margin:0;padding:0;list-style-type:none;} a,img{border:0;} body{font:12px/180% Arial, Helvetica, sans-serif, "新宋体";} .wrapper { width: 600px; position: relative; } /* 棋盘 */ div.chessboard { margin: 30px 0 0 50px; width: 542px; background: url(/blog/Public/static/games/gobang/img/chessboard.png) no-repeat 14px 14px rgb(250, 250, 250); overflow: hidden; box-shadow: 2px 2px 8px #888; -webkit-box-shadow: 2px 2px 8px #888; -moz-box-shadow: 2px 2px 8px #888; } div.chessboard div { float: left; width: 36px; height: 36px; border-top: 0px solid #ccc; border-left: 0px solid #ccc; border-right: 0; border-bottom: 0; cursor: pointer; } /* 棋子 */ div.chessboard div.black { background: url(/blog/Public/static/games/gobang/img/black.png) no-repeat 4px 4px; } div.chessboard div.white { background: url(/blog/Public/static/games/gobang/img/white.png) no-repeat 4px 4px; } div.chessboard div.hover { background: url(/blog/Public/static/games/gobang/img/hover.png) no-repeat 1px 1px; } div.chessboard div.hover-up { background: url(/blog/Public/static/games/gobang/img/hover_up.png) no-repeat 1px 1px; } div.chessboard div.hover-down { background: url(/blog/Public/static/games/gobang/img/hover_down.png) no-repeat 1px 1px; } div.chessboard div.hover-up-left { background: url(/blog/Public/static/games/gobang/img/hover_up_left.png) no-repeat 1px 1px; } div.chessboard div.hover-up-right { background: url(/blog/Public/static/games/gobang/img/hover_up_right.png) no-repeat 1px 1px; } div.chessboard div.hover-left { background: url(/blog/Public/static/games/gobang/img/hover_left.png) no-repeat 1px 1px; } div.chessboard div.hover-right { background: url(/blog/Public/static/games/gobang/img/hover_right.png) no-repeat 1px 1px; } div.chessboard div.hover-down-left { background: url(/blog/Public/static/games/gobang/img/hover_down_left.png) no-repeat 1px 1px; } div.chessboard div.hover-down-right { background: url(/blog/Public/static/games/gobang/img/hover_down_right.png) no-repeat 1px 1px; } div.chessboard div.white-last { background: url(/blog/Public/static/games/gobang/img/white_last.png) no-repeat 4px 4px; } div.chessboard div.black-last { background: url(/blog/Public/static/games/gobang/img/black_last.png) no-repeat 4px 4px; } /* 右侧 */ div.operating-panel { position: absolute; left: 610px; top: 150px; width: 200px; text-align: center; } .operating-panel a { display: inline-block; padding: 10px 15px; margin-bottom: 39px; margin-right: 8px; margin-left: 8px; background: rgb(100, 167, 233); text-decoration: none; color: #333; font-weight: bold; font-size: 16px; font-family: "微软雅黑", "宋体"; } .operating-panel a:hover { background: rgb(48, 148, 247); text-decoration: none; } .operating-panel a.disable, .operating-panel a.disable:hover { cursor: default; background: rgb(197, 203, 209); color: rgb(130, 139, 148); } .operating-panel a.selected { border: 5px solid #F3C242; padding: 5px 10px; } #result_tips { color: #CE4242; font-size: 26px; font-family: "微软雅黑"; } #result_info { margin-bottom: 26px; }</style> <script>$(document).ready(function() { fiveChess.init(); }); var fiveChess = { NO_CHESS: 0, BLACK_CHESS: -1, WHITE_CHESS: 1, chessArr: [], //记录棋子 chessBoardHtml: "", humanPlayer: "black", //玩家棋子颜色 AIPlayer: "white", //AI棋子颜色 isPlayerTurn: true, //轮到player下棋 totalGames: cookieHandle.getCookie("totalGames") || 0, //总局数 winGames: cookieHandle.getCookie("winGames") || 0, //玩家赢局数 isGameStart: false, //游戏已经开始 isGameOver: false, //游戏结束 playerLastChess: [], //玩家最后下子位置 AILastChess: [], //AI最后下子位置 init: function () { this.chessBoardHtml = $("div.chessboard").html(); var _fiveChess = this; //右侧操作按钮 $(".operating-panel a").click(function (event) { event.preventDefault(); var id = $(this).attr("id"); if (_fiveChess.isGameStart && id !== "replay_btn" ) { return; } //正在游戏 不操作 switch (id) { case "black_btn": _fiveChess.humanPlayer = "black"; _fiveChess.AIPlayer = "white"; break; case "white_btn": _fiveChess.humanPlayer = "white"; _fiveChess.AIPlayer = "black"; break; case "first_move_btn": _fiveChess.isPlayerTurn = true; break; case "second_move_btn": _fiveChess.isPlayerTurn = false; break; case "replay_btn": _fiveChess.resetChessBoard(); if (_fiveChess.isGameStart) { //点重玩 _fiveChess.gameOver(); } else { //点开始 _fiveChess.gameStart(); } break; } if (id !== "replay_btn") { $(this).addClass("selected").siblings().removeClass("selected"); } }); this.resetChessBoard(); $("#result_info").html("胜率:" + (this.winGames * 100 / this.totalGames | 0) + "%"); }, //重置棋盘 resetChessBoard: function () { $("div.chessboard").html(this.chessBoardHtml); $("#result_tips").html(""); this.isGameOver = false; this.isPlayerTurn = $("#first_move_btn").hasClass("selected"); //初始化棋子状态 var i, j; for (i = 0; i < 15; i++) { this.chessArr[i] = []; for (j = 0; j < 15; j++) { this.chessArr[i][j] = this.NO_CHESS; } } //player下棋事件 var _fiveChess = this; $("div.chessboard div").click(function () { if (!_fiveChess.isPlayerTurn || _fiveChess.isGameOver) { return; } if (!_fiveChess.isGameStart) { _fiveChess.gameStart(); } var index = $(this).index(), i = index / 15 | 0, j = index % 15; if (_fiveChess.chessArr[i][j] === _fiveChess.NO_CHESS) { _fiveChess.playChess(i, j, _fiveChess.humanPlayer); if (i === 0 && j === 0) { $(this).removeClass("hover-up-left"); } else if (i === 0 && j === 14) { $(this).removeClass("hover-up-right"); } else if (i === 14 && j === 0) { $(this).removeClass("hover-down-left"); } else if (i === 14 && j === 14) { $(this).removeClass("hover-down-right"); } else if (i === 0) { $(this).removeClass("hover-up"); } else if (i === 14) { $(this).removeClass("hover-down"); } else if (j === 0) { $(this).removeClass("hover-left"); } else if (j === 14) { $(this).removeClass("hover-right"); } else { $(this).removeClass("hover"); } _fiveChess.playerLastChess = [i, j]; _fiveChess.playerWinOrNot(i, j); } }); //鼠标在棋盘上移动效果 $("div.chessboard div").hover( function () { if (!_fiveChess.isPlayerTurn || _fiveChess.isGameOver) { return; } var index = $(this).index(), i = index / 15 | 0, j = index % 15; if (_fiveChess.chessArr[i][j] === _fiveChess.NO_CHESS) { if (i === 0 && j === 0) { $(this).addClass("hover-up-left"); } else if (i === 0 && j === 14) { $(this).addClass("hover-up-right"); } else if (i === 14 && j === 0) { $(this).addClass("hover-down-left"); } else if (i === 14 && j === 14) { $(this).addClass("hover-down-right"); } else if (i === 0) { $(this).addClass("hover-up"); } else if (i === 14) { $(this).addClass("hover-down"); } else if (j === 0) { $(this).addClass("hover-left"); } else if (j === 14) { $(this).addClass("hover-right"); } else { $(this).addClass("hover"); } } }, function () { if (!_fiveChess.isPlayerTurn || _fiveChess.isGameOver) { return; } var index = $(this).index(), i = index / 15 | 0, j = index % 15; if (i === 0 && j === 0) { $(this).removeClass("hover-up-left"); } else if (i === 0 && j === 14) { $(this).removeClass("hover-up-right"); } else if (i === 14 && j === 0) { $(this).removeClass("hover-down-left"); } else if (i === 14 && j === 14) { $(this).removeClass("hover-down-right"); } else if (i === 0) { $(this).removeClass("hover-up"); } else if (i === 14) { $(this).removeClass("hover-down"); } else if (j === 0) { $(this).removeClass("hover-left"); } else if (j === 14) { $(this).removeClass("hover-right"); } else { $(this).removeClass("hover"); } } ); }, gameStart: function () { this.totalGames++; cookieHandle.setCookie({ name: "totalGames", value: this.totalGames, expiresHours: 365 * 24 }); //AI先手 if (!this.isPlayerTurn) { this.AImoveChess(); } this.isGameStart = true; $(".operating-panel p a").addClass("disable"); $("#replay_btn").html("重&nbsp;&nbsp;&nbsp;玩"); }, gameOver: function () { this.isGameStart = false; $(".operating-panel a").removeClass("disable"); $("#replay_btn").html("开&nbsp;&nbsp;&nbsp;始"); $("#result_info").html("胜率:" + (this.winGames * 100 / this.totalGames | 0) + "%"); }, //下棋 i行,j列,color颜色 playChess: function (i, j, color) { this.chessArr[i][j] = color === "black" ? this.BLACK_CHESS : this.WHITE_CHESS; if (color === this.AIPlayer) { $("div.chessboard div." + color + "-last").addClass(color).removeClass(color + "-last"); $("div.chessboard div:eq(" + (i * 15 + j) + ")").addClass(color + "-last"); } else { $("div.chessboard div:eq(" + (i * 15 + j) + ")").addClass(color); } }, //玩家是否取胜 playerWinOrNot: function (i, j) { var nums = 1, //连续棋子个数 chessColor = this.humanPlayer === "black" ? this.BLACK_CHESS : this.WHITE_CHESS, m, n; //x方向 for (m = j - 1; m >= 0; m--) { if (this.chessArr[i][m] === chessColor) { nums++; } else { break; } } for (m = j + 1; m < 15; m++) { if (this.chessArr[i][m] === chessColor) { nums++; } else { break; } } if (nums >= 5) { this.playerWin(); return; } else { nums = 1; } //y方向 for (m = i - 1; m >= 0; m--) { if (this.chessArr[m][j] === chessColor) { nums++; } else { break; } } for (m = i + 1; m < 15; m++) { if (this.chessArr[m][j] === chessColor) { nums++; } else { break; } } if (nums >= 5) { this.playerWin(); return; } else { nums = 1; } //左斜方向 for (m = i - 1, n = j - 1; m >= 0 && n >= 0; m--, n--) { if (this.chessArr[m][n] === chessColor) { nums++; } else { break; } } for (m = i + 1, n = j + 1; m < 15 && n < 15; m++, n++) { if (this.chessArr[m][n] === chessColor) { nums++; } else { break; } } if (nums >= 5) { this.playerWin(); return; } else { nums = 1; } //右斜方向 for (m = i - 1, n = j + 1; m >= 0 && n < 15; m--, n++) { if (this.chessArr[m][n] === chessColor) { nums++; } else { break; } } for (m = i + 1, n = j - 1; m < 15 && n >= 0; m++, n--) { if (this.chessArr[m][n] === chessColor) { nums++; } else { break; } } if (nums >= 5) { this.playerWin(); return; } this.AImoveChess(); }, playerWin: function () { this.winGames++; cookieHandle.setCookie({ name: "winGames", value: this.winGames, expiresHours: 365 * 24 }); this.showResult(true); this.gameOver(); }, //AI下棋 AImoveChess: function () { this.isPlayerTurn = false; var maxX = 0, maxY = 0, maxWeight = 0, i, j, tem; for (i = 14; i >= 0; i--) { for (j = 14; j >= 0; j--) { if (this.chessArr[i][j] !== this.NO_CHESS) { continue; } tem = this.computeWeight(i, j); if (tem > maxWeight) { maxWeight = tem; maxX = i; maxY = j; } } } this.playChess(maxX, maxY, this.AIPlayer); this.AILastChess = [maxX, maxY]; if ((maxWeight >= 100000 && maxWeight < 250000) || (maxWeight >= 500000)) { this.showResult(false); this.gameOver(); } else { this.isPlayerTurn = true; } }, showResult: function(isPlayerWin) { if (isPlayerWin) { $("#result_tips").html("恭喜你获胜!"); } else { $("#result_tips").html("哈哈,你输咯!"); } this.isGameOver = true; this.showWinChesses(isPlayerWin); }, //标记显示获胜棋子 showWinChesses: function (isPlayerWin) { var nums = 1, //连续棋子个数 lineChess = [], //连续棋子位置 i, j, chessColor, m, n; if (isPlayerWin) { chessColor = this.humanPlayer === "black" ? this.BLACK_CHESS : this.WHITE_CHESS; i = this.playerLastChess[0]; j = this.playerLastChess[1]; } else { chessColor = this.AIPlayer === "black" ? this.BLACK_CHESS : this.WHITE_CHESS; i = this.AILastChess[0]; j = this.AILastChess[1]; } $("div.chessboard div." + this.AIPlayer + "-last").addClass(this.AIPlayer).removeClass(this.AIPlayer + "-last"); //x方向 lineChess[0] = [i]; lineChess[1] = [j]; for (m = j - 1; m >= 0; m--) { if (this.chessArr[i][m] === chessColor) { lineChess[0][nums] = i; lineChess[1][nums] = m; nums++; } else { break; } } for (m = j + 1; m < 15; m++) { if (this.chessArr[i][m] === chessColor) { lineChess[0][nums] = i; lineChess[1][nums] = m; nums++; } else { break; } } if (nums >= 5) { for (k = nums - 1; k >= 0; k--) { this.markChess(lineChess[0][k] * 15 + lineChess[1][k], isPlayerWin ? this.humanPlayer : this.AIPlayer); } return; } //y方向 nums = 1; lineChess[0] = [i]; lineChess[1] = [j]; for (m = i - 1; m >= 0; m--) { if (this.chessArr[m][j] === chessColor) { lineChess[0][nums] = m; lineChess[1][nums] = j; nums++; } else { break; } } for (m = i + 1; m < 15; m++) { if (this.chessArr[m][j] === chessColor) { lineChess[0][nums] = m; lineChess[1][nums] = j; nums++; } else { break; } } if (nums >= 5) { for (k = nums - 1; k >= 0; k--) { this.markChess(lineChess[0][k] * 15 + lineChess[1][k], isPlayerWin ? this.humanPlayer : this.AIPlayer); } return; } //左斜方向 nums = 1; lineChess[0] = [i]; lineChess[1] = [j]; for (m = i - 1, n = j - 1; m >= 0 && n >= 0; m--, n--) { if (this.chessArr[m][n] === chessColor) { lineChess[0][nums] = m; lineChess[1][nums] = n; nums++; } else { break; } } for (m = i + 1, n = j + 1; m < 15 && n < 15; m++, n++) { if (this.chessArr[m][n] === chessColor) { lineChess[0][nums] = m; lineChess[1][nums] = n; nums++; } else { break; } } if (nums >= 5) { for (k = nums - 1; k >= 0; k--) { this.markChess(lineChess[0][k] * 15 + lineChess[1][k], isPlayerWin ? this.humanPlayer : this.AIPlayer); } return; } //右斜方向 nums = 1; lineChess[0] = [i]; lineChess[1] = [j]; for (m = i - 1, n = j + 1; m >= 0 && n < 15; m--, n++) { if (this.chessArr[m][n] === chessColor) { lineChess[0][nums] = m; lineChess[1][nums] = n; nums++; } else { break; } } for (m = i + 1, n = j - 1; m < 15 && n >= 0; m++, n--) { if (this.chessArr[m][n] === chessColor) { lineChess[0][nums] = m; lineChess[1][nums] = n; nums++; } else { break; } } if (nums >= 5) { for (k = nums - 1; k >= 0; k--) { this.markChess(lineChess[0][k] * 15 + lineChess[1][k], isPlayerWin ? this.humanPlayer : this.AIPlayer); } } }, markChess: function (pos, color) { $("div.chessboard div:eq(" + pos + ")").removeClass(color).addClass(color + "-last"); }, //下子到i,j X方向 结果: 多少连子 两边是否截断 putDirectX: function (i, j, chessColor) { var m, n, nums = 1, side1 = false, side2 = false; for (m = j - 1; m >= 0; m--) { if (this.chessArr[i][m] === chessColor) { nums++; } else { if (this.chessArr[i][m] === this.NO_CHESS) { side1 = true; } break; } } for (m = j + 1; m < 15; m++) { if (this.chessArr[i][m] === chessColor) { nums++; } else { if (this.chessArr[i][m] === this.NO_CHESS) { side2 = true; } break; } } return {"nums": nums, "side1": side1, "side2": side2}; }, //下子到i,j Y方向 结果 putDirectY: function (i, j, chessColor) { var m, n, nums = 1, side1 = false, side2 = false; for (m = i - 1; m >= 0; m--) { if (this.chessArr[m][j] === chessColor) { nums++; } else { if (this.chessArr[m][j] === this.NO_CHESS) { side1 = true; } break; } } for (m = i + 1; m < 15; m++) { if (this.chessArr[m][j] === chessColor) { nums++; } else { if (this.chessArr[m][j] === this.NO_CHESS) { side2 = true; } break; } } return {"nums": nums, "side1": side1, "side2": side2}; }, //下子到i,j XY方向 结果 putDirectXY: function (i, j, chessColor) { var m, n, nums = 1, side1 = false, side2 = false; for (m = i - 1, n = j - 1; m >= 0 && n >= 0; m--, n--) { if (this.chessArr[m][n] === chessColor) { nums++; } else { if (this.chessArr[m][n] === this.NO_CHESS) { side1 = true; } break; } } for (m = i + 1, n = j + 1; m < 15 && n < 15; m++, n++) { if (this.chessArr[m][n] === chessColor) { nums++; } else { if (this.chessArr[m][n] === this.NO_CHESS) { side2 = true; } break; } } return {"nums": nums, "side1": side1, "side2": side2}; }, putDirectYX: function (i, j, chessColor) { var m, n, nums = 1, side1 = false, side2 = false; for (m = i - 1, n = j + 1; m >= 0 && n < 15; m--, n++) { if (this.chessArr[m][n] === chessColor) { nums++; } else { if (this.chessArr[m][n] === this.NO_CHESS) { side1 = true; } break; } } for (m = i + 1, n = j - 1; m < 15 && n >= 0; m++, n--) { if (this.chessArr[m][n] === chessColor) { nums++; } else { if (this.chessArr[m][n] === this.NO_CHESS) { side2 = true; } break; } } return {"nums": nums, "side1": side1, "side2": side2}; }, //计算下子至i,j的权重 computeWeight: function (i, j) { var weight = 14 - (Math.abs(i - 7) + Math.abs(j - 7)), //基于棋盘位置权重 pointInfo = {}, //某点下子后连子信息 chessColor = this.AIPlayer === "black" ? this.BLACK_CHESS : this.WHITE_CHESS; //x方向 pointInfo = this.putDirectX(i, j, chessColor); weight += this.weightStatus(pointInfo.nums, pointInfo.side1, pointInfo.side2, true);//AI下子权重 pointInfo = this.putDirectX(i, j, -chessColor); weight += this.weightStatus(pointInfo.nums, pointInfo.side1, pointInfo.side2, false);//player下子权重 //y方向 pointInfo = this.putDirectY(i, j, chessColor); weight += this.weightStatus(pointInfo.nums, pointInfo.side1, pointInfo.side2, true);//AI下子权重 pointInfo = this.putDirectY(i, j, -chessColor); weight += this.weightStatus(pointInfo.nums, pointInfo.side1, pointInfo.side2, false);//player下子权重 //左斜方向 pointInfo = this.putDirectXY(i, j, chessColor); weight += this.weightStatus(pointInfo.nums, pointInfo.side1, pointInfo.side2, true);//AI下子权重 pointInfo = this.putDirectXY(i, j, -chessColor); weight += this.weightStatus(pointInfo.nums, pointInfo.side1, pointInfo.side2, false);//player下子权重 //右斜方向 pointInfo = this.putDirectYX(i, j, chessColor); weight += this.weightStatus(pointInfo.nums, pointInfo.side1, pointInfo.side2, true);//AI下子权重 pointInfo = this.putDirectYX(i, j, -chessColor); weight += this.weightStatus(pointInfo.nums, pointInfo.side1, pointInfo.side2, false);//player下子权重 return weight; }, //权重方案 独:两边为空可下子,单:一边为空 weightStatus: function (nums, side1, side2, isAI) { var weight = 0; switch (nums) { case 1: if (side1 && side2) { weight = isAI ? 15 : 10; //独一 } break; case 2: if (side1 && side2) { weight = isAI ? 100 : 50; //独二 } else if (side1 || side2) { weight = isAI ? 10 : 5; //单二 } break; case 3: if (side1 && side2) { weight = isAI ? 500 : 200; //独三 } else if (side1 || side2) { weight = isAI ? 30 : 20; //单三 } break; case 4: if (side1 && side2) { weight = isAI ? 5000 : 2000; //独四 } else if (side1 || side2) { weight = isAI ? 400 : 100; //单四 } break; case 5: weight = isAI ? 100000 : 10000; //五 break; default: weight = isAI ? 500000 : 250000; break; } return weight; } };</script><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>lzmblog后台管理</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link href="/blog/Public/static/icon/favicon.ico" rel="shortcut icon"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/bootstrap-3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/bootstrap-3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/font-awesome-4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/css/bjy.css"> <link rel="stylesheet" type="text/css" href="/blog/Template/default/Home/Public/css/index.css"> <link rel="stylesheet" type="text/css" href="/blog/Template/default/Admin/Public/css/index.css" /> </head> <body> <div id="nav-top"> <div class="nt-logo"> <a href="<?php echo U('Admin/Index/index');?>" style="background: url('/blog/Template/default/Admin/Public/image/admin-logo.png');"></a> <!-- <span>JTM-BLOG</span> --> </div> <ul class="nt-nav list-unstyled"> <li class="ntn-li ntn-active"><span class="fa fa-list-ul nt-ico"></span> 内容管理</li> <li class="ntn-li"><span class="fa fa-comments nt-ico"></span> 碎言评论</li> <li class="ntn-li"><span class="fa fa-trash nt-ico"></span> 回收管理</li> <li class="ntn-li"><span class="fa fa-users nt-ico"></span> 用户管理</li> <li class="ntn-li"><span class="fa fa-fire nt-ico"></span> 管理员管理</li> <li class="ntn-li"><span class="fa fa-cogs nt-ico"></span> 网站设置</li> </ul> <ul class="nt-msg list-unstyled"> <li class="nt-go-index"><a href="<?php echo U('Home/Index/index');?>" target="_blank"><span class="fa fa-home"></span> 前台首页</a></li> <li class="nt-sign-out"><a href="<?php echo U('Admin/Login/logout');?>"><span class="fa fa-sign-out"></span> 退出</a></li> </ul> </div> <div id="nav-left"> <div class="nl-con nl-show"> <dl> <dt><span class="fa fa-th"></span> 文章管理</dt> <dd><a href="<?php echo U('Admin/Article/add');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 添加文章 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd><dd><a href="<?php echo U('Admin/Article/index');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 文章列表 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd> </dl> <dl> <dt><span class="fa fa-tags"></span> 标签管理</dt> <dd><a href="<?php echo U('Admin/Tag/add');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 添加标签 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd><dd><a href="<?php echo U('Admin/Tag/index');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 标签列表 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd> </dl> <dl> <dt><span class="fa fa-columns"></span> 分类管理</dt> <dd><a href="<?php echo U('Admin/Category/add');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 添加分类 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd><dd><a href="<?php echo U('Admin/Category/index');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 分类列表 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd> </dl> </div> <div class="nl-con"> <dl> <dt><span class="fa fa-comment-o"></span> 评论管理</dt> <dd><a href="<?php echo U('Admin/Comment/index');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 评论列表 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd> </dl> <dl> <dt><span class="fa fa-list-alt"></span> 随言碎语</dt> <dd><a href="<?php echo U('Admin/Chat/add');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 添加碎言 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd><dd><a href="<?php echo U('Admin/Chat/index');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 碎言列表 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd> </dl> </div> <div class="nl-con"> <dl> <dt><span class="fa fa-trash-o"></span> 回收管理</dt> <dd><a href="<?php echo U('Admin/Recycle/article');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 已删文章 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd><dd><a href="<?php echo U('Admin/Recycle/comment');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 已删评论 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd><dd><a href="<?php echo U('Admin/Recycle/chat');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 已删随言 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd><dd><a href="<?php echo U('Admin/Recycle/link');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 已删友链 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd> </dl> </div> <div class="nl-con"> <dl> <dt><span class="fa fa-user"></span> 用户管理</dt> <dd><a href="<?php echo U('Admin/User/index');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 第三方用户 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd> </dl> </div> <div class="nl-con"> <dl> <dt><span class="fa fa-user"></span> 管理员管理</dt> <dd><a href="<?php echo U('Admin/Admin/index');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 管理员列表 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd> <dd><a href="<?php echo U('Admin/Admin/add');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 管理员添加 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd> </dl> </div> <div class="nl-con"> <dl> <dt><span class="fa fa-cog"></span> 基本设置</dt> <dd><a href="<?php echo U('Admin/Config/index');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 网站信息 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd><dd><a href="<?php echo U('Admin/Config/change_password');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 修改密码 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd> </dl> <dl> <dt><span class="fa fa-heart"></span> 友情链接</dt> <dd><a href="<?php echo U('Admin/Link/add');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 添加友链 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd><dd><a href="<?php echo U('Admin/Link/index');?>" target="right_content"></a><span class="fa fa-caret-right"></span> 友链列表 <div class="nl-checked"> <div class="nl-arrows"> </div> </div> </dd> </dl> </div> </div> <div id="content"> <iframe id="content-iframe" src="<?php echo U('Admin/Index/welcome');?>" frameborder="0" width="100%" height="100%" name="right_content" scrolling="auto" frameborder="0" scrolling="no"> </iframe> </div> <script src="/blog/Public/static/js/jquery-2.0.0.min.js"></script> <script> logoutUrl="<?php echo U('Home/User/logout');?>"; </script> <script src="/blog/Public/static/bootstrap-3.3.5/js/bootstrap.min.js"></script> <!--[if lt IE 9]> <script src="/blog/Public/static/js/html5shiv.min.js"></script> <script src="/blog/Public/static/js/respond.min.js"></script> <![endif]--> <script src="/blog/Public/static/pace/pace.min.js"></script> <script src="/blog/Template/default/Home/Public/js/index.js"></script> <!-- 百度页面自动提交开始 --> <script> (function(){ var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })(); </script> <!-- 百度页面自动提交结束 --> <!-- 百度统计开始 --> <!-- 百度统计结束 --> <script type="text/javascript" src="/blog/Template/default/Admin/Public/js/index.js"></script> <script> // 动态调整iframe的高度以适应不同高度的显示器 $('#content').height($(window).height()); $('#content').css('padding-bottom',50); </script></body></html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>bjyblog后台管理</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/bootstrap-3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/bootstrap-3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/font-awesome-4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/css/bjy.css"> <link rel="stylesheet" type="text/css" href="/blog/Template/default_src/Home/Public/css/index.css"> <link rel="stylesheet" type="text/css" href="/blog/Template/default_src/Admin/Public/css/index.css" /> </head> <body> <!-- 顶部导航菜单开始 --> <div id="nav-top"> <div class="nt-logo"> <a href="<?php echo U('Admin/Index/index');?>"></a> <span>bjyblog</span> </div> <ul class="nt-nav list-unstyled"> <li class="ntn-li ntn-active"> <span class="fa fa-list-ul nt-ico"></span> 内容管理 </li> <li class="ntn-li"> <span class="fa fa-comments nt-ico"></span> 碎言评论 </li> <li class="ntn-li"> <span class="fa fa-trash nt-ico"></span> 回收管理 </li> <li class="ntn-li"> <span class="fa fa-users nt-ico"></span> 用户管理 </li> <li class="ntn-li"> <span class="fa fa-cogs nt-ico"></span> 网站设置 </li> </ul> <ul class="nt-msg list-unstyled"> <li class="nt-go-index"> <a href="<?php echo U('Home/Index/index');?>" target="_blank"><span class="fa fa-home"></span>前台首页</a> </li> <li class="nt-sign-out"> <a href="<?php echo U('Admin/Login/logout');?>"><span class="fa fa-sign-out"></span>退出</a> </li> </ul> </div> <!-- 顶部导航菜单结束 --> <!-- 左侧导航菜单开始 --> <div id="nav-left"> <!-- 内容管理开始 --> <div class="nl-con nl-show"> <dl> <dt> <span class="fa fa-th"></span>文章管理 </dt> <dd> <a href="<?php echo U('Admin/Article/add');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>添加文章 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> <dd> <a href="<?php echo U('Admin/Article/index');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>文章列表 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> </dl> <dl> <dt> <span class="fa fa-tags"></span>标签管理 </dt> <dd> <a href="<?php echo U('Admin/Tag/add');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>添加标签 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> <dd> <a href="<?php echo U('Admin/Tag/index');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>标签列表 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> </dl> <dl> <dt> <span class="fa fa-columns"></span>分类管理 </dt> <dd> <a href="<?php echo U('Admin/Category/add');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>添加分类 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> <dd> <a href="<?php echo U('Admin/Category/index');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>分类列表 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> </dl> </div> <!-- 内容管理结束 --> <!-- 留言评论开始 --> <div class="nl-con"> <dl> <dt> <span class="fa fa-comment-o"></span>评论管理 </dt> <dd> <a href="<?php echo U('Admin/Comment/index');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>评论列表 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> </dl> <dl> <dt> <span class="fa fa-list-alt"></span>随言碎语 </dt> <dd> <a href="<?php echo U('Admin/Chat/add');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>添加碎言 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> <dd> <a href="<?php echo U('Admin/Chat/index');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>碎言列表 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> </dl> </div> <!-- 留言评论结束 --> <!-- 回收管理开始 --> <div class="nl-con"> <dl> <dt> <span class="fa fa-trash-o"></span>回收管理 </dt> <dd> <a href="<?php echo U('Admin/Recycle/article');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>已删文章 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> <dd> <a href="<?php echo U('Admin/Recycle/comment');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>已删评论 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> <dd> <a href="<?php echo U('Admin/Recycle/chat');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>已删随言 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> <dd> <a href="<?php echo U('Admin/Recycle/link');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>已删友链 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> </dl> </div> <!-- 回收管理结束 --> <!-- 用户管理开始 --> <div class="nl-con"> <dl> <dt> <span class="fa fa-user"></span>用户管理 </dt> <dd> <a href="<?php echo U('Admin/User/index');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>第三方用户 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> </dl> </div> <!-- 用户管理结束 --> <!-- 网站设置开始 --> <div class="nl-con"> <dl> <dt> <span class="fa fa-cog"></span>基本设置 </dt> <dd> <a href="<?php echo U('Admin/Config/index');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>网站信息 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> <dd> <a href="<?php echo U('Admin/Config/change_password');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>修改密码 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> </dl> <dl> <dt> <span class="fa fa-heart"></span>友情链接 </dt> <dd> <a href="<?php echo U('Admin/Link/add');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>添加友链 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> <dd> <a href="<?php echo U('Admin/Link/index');?>" target="right_content"></a> <span class="fa fa-caret-right"></span>友链列表 <div class="nl-checked"> <div class="nl-arrows"></div> </div> </dd> </dl> </div> <!-- 网站设置结束 --> </div> <!-- 左侧导航菜单结束 --> <!-- 右侧内容开始 --> <div id="content"> <iframe id="content-iframe" src="<?php echo U('Admin/Index/welcome');?>" frameborder="0" width="100%" height="100%" name="right_content" scrolling="auto" frameborder="0" scrolling="no"></iframe> </div> <!-- 右侧内容结束 --> <script src="/blog/Public/static/js/jquery-2.0.0.min.js"></script> <script> logoutUrl="<?php echo U('Home/User/logout');?>"; </script> <script src="/blog/Public/static/bootstrap-3.3.5/js/bootstrap.min.js"></script> <!--[if lt IE 9]> <script src="/blog/Public/static/js/html5shiv.min.js"></script> <script src="/blog/Public/static/js/respond.min.js"></script> <![endif]--> <script src="/blog/Public/static/pace/pace.min.js"></script> <script src="/blog/Template/default_src/Home/Public/js/index.js"></script> <!-- 百度页面自动提交开始 --> <script> (function(){ var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })(); </script> <!-- 百度页面自动提交结束 --> <!-- 百度统计开始 --> <!-- 百度统计结束 --> <script type="text/javascript" src="/blog/Template/default_src/Admin/Public/js/index.js"></script> <script> // 动态调整iframe的高度以适应不同高度的显示器 $('#content').height($(window).height()); $('#content').css('padding-bottom',50); </script> </body> </html><file_sep><?php namespace Home\Controller; use Common\Controller\HomeBaseController; class GamesController extends HomeBaseController { /*五子棋*/ public function gobang(){ $this->display(); } }<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>网站信息</title><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/bootstrap-3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/bootstrap-3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/font-awesome-4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="/blog/Public/static/css/bjy.css"> <link rel="stylesheet" type="text/css" href="/blog/Template/default/Home/Public/css/index.css"> <link rel="stylesheet" href="/blog/Public/static/iCheck-1.0.2/skins/all.css"> </head> <body> <form action="<?php echo U('Admin/Config/index');?>" method="post"> <ul class="nav nav-tabs"> <li class="active"><a href="#basic" data-toggle="tab">网站设置</a></li> <li><a href="#seo" data-toggle="tab">优化推广</a></li> <li><a href="#water" data-toggle="tab">文章水印</a></li> <li><a href="#oauth" data-toggle="tab">第三方登录</a></li> <li><a href="#other" data-toggle="tab">其他第三方接口</a></li> <li><a href="#email" data-toggle="tab">邮箱设置</a></li> <li><a href="#comment" data-toggle="tab">评论设置</a></li> </ul> <div class="tab-content"> <div class="tab-pane fade in active" id="basic"> <table class="table table-bordered table-hover"> <tr> <th> 网站状态: </th> <td> <span class="inputword">开启</span><input class="icheck" type="radio" name="WEB_STATUS" value="1" <?php if(($data['WEB_STATUS']) == "1"): ?>checked="checked"<?php endif; ?> > <span class="inputword">关闭</span><input class="icheck" type="radio" name="WEB_STATUS" value="0" <?php if(($data['WEB_STATUS']) == "0"): ?>checked="checked"<?php endif; ?> > </td> </tr> <tr> <th> 网站关闭时提示文字: </th> <td> <textarea class="form-control modal-sm" name="WEB_CLOSE_WORD" rows="5" placeholder=""><?php echo ($data['WEB_CLOSE_WORD']); ?></textarea> </td> </tr> <tr> <th> 备案号: </th> <td> <input class="form-control modal-sm" type="text" name="WEB_ICP_NUMBER" value="<?php echo ($data['WEB_ICP_NUMBER']); ?>"> </td> </tr> <tr> <th> 站长邮箱: </th> <td> <input class="form-control modal-sm" type="text" name="ADMIN_EMAIL" value="<?php echo ($data['ADMIN_EMAIL']); ?>"> </td> </tr> </table> </div> <div class="tab-pane fade" id="seo"> <table class="table table-bordered table-hover"> <tr> <th> 网站名: </th> <td> <input class="form-control modal-sm" type="text" name="WEB_NAME" value="<?php echo ($data['WEB_NAME']); ?>"> </td> </tr> <tr> <th> 网站关键字: </th> <td> <textarea class="form-control modal-sm" name="WEB_KEYWORDS" rows="5" placeholder=""><?php echo ($data['WEB_KEYWORDS']); ?></textarea> </td> </tr> <tr> <th> 网站描述: </th> <td> <textarea class="form-control modal-sm" name="WEB_DESCRIPTION" rows="5" placeholder=""><?php echo ($data['WEB_DESCRIPTION']); ?></textarea> </td> </tr> <tr> <th> 默认作者: </th> <td> <input class="form-control modal-sm" type="text" name="AUTHOR" value="<?php echo ($data['AUTHOR']); ?>"> </td> </tr> <tr> <th> 文章保留版权提示: </th> <td> <textarea class="form-control modal-sm" name="COPYRIGHT_WORD" rows="5" placeholder=""><?php echo ($data['COPYRIGHT_WORD']); ?></textarea> </td> </tr> <tr> <th> 文章图片title和alt内容: </th> <td> <input class="form-control modal-sm" type="text" name="IMAGE_TITLE_ALT_WORD" value="<?php echo ($data['IMAGE_TITLE_ALT_WORD']); ?>"> </td> </tr> </table> </div> <div class="tab-pane fade" id="water"> <table class="table table-bordered table-hover"> <tr> <th> 水印类型: </th> <td> <span class="inputword">文字水印</span><input class="icheck" type="radio" name="WATER_TYPE" value="1" <?php if(($data['WATER_TYPE']) == "1"): ?>checked="checked"<?php endif; ?> > <span class="inputword">图片水印</span><input class="icheck" type="radio" name="WATER_TYPE" value="2" <?php if(($data['WATER_TYPE']) == "2"): ?>checked="checked"<?php endif; ?> > <span class="inputword">关闭水印</span><input class="icheck" type="radio" name="WATER_TYPE" value="0" <?php if(($data['WATER_TYPE']) == "0"): ?>checked="checked"<?php endif; ?> > </td> </tr> <tr> <th> 文字水印内容: </th> <td> <input class="form-control modal-sm" type="text" name="TEXT_WATER_WORD" value="<?php echo ($data['TEXT_WATER_WORD']); ?>"> </td> </tr> <tr> <th> 文字水印字体路径: </th> <td> <input class="form-control modal-sm" type="text" name="TEXT_WATER_TTF_PTH" value="<?php echo ($data['TEXT_WATER_TTF_PTH']); ?>"> </td> </tr> <tr> <th> 文字水印文字字号: </th> <td> <input class="form-control modal-sm" type="text" name="TEXT_WATER_FONT_SIZE" value="<?php echo ($data['TEXT_WATER_FONT_SIZE']); ?>"> </td> </tr> <tr> <th> 文字水印文字颜色: </th> <td> <input class="form-control modal-sm" type="text" name="TEXT_WATER_COLOR" value="<?php echo ($data['TEXT_WATER_COLOR']); ?>"> </td> </tr> <tr> <th> 文字水印文字倾斜程度: </th> <td> <input class="form-control modal-sm" type="text" name="TEXT_WATER_ANGLE" value="<?php echo ($data['TEXT_WATER_ANGLE']); ?>"> </td> </tr> <tr> <th> 文字水印位置: </th> <td> <span class="inputword">上左</span><input class="icheck" type="radio" name="TEXT_WATER_LOCATE" value="1" <?php if(($data['TEXT_WATER_LOCATE']) == "1"): ?>checked="checked"<?php endif; ?> > <span class="inputword">上中</span><input class="icheck" type="radio" name="TEXT_WATER_LOCATE" value="2" <?php if(($data['TEXT_WATER_LOCATE']) == "2"): ?>checked="checked"<?php endif; ?> > <span class="inputword">上右</span><input class="icheck" type="radio" name="TEXT_WATER_LOCATE" value="3" <?php if(($data['TEXT_WATER_LOCATE']) == "3"): ?>checked="checked"<?php endif; ?> ><br> <span class="inputword">中左</span><input class="icheck" type="radio" name="TEXT_WATER_LOCATE" value="4" <?php if(($data['TEXT_WATER_LOCATE']) == "4"): ?>checked="checked"<?php endif; ?> > <span class="inputword">中中</span><input class="icheck" type="radio" name="TEXT_WATER_LOCATE" value="5" <?php if(($data['TEXT_WATER_LOCATE']) == "5"): ?>checked="checked"<?php endif; ?> > <span class="inputword">中右</span><input class="icheck" type="radio" name="TEXT_WATER_LOCATE" value="6" <?php if(($data['TEXT_WATER_LOCATE']) == "6"): ?>checked="checked"<?php endif; ?> ><br> <span class="inputword">下左</span><input class="icheck" type="radio" name="TEXT_WATER_LOCATE" value="7" <?php if(($data['TEXT_WATER_LOCATE']) == "7"): ?>checked="checked"<?php endif; ?> > <span class="inputword">下中</span><input class="icheck" type="radio" name="TEXT_WATER_LOCATE" value="8" <?php if(($data['TEXT_WATER_LOCATE']) == "8"): ?>checked="checked"<?php endif; ?> > <span class="inputword">下右</span><input class="icheck" type="radio" name="TEXT_WATER_LOCATE" value="9" <?php if(($data['TEXT_WATER_LOCATE']) == "9"): ?>checked="checked"<?php endif; ?> > </td> </tr> <tr> <th> 图片水印来源路径: </th> <td> <input class="form-control modal-sm" type="text" name="IMAGE_WATER_PIC_PTAH" value="<?php echo ($data['IMAGE_WATER_PIC_PTAH']); ?>"> </td> </tr> <tr> <th> 图片水印位置: </th> <td> <span class="inputword">上左</span><input class="icheck" type="radio" name="IMAGE_WATER_LOCATE" value="1" <?php if(($data['IMAGE_WATER_LOCATE']) == "1"): ?>checked="checked"<?php endif; ?> > <span class="inputword">上中</span><input class="icheck" type="radio" name="IMAGE_WATER_LOCATE" value="2" <?php if(($data['IMAGE_WATER_LOCATE']) == "2"): ?>checked="checked"<?php endif; ?> > <span class="inputword">上右</span><input class="icheck" type="radio" name="IMAGE_WATER_LOCATE" value="3" <?php if(($data['IMAGE_WATER_LOCATE']) == "3"): ?>checked="checked"<?php endif; ?> ><br> <span class="inputword">中左</span><input class="icheck" type="radio" name="IMAGE_WATER_LOCATE" value="4" <?php if(($data['IMAGE_WATER_LOCATE']) == "4"): ?>checked="checked"<?php endif; ?> > <span class="inputword">中中</span><input class="icheck" type="radio" name="IMAGE_WATER_LOCATE" value="5" <?php if(($data['IMAGE_WATER_LOCATE']) == "5"): ?>checked="checked"<?php endif; ?> > <span class="inputword">中右</span><input class="icheck" type="radio" name="IMAGE_WATER_LOCATE" value="6" <?php if(($data['IMAGE_WATER_LOCATE']) == "6"): ?>checked="checked"<?php endif; ?> ><br> <span class="inputword">下左</span><input class="icheck" type="radio" name="IMAGE_WATER_LOCATE" value="7" <?php if(($data['IMAGE_WATER_LOCATE']) == "7"): ?>checked="checked"<?php endif; ?> > <span class="inputword">下中</span><input class="icheck" type="radio" name="IMAGE_WATER_LOCATE" value="8" <?php if(($data['IMAGE_WATER_LOCATE']) == "8"): ?>checked="checked"<?php endif; ?> > <span class="inputword">下右</span><input class="icheck" type="radio" name="IMAGE_WATER_LOCATE" value="9" <?php if(($data['IMAGE_WATER_LOCATE']) == "9"): ?>checked="checked"<?php endif; ?> > </td> </tr> <tr> <th> 图片水印透明度: </th> <td> <input class="form-control modal-sm" type="text" name="IMAGE_WATER_ALPHA" value="<?php echo ($data['IMAGE_WATER_ALPHA']); ?>"> </td> </tr> </table> </div> <div class="tab-pane fade" id="oauth"> <table class="table table-bordered table-hover"> <tr> <th> QQ登录APP ID: </th> <td> <input class="form-control modal-sm" type="text" name="QQ_APP_ID" value="<?php echo ($data['QQ_APP_ID']); ?>"> </td> </tr> <tr> <th> QQ登录APP KEY: </th> <td> <input class="form-control modal-sm" type="text" name="QQ_APP_KEY" value="<?php echo ($data['QQ_APP_KEY']); ?>"> </td> </tr> <tr> <th> 新浪微博登录API KEY: </th> <td> <input class="form-control modal-sm" type="text" name="SINA_API_KEY" value="<?php echo ($data['SINA_API_KEY']); ?>"> </td> </tr> <tr> <th> 新浪微博登录SECRET: </th> <td> <input class="form-control modal-sm" type="text" name="SINA_SECRET" value="<?php echo ($data['SINA_SECRET']); ?>"> </td> </tr> <tr> <th> 豆瓣登录API KEY: </th> <td> <input class="form-control modal-sm" type="text" name="DOUBAN_API_KEY" value="<?php echo ($data['DOUBAN_API_KEY']); ?>"> </td> </tr> <tr> <th> 豆瓣登录SECRET: </th> <td> <input class="form-control modal-sm" type="text" name="DOUBAN_SECRET" value="<?php echo ($data['DOUBAN_SECRET']); ?>"> </td> </tr> <tr> <th> 人人登录API KEY: </th> <td> <input class="form-control modal-sm" type="text" name="RENREN_API_KEY" value="<?php echo ($data['RENREN_API_KEY']); ?>"> </td> </tr> <tr> <th> 人人登录SECRET: </th> <td> <input class="form-control modal-sm" type="text" name="RENREN_SECRET" value="<?php echo ($data['RENREN_SECRET']); ?>"> </td> </tr> <tr> <th> 开心网登录API KEY: </th> <td> <input class="form-control modal-sm" type="text" name="KAIXIN_API_KEY" value="<?php echo ($data['KAIXIN_API_KEY']); ?>"> </td> </tr> <tr> <th> 开心网登录SECRET: </th> <td> <input class="form-control modal-sm" type="text" name="KAIXIN_SECRET" value="<?php echo ($data['KAIXIN_SECRET']); ?>"> </td> </tr> <tr> <th> github Client ID: </th> <td> <input class="form-control modal-sm" type="text" name="GITHUB_CLIENT_ID" value="<?php echo ($data['GITHUB_CLIENT_ID']); ?>"> </td> </tr> <tr> <th> github Client Secret: </th> <td> <input class="form-control modal-sm" type="text" name="GITHUB_CLIENT_SECRET" value="<?php echo ($data['GITHUB_CLIENT_SECRET']); ?>"> </td> </tr> <tr> <th> 搜狐登录API KEY: </th> <td> <input class="form-control modal-sm" type="text" name="SOHU_API_KEY" value="<?php echo ($data['SOHU_API_KEY']); ?>"> </td> </tr> <tr> <th> 搜狐登录SECRET: </th> <td> <input class="form-control modal-sm" type="text" name="SOHU_SECRET" value="<?php echo ($data['SOHU_SECRET']); ?>"> </td> </tr> </table> </div> <div class="tab-pane fade" id="other"> <table class="table table-bordered table-hover"> <tr> <th> 百度推送site提交链接: </th> <td> <input class="form-control modal-sm" type="text" name="BAIDU_SITE_URL" value="<?php echo ($data['BAIDU_SITE_URL']); ?>"> </td> </tr> <tr> <th> 第三方统计代码: </th> <td> <textarea class="form-control modal-sm" name="WEB_STATISTICS" rows="5" placeholder=""><?php echo ($data['WEB_STATISTICS']); ?></textarea> </td> </tr> </table> </div> <div class="tab-pane fade" id="email"> <table class="table table-bordered table-hover"> <tr> <th> SMTP服务器: </th> <td> <input class="form-control modal-sm" type="text" name="EMAIL_SMTP" value="<?php echo ($data['EMAIL_SMTP']); ?>"> </td> </tr> <tr> <th> 邮箱账号: </th> <td> <input class="form-control modal-sm" type="text" name="EMAIL_USERNAME" value="<?php echo ($data['EMAIL_USERNAME']); ?>"> </td> </tr> <tr> <th> 邮箱密码: </th> <td> <input class="form-control modal-sm" type="text" name="EMAIL_PASSWORD" value="<?php echo ($data['EMAIL_PASSWORD']); ?>"> </td> </tr> <tr> <th> 发件人名称: </th> <td> <input class="form-control modal-sm" type="text" name="EMAIL_FROM_NAME" value="<?php echo ($data['EMAIL_FROM_NAME']); ?>"> </td> </tr> </table> </div> <div class="tab-pane fade" id="comment"> <table class="table table-bordered table-hover"> <tr> <th> 开启评论审核: </th> <td> <span class="inputword">开启</span><input class="icheck" type="radio" name="COMMENT_REVIEW" value="1" <?php if(($data['COMMENT_REVIEW']) == "1"): ?>checked="checked"<?php endif; ?> > <span class="inputword">关闭</span><input class="icheck" type="radio" name="COMMENT_REVIEW" value="0" <?php if(($data['COMMENT_REVIEW']) == "0"): ?>checked="checked"<?php endif; ?> > </td> </tr> <tr> <th> 发送被评论邮件: </th> <td> <span class="inputword">开启</span><input class="icheck" type="radio" name="COMMENT_SEND_EMAIL" value="1" <?php if(($data['COMMENT_SEND_EMAIL']) == "1"): ?>checked="checked"<?php endif; ?> > <span class="inputword">关闭</span><input class="icheck" type="radio" name="COMMENT_SEND_EMAIL" value="0" <?php if(($data['COMMENT_SEND_EMAIL']) == "0"): ?>checked="checked"<?php endif; ?> > </td> </tr> <tr> <th> 接收评论通知邮箱: </th> <td> <input class="form-control modal-sm" type="text" name="EMAIL_RECEIVE" value="<?php echo ($data['EMAIL_RECEIVE']); ?>"> </td> </tr> </table> </div> </div> <div> <input class="btn btn-success" type="submit" value="提交"> </div> </form> <script src="/blog/Public/static/js/jquery-2.0.0.min.js"></script> <script> logoutUrl="<?php echo U('Home/User/logout');?>"; </script> <script src="/blog/Public/static/bootstrap-3.3.5/js/bootstrap.min.js"></script> <!--[if lt IE 9]> <script src="/blog/Public/static/js/html5shiv.min.js"></script> <script src="/blog/Public/static/js/respond.min.js"></script> <![endif]--> <script src="/blog/Public/static/pace/pace.min.js"></script> <script src="/blog/Template/default/Home/Public/js/index.js"></script> <!-- 百度页面自动提交开始 --> <script> (function(){ var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })(); </script> <!-- 百度页面自动提交结束 --> <!-- 百度统计开始 --> <!-- 百度统计结束 --><icheckjs/> </body> </html><file_sep><?php namespace Admin\Controller; use Common\Controller\AdminBaseController; /** * 管理员管理 */ class AdminController extends AdminBaseController{ // 定义数据表 private $db; private $viewDb; // 构造函数 实例化ArticleModel表 public function __construct(){ parent::__construct(); $this->db=D('Admin'); } //管理员列表 public function index(){ $data=$this->db->select(); $this->assign('data',$data); $this->display(); } //管理员添加 public function add(){ if (IS_POST) { }else{ $this->display(); } } } <file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加管理员</title><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" type="text/css" href="/Public/static/bootstrap-3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/Public/static/bootstrap-3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="/Public/static/font-awesome-4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="/Public/static/css/bjy.css"> <link rel="stylesheet" type="text/css" href="/Template/default/Home/Public/css/index.css"> <link rel="stylesheet" href="/Public/static/iCheck-1.0.2/skins/all.css"> <style> .modal-sm{ float: left; } .tishi{ float: left; line-height: 34px; } </style> </head> <body> <form class="form-group" action="<?php echo U('Admin/Admin/add');?>" method="post"> <table class="table table-bordered table-striped table-hover table-condensed"> <tr> <th> 管理员名称 </th> <td> <input class="form-control modal-sm" type="text" name="name" placeholder=""> <span class="tishi">123</span> </td> </tr> <tr> <th> 密码 </th> <td> <input class="form-control modal-sm" type="text" name="password"> <span class="tishi">123</span> </td> </tr> <tr> <th> 确认密码 </th> <td> <input class="form-control modal-sm" placeholder="请重复密码" type="text" name="confirm"> <span class="tishi">123</span> </td> </tr> <tr> <th> 邮箱 </th> <td> <input class="form-control modal-sm" placeholder="" type="text" name="email"> <span class="tishi">123</span> </td> </tr> <tr> <th width="80px"> 权限角色 </th> <td> <select class="form-control modal-sm" name="rool"> <!-- <?php if(is_array($allCategory)): foreach($allCategory as $key=>$v): ?><option value="<?php echo ($v['cid']); ?>"><?php echo ($v['_name']); ?></option><?php endforeach; endif; ?> --> </select> </td> </tr> <tr> <th> 性别 </th> <td> <label><span class="inputword">男</span><input class="icheck" type="radio" name="sex" value="1" checked="checked"></label> &emsp; <label><span class="inputword">女</span><input class="icheck" type="radio" name="sex" value="2"></label>&emsp; <label><span class="inputword">保密</span><input class="icheck" type="radio" name="sex" value="0"></label> </td> </tr> <tr> <th> </th> <td> <input class="btn btn-success" type="submit" value="添加管理员"> </td> </tr> </table> </form> <script src="/Public/static/js/jquery-2.0.0.min.js"></script> <script> logoutUrl="<?php echo U('Home/User/logout');?>"; </script> <script src="/Public/static/bootstrap-3.3.5/js/bootstrap.min.js"></script> <!--[if lt IE 9]> <script src="/Public/static/js/html5shiv.min.js"></script> <script src="/Public/static/js/respond.min.js"></script> <![endif]--> <script src="/Public/static/pace/pace.min.js"></script> <script src="/Template/default/Home/Public/js/index.js"></script> <!-- 百度页面自动提交开始 --> <script> (function(){ var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })(); </script> <!-- 百度页面自动提交结束 --> <!-- 百度统计开始 --> <!-- 百度统计结束 --><script src="/Public/static/iCheck-1.0.2/icheck.min.js"></script> <script> $(document).ready(function(){ $('.icheck').iCheck({ checkboxClass: "icheckbox_square-blue", radioClass: "iradio_square-blue", increaseArea: "20%" }); }); </script> </body> </html><file_sep># thinkphp-JTMblog ## 链接 - 博客:http://www.lizhengmeng.club - github:https://github.com/lizhengmeng ## 使用说明 1. 请将项目内的所有文件直接放在根目录下;不要多层目录; 例如正确:www/;错误:www/thinkjtm/; 2. 后台登录密码默认为<PASSWORD>; 3. 如果确认开启了mod_rewrite 请将/Application/Common/Conf/config.php中的URL_MODEL改为2以优化url; 未开启路由:http://www.lizhengmeng.com/index.php/Home/Index/article/aid/60 开启路由后:http://www.lizhengmeng.com/article/60 4. 把根目录下的robots.txt中的 www.lizhengmeng.com 改为自己的域名; 5. 可以在用户管理中;将第三方账号标记为站长;然后后台就必须使用第三方账号登录以增强安全性; ## 针对thinkphp的改进优化; 1. 修复tinkphp的session设置周期无效的bug; 2. 自定义标签 /Application/Common/Tag/My.class.php; 3. 将html视图页面分离; ## 项目介绍 1. 前台基于boostrap的响应式页面布局适配手机和平板; 2. 带表情的ajax无限级评论系统; 3. PHPMail邮件系统; 4. QQ、微博、豆瓣、人人、开心网等第三方登录; 5. ueditor 百度富文本编辑器; 7. font-awesome; 8. iCheck; ## 商业友好的开源协议 jtmblog遵循Apache2开源协议发布。Apache Licence是著名的非盈利开源组织Apache采用的协议。该协议和BSD类似,鼓励代码共享和尊重原作者的著作权,同样允许代码修改,再作为开源或商业软件发布。 <file_sep>"use strict"; function getWidthLeft(t, o) { var e = t.position().left, i = t.width(), n = { left: e, width: i }; return o ? void $(".b-nav-mobile").stop().animate({ left: e, width: i }, 300) : n } function login() { $("#b-modal-login").modal("show"), setCookie("this_url", window.location.href) } function logout() { $.post(logoutUrl), setTimeout(function() { location.replace(location) }, 500) } function goTop() { return $("body,html").animate({ scrollTop: 0 }, 500), !1 } function setCookie(t, o, e) { if (e) { var i = new Date; i.setTime(i.getTime() + 24 * e * 60 * 60 * 1e3); var n = "; expires=" + i.toGMTString() } else var n = ""; document.cookie = t + "=" + o + n + "; path=/" } function getCookie(t) { for (var o = t + "=", e = document.cookie.split(";"), i = 0; i < e.length; i++) { for (var n = e[i]; " " == n.charAt(0);) n = n.substring(1, n.length); if (0 == n.indexOf(o)) return n.substring(o.length, n.length) } return null } function deleteCookie(t) { setCookie(t, "", -1) } function recordId(t, o) { return setCookie("cid", 0), setCookie("tid", 0), setCookie("search_word", 0), "index" != t && "/" != t && setCookie(t, o), !0 } $(function() { var a_idx = 0; $("body").click(function(e) { var a = new Array("富强", "民主", "文明", "和谐", "自由", "平等", "公正" ,"法治", "爱国", "敬业", "诚信", "友善"); // var a = new Array("哈喽", "看到我吗", "我在这儿", "我是彩蛋", "嘻嘻", "好玩吗", "好玩你就多点点" ,"你一点", "我就", "出来", "好了", "认真点", "我要说正事了", "为了防止世界被破坏", "为了守护世界的和平", "贯彻爱与真实的邪恶", "贯彻爱与真实的邪恶", "接下来", "跟我念!", "富强", "民主", "文明", "和谐", "自由", "平等", "公正" ,"法治", "爱国", "敬业", "诚信", "友善", "好了", "我说完了", "说了好多", "有点累了", "我要休息了", "你自己玩吧", "别打扰我", "886", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "你还在点吗", "你好执着哦", "都说了", "我要睡了", "你不累吗", "我要睡了", "求求你", "让我休息", "一下下", "好不好", "(o-ωq))", "再见咯", "有空常来", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "zzzzZ~", "你还在点", "好吧好吧", "I服了U"); var $i = $("<span/>").text(a[a_idx]); a_idx = (a_idx + 1) % a.length; var x = e.pageX, y = e.pageY; $i.css({ "z-index": 999999999999999999999999999999999999999999999999999999999999999999999, "top": y - 20, "left": x, "position": "absolute", "font-weight": "bold", "color": "#ff6651" }); $("body").append($i); $i.animate({ "top": y - 180, "opacity": 0 }, 1500, function() { $i.remove(); }); }); if ("block" == $(".b-nav-mobile").css("display")) { var t = getWidthLeft($(".b-nav-active"), !1); $(".b-nav-mobile").css({ width: t.width, left: t.left }) } $(".b-nav-parent li").hover(function() { getWidthLeft($(this), !0) }, function() { getWidthLeft($(".b-nav-active"), !0) }), $(".b-article iframe").width("95%"), $(window).scroll(function(t) { $(window).scrollTop() > 200 ? ($(".go-top").show(), $(".go-top").removeClass("animated rotateOut"), $(".go-top").addClass("animated rotateIn")) : ($(".go-top").removeClass("animated rotateIn"), $(".go-top").addClass("animated rotateOut")) }), window.innerWidth >= 768 && $(window).scroll(function(t) { $(window).scrollTop() > 100 ? $("#b-public-nav").stop().animate({ "padding-top": "0px", "padding-bottom": "0px" }, 100) : $("#b-public-nav").stop().animate({ "padding-top": "5px", "padding-bottom": "5px" }, 100) }), $(".b-page .first,.num,.end").addClass("hidden-xs"), $(".b-page .rows").addClass("hidden-xs"), $(".b-chat-middle").height($(".b-chat").height()), $(".b-arrows-right1,.b-arrows-right2").each(function(t, o) { $(o).css("top", $(o).parent(".b-chat-one").height() / 2.5) }), $.each($(".js-head-img"), function(t, o) { var e = $(o).attr("_src"); $(o).attr("src", e) }) });<file_sep><?php // 重定向到后台登录页面 header('Location:/blog/Admin/Index/index'); exit();
b5bcbb2bf03d66a171a26b74acb3922bfe29d697
[ "Markdown", "HTML", "JavaScript", "PHP" ]
13
Markdown
lizhengmeng/jtm_blog
54f34f090fd435d64d14578b63d23d96deb653f9
3e534c9a5c6c4de15092514862b35b16654a806b
refs/heads/master
<file_sep>'use strict' var pull = require('pull-stream') var para = require('pull-paramap') var Notify = require('pull-notify') var many = require('pull-many') var Cat = require('pull-cat') var Abort = require('pull-abortable') var Debounce = require('observ-debounce') var mdm = require('mdmanifest') var apidoc = require('../lib/apidocs').replicate var Pushable = require('pull-pushable') // compatibility function for old implementations of `latestSequence` function toSeq (s) { return 'number' === typeof s ? s : s.sequence } function last (a) { return a[a.length - 1] } module.exports = { name: 'replicate', version: '2.0.0', manifest: mdm.manifest(apidoc), //replicate: replicate, init: function (sbot, config) { var debounce = Debounce(200) var listeners = {} var notify = Notify() var newPeer = Notify() var total=0, progress=0, start, count = 0, rate=0 var to_send = {} var to_recv = {} var feeds = 0 debounce(function () { var _progress = progress, _total = total progress = 0; total = 0 for(var k in to_send) progress += to_send[k] for(var k in to_recv) if(to_send[k] !== null) total += to_recv[k] if(_progress !== progress || _total !== total) { notify({ id: sbot.id, total: total, progress: progress, rate: rate, feeds: feeds }) } }) pull( sbot.createLogStream({old: false, live: true, sync: false, keys: false}), pull.drain(function (e) { //track writes per second, mainly used for developing initial sync. if(!start) start = Date.now() var time = (Date.now() - start)/1000 if(time >= 1) { rate = count / time start = Date.now() count = 0 } var pushable = listeners[e.author] if(pushable && pushable.sequence == e.sequence) { pushable.sequence ++ pushable.forEach(function (p) { p.push(e) }) } count ++ addPeer({id: e.author, sequence: e.sequence}) }) ) //keep track of maximum requested value, per feed. sbot.createHistoryStream.hook(function (fn, args) { var upto = args[0] || {} var seq = upto.sequence || upto.seq to_recv[upto.id] = Math.max(to_recv[upto.id] || 0, seq) if(this._emit) this._emit('call:createHistoryStream', args[0]) //if we are calling this locally, skip cleverness if(this===sbot) return fn.call(this, upto) debounce.set() //handle creating lots of histor streams efficiently. //maybe this could be optimized in map-filter-reduce queries instead? if(to_send[upto.id] == null || (seq > to_send[upto.id])) { upto.old = false if(!upto.live) return pull.empty() var pushable = listeners[upto.id] = listeners[upto.id] || [] var p = Pushable(function () { var i = pushable.indexOf(p) pushable.splice(i, 1) }) pushable.push(p) pushable.sequence = upto.sequence return p } return fn.call(this, upto) }) // collect the IDs of feeds we want to request var opts = config.replication || {} opts.hops = opts.hops || 3 opts.dunbar = opts.dunbar || 150 opts.live = true opts.meta = true function localPeers () { if(!sbot.gossip) return sbot.gossip.peers() .forEach(function (e) { if(to_send[e.key] == null) addPeer({id: e.key, sequence: 0}) }) } //also request local peers. if (sbot.gossip) { // if we have the gossip plugin active, then include new local peers // so that you can put a name to someone on your local network. var int = setInterval(localPeers, 1000) if(int.unref) int.unref() localPeers() } function addPeer (upto) { if(upto.sync) return if(!upto.id) return console.log('invalid', upto) if(to_send[upto.id] == null) { to_send[upto.id] = Math.max(to_send[upto.id] || 0, upto.sequence || upto.seq || 0) newPeer({id: upto.id, sequence: to_send[upto.id] , type: 'new' }) } else to_send[upto.id] = Math.max(to_send[upto.id] || 0, upto.sequence || upto.seq || 0) debounce.set() } // create read-streams for the desired feeds var S = false pull( sbot.friends.createFriendStream(opts), // filter out duplicates, and also keep track of what we expect to receive // lookup the latest sequence from each user para(function (data, cb) { if(data.sync) return cb(null, S = data) var id = data.id || data sbot.latestSequence(id, function (err, seq) { cb(null, { id: id, sequence: err ? 0 : toSeq(seq) }) }) }, 32), pull.drain(addPeer) ) function upto (opts) { opts = opts || {} var ary = Object.keys(to_send).map(function (k) { return { id: k, sequence: to_send[k] } }) if(opts.live) return Cat([pull.values(ary), pull.once({sync: true}), newPeer.listen()]) return pull.values(ary) } sbot.on('rpc:connect', function(rpc) { // this is the cli client, just ignore. if(rpc.id === sbot.id) return //check for local peers, or manual connections. localPeers() var drain sbot.emit('replicate:start', rpc) rpc.on('closed', function () { sbot.emit('replicate:finish', to_send) }) var SYNC = false pull( upto({live: opts.live}), drain = pull.drain(function (upto) { if(upto.sync) return feeds++ debounce.set() pull( rpc.createHistoryStream({ id: upto.id, seq: (upto.sequence || upto.seq || 0) + 1, live: true, keys: false }), sbot.createWriteStream(function (err) { if(err) console.error(err.stack) feeds-- debounce.set() }) ) }, function (err) { if(err) sbot.emit('log:error', ['replication', rep.id, 'error', err]) }) ) }) return { changes: notify.listen, upto: upto, } } }
1ebedb4aaf82eedfbee8f557435694ebfd85ca12
[ "JavaScript" ]
1
JavaScript
marcbachmann/scuttlebot
2df2c99636d2696c17aecdfff99b2f9b184d4c40
44cb0c6dbff522e05289b7144c21c2986602e983
refs/heads/master
<repo_name>i14564/Practice-2016<file_sep>/src/main_check.py from checks import dates from checks import existance from checks import visitors from checks import whois_check from checks import subdomains def main_check(url): if existance.check('http://' + url)['status'] != 'Exist': print 'Site does not exist' else: print 'Connection established' whois_test = whois_check.check(url) if (whois_test["code"] == 0): print 'Domain not delegated' print 'It is fake' return subdomains_list = subdomains.check(url) subdomain_visitors = 0 if (len(subdomains_list) == 0): print 'site does not have subdomains' else: for subdomain in subdomains_list: subdomain_visitors+=visitors.check(subdomain)['value'] print 'site has ' + str(len(subdomains_list)) + ' subdomais' dates_test = dates.check('http://' + url) visitors_test = visitors.check(url) if ( visitors_test['code'] and (dates_test['code'] == 1)): print 'Site have ' + str(visitors_test['value']) + ' unique visitors each month.' print 'Site have an entity written ' + str(dates_test['last_entity']) + ' days ago.' print 'This site is not fake' elif (visitors_test['value'] >= 10000 + subdomain_visitors): print 'Site have ' + str(visitors_test['value']) + ' unique visitors each month. It is not fake' elif ( visitors_test['value'] >= 3000): print 'Site have ' + str(visitors_test['value']) + ' unique visitors each month. It may be not fake' elif ((dates_test['code'] != -1) and dates_test['last_entity'] < 100): print 'Site have an entity written ' + str(dates_test['last_entity']) + ' days ago. It may be not fake' else: print 'It is fake'<file_sep>/src/checks/subdomains.py import subbrute def check(url): data = [] for d in subbrute.run(url): data.append(d[0]) return data<file_sep>/src/checks/whois_check.py import whois def check(url): w = whois.whois(url) if (w.status.find('DELEGATED') != -1): print 'Domain delegated' return {'status': 'Delegated', 'code': 1} else: print 'Domain not delegated' return {'status': 'Not delegated', 'code': 0}<file_sep>/src/checks/existance.py import urllib def check(url): try: response = urllib.urlopen(url) except: return {'status':'Not Exist','code':0} return {'status': 'Exist', 'code': 1} <file_sep>/src/checks/visitors.py import lxml.html as LH def check(url): try: doc = LH.parse('http://www.siteworthtraffic.com/report/' + url) rows = doc.xpath("//table")[1].findall("tr") except IndexError : return {'status': 'Ok', 'code': 0, 'value': 0} data = list() for row in rows: data.append([c.text_content() for c in row.getchildren()]) visitors = int(data[0][1].replace(',', '')) if (visitors >= 3000): return {'status':'Ok','code':1,'value':visitors} else : return {'status': 'Ok', 'code': 0, 'value': visitors}<file_sep>/src/test.py from main_check import main_check print 'Testing yandex.ru' main_check('yandex.ru') print '_______________________' print 'Testing forte-it.ru' main_check('forte-it.ru') print '_______________________' print 'Testing sergeev-vf.ru' main_check('sergeev-vf.ru') print '_______________________' print 'Testing ruspred.ru' main_check('ruspred.ru') print '_______________________' <file_sep>/README.md # Задание Необходимо было проверить поддерживается ли сайт с помощью числа просмотров и дат на странице. Выполнил: <NAME> ИУ8-44 # Проверка сайта 1. Проверка существования сайта 2. Проверка делегирования домена 3. Проверка данных всех поддоменов 4. Проверка всех дат на сайте и оценка времени прошедшего с последней записи 5. Проверка посещяемости веб-сайта с помощью данных с каталога siteworthtraffic.com 6. Сравнение всей полученой информации # Технологии Использовался python 2.7 с помощью виртуализации в [Vagrant](https://www.vagrantup.com/) и python - пакеты : urllib, lxml, datefinder, argparse, dnslib, subbrute, knock, pywhois # Тесты Было протестированно несколько сайтов: 1. [yandex.ru](http://yandex.ru) - Поддерживается 2. [forte-it.ru](http://forte-it.ru) - Возможно поддерживается 3. [sergeev-vf](http://sergeev-vf).ru - Возможно поддерживается 4. [ruspred.ru](http://ruspred.ru) - Не поддерживается Видно что тесты были пройдены без ошибок # Скриншоты ![Terminal](https://raw.githubusercontent.com/i14564/Practice-2016/master/screenshots/command-line.png) ![Tests](https://raw.githubusercontent.com/i14564/Practice-2016/master/screenshots/tests.png) <file_sep>/src/main.py from main_check import main_check import argparse parser = argparse.ArgumentParser(description='Check website for fake') parser.add_argument('url', help='site url without protocol') url = args = parser.parse_args().url main_check(url) <file_sep>/bootstrap.sh #!/usr/bin/env bash sudo apt-get update sudo apt-get -y install python-pip sudo apt-get -y install libevent-dev python-dev sudo apt-get -y install libxml2-dev libxslt1-dev zlib1g-dev sudo apt-get -y build-dep python3-lxml sudo pip install datefinder sudo pip install urllib sudo pip install lxml sudo pip install regex sudo pip install python-whois sudo apt-get install python-dnslib <file_sep>/src/checks/dates.py import datetime import re import urllib import datefinder def check(url): response = urllib.urlopen(url) doc = response.read() dates_list = datefinder.find_dates(doc) days_ago = [(datetime.datetime.today() - date).days for date in dates_list] if (days_ago == []): return {'status':'No Dates','code':-1,'last_entity':0} else: last_date_validated = min([i for i in days_ago if i > 0]) if last_date_validated > 100: return {'status':'Not Maintained','code':0,'last_entity':last_date_validated} else: return {'status':'Maintained','code':1,'last_entity':last_date_validated}
6671121703cd83b2672dbb9023a5769411247ee0
[ "Markdown", "Shell", "Python" ]
10
Markdown
i14564/Practice-2016
7ecf62281cb39a8dbd714d47d9459668281e65ea
cac453ee0298106a024bd8baff09dbc26b7307a0
refs/heads/master
<file_sep># This script is for Ubuntu Ver18.04. #!/bin/sh PATH_DAPPS=~/dapps PATH_LOOM=$PATH_DAPPS/loomNetwork echo "\n<Setup>" echo "Set up Loom Network SDK." echo "\n" mkdir -p $PATH_LOOM cd $PATH_LOOM curl https://raw.githubusercontent.com/loomnetwork/loom-sdk-documentation/master/scripts/get_loom.sh | sh ./loom init <file_sep># [setup0030_loomNetwork](https://github.com/zombietimes/setup0030_loomNetwork) This script file is for setting up the DApps development environment on Ubuntu. ## Overview [setup0030_loomNetwork](https://github.com/zombietimes/setup0030_loomNetwork) is one of the script files for setting up the development environment on Ubuntu desktop. [setup0030_loomNetwork](https://github.com/zombietimes/setup0030_loomNetwork) is a part of [setup0000_all](https://github.com/zombietimes/setup0000_all). The role of [setup0030_loomNetwork](https://github.com/zombietimes/setup0030_loomNetwork) is to set up Loom Network SDK. ## Description Let's set up the DApps development environment on your local computer by using this script file. I think that it is worth learning the smart contract development. I focus on Ethereum and Loom Network as the DApps. ### Loom Network SDK Loom Network SDK allows generating your own blockchain. We can generate our own coins, assets, games, and services by using smart contracts. Loom Network Team maintains one of the blockchains which is called [Plasma Chain](https://medium.com/loom-network/loom-plasmachain-staking-is-officially-live-how-to-stake-your-loom-and-help-secure-plasmachain-e321dc462674). - [Loom Network SDK : Official](https://loomx.io/developers/) ### Constitution [setup0000_all](https://github.com/zombietimes/setup0000_all) is the instruction script file to run the other script files. [setup0000_all](https://github.com/zombietimes/setup0000_all) consists of the external script files below. - [setup0010_directory](https://github.com/zombietimes/setup0010_directory) - [setup0020_ubuntu](https://github.com/zombietimes/setup0020_ubuntu) - [setup0030_loomNetwork](https://github.com/zombietimes/setup0030_loomNetwork) : Here! - [setup0040_nodeJs](https://github.com/zombietimes/setup0040_nodeJs) - [setup0050_truffle](https://github.com/zombietimes/setup0050_truffle) - [setup0060_openZeppelin](https://github.com/zombietimes/setup0060_openZeppelin) - [setup0070_ganache](https://github.com/zombietimes/setup0070_ganache) - [setup0080_express](https://github.com/zombietimes/setup0080_express) ### Environment This script file is for Ubuntu(Linux). I recommend that you use VirtualBox + Ubuntu. ### Sample DApps I created some sample smart contracts below. I hope to be useful to you when you develop DApps. - [Hello world : HelloZombies.sol](https://github.com/zombietimes/dapp_helloWorld) - [ERC20 : Coin20.sol](https://github.com/zombietimes/dapp_erc20) - [ERC721 : Asset721.sol](https://github.com/zombietimes/dapp_erc721) - [Multi contract : ImportZombies.sol](https://github.com/zombietimes/dapp_multiContract) - [Sending Ether](https://github.com/zombietimes/dapp_sendEther) ## Usage ### Set up Run the command on Ubuntu console window. ```sh # Ubuntu commands. git clone https://github.com/zombietimes/setup0030_loomNetwork.git cd setup0030_loomNetwork sh ./ubuntuCmd_setupLoomNetwork.sh ``` ![setup0030_loomNetwork_0000](https://user-images.githubusercontent.com/50263232/57186191-6a4df100-6f15-11e9-8ad1-773ce39ae263.png) ### Run Loom Network ```sh # Ubuntu commands. cd ~/dapps/loomNetwork ./loom run ``` ![setup0030_loomNetwork_0001](https://user-images.githubusercontent.com/50263232/57186198-7e91ee00-6f15-11e9-83db-2ead46e81e94.png) The error message `Couldn't connect to any seeds` is shown because of solo-mining. No problem. ### Stop Loom Network ```sh # Ubuntu commands. [CTRL] + c lsof -i ``` ![setup0030_loomNetwork_0002](https://user-images.githubusercontent.com/50263232/57186204-9c5f5300-6f15-11e9-859b-a67940370ef5.png) By using `lsof -i`, you can confirm the remaining process. In the case of remaining, kill the process. ## Requirement I confirmed that it works on Ubuntu Desktop 18.04 in VirtualBox. It works on the environment below. - On Ubuntu. - Google Chrome. ## Relative link ### Overview - [Ethereum : Official](https://www.ethereum.org/) - [Ethereum : Wikipedia](https://en.wikipedia.org/wiki/Ethereum) - [Loom Network : Official](https://loomx.io/) - [Loom Network : Binance wiki](https://info.binance.com/en/currencies/loom-network) ### Development - [Online editor : EthFiddle](https://ethfiddle.com/) - [Online editor : Remix](https://remix.ethereum.org/) ### Learning - [Online learning : CryptoZombies](https://cryptozombies.io/) - [Grammar : Solidity](https://solidity.readthedocs.io/) - [Grammar : Best Practices](https://github.com/ConsenSys/smart-contract-best-practices) ### DApps - [DApps : CryptoKitties](https://www.cryptokitties.co/) - [DApps : Zombie Battle ground](https://loom.games/en/) ## Messages Do you believe that the decentralized world is coming? When do you use [DApps](https://en.wikipedia.org/wiki/Decentralized_application)? Why? ## License BSD 3-Clause, see `LICENSE` file for details.
0f2bd3e9418549989324e49871e38c2753e387f1
[ "Markdown", "Shell" ]
2
Markdown
zombietimes/setup0030_loomNetwork
7578f4f1645e6aff573cb8cd2220aaa162c69cdd
ff801a58c5d334c0f26111c7437532e9d352d256
refs/heads/main
<repo_name>ShrirangChaware/shrirangchaware<file_sep>/README.md <h1 align="center">Hi 👋, I'm <NAME></h1> <h3 align="center">Innovative with ideas, Efficiency in make or break situations.</h3> - 🌱 I’m currently learning **python programming Language** - 📫 How to reach me **<EMAIL>** ### Blogs posts <!-- BLOG-POST-LIST:START --> <!-- BLOG-POST-LIST:END --> <h3 align="left">Connect with me:</h3> <p align="left"> <a href="https://dev.to/shrirangchaware" target="blank"><img align="center" src="https://cdn.jsdelivr.net/npm/simple-icons@3.0.1/icons/dev-dot-to.svg" alt="shrirangchaware" height="30" width="40" /></a> <a href="https://linkedin.com/in/shrirang chaware" target="blank"><img align="center" src="https://raw.githubusercontent.com/rahuldkjain/github-profile-readme-generator/master/src/images/icons/Social/linked-in-alt.svg" alt="<NAME>" height="30" width="40" /></a> <a href="https://fb.com/shrirang chaware" target="blank"><img align="center" src="https://raw.githubusercontent.com/rahuldkjain/github-profile-readme-generator/master/src/images/icons/Social/facebook.svg" alt="<NAME>" height="30" width="40" /></a> <a href="https://instagram.com/shrirang_chaware" target="blank"><img align="center" src="https://raw.githubusercontent.com/rahuldkjain/github-profile-readme-generator/master/src/images/icons/Social/instagram.svg" alt="shrirang_chaware" height="30" width="40" /></a> </p> <h3 align="left">Languages and Tools:</h3> <p align="left"> <a href="https://www.w3schools.com/cpp/" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/cplusplus/cplusplus-original.svg" alt="cplusplus" width="40" height="40"/> </a> <a href="https://www.w3.org/html/" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/html5/html5-original-wordmark.svg" alt="html5" width="40" height="40"/> </a> <a href="https://www.adobe.com/in/products/illustrator.html" target="_blank"> <img src="https://www.vectorlogo.zone/logos/adobe_illustrator/adobe_illustrator-icon.svg" alt="illustrator" width="40" height="40"/> </a> <a href="https://www.java.com" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/java/java-original.svg" alt="java" width="40" height="40"/> </a> <a href="https://www.photoshop.com/en" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/photoshop/photoshop-line.svg" alt="photoshop" width="40" height="40"/> </a> <a href="https://www.python.org" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/python/python-original.svg" alt="python" width="40" height="40"/> </a> <a href="https://www.adobe.com/products/xd.html" target="_blank"> <img src="https://cdn.worldvectorlogo.com/logos/adobe-xd.svg" alt="xd" width="40" height="40"/> </a> </p> <p><img align="left" src="https://github-readme-stats.vercel.app/api/top-langs?username=shrirangchaware&show_icons=true&locale=en&layout=compact" alt="shrirangchaware" /></p> <p>&nbsp;<img align="center" src="https://github-readme-stats.vercel.app/api?username=shrirangchaware&show_icons=true&locale=en" alt="shrirangchaware" /></p> <p><img align="center" src="https://github-readme-streak-stats.herokuapp.com/?user=shrirangchaware&" alt="shrirangchaware" /></p>
45375ee8a9e3bb2a9792fb86fb6d6392cbddbed9
[ "Markdown" ]
1
Markdown
ShrirangChaware/shrirangchaware
0d241cfc9a6b09ec8002dfb6e792e1c605b91a39
c23137bffbad1e8a6583862eef7898f10ec76c5d
refs/heads/master
<repo_name>Dzol/snap<file_sep>/README.md [![Build Status](https://travis-ci.org/Dzol/snap.svg?branch=master)](https://travis-ci.org/Dzol/snap) # Snap A program to jog my memory about Python. <file_sep>/snap/snap.py #! /usr/bin/env python '''A program that prints out the numbers 1 to 100 (inclusive). If the number is divisible by 3, print `Crackle' instead of the number. If it's divisible by 5, print `Pop'. If it's divisible by both 3 and 5, print `CracklePop'. ''' def snap(n): '''snap(n :: integer) :: string''' if n % 3 == 0 and n % 5 == 0: return "CracklePop" elif n % 3 == 0: return "Crackle" elif n % 5 == 0: return "Pop" else: return str(n) if __name__ == "__main__": for i in xrange(1, 100 + 1): print(snap(i)) <file_sep>/tests/test_snap.py #! /usr/bin/env python from snap.snap import snap def test(): assert "1" == snap(1) assert "Crackle" == snap(3) assert "Pop" == snap(5) assert "CracklePop" == snap(15) def tricky(n): assert "CracklePop" == snap(n) ## steps of 15 mean the number will be divisible by 3 and 5 [ tricky(n) for n in range(0, 100 + 1, 15) ] if __name__ == "__main__": test()
f4785b16b668006abbd3ead49627957f8087ca6e
[ "Markdown", "Python" ]
3
Markdown
Dzol/snap
2933226ffdb7833551979d4c5f9aff096780c235
2063d593b7ec9f6209d0b19aec89ddf159bb272e
refs/heads/master
<file_sep><?php /** * direct - This class is designed for interaction with a service yandex direct with the authorization using OAuth tokens * * @author <NAME> <<EMAIL>> * @version 0.0.1 */ class YDirectApi { private $login = ''; private $token = ''; private $appId = ''; /** * */ public function __construct($ydLogin,$authToken,$applicationId) { $this->login = $ydLogin; //login $this->token = $authToken; //authorize token $this->appId = $applicationId; //id - application } /** * */ function setMethod($name) { $this->method = $name; } /** * */ function buildParam($arr) { $this->param = $this->utf8($arr); } /** * */ function sendQuery() { $request = array( 'token'=> $this->token, 'application_id'=> $this->appId, 'login'=> $this->login, 'method'=> $this->method, 'param'=> $this->param, 'locale'=> 'ru', ); // convert to JSON $request = json_encode($request); $requestParams = array( 'http'=>array( 'header' => "Connection: close\r\n". "Content-type: application/x-www-form-urlencoded\r\n". "Content-Length: ".strlen($request)."\r\n", 'method'=>"POST", 'content'=>$request, ) ); $context = stream_context_create($requestParams); // send request and get answer form server $result = file_get_contents('https://api.direct.yandex.ru/v4/json', 0, $context); return json_decode($result); } /** * */ private function utf8($struct) { foreach ($struct as $key => $value) { if (is_array($value)) { $struct[$key] = $this->utf8($value); } elseif (is_string($value)) { $struct[$key] = utf8_encode($value); } } return $struct; } /** * Returns a list of campaigns with brief information about them. */ public function GetCampaignsList() { $this->setMethod('GetCampaignsList'); $this->buildParam(array()); $result = $this->sendQuery(); return $result; } /** * Creates a campaign with the specified parameters, or changes the parameters of an existing campaign. * Set CampaignID = 0 if you want to create company, or exists ID for update */ public function CreateOrUpdateCampaign($params) { if (!is_array($params) || empty($params)) return false; $params['Login'] = $this->login; $this->setMethod('CreateOrUpdateCampaign'); $this->buildParam($params); return $this->sendQuery(); } /** * */ public function GetCampaignsListFilter() { //TODO: create realisation return false; } /** * */ public function DeleteCampaign() { //TODO: create realisation } /** * */ public function CreateOrUpdateBanners() { //TODO: create realisation } /** * */ public function GetBanners() { //TODO: create realisation } /** * */ public function GetBannerPhrases() { //TODO: create realisation } /** * */ public function GetBannerPhrasesFilter () { //TODO: create realisation } /** * */ public function DeleteBanners() { //TODO: create realisation } /** * */ public function ResumeCampaign() { //TODO: create realisation } /** * */ public function StopCampaign() { //TODO: create realisation } /** * */ public function ArchiveCampaign() { //TODO: create realisation } /** * */ public function UnArchiveCampaign() { //TODO: create realisation } /** * */ public function ModerateBanners() { //TODO: create realisation } /** * */ public function ResumeBanners() { //TODO: create realisation } /** * */ public function StopBanners() { //TODO: create realisation } /** * */ public function ArchiveBanners() { //TODO: create realisation } /** * */ public function UnArchiveBanners() { //TODO: create realisation } /** * */ public function SetAutoPrice() { //TODO: create realisation } /** * */ public function UpdatePrices() { //TODO: create realisation } /** * Returns the campaign parameters. */ public function GetCampaignsParams($CampaignIDS) { $this->setMethod('GetCampaignsParams'); $this->buildParam(array("CampaignIDS"=>$CampaignIDS)); return $this->sendQuery(); } /** * Returns statistics for the specified campaigns for each day of the specified period. * $CampaignIDS - array(<int>), $StartDate - 2011-05-14, $EndDate - 2011-05-19 */ public function GetSummaryStat($CampaignIDS, $StartDate, $EndDate) { $this->setMethod('GetSummaryStat'); $this->buildParam(array("CampaignIDS"=>$CampaignIDS, "StartDate"=>$StartDate, "EndDate"=>$EndDate)); return $this->sendQuery(); } } ?>
1377aa0185cf3afac98741d2b0c086ccde49a53d
[ "PHP" ]
1
PHP
kimi2k/yandex-direct-api
1c683a5335bcc355ba5964db66adb2f7c3274903
b6bc41ce93e2035996f515d277c70701d559cab9
refs/heads/main
<file_sep>import react, { Component } from 'react'; import './App.css'; import SampleData from './fire/SampleData'; import firebase from "firebase"; // Firebaseの設定 var config = { apiKey: "<KEY>", authDomain: "sue-react.firebaseapp.com", databaseURL: "https://sue-react-default-rtdb.firebaseio.com", projectId: "sue-react", storageBucket: "sue-react.appspot.com", messagingSenderId: "240951514920", appId: "1:240951514920:web:5ec1312a42bb4a76c3a21d", measurementId: "G-33XWHTJXSL" }; // Firebaseの初期化 firebase.initializeApp(config); // Appコンポーネント class App extends Component { render() { return ( <div> <h1>Fire</h1> <h2>Sample data.</h2> <SampleData /> </div> ); } } export default App; <file_sep>import { createStore, applyMiddleware } from 'redux'; import thunkMiddleware from 'redux-thunk'; import firebase from 'firebase'; var config = { apiKey: "<KEY>", authDomain: "sue-react.firebaseapp.com", databaseURL: "https://sue-react-default-rtdb.firebaseio.com", projectId: "sue-react", storageBucket: "sue-react.appspot.com", messagingSenderId: "240951514920", appId: "1:240951514920:web:5ec1312a42bb4a76c3a21d", measurementId: "G-33XWHTJXSL" }; var fireapp; try { firebase.initializeApp(config); } catch (error) { console.log(error.message); } export default fireapp; const initial = { } function fireReducer(state = initial, action) { switch (action.type) { case 'TRANSACTION': return state; default: return state; } } export function initStore(state = initial) { return createStore(fireReducer, state, applyMiddleware(thunkMiddleware)); }
f674e8c74a7199b52829b66c74408828039aa36f
[ "JavaScript" ]
2
JavaScript
moyongkexing/react_next
3bfbbec97b43f02dfc2ced0f60bfb5875804cbb7
9b7bf75bd9c5d518b594bd20b5fbdbf219d893fa
refs/heads/master
<repo_name>andypyle/angular-js-calendar-directive-challenge<file_sep>/app/main.less // INCLUDES @import './bower_components/normalize.css/normalize.less'; // MIXINS .flex { display: flex; } // GLOBAL STUFF * { box-sizing: border-box; } // VARIABLES @daySize : 100% / 7; @dayHeight : 100% / 6; @textColor : lighten(#072730, 10%); @colorOtherMonth : spin(lighten(desaturate(@textColor, 25%), 50%), 180deg); @colorThisMonth : #C2FCF7; @colorToday : #85BDBF; // THE CSS html, body { padding: 0 !important; margin: 0 !important; } header { width: 100%; padding: 2%; background-color: lighten(spin(@colorToday, -90deg), 15%); .flex; align-items: baseline; .pickMonthYear { .flex; width:33.3333%; select { margin: .5rem; margin-left: 0; padding: 2%; width: 100%; font-size: 1.5rem; border: 0; outline: none; } } .currentMonthYear { .flex; justify-content: center; width: 100%; h2 { font-size: 2rem; color: white; text-transform: uppercase; margin: 0; padding: 0; line-height: 1; } } } .calendar { .flex; flex-flow: row wrap; margin: 0; padding: 0; li { .flex; justify-content: center; align-items: center; margin: 0; min-width: @daySize; max-width: @daySize; height: @dayHeight !important; padding: 0; .dayName { font-size: 1.5rem; font-weight: bold; color: darken(@textColor, 5%); } .calDay { .flex; align-items: flex-start; justify-content: flex-start; min-width: 100%; max-height: 100%; height: 80px; margin: 0; padding: 0%; background-color: @colorThisMonth; border: 2px solid @textColor; font-size: 3rem; color: @textColor; font-weight: bolder; overflow: hidden; span { font-size: 3rem; padding: 0; margin: 0; line-height: .5; transition: all 180ms ease-in-out; } &:hover { cursor: pointer; } &:hover span { line-height: 1; color: lighten(@textColor, 10%); text-shadow: 2px 2px 1px fade(darken(@textColor, 15), 35%); transition: all 200ms ease-in-out; } &.notThisMonth { background-color: @colorOtherMonth; color: darken(@colorOtherMonth, 10%); &:hover { cursor: default; span { line-height: .5; color: inherit; text-shadow: none; } } } &.today { background-color: @colorToday; } } &:nth-child(-n+14) .calDay { border-top: 4px solid @textColor; } &:nth-child(7n){ //border: 15px solid black; } &:nth-child(7n+1){ //margin-left: 0; } &:nth-last-child(-n+7) { .calDay { border-bottom: 4px solid @textColor; } } } }<file_sep>/gulpfile.js // Include gulp & friends. var gulp = require('gulp'), less = require('gulp-less'), prefix = require('gulp-autoprefixer'), plumb = require('gulp-plumber'), minify = require('gulp-minify-css') concat = require('gulp-concat'), rename = require('gulp-rename'), gutil = require('gulp-util'); var lessOpts = { 'in':'app/main.less', 'out':'app' }; // LESS task. gulp.task('less', function(){ return gulp.src(lessOpts.in) .pipe(plumb()) .pipe(less()) .on('error', function(err){ gutil.log(err); this.emit('end'); }) .pipe(prefix({ browsers: [ '> 1%', 'last 2 versions', 'firefox >= 4', 'safari 7', 'safari 8', 'IE 8', 'IE 9', 'IE 10', 'IE 11' ], cascade: true })) .pipe(rename('main.css')) .pipe(gulp.dest('app')) .pipe(minify()) .pipe(concat('main.min.css')) .pipe(gulp.dest('app')).on('error', gutil.log) }); gulp.task('watch', function(){ gulp.watch(['app/**/*.less'], ['less']); }); gulp.task('default', ['less', 'watch']);
fafd92e907e412fe10f2c35654c436d6307013a3
[ "JavaScript", "Less" ]
2
JavaScript
andypyle/angular-js-calendar-directive-challenge
34b67205979589cacef811cfd8c287655ea5f3d7
351116a5687629e92ec7699c9481eba2d2757ac4
refs/heads/master
<repo_name>ki-project/files<file_sep>/README.md # files files are at gh-pages
e8552673023a965525db62c33b656bf47808b9e7
[ "Markdown" ]
1
Markdown
ki-project/files
c9d0e1a0278875d47ac0ece2a559f96c52195e30
bacac00d217a7b2b5523abcd4df5330c55329ccd
refs/heads/master
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AnticipationReceivables3Component } from './anticipation-receivables3.component'; describe('AnticipationReceivables3Component', () => { let component: AnticipationReceivables3Component; let fixture: ComponentFixture<AnticipationReceivables3Component>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AnticipationReceivables3Component ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AnticipationReceivables3Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { StorageService } from 'src/app/services/storage/storage.service'; @Component({ selector: 'app-management-panel', templateUrl: './management-panel.component.html', styleUrls: ['./management-panel.component.css'] }) export class ManagementPanelComponent implements OnInit { public page: string; public products: any[]; public actions: any[]; constructor(private storage: StorageService) { this.page = this.storage.getStorageService('Page'); this.products = ['Produto1', 'Produto2', 'Produto3', 'Produto4', 'Produto5']; this.actions = ['Ação1', 'Ação2', 'Ação3', 'Ação4', 'Ação5']; } ngOnInit() { } public selectProduct(p:number):void{ //Action } public selectAction1(a: string): void { switch (a) { case 'Ação1': break; case 'Ação2': break; case 'Ação3': break; case 'Ação4': break; case 'Ação5': break; default: break; } } public selectAction2(a: string): void { switch (a) { case 'Ação1': break; case 'Ação2': break; case 'Ação3': break; case 'Ação4': break; case 'Ação5': break; default: break; } } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Menu } from 'src/app/models/menu.models'; import { StorageService } from 'src/app/services/storage/storage.service'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-sidebar', templateUrl: './sidebar.component.html', styleUrls: ['./sidebar.component.css'] }) export class SidebarComponent implements OnInit { public formSearch: FormGroup; public menuItems: Menu[]; public subMenuItems: Menu[]; constructor(private storage: StorageService) { this.menuItems = new Array<Menu>(); this.menuItems.push({ path: '/painel-gestao', title: 'Painel de Gestão', image: '../../../assets/img/menu1.png', class: '', children: '' }); this.menuItems.push({ path: '/conta-digital', title: 'Conta Digital', image: '../../../assets/img/menu2.png', class: '', children: '' }); this.menuItems.push({ path: '', title: 'Ant. de Recebíveis', image: '../../../assets/img/menu3.PNG', class: '', children: 'subMenu' }); this.subMenuItems = new Array<Menu>(); this.subMenuItems.push({ path: '/ant-recebiveis1', title: 'Submenu 1', image: '', class: '', children: '' }); this.subMenuItems.push({ path: '/ant-recebiveis2', title: 'Submenu 2', image: '', class: '', children: '' }); this.subMenuItems.push({ path: '/ant-recebiveis3', title: 'Submenu 3', image: '', class: '', children: '' }); this.formSearch = new FormGroup({ 'search': new FormControl(null, [Validators.required, Validators.minLength(1), Validators.maxLength(50)]), }); } ngOnInit() { let page = this.storage.getStorageService('Page'); for (let i: number = 0; i < this.menuItems.length; i++) { if (this.menuItems[i].title === page) { this.menuItems[i].class = 'activeMenu'; } else { this.menuItems[i].class = ''; } } } public titlePage(name): void { this.storage.setPage(name); console.log(this.storage.getStorageService('Page')); for (let i: number = 0; i < this.menuItems.length; i++) { if (this.menuItems[i].title === name) { this.menuItems[i].class = 'activeMenu'; } else { this.menuItems[i].class = ''; } } this.menuItems.slice(); for (let i: number = 0; i < this.subMenuItems.length; i++) { if (this.subMenuItems[i].title === name) { this.subMenuItems[i].class = 'activeMenu'; } else { this.subMenuItems[i].class = ''; } } } public search(): void { console.log(this.formSearch.value.search) //Action } } <file_sep>import { Component, OnInit } from '@angular/core'; import { StorageService } from 'src/app/services/storage/storage.service'; @Component({ selector: 'app-anticipation-receivables1', templateUrl: './anticipation-receivables1.component.html', styleUrls: ['./anticipation-receivables1.component.css'] }) export class AnticipationReceivables1Component implements OnInit { public page:string; constructor(private storage: StorageService) { this.page = this.storage.getStorageService('Page'); } ngOnInit() { } } <file_sep>export class Menu { public path: string; public title: string; public image: string; public class: string; public children: string; }<file_sep># TestSRM Projeto Front-End em Angular 7.3.8. ## Primeira execução Execute o comando `npm install` para instalar os modulos ## Executando o servidor Execute o comando `ng serve` para iniciar um servidor local. Navegue para `http://localhost:4200/`, o site sera carregado nesta página. <file_sep>import { Injectable, Inject } from '@angular/core'; import { WebStorageService, LOCAL_STORAGE } from 'angular-webstorage-service'; @Injectable({ providedIn: 'root' }) export class StorageService { constructor( @Inject(LOCAL_STORAGE) private storage: WebStorageService ) { this.setPage('Painel de Gestão'); } public getStorageService(name):any{ return this.storage.get(name); } public setPage(name): void { this.storage.set('Page', name); } public deleteStorage(name):any{ this.storage.remove(name); } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; /* Pages */ import { ManagementPanelComponent } from './pages/management-panel/management-panel.component'; import { DigitalAccountComponent } from './pages/digital-account/digital-account.component'; import { AnticipationReceivables1Component } from './pages/anticipation-receivables/anticipation-receivables1/anticipation-receivables1.component'; import { AnticipationReceivables2Component } from './pages/anticipation-receivables/anticipation-receivables2/anticipation-receivables2.component'; import { AnticipationReceivables3Component } from './pages/anticipation-receivables/anticipation-receivables3/anticipation-receivables3.component'; const routes: Routes = [ { path: '', redirectTo: 'painel-gestao', pathMatch: 'full' }, { path: '', component: ManagementPanelComponent }, { path: 'painel-gestao', component: ManagementPanelComponent }, { path: 'conta-digital', component: DigitalAccountComponent }, { path: 'ant-recebiveis1', component: AnticipationReceivables1Component }, { path:'ant-recebiveis2', component: AnticipationReceivables2Component }, { path:'ant-recebiveis3', component: AnticipationReceivables3Component } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { AnticipationReceivables1Component } from './anticipation-receivables1/anticipation-receivables1.component'; import { AnticipationReceivables2Component } from './anticipation-receivables2/anticipation-receivables2.component'; import { AnticipationReceivables3Component } from './anticipation-receivables3/anticipation-receivables3.component'; import { RouterModule } from '@angular/router'; @NgModule({ declarations: [ AnticipationReceivables1Component, AnticipationReceivables2Component, AnticipationReceivables3Component ], imports: [ CommonModule, RouterModule ], exports: [ AnticipationReceivables1Component, AnticipationReceivables2Component, AnticipationReceivables3Component ] }) export class AnticipationReceivablesModule { } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; //Compoenents & Module import { ComponentsModule } from './components/components.module'; import { ManagementPanelComponent } from './pages/management-panel/management-panel.component'; import { DigitalAccountComponent } from './pages/digital-account/digital-account.component'; import { AnticipationReceivablesModule } from './pages/anticipation-receivables/anticipation-receivables.module'; //Services import { StorageService } from './services/storage/storage.service'; import { StorageServiceModule } from 'angular-webstorage-service'; @NgModule({ declarations: [ AppComponent, ManagementPanelComponent, DigitalAccountComponent, ], imports: [ BrowserModule, AppRoutingModule, ComponentsModule, StorageServiceModule, RouterModule, FormsModule, ReactiveFormsModule, AnticipationReceivablesModule ], providers: [ StorageService ], bootstrap: [AppComponent] }) export class AppModule { }
55ffc379f900b0b9bb7f85d752ada82c05e812a6
[ "Markdown", "TypeScript" ]
10
Markdown
thales-muller/TestSRM
4a7ed6a98f32a63dd7bb6a3b4ad35e3a5c302149
19a904ac0086b94cfd6ea714dcca2c20e2d5a55e
refs/heads/master
<file_sep>import { HeaderComponent } from "./header/header.component"; import { ListingComponent } from "./listing/listing.component" import { MyListingsComponent } from "./my-listings/my-listings.component"; import { NgModule } from "@angular/core"; import { Routes, RouterModule } from "@angular/router"; const routes: Routes = [ { path: "header", component: HeaderComponent }, { path: "listing", component: ListingComponent }, { path: "my-listings", component: MyListingsComponent }, { path: "", pathMatch: "full", redirectTo: "" }, { path: "**", redirectTo: "" } ] @NgModule( { imports: [RouterModule.forRoot( routes )], exports: [RouterModule] }) export class AppRoutingModule{}<file_sep>console.log( "******** listing.component.ts ********" ); import { Component, OnInit } from '@angular/core'; import { BikeService } from "./../bike.service"; @Component({ selector: 'app-listing', templateUrl: './listing.component.html', styleUrls: ['./listing.component.css'] }) export class ListingComponent implements OnInit { listings_all = {}; listings_one = {}; listings_delete_res = {}; users_one = {}; constructor( private _bikeService: BikeService ){} ngOnInit() { this.listings_get(); } listings_get(){ let observable = this._bikeService.listings_get(); observable.subscribe( data => { this.listings_all = data; console.log( "listings_get in listing.component.ts:", this.listings_all ); }) } listings_get_one( id ){ let observable = this._bikeService.listings_get_one( id ); observable.subscribe( data => { this.listings_one = data; console.log( "listings_one in listing.component.ts:", this.listings_one ); }) } listings_delete_one( id ){ let observable = this._bikeService.listings_delete_one( id ); observable.subscribe( data => { this.listings_delete_res = data; console.log( "listings_delete_one in listing.component.ts:", this.listings_delete_res ) this.listings_get(); }) } users_get_one( id ){ let observable = this._bikeService.users_get_one( id ); observable.subscribe( data => { this.users_one = data; console.log( "users_one in listing.component.ts:", this.users_one ); let u: String = `${this.users_one["users"][0].f_name} ${this.users_one["users"][0].l_name}, ${this.users_one["users"][0].email}` alert( u ); }) } } <file_sep>console.log( "******** listing-edit.component.ts ********" ); import { Component, OnInit } from '@angular/core'; import { BikeService } from "./../bike.service"; @Component({ selector: 'app-listing-edit', templateUrl: './listing-edit.component.html', styleUrls: ['./listing-edit.component.css'] }) export class ListingEditComponent implements OnInit { num: number; listings_by_user: any; constructor( private _bikeService: BikeService ){} ngOnInit() { this.listings_by_user = {}; this.num = this._bikeService.service_num; //VAR STORED ON THE SERVICE this.listings_get_by_user( this._bikeService.logged_in_user_id ) } listings_get_by_user( user_id ){ let observable = this._bikeService.listings_get_by_user( user_id ); observable.subscribe( data => { this.listings_by_user = data; console.log( "listings_get_by_user in listing-edit.compontnent.ts:", data ); }) } listings_update( form_data ){ let observable = this._bikeService.listings_update( form_data._id, form_data ); console.log( "id in listing-edit.component.ts:", form_data._id ); console.log( "updated_listing in listing-edit.component.ts:", form_data ); observable.subscribe( data => { console.log( "listings_update in listing-edit.compontnent.ts:", data ); }) } // listings_update( id ){ // let observable = this._bikeService.listings_update( id, this.updated_listing ); // console.log( "id in listing-edit.component.ts:", id ); // console.log( "updated_listing in listing-edit.component.ts:", this.updated_listing ); // observable.subscribe( data => { // console.log( "listings_update in listing-edit.compontnent.ts:", data ); // }) // } // RESET FORM FIELDS HERE IF NECESSARY } <file_sep>console.log( "******** server.js ********" ); let express = require( "express"); let app = express(); let bodyParser = require( "body-parser" ); let path = require( "path" ); let mongoose = require( "mongoose" ); mongoose.Promise = global.Promise; app.use( bodyParser.urlencoded( { extended: true } ) ); app.use( bodyParser.json() ); app.use( express.static( __dirname + "/client/dist" ) ); mongoose.connect( "mongodb://localhost/bicycle_marketplace" ); let Schema = mongoose.Schema; let ListingSchema = new mongoose.Schema( { _user: { type: Schema.Types.ObjectId, ref: "User" }, title: { type: String, required: true }, desc: { type: String, required: true }, price: { type: Number, required: true }, city: { type: String, required: true }, state: { type: String, required: true } }, { timestamps: true } ); let Listing = mongoose.model( "Listing", ListingSchema ); let UserSchema = new mongoose.Schema( { f_name: { type: String, required: true }, l_name: { type: String, required: true }, city: {type: String, required: true }, state: {type: String, required: true }, email: { type: String, required: true }, pw: { type: String, required: true }, listings: [{ type: Schema.Types.ObjectId, ref: "Listing" }] }, { timestamps: true } ); let User = mongoose.model( "User", UserSchema ) // LISTING ROUTES app.get( "/listings", function( req, res ){ Listing.find( {}, function( err, data ){ if( err ){ res.json( { message: "Error", error: err } ) } else{ res.json( { message: "Success", listings: data } ) } }); }); app.get( "/users/:id/listings", function( req, res ){ Listing.find( { _user: req.params.id }, function( err, data ){ if( err ){ res.json( { message: "Error", error: err } ) } else{ res.json( { message: "Success", listings: data } ) } }); }); app.get( "/listings/:id", function( req, res ){ Listing.find( { _id: req.params.id }, function( err, data ){ if( err ){ res.json( { message: "Error", error: err } ) } else{ res.json( { message: "Success", listings: data } ) } }); }); app.post( "/users/:id/listings/", function( req, res ){ User.findOne( { _id: req.params.id }, function ( err, user ){ if( err ){ res.json( { message: "Error", error: err } ) } else{ // res.json( { message: "Success", user: user } ); let listing = new Listing( req.body ); listing._user = user._id; listing.city = user.city; listing.state = user.state; title: req.body.title; desc: req.body.desc; price: req.body.price; listing.save( function( err, data ){ if( err ){ res.json( { message: "Error", error: err } ) } else{ res.json( { message: "Success", listings: data } ) } }) } }) }); app.put( "/listings/:id", function( req, res ){ Listing.update( { _id: req.params.id },{ title: req.body.title, desc: req.body.desc, price: req.body.price, city: req.body.city, state: req.body.state }, function( err, data ){ if( err ){ res.json( { message: "Error", error: err } ) } else{ res.json( { message: "Success", listings: data } ) } }); }); app.delete( "/listings/:id", function( req, res ){ Listing.remove( { _id: req.params.id }, function( err, data ){ if( err ){ res.json( { message: "Error", error: err } ) } else{ res.json( { message: "Success", listings: data } ) } }); }); //USER ROUTES app.get( "/users", function( req, res ){ User.find( {}, function( err, data ) { if( err ){ res.json( { message: "Error", error: err } ) } else{ res.json( { message: "Success", users: data } ) } }); }); app.get( "/users/:id", function( req, res ){ User.find( { _id: req.params.id }, function( err, data ){ if( err ){ res.json( { message: "Error", error: err } ) } else{ res.json( { message: "Success", users: data } ) } }); }); app.post( "/users", function( req, res ){ let user = new User( { f_name: req.body.f_name, l_name: req.body.l_name, city: req.body.city, state: req.body.state, email: req.body.email, pw: "<PASSWORD>", //>>> fix this }) user.save( function( err, data ){ if( err ){ res.json( { message: "Error", error: err } ) } else{ res.json( { message: "Success", users: data } ) } }); }); app.put( "/users/:id", function( req, res ){ User.update( { _id: req.params.id }, { f_name: req.body.f_name, l_name: req.body.l_name, city: req.body.city, state: req.body.state, email: req.body.email, pw: "<PASSWORD>", //>>> fix this }, function( err, data ){ if( err ){ res.json( { message: "Error", error: err } ) } else{ res.json( { message: "Success", users: data } ) } }); }); app.delete( "/users", function( req, res ){ User.remove( { _id: req.params.id }, function( err, data ){ if( err ){ res.json( { message: "Error", error: err } ) } else{ res.json( { message: "Success", users: data } ) } }); }); app.all( "*", ( req, res, next ) => { res.sendFile( path.resolve( "./client/dist/index.html" ) ); }); app.listen( 8001, function(){ console.log( "listening on port 8000" ); });<file_sep>console.log( "******** listing-new.component.ts ********" ); import { Component, OnInit } from '@angular/core'; import { BikeService } from "./../bike.service"; // import { ListingEditComponent } from "./../listing-edit/listing-edit.component"; @Component({ selector: 'app-listing-new', templateUrl: './listing-new.component.html', styleUrls: ['./listing-new.component.css'] }) export class ListingNewComponent implements OnInit { user_id: String; new_listing = {}; listings_create_res = {}; // l_user_id: String; constructor( private _bikeService: BikeService, // private _listingEditComponent: ListingEditComponent ){} ngOnInit() { // this.l_user_id = this._bikeService.logged_in_user_id; } listings_create(){ this.user_id = this._bikeService.logged_in_user_id; let observable = this._bikeService.listings_create( this.user_id, this.new_listing ) observable.subscribe( data => { this.listings_create_res = data console.log( "listings_create in listing-new.component.ts:", this.listings_create_res) }) this.new_listing = { title: "", desc: "", price: "" } // this._listingEditComponent.listings_get_by_user( this.l_user_id ); } } <file_sep>console.log( "******** bike.service.ts ********" ); import { Injectable } from '@angular/core'; import { HttpClient } from "@angular/common/http"; @Injectable() export class BikeService { service_num = 1234; logged_in_user_id = "<PASSWORD>"; constructor( private _bike: HttpClient ) {} listings_get(){ return this._bike.get( "listings" ); } listings_get_by_user( user_id ){ return this._bike.get( `/users/${user_id}/listings` ) } listings_get_one( id ){ return this._bike.get( `/listings/${id}`) } listings_create( user_id, new_listing ){ return this._bike.post( `/users/${user_id}/listings`, new_listing ) } listings_update( id, updated_listing ){ return this._bike.put( `/listings/${id}`, updated_listing ); } listings_delete_one( id ){ return this._bike.delete( `/listings/${id}`) } users_get_one( id ){ return this._bike.get( `/users/${id}`) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { BikeService } from "./../bike.service" @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit { logged_in_user_name: string; logged_in_user_city: string; constructor( private _bikeService: BikeService ){} ngOnInit() { this.users_get_one( this._bikeService.logged_in_user_id ) } users_get_one( id ){ let observable = this._bikeService.users_get_one( id ) observable.subscribe( data => { this.logged_in_user_name = data["users"][0].f_name this.logged_in_user_city = data["users"][0].city }) } }
e8891f286f6f31431bb7d91b84f43217b3e30b2f
[ "TypeScript", "JavaScript" ]
7
TypeScript
BryantCR/bicycle_marketplace
42c17ce6582df6b43f4722f440d2fb7251bd26db
a8e6b4fbca996277bf537257c82712076353018a
refs/heads/master
<file_sep># 勤怠システムを開発しよう! これはセレブエンジニアサロンの教材で作られたサンプルアプリケーションです。 ## 開発環境 * AWS Cloud9 * Ruby * Rails * Git(HTTPSからSSH通信へ変更)
a30a2ebf092606c3e7bb38e3f277a11c31d5abb7
[ "Markdown" ]
1
Markdown
Wataru-Miyamoto/Attendance-Tutorial
af68cf5b40b955b94069778c2a723cd4598df611
47462f30416cdd45ed3b9f78e7d3bdf1473e67b3
refs/heads/main
<file_sep><!doctype html> <html lang="en" class="h-100"> <head> <title>Rotator: A Coding Project By <NAME></title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous"> <!-- Custom CSS --> <link href="./css/site.css" rel="stylesheet"> <!-- Prism CSS --> <link href="./css/prism.css" rel="stylesheet"> <!-- Favicon--> <link rel="icon" type="image/png" href="./img/favicon-32x32.png"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Tourney:ital@1&display=swap" rel="stylesheet"> <!-- Font Awesome --> <script src="https://kit.fontawesome.com/5db21ba9c6.js" crossorigin="anonymous"></script> </head> <body class="d-flex flex-column h-100"> <!-- Nav Section --> <nav class="navbar navbar-expand-md navbar-dark fixed-top shadow"> <div class="container-fluid"> <a class="navbar-brand logoFont" href="#"><img src="./img/kg.webp" class="d-inline-block align-text-top" width="30" height="24"> Rotator</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav me-auto mb-2 mb-md-0"> <li class="nav-item"> <a class="nav-link" aria-current="page" href="./index.html">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="./app.html">The App</a> </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="./code.html">The Code</a> </li> <li class="nav-item"> <a class="nav-link" target="_blank" href="https://github.com/JoyfulReaper/Rotator">Git Repo</a> </li> <li class="nav-item"> <a class="nav-link" target="_blank" href="https://kgivler.com">About</a> </li> </ul> </div> </div> </nav> <!-- Main Section --> <main class="flex-shrink-0"> <div class="container py-5 px-5 mt-5"> <h2 class="border-1 border-bottom border-dark logoFont">The Code for Rotator.</h2> <div class="row row-cols-1 row-cols-lg-2"> <div class="col-lg-8"> <pre class="line-numbers"><code class="language-javascript"> function getInput() { document.getElementById("alert").classList.add("invisible"); let input = document.getElementById("userString").value; let resultObj = isPalindrome(input); displayResult(resultObj); } function preparePhrase(input) { input = input.toLowerCase(); // Lowercase input = input.replace(/\W/g, ''); // Remove non-alpha return input; } function isPalindrome(input) { let resultObj = {}; let reversed = preparePhrase(input); let original = reversed; reversed = reversed.split("").reverse().join(""); // Reverse if(reversed == original) { resultObj.msg = "Well Done! You entered a palindrome!"; resultObj.isPalindrome = true; } else { resultObj.msg = "Sorry! You didn't enter a palindrome!"; resultObj.isPalindrome = false; } resultObj.reversed = reversed; return resultObj; } function displayResult(palindromeObj) { let message = []; if(palindromeObj.isPalindrome) { if(palindromeObj.reversed == "") { message = "I guess an empty string is a palindrome! " } } message += `Your phrase reversed is: ${palindromeObj.reversed}`; document.getElementById("resultHeader").innerHTML = palindromeObj.msg; document.getElementById("msg").innerHTML = message; document.getElementById("alert").classList.remove("invisible"); } </code></pre> </div> <div class="col-lg-4"> <p><span class="logoFont">Rotator</span> is a JavaScript coding challenge to detect palindromes.</p> <h5>getInput()</h5> <p>Controller function that is called when the button is pressed. Used the JavaScript document API to get the string that the user inputted. It then called isPalindrome() with the user's input. The resulting object is then passed to displayResult() which outputs the results. </p> <h5>preparePhrase()</h5> <p> converts the parameter to lowercase and strips out any non-alpha characters. </p> <h5>isPalindrome()</h5> <p> Returns an object representing the entered phrase and wether or not it is a palindrome. It uses preparePhrase() to convert the user's input to lowercase, strip out non-alpha characters. Reverse the prepared input, then builds a result object. </p> <h5>displayResults()</h5> <p> Access the properties of the object returned by isPalindrome() to display a message indicating if the inputted string was a palindrome or not, as well as displaying the reversed input regardless. </p> </div> </div> </div> </main> <!-- Footer Section --> <footer class="footer mt-auto py-3"> <div class="container-fluid"> <div class="row row-cols-1 row-cols-lg-3 gy-2"> <div class="col text-light order-last order-lg-first"> <div> <span class="text-muted">&copy;2021</span> <NAME> | <a class="alight" href="https://kgivler.com">kgivler.com</a> </div> </div> <div class="col d-flex align-items-center justify-content-start justify-content-lg-center"> <img src="./img/kyle.webp" alt="<NAME> Logo" height="24"> </div> <div class="col d-flex align-items-center justify-content-start justify-content-lg-end"> <div class="row"> <div class="col social"><a href="https://www.linkedin.com/in/kyle-givler/" target="_blank"><i class="fab fa-linkedin fa-2x"></i></a></div> <div class="col social"><a href="https://github.com/joyfulreaper" target="_blank"><i class="fab fa-github fa-2x"></i></a></div> </div> </div> </div> </div> </footer> <!-- Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"> </script> <script src="./js/prism.js"></script> <script> Prism.plugins.NormalizeWhitespace.setDefaults({ 'remove-trailing': true, 'remove-indent': true, 'left-trim': true, 'right-trim': true }) </script> </body> </html>
ae38ced139359188275c8fe56ad01a57863e10f8
[ "HTML" ]
1
HTML
JoyfulReaper/Rotator
044be1606ce521e8e540886e9ed86543d8f3a036
9b784359f16e3c3cda3d18840691c54b8f753b80
refs/heads/master
<repo_name>zscumt123/vapp<file_sep>/src/views/login/LoginForm.vue <template> <div class="yq-login-form" @keyup.enter="onSubmit"> <div> <div class="form-group has-feedback"> <input type="text" v-model="loginData.number" class="form-control input-lg" placeholder="请输入商户号"> <span class="glyphicon glyphicon-edit form-control-feedback"></span> </div> <div class="form-group has-feedback"> <input type="text" v-model="loginData.account" class="form-control input-lg" placeholder="请输入账号"> <span class="glyphicon glyphicon-user form-control-feedback"></span> </div> <div class="form-group has-feedback"> <input type="<PASSWORD>" v-model="loginData.password" class="form-control input-lg" placeholder="请输入密码"> <span class="glyphicon glyphicon-lock form-control-feedback"></span> </div> <div class="checkbox"> <label> <input type="checkbox" v-model="isRemember"> 记住账号 </label> </div> <!--<button type="submit" class="btn btn-success btn-block btn-lg yq-login-button" @click="onSubmit">登录</button>--> <Btn class="yq-login-button" status="success" block size="lg" v-on:click="onSubmit">登录</Btn> </div> </div> </template> <script> import axios from "axios"; import Btn from "../../components/button/Button.vue"; import Radio from "../../components/radio/Radio.vue"; export default{ name: "LoginForm", data() { return { loginData: { number: "", account: "", password: "", }, isRemember: false, isLoading: false, model: "1" }; }, components: { Btn, Radio }, methods: { onSubmit() { let that = this; let loginData = this.loginData; //get token this.axios({ method: "post", url: "token", data: { "grant_type": "client_credentials", "client_id": "84668-39563-41171-50000", "client_secret": "7A876B447827ED06911C1A6EED0A6B02" }, params: { "ProductType": 0, "loginname": loginData.account, "password": <PASSWORD>, "productInstanceId": loginData.number } }).then(function(res) { if (res.status == 200) { let token = `Bearer ${res.data.access_token}`; //login success that.$store.dispatch("USER_LOGIN", { username: that.loginData.account, token: token }); //set token in global axios with token axios.defaults.headers.common["Authorization"] = token; that.$router.replace({path: "main"}); } }); } } }; </script> <style lang="less"> .yq-login-form{ box-sizing: border-box; border-radius: 8px; width:456px; height: 300px; background-color: #ffffff; margin-top:188px; float: right; padding:22px 30px 0; input{ font-size: 14px; } .yq-login-button{ letter-spacing: 10px; } } </style> <file_sep>/src/views/login/Login.vue <template> <div class="yq-page-container"> <div class="yq-login-container"> <div class="container-fluid"> <div class="row"> <div class="col-xs-6"><Logo></Logo></div> <div class="col-xs-6"><LoginForm></LoginForm></div> </div> </div> </div> </div> </template> <script> import Logo from "./Logo.vue"; import LoginForm from "./LoginForm.vue"; export default{ name: "Login", beforeRouteEnter(to, from, next) { //if login, go to main page next((vm) => { if (vm.$store.state.isLogin) { vm.$router.replace({path: "main"}); } }); }, components: { Logo, LoginForm } }; </script> <style lang="less"> .yq-page-container{ height: 100%; background: url("../../assets/images/login_bg.png") no-repeat; background-size: 100% 100%; /*.row {*/ /*min-width:900px;*/ /*}*/ } @media (max-width: 992px){ .yq-login-container{ padding:0 30px; } } @media screen and(min-width: 992px) and (max-width: 1200px){ .yq-login-container{ padding:0 80px; } } @media (min-width: 1200px){ .yq-login-container{ padding:0 192px; } } </style><file_sep>/src/views/quickstart/CommonUse.vue <template> <div class="yq-common-container"> <div></div> <div class="yq-common-list"> </div> </div> </template> <script> export default{ name: "commonuse", data() { return { tester: "world" }; } }; </script> <style lang="less"> .yq-common-container{ div:first-child{ height: 30px; background-color: #18b025; } } </style> <file_sep>/src/http/config.js /** * Created by ZhanG on 2016/12/2. */ import axios from "axios"; axios.defaults.baseURL = "http://192.168.127.12:801/v1/"; export default axios; <file_sep>/src/components/menu/menu-mixin.js /** * Created by ZhanG on 2016/12/12. */ module.exports = { computed: { indexPath() { const path = [this.index]; let parent = this.$parent; while (parent.$options.componentName !== "Menu") { if (parent.index) { path.unshift(parent.index); } parent = parent.$parent; } return path; }, rootMenu() { let parent = this.$parent; while (parent.$options.componentName !== "Menu") { parent = parent.$parent; } return parent; } } };<file_sep>/src/components/menu/Menu.vue <template> <ul class="yq-menu"> <slot></slot> </ul> </template> <script> export default { name: "Menu", componentName: "Menu", props: { defaultActive: { type: String, default: "" }, defaultOpeneds: Array, uniqueOpened: Boolean, }, data() { return { activeIndex: this.defaultActive, openedMenus: this.defaultOpeneds ? this.defaultOpeneds.slice[0] : [], menuItems: {}, submenus: {} }; }, watch: { defaultActive(value) { this.activeIndex = value; if (!this.menuItems[value]) { return; } let menuItem = this.menuItems[value]; let indexPath = menuItem.indexPath; this.handleSelect(value, indexPath, menuItem); }, defaultOpeneds(value) { this.openedMenus = value; } }, methods: { openMenu(index, indexPath) { let openedMenus = this.openedMenus; if (openedMenus.indexOf(index) !== -1) { return; } if (this.uniqueOpened) { this.openedMenus = openedMenus.filter((index) => { return indexPath.indexOf(index) !== -1; }) ; } this.openedMenus.push(index); console.log(this); }, closeMenu(index) { this.openedMenus.splice(this.openedMenus.indexOf(index), 1); }, handleSubmenuClick(index, indexPath) { let isOpened = this.openedMenus.indexOf(index) !== -1; let nextOption = isOpened ? "close" : "open"; isOpened ? this.closeMenu(index) : this.openMenu(index, indexPath); this.$emit(nextOption, index, indexPath); }, handleSelect(index, indexPath, instance) { this.activeIndex = index; this.$emit("select", index, indexPath, instance); this.openActiveItemMenus(); }, openActiveItemMenus() { let index = this.activeIndex; if (!this.menuItems[index]) { return; } if (index) { let indexPath = this.menuItems[index].indexPath; indexPath.forEach((index) => { let submenu = this.submenus[index]; submenu && this.openMenu(index, submenu.indexPath); }); } } }, mounted() { console.log(this); this.openActiveItemMenus(); } }; </script> <style lang="less" scoped> .yq-menu{ width:182px; } </style><file_sep>/src/components/radio/Radio.vue <template> <label class="radio-container"> <span class="radio-wrapper" :class="{ 'radio-disabled':disabled, 'radio-focus':focus, 'radio-active':model===label}"> <input :value="label" :disabled="disabled" v-model="model" @focus="focus=true" @blur="focus=false" :name="name" class="radio-input" type="radio"> </span> <span class="radio-content" v-if="$slots.default"><slot></slot></span> <span class="radio-content" v-else>{{label}}</span> </label> </template> <script> export default{ name: "Radio", props: { value: {}, label: [String, Number], disabled: Boolean, name: String }, data() { return { focus: false }; }, computed: { model: { get() { return this.value; }, set(val) { this.$emit("input", val); } } } }; </script> <style lang="less" scoped> .radio-container{ margin:0; padding:0; .radio-wrapper{ width:16px; height: 16px; display: inline-block; box-sizing: border-box; border:1px solid #cccccc; border-radius: 50%; cursor: pointer; position: relative; background: #ffffff; vertical-align:middle; } .radio-input{ display: block; opacity: 0; width:14px; height: 14px; cursor: pointer; margin: 0; } .radio-wrapper:after{ content: " "; display: block; width: 6px; height: 6px; border-radius: 50%; /*background: #ffffff;*/ z-index: 1000; margin:0; position: absolute; top:4px; left:4px; } .radio-wrapper.radio-active{ border-color: #18b025; } .radio-wrapper.radio-active:after{ background-color:#18b025; } .radio-wrapper.radio-disabled{ background-color: #eff2f7; cursor: not-allowed; .radio-input{ cursor: not-allowed; } } .radio-wrapper.radio-active.radio-disabled{ background-color:#e4e3e3; border-color:#cccccc; &:after{ background-color: #ffffff; } } .radio-content{ display: inline-block; vertical-align:middle; } } </style><file_sep>/src/components/menu/MenuItem.vue <template> <li class="yq-menu-item" @click="handleClick" :class="{ 'is-active':active }"><slot></slot></li> </template> <script> import Menu from "./menu-mixin"; export default { name: "MenuItem", componentName: "MenuItem", mixins: [Menu], props: { index: { type: String, required: true } }, computed: { active() { return this.index === this.rootMenu.activeIndex; } }, methods: { handleClick() { this.rootMenu.handleSelect(this.index, this.indexPath, this); } }, created() { this.rootMenu.menuItems[this.index] = this; } }; </script> <style lang="less" scoped> .yq-menu-item{ line-height: 32px; color: #999999; padding-left: 40px; border-bottom: 1px solid #eeefef; cursor: pointer; &:hover{ color:#4db232; } &.is-active{ color:#4db232; } } </style><file_sep>/src/components/menu/SubMenu.vue <template> <li class="yq-sub-menu" :class="{ 'is-opened':opened }"> <div @click="handleClick"> <slot name="title"></slot> <Icon name="chevron-down"></Icon> </div> <ul v-show="opened"><slot></slot></ul> </li> </template> <script> import menuMixin from "./menu-mixin"; import Icon from "../icon/Icon.vue"; export default{ name: "SubMenu", componentName: "SubMenu", mixins: [menuMixin], components: { Icon }, props: { index: { type: String, required: true } }, computed: { opened() { return this.rootMenu.openedMenus.indexOf(this.index) !== -1; } }, methods: { handleClick() { this.rootMenu.handleSubmenuClick(this.index, this.indexPath); } }, created() { this.rootMenu.submenus[this.index] = this; }, }; </script> <style lang="less" scoped> .yq-sub-menu > div{ line-height: 34px; color: #ffffff; padding-left:40px; background-color:#18b025; cursor: pointer; border-bottom: 2px solid #ffffff; font-size: 16px; } .yq-sub-menu .glyphicon{ float: right; margin:10px 10px 0 0; transition: 0.3s; font-size: 12px; } .yq-sub-menu.is-opened .glyphicon{ transform: rotate(180deg); } </style><file_sep>/README.md # yqapp > A Vue.js project for study Vue.js <file_sep>/src/views/content/MainPage.vue <template> <div class="yq-main-page"> <div v-on:openTab="handleOpenTab">hello</div> <div class="yq-main-wrapper" v-if="!isShowTab"> 欢迎使用云祺管理系统 </div> <tab :closable="true" @tab-remove="handleRemoveTab" v-if="isShowTab"> <!--<tabpane v-for="item in navData" :key="item" :label="item">{{item}}</tabpane>--> <tabpane label="hello">hello</tabpane> <tabpane label="world">world</tabpane> <tabpane label="java">world</tabpane> </tab> </div> </template> <script> import tab from "../../components/tab/Tabs.vue"; import tabpane from "../../components/tab/TabPane.vue"; export default{ name: "MainPage", components: { tab, tabpane }, data() { return { activeTab: "", tabs: ["java", "hello", "world"] }; }, computed: { isShowTab() { return this.navData.length !== 0; }, navData() { return this.tabs; } }, watch: { // navData(val) { // this.activeTab = val.length !== 0 ? val[val.length - 1] : ""; // } }, methods: { handleRemoveTab() { // let index = this.$store.state.hasOpenedTabs.indexOf(tab.label); // console.log(tab.label); // this.$store.state.hasOpenedTabs.splice(index, 1); // console.log(this.$store.state.hasOpenedTabs); // console.log(this.navData); // this.$nextTick(() => { // this.$forceUpdate(); // }); // let index = this.tabs.indexOf(tab); // this.tabs.splice(index, 1); }, handleOpenTab() { this.tabs.push("php"); } } }; </script> <style lang="less" scoped> .yq-main-page{ padding:1px 4px 0 190px; width:100%; height: 100%; box-sizing: border-box; .yq-main-wrapper{ width:100%; height: 100%; box-sizing: border-box; border:1px solid #ebebeb; border-radius: 4px; font-size: 50px; font-weight: bold; } } </style><file_sep>/src/components/tab/TabPane.vue <template> <div class="yq-tab-pane" v-show="show && $slots.default"> <slot></slot> </div> </template> <script> export default { name: "TabPane", props: { label: String, name: String }, data() { return { index: "", isClosable: null }; }, created() { this.isClosable = this.$parent.closable; if (!this.index) { this.index = this.$parent.$children.indexOf(this) + 1 + ""; } if (this.$parent.panes) { this.$parent.panes.push(this); } }, computed: { show() { return this.$parent.currentName === this.index; } }, destroyed() { if (this.$el && this.$el.parentNode) { this.$el.parentNode.removeChild(this.$el); } const panes = this.$parent.panes; if (panes) { panes.splice(this, panes.indexOf(this)); } }, watch: { name: { immediate: true, handler(val) { this.index = val; } } } }; </script> <style> .yq-tab-pane{ } </style><file_sep>/src/views/login/Logo.vue <template> <div class="yq-logo-container"> <img src="../../assets/images/logo.png"> <span>CLOUD LUCK</span> <h3 v-once>{{logoTitle}}</h3> <h5 v-once>{{logoInfo}}</h5> <!--<div><Loading></Loading></div>--> </div> </template> <script> import Loading from "../../components/loading/loading.vue"; export default{ name: "logo", data() { return { logoTitle: "新一代智慧云餐饮管理系统", logoInfo: "让管理更加轻松、高效、安全、智能" }; }, components: { Loading } }; </script> <style lang="less"> .yq-logo-container{ margin-top:228px; span{ display: block; margin-top:8px; font-size: 20px; } h3{ font-weight: bold; margin:18px 0 14px; font-size: 24px; } h5{ font-weight: normal; font-size: 18px; margin: 0; color:#999999; } } </style><file_sep>/src/stores/login/login.js /** * Created by ZhanG on 2016/12/5. */ <file_sep>/src/components/loading/loading.vue <template> <div class="yq-loading-mask" :class="[customClass,{'is-fullscreen':fullscreen}]"> <div class="yq-loading-spinner"> <svg class="circular" viewBox="25 25 50 50"> <circle class="path" cx="50" cy="50" r="20" fill="none"></circle> </svg> <p v-if="text" class="yq-loading-text">{{text}}</p> </div> </div> </template> <script> export default{ data() { return { text: null, fullscreen: true, customClass: "" }; } }; </script> <style> .yq-loading-mask { position: absolute; z-index: 10000; background-color: hsla(0,0%,100%,.9); margin: 0; top: 0; right: 0; bottom: 0; left: 0; } .yq-loading-mask.is-fullscreen { position: fixed } .yq-loading-mask.is-fullscreen .yq-loading-spinner { margin-top: -25px } .yq-loading-mask.is-fullscreen .yq-loading-spinner .circular { width: 50px } .yq-loading-spinner { top: 50%; margin-top: -21px; width: 100%; text-align: center; position: absolute } .yq-loading-spinner .yq-loading-text { color: #20a0ff; margin: 3px 0; font-size: 14px } .yq-loading-spinner .circular { width: 42px; animation: rotate 2s linear infinite; } .yq-loading-spinner .path { animation: dash 1.5s ease-in-out infinite; stroke-dasharray: 1,100; stroke-dashoffset: 0; stroke-width: 2; stroke: #20a0ff; stroke-linecap: round; } @keyframes rotate { to { transform: rotate(1turn) } } @keyframes dash { 0% { stroke-dasharray: 1,150; stroke-dashoffset: 0 } 50% { stroke-dasharray: 90,150; stroke-dashoffset: -35 } to { stroke-dasharray: 90,150; stroke-dashoffset: -124 } } </style> <file_sep>/src/views/main/TopNav.vue <template> <div class="yq-content-nav"> <div class="container-fluid"> <div class="row"> <div class="col-xs-2 yq-nav-logo"> <img src="../../assets/images/logo.png"> <p>CLOUD LUCK</p> </div> <div class="col-xs-8 clearfix"> <div class="yq-nav-item pull-left" v-for="(item,index) in routerParams"> <router-link :to="{name:'content',params:{category:item.Route}}"> <div><Icon :name="navIcons[index]"></Icon></div> <span class="yq-nav-title">{{item.Name}}</span> </router-link> </div> </div> <div class="col-xs-2"></div> </div> </div> </div> </template> <script> import Icon from "../../components/icon/Icon.vue"; export default{ name: "topNav", data() { return { routerParams: this.$store.state.systemParameters, navIcons: ["star", "book", "record", "list-alt", "link", "th-list"] }; }, components: { Icon }, computed: { routerParams: function () { return this.$store.getters.childParam; } }, watch: { "$route"({params}) { if (params.hasOwnProperty("category")) { let param = params.category; if (!this.$store.getters.navRouteParam.includes(param)) { this.$router.push({path: "/main"}); } } // console.log(this.$store.getters.navRouteParam); } } }; </script> <style lang="less"> .yq-content-nav{ padding-top:20px; color:#999999; .yq-nav-logo{ margin-left: 30px; p{ letter-spacing: 2px; color:#18b025; font-weight: bold; text-align: center; width:130px; } } .yq-nav-item{ width:16.6%; a{ display: inline-block; color:#cecece; text-decoration: none; width:60px; text-align: center; } a.router-link-active{ color:#18b025; } a:hover{ color:#18b025; } .glyphicon{ font-size: 40px; } .yq-nav-title{ display: block; width:60px; text-align: center; margin-top: 10px; } } } </style><file_sep>/src/views/content/Content.vue <template> <div v-calheight> <common v-show="isQuick"></common> <!--<div v-else>主体{{this.$route.params.category}}</div>--> <section class="yq-content" v-show="!isQuick"> <div class="yq-left-nav pull-left"> <yqmenu :default-openeds="navFirstItem" unique-opened @select="handleSelect"> <yqsubmenu v-for="item in leftNavParam" :index="item.Route"> <template slot="title">{{item.Name}}</template> <yqmenuitem v-for="v in item.Childs" :index="v.Route">{{v.Name}}</yqmenuitem> </yqsubmenu> </yqmenu> </div> <mainpage></mainpage> </section> </div> </template> <script> import common from "../quickstart/CommonUse.vue"; import yqmenu from "../../components/menu/Menu.vue"; import yqmenuitem from "../../components/menu/MenuItem.vue"; import yqsubmenu from "../../components/menu/SubMenu.vue"; import mainpage from "./MainPage.vue"; export default{ name: "Content", components: { common, yqmenu, yqmenuitem, yqsubmenu, mainpage }, computed: { isQuick: function() { return this.$route.params.category == "quickstart"; }, leftNavParam: function() { let paramObj; if (!this.isQuick) { let obj = this.$store.getters.childParam; let currentParam = this.$route.params.category; obj.forEach((item) => { if (item.Route == currentParam) { if (item.Childs) { paramObj = item.Childs; } } }); } return paramObj; }, navFirstItem: function() { if (!this.isQuick) { if (this.leftNavParam) { return [this.leftNavParam[0].Route]; } } } }, methods: { // handleOpen(index, indexPath) { // console.log(index, indexPath); // }, // handleClose(index, indexPath) { // console.log(index, indexPath); // }, handleSelect(index) { // console.log(index, indexPath); this.$store.state.hasOpenedTabs.push(index); } } }; </script> <style lang="less" scoped> .yq-content{ height: 100%; padding: 0 0 5px 4px; } .yq-left-nav{ height: 100%; width:184px; border:1px solid #ebebeb; border-radius: 4px; overflow:hidden; } </style> <file_sep>/src/components/tab/Tabs.vue <template> <div class="yq-tab"> <div class="yq-tab-header"> <div class="yq-tab-item pull-left" :class="{ 'active':currentName === n.index }" v-for="n in $children" @click="handleTabClick(n, $event)"> {{n.label}} <span class="glyphicon glyphicon-remove" v-if="closable" @click="handleTabRemove(n, $event)"></span> </div> </div> <div class="yq-tab-content" v-caltabheight> <slot></slot> </div> </div> </template> <script> export default { name: "Tabs", props: { type: { type: String, default: "tabs" }, activeName: String, closable: { type: Boolean, default: false } }, data() { return { children: null, activeTab: null, currentName: 0, panes: [] }; }, watch: { activeName: { handler(val) { console.log(this.activeName); this.currentName = val; } } }, methods: { handleTabRemove(tab, event) { event.stopPropagation(); let tabs = this.$children; let index = tabs.indexOf(tab); tab.$destroy(true); if (tab.index === this.currentName) { console.log("true"); let nextChild = tabs[index]; let prevChild = tabs[index - 1]; this.currentName = nextChild ? nextChild.index : prevChild ? prevChild.index : "-1"; } this.$emit("tab-remove", tab); this.$forceUpdate(); }, handleTabClick(tab, event) { this.currentName = tab.index; this.$emit("tab-click", tab, event); }, }, mounted() { this.currentName = this.activeName || this.$children[0].index || "1"; this.$nextTick(() => { this.$forceUpdate(); }); }, directives: { caltabheight: { inserted: function() { const wrapper = document.querySelector(".yq-main-page"); console.log(wrapper.getBoundingClientRect()); // console.log(el.getBoundingClientRect()); } } } }; </script> <style lang="less"> .yq-tab{ background-color: #fff; .yq-tab-header{ border-bottom:1px solid #ccc; height:40px; .yq-tab-item{ margin-bottom: -1px; margin-right: 2px; height: 40px; line-height: 40px; border: 1px solid transparent; border-bottom: 1px solid #cccccc; padding:0 20px; border-top-left-radius: 4px; border-top-right-radius: 4px; cursor: pointer; } .yq-tab-item:last-child{ margin-right: 0; } .yq-tab-item:hover{ background-color: #cccccc; } .yq-tab-item.active{ border: 1px solid #cccccc; border-bottom: 1px solid transparent; background-color: #ffffff; color: #18b025; } } .yq-tab-content{ padding:15px; border:1px solid #ccc; border-top:none; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; } } </style><file_sep>/src/main.js import Vue from "vue"; import axios from "axios"; import "bootstrap/dist/css/bootstrap.css"; import "./assets/css/base.less"; import App from "./App"; import {router} from "./routes/index"; import store from "./stores/index"; import * as Directive from "./global/directive/calheight"; Vue.use(Directive); //the url of api request axios.defaults.baseURL = "http://172.16.17.32:801/v1/"; Vue.prototype.axios = axios; //if response error code===401, go to login page axios.interceptors.response.use((res) => { return res; }, (error) => { if (error.response.status === 401) { console.log(error.response.status); store.dispatch("USER_LOGOUT"); router.replace({path: "login"}); } return Promise.reject(error); }); //set token in http header if (store.state.isLogin) { let token = store.state.userInfo.token; axios.defaults.headers.common["Authorization"] = token; } router.beforeEach(({path, name}, from, next) => { let isLogin = store.state.isLogin; if (!isLogin && name != "login" && name != "index") { return next({path: "/login"}); } next(); }); new Vue({ router, store, template: "<App/>", components: {App} }).$mount("#container"); export default Vue;<file_sep>/src/assets/css/base.less @import (reference) "./variables.less"; html{ height: 100%; } body{ height: 100%; margin: 0; font-family:Helvetica Neue,Helvetica,PingFang SC,Hiragino Sans GB,Microsoft YaHei,SimSun,sans-serif; color:@color-666; } input,button{ font-family:Helvetica Neue,Helvetica,PingFang SC,Hiragino Sans GB,Microsoft YaHei,SimSun,sans-serif; } ul{ margin:0; list-style: none; padding:0; } <file_sep>/src/components/button/Button.vue <template> <button type="button" class="btn" :disabled="disabled" @click="handleClick" :class="[ status ? 'btn-'+status : 'btn-default', size ? 'btn-'+size : '', { 'btn-block':block, } ]"> <Icon :name="icon" v-if="icon"></Icon> <span v-if="$slots.default"><slot></slot></span> </button> </template> <script> import Icon from "../icon/Icon.vue"; export default { name: "btn", props: { status: String, size: String, icon: { type: String, default: "" }, disabled: { type: Boolean, default: false }, block: Boolean }, components: { Icon }, methods: { handleClick(event) { console.log(event); this.$emit("click", event); } } }; </script>
22b6609fb274b5017418a34413f63ecc1ca32752
[ "Markdown", "Vue", "JavaScript", "Less" ]
21
Markdown
zscumt123/vapp
710593b0981dead7628e16b97e8acb04bf3805b8
307530328bca0dc5890c846fb9c3b5413b2679d5
refs/heads/master
<file_sep>{% load define_action %} <div class="paymentsTable col-xs-12 pad-0"> <div class="row heading" style="font-weight: bold;"> <div class="col-xs-6 text-left">Date</div> <div class="col-xs-6 text-right" style="padding-right: 38px;">Amount</div> </div><div class="spacer"></div> <div class="payments-list col-xs-12"> {% if data.isSuccess == True %} {% if data.data.payments %} {% for payment in data.data.payments %} <div class="row"> <div class="col-xs-6 text-left">{{ payment.payments_date }}</div> <div class="col-xs-6 text-right">{{ payment.discount_allowed_amount|amountFormat }}</div> </div> {% endfor %} {% else %} <div class="row"> <div class="col-xs-12">No Record Found</div> </div> {% endif %} {% endif %} </div> </div> <!-- <table style="display: block"> <tbody> <tr> <th>Date</th> <th>Amount</th> </tr> {% if data.isSuccess == True %} {% if data.data.payments %} {% for payment in data.data.payments %} <tr> <td>{{ payment.payments_date }}</td> <td>$ {{ payment.discount_allowed_amount }}</td> </tr> {% endfor %} {% else %} <tr><td>No Record Found</td></tr> {% endif %} {% endif %} </tbody> </table> --><file_sep>from django import template register = template.Library() @register.simple_tag def define(val=None): return val @register.filter def amountFormat(value, arg=None): if value == "" or value == None: return '$ 0.00' return "$ "+"{:0,.2f}".format(value) @register.filter def noneCheck(value, arg=None): if value == None: return '' return value @register.filter def active_route(request, path): if path in request.path: return 'active' return '' @register.filter def empty_dashes(value, arg=None): if value == None or value == '': return '------' return value @register.filter def page_heading(path, arg=None): if 'account/maintain' in path: return 'Maintain Account' elif 'partner/maintain' in path: return 'Maintain Partner' elif 'account/create' in path: return 'Create Account' return '' @register.filter def quantityCheck(qty, arg=None): if qty == None or qty == 0 or qty == '': return 1 return qty @register.filter def divide(divider, dividend): return dividend/divider <file_sep>from django.urls import path from ops import views urlpatterns = [ # path('', views.index, name='index'), path('', views.maintainAccountView, name='maintainAccountView'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), path('home', views.home, name='home'), path('api/userlogin', views.proccessLogin, name='userlogin'), path('account/create', views.createAccountView, name='createAccountView'), path('account/maintain/<str:client_id>', views.maintainAccountView, name='maintainAccountView'), path('account/creating', views.createAccount, name='createAccount'), path('business/getBusinessTypes', views.getBusinessTypes, name='getBusinessTypes'), path('area/getAreaNames', views.getAreaNames, name='getAreaNames'), path('industry/getIndustries', views.getIndustries, name='getIndustries'), path('country/getCountries', views.getCountries, name='getCountries'), path('payment/getPaymentOptions', views.getPaymentOptions, name='getPaymentOptions'), path('area/getAreaNames/<str:area_code>', views.getAreaNames, name='getAreaNames'), path('linetype/getLineTypes', views.getLineTypes, name='getLineTypes'), path('staff/getAllStaffs', views.getAllStaffs, name='getAllStaffs'), path('positions/getCompanyPositions', views.getCompanyPositions, name='getCompanyPositions'), path('api/searchClient', views.searchClient, name='searchClient'), path('getcreateAccountPage', views.getcreateAccountPage, name='getcreateAccountPage'), path('getInvoices/<str:clientId>', views.getInvoices, name='getInvoices'), path('client/getCredits/<str:clientId>', views.getCredits, name='getCredits'), path('client/getOneoffinvoices/<str:clientId>', views.getOneoffinvoices, name='getOneoffinvoices'), path('client/getOneOffCharges/<str:clientId>', views.getOneOffCharges, name='getOneOffCharges'), path('client/getContacts/<str:clientId>', views.getContacts, name='getContacts'), path('client/getClientPhones/<str:clientId>', views.getClientPhones, name='getClientPhones'), path('client/getAccountSummary/<str:clientId>', views.getAccountSummary, name='getAccountSummary'), path('client/createContact/<str:clientId>', views.createContact, name='createContact'), path('client/createPhone/<str:clientId>', views.createPhone, name='createPhone'), path('client/createTollfree/<str:clientId>', views.createTollfree, name='createTollfree'), path('client/createStandingCharges/<str:clientId>', views.createStandingCharges, name='createStandingCharges'), path('client/createOneOffCharges/<str:clientId>', views.createOneOffCharges, name='createOneOffCharges'), path('client/getPayments/<str:clientId>', views.getPayments, name='getPayments'), path('client/getMobiles/<str:clientId>', views.getMobiles, name='getMobiles'), path('client/getTollFree/<str:clientId>', views.getTollFree, name='getTollFree'), path('client/getStandingCharges/<str:clientId>', views.getStandingCharges, name='getStandingCharges'), path('client/getWhitelabel/<str:clientId>', views.getWhitelabel, name='getWhitelabel'), path('client/createWhiteLabel/<str:clientId>', views.createWhiteLabel, name='createWhiteLabel'), path('client/editClient', views.createAccount), path('plans/getMobilePlans', views.getMobilePlans, name='getMobilePlans'), path('plans/getMobileGroupPlans', views.getMobileGroupPlans, name='getMobileGroupPlans'), path('partner/maintain/<str:partner_id>', views.maintainPartnerView, name='maintainPartnerView'), path('partner/edit', views.editPartner, name='editPartner'), path('partner/searchPartner', views.searchPartner, name='searchPartner'), path('partner/getClients/<str:partner_id>', views.getClients), path('providers/getServiceProviders', views.getServiceProviders, name='getServiceProviders'), path('staff/getAllStaffs', views.getAllStaffs, name='getAllStaffs'), ]<file_sep>import json from django.conf import settings import requests class Request(object): def __init__(self): # cursor = conn.cursor() # cursor.execute("SELECT * FROM uf1_users") # records = cursor.fetchall() # pprint.pprint(records) self.data = [] def post(self, params, method, token=None): url = settings.API['base_url']+'v1/'+method+'/' payload = params headers = { 'content-type': 'application/json', 'Authorization':settings.API['key'] } if token is not None: headers['Authorization'] += '.'+token return requests.post(url, data=payload, headers=headers) def get(self, params, method, token=None): url = settings.API['base_url']+'v1/'+method+'/' payload = params headers = { 'content-type': 'application/json', 'Authorization':settings.API['key'] } if token is not None: headers['Authorization'] += '.'+token return requests.get(url, data=payload, headers=headers) <file_sep>from django.shortcuts import render, redirect import time from django.http import HttpResponseRedirect, HttpResponse from django.views.decorators.csrf import csrf_exempt import json, locale , calendar, datetime from django.conf import settings from ops.Custom.Request import * from dateutil.relativedelta import * import csv from calendar import monthrange # Create your views here. def index(request): # salt = hex(random.getrandbits(128)).encode() # return HttpResponse(len(salt)) # dk = hashlib.pbkdf2_hmac('sha256',b'mypass',salt, 1000000) # return HttpResponse(binascii.hexlify(dk)) if 'user_data' not in request.session : return HttpResponseRedirect("/login") # do further call to get user information staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+'}' r = Request() r = r.post(params, 'services', request.session['user_data']['tokens']['access_token']) data = r.json() if 'isSuccess' in data: services = {'total_amt':0,'toll_calls_amt':0,'local_ditto_amt':0,'fax_amt':0,'st_charges_amt':0} if data['data']['services'] is not None: for index in data['data']['services']: services['total_amt'] += index['invoice_net_amount'] services['toll_calls_amt'] += index['toll_traffic_amount'] services['local_ditto_amt'] += index['local_traffic_amount'] services['fax_amt'] += index['fax_traffic_amount'] services['st_charges_amt'] += index['standing_charges_amount'] context = {'user_data': request.session['user_data']['user_info'], 'data':services} return render(request, 'portal/index.html', context) else: del request.session['user_data'] request.session['errors'] = data['errors'] return HttpResponseRedirect("/login") def login(request): if 'errors' in request.session: context = {'errors':request.session['errors']} del request.session['errors'] else: context = {'errors':''} return render(request, 'portal/login.html', context) def home(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api context = {'user_data': request.session['user_data']['user_info']} return render(request, 'portal/home.html', context) @csrf_exempt def proccessLogin(request): if request.method == "POST": if(request.POST['account'] and request.POST['pass']): try: username = request.POST['account'] password = request.POST['pass'] # send request to api params = '{"username":'+username+',"password":"'+<PASSWORD>+'"}' r = Request() r = r.post(params, 'login') data = r.json() if data['isSuccess'] and checkUserType(data['data']['user_info']['type']): # save tokens in session request.session['user_data'] = data['data'] return redirect("maintainAccountView",client_id=608) else: request.session['errors'] = data['errors'] return HttpResponseRedirect("/login") except ValueError: request.session['error'] = 'Account and Password do not match' else : request.session['error'] = 'Account and Password do not match' else: request.session['error'] = 'Invalid Request Method' return HttpResponseRedirect("/login") def createAccountView(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) context = {'user_data': request.session['user_data']['user_info']} return render(request, 'portal/account/create.html', context) @csrf_exempt def createAccount(request): if request.method == "POST": staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api post_data = request.POST if 'client_id' in post_data and post_data['client_id'] != "": url = "clients/edit" else: url = "clients/create" params = '{"staff_id":'+staff_id+', "data":'+json.dumps(post_data)+'}' r = Request() r = r.post(params, url, request.session['user_data']['tokens']['access_token']) data = r.json() if 'client_id' in data['data']['client'] and data['data']['client']['client_id'] != 0: msg = 'Account created with id : '+str(data['data']['client']['client_id']) data = {'alert':'success','message':msg} elif 'client_updated' in data['data']['client']: data = {'alert':'success', 'message':"Account Updated"} else: data = {'alert':'error','message':data['data']['client']['msg']} return HttpResponse(json.dumps(data)) def maintainAccountView(request, client_id=""): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+', "client_id":"'+str(client_id)+'"}' r = Request() data = r.get(params, 'clients/getClients', request.session['user_data']['tokens']['access_token']) data = data.json() if data['isSuccess']: # get rate plans r = Request() rate_plans = r.get(params, 'plans/getRatePlans', request.session['user_data']['tokens']['access_token']) data['rate_plans'] = rate_plans.json()['data']['rate_plans'] context = {'user_data': request.session['user_data']['user_info'],'data':data} return render(request, 'portal/account/maintain.html', context) return HttpResponseRedirect("/login") def getBusinessTypes(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+'}' r = Request() r = r.get(params, 'business/getBusinessTypes', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/dropdown_list.html', {'data':data}) def getAreaNames(request, area_code = ""): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api if area_code != "": params = '{"staff_id":'+staff_id+', "area_code":'+area_code+'}' else: params = '{"staff_id":'+staff_id+'}' r = Request() r = r.get(params, 'area/getAreaNames', request.session['user_data']['tokens']['access_token']) if area_code == "": data = r.json() return render(request, 'portal/account/dropdown_list.html', {'data':data}) else: return HttpResponse(r) def getIndustries(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+'}' r = Request() r = r.get(params, 'industry/getIndustries', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/dropdown_list.html', {'data':data}) def getCountries(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+'}' r = Request() r = r.get(params, 'country/getCountries', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/dropdown_list.html', {'data':data}) def getPaymentOptions(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+'}' r = Request() r = r.get(params, 'payment/getPaymentOptions', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/dropdown_list.html', {'data':data}) def getAllStaffs(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+'}' r = Request() r = r.get(params, 'staff/getAllStaffs', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/dropdown_list.html', {'data':data}) def getLineTypes(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+'}' r = Request() r = r.get(params, 'linetypes/getLineTypes', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/dropdown_list.html', {'data':data}) def getInvoices(request, clientId): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+',"client_id":"'+clientId+'", "limit":"1"}' r = Request() r = r.get(params, 'clients/getInvoices', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/tabs/acc_invoice.html', {'data':data}) def getOneoffinvoices(request, clientId): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+',"client_id":"'+clientId+'", "limit":"1"}' r = Request() r = r.get(params, 'clients/getOneOffInvoices', request.session['user_data']['tokens']['access_token']) data = r.json() oneoffinvoices = [] for index in data['data']['oneoffinvoices']: temp = {} temp['invoice_number'] = index['invoice_number'] temp['invoice_date'] = index['invoice_date'] temp['oi_description'] = index['oi_description'] temp['oi_gross_amount'] = '$' +str(index['oi_gross_amount']) temp['credits'] = '$ 0.00' temp['payments'] = '$ 0.00' temp['total_amount'] = '$'+str(index['oi_gross_amount']) temp['oi_transaction_id'] = index['oi_transaction_id'] oneoffinvoices.append(temp) return HttpResponse(json.dumps({'aaData':oneoffinvoices})) def getOneOffCharges(request, clientId): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) params = {"staff_id":staff_id,"client_id":clientId} # send request to api if 'charges_id' in request.GET: if request.GET['charges_id'] != '0': params['other_charges_transaction_id'] = request.GET['charges_id'] else: return render(request, 'portal/account/tabs/charges_detail.html', {'oneoff_charges':{'client_id':clientId}}) r = Request() r = r.get(json.dumps(params), 'clients/getOneOffCharges', request.session['user_data']['tokens']['access_token']) data = r.json() if 'charges_id' in request.GET: # mobile detail.html return render(request, 'portal/account/tabs/charges_detail.html', {'oneoff_charges':data['data']['oneoffcharges'][0]}) else: return HttpResponse(json.dumps({'aaData':data['data']['oneoffcharges']})) @csrf_exempt def searchClient(request): if request.method == "POST": if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # user search string search_str = request.POST['search_str'] params = '{"staff_id":'+staff_id+', "limit":"20", "search_str":"'+search_str+'"}' r = Request() r = r.post(params, 'clients', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/components/search_result.html',{'data':data}) def getCredits(request, clientId): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+',"client_id":"'+clientId+'"}' r = Request() r = r.get(params, 'clients/getCredits', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/tabs/acc_credits.html', {'data':data}) def getCompanyPositions(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+'}' r = Request() r = r.get(params, 'positions/getCompanyPositions', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/dropdown_list.html', {'data':data}) def getMobilePlans(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+'}' r = Request() r = r.get(params, 'plans/getMobilePlans', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/dropdown_list.html', {'data':data}) def getMobileGroupPlans(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+'}' r = Request() r = r.get(params, 'plans/getMobileGroupPlans', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/dropdown_list.html', {'data':data}) def getServiceProviders(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+'}' r = Request() r = r.get(params, 'providers/getServiceProviders', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/dropdown_list.html', {'data':data}) def getAccountSummary(request, clientId): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = json.dumps({"staff_id":staff_id,"client_id":clientId}) r = Request() r = r.get(params, 'clients/getAccountSummary', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/tabs/acc_account_summary.html', {'data':data}) def getPayments(request, clientId): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+',"client_id":"'+clientId+'"}' r = Request() r = r.get(params, 'clients/getPayments', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/account/tabs/acc_payments.html', {'data':data}) def getContacts(request, clientId): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = {"staff_id":staff_id,"client_id":clientId} if 'contactId' in request.GET: if request.GET['contactId'] != '0': params['contact_id'] = request.GET['contactId'] else: return render(request, 'portal/account/tabs/cont_contact_detail.html', {'contact':{'client_id':clientId}}) params = json.dumps(params) r = Request() r = r.get(params, 'clients/getContacts', request.session['user_data']['tokens']['access_token']) data = r.json() if 'contactId' in request.GET: return render(request, 'portal/account/tabs/cont_contact_detail.html', {'contact':data['data']['contacts'][0]}) else: return HttpResponse(json.dumps({'aaData':data['data']['contacts']})) def getClientPhones(request, clientId): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = {"staff_id":staff_id,"client_id":clientId} if 'phoneId' in request.GET: if request.GET['phoneId'] != '0': params['phone_id'] = request.GET['phoneId'] else: return render(request, 'portal/account/tabs/ph_phone_detail.html', {'phone':{'client_id':clientId}}) params = json.dumps(params) r = Request() r = r.get(params, 'clients/getClientPhones', request.session['user_data']['tokens']['access_token']) data = r.json() if 'phoneId' in request.GET: return render(request, 'portal/account/tabs/ph_phone_detail.html', {'phone':data['data']['client_phones'][0]}) elif 'type' in request.GET and request.GET['type'] == 'dropdown': return render(request, 'portal/account/dropdown_list.html', {'data':data}) else: return HttpResponse(json.dumps({'aaData':data['data']['client_phones']})) def getMobiles(request, clientId): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = {"staff_id":staff_id,"client_id":clientId} if 'mobileId' in request.GET: if request.GET['mobileId'] != '0': params['mobileId'] = request.GET['mobileId'] else: return render(request, 'portal/account/tabs/mobile_detail.html', {'phone':{'client_id':clientId}}) params = json.dumps(params) r = Request() r = r.get(params, 'clients/getMobiles', request.session['user_data']['tokens']['access_token']) data = r.json() if 'mobileId' in request.GET: # mobile detail.html return render(request, 'portal/account/tabs/ph_phone_detail.html', {'phone':data['data']['client_mobiles'][0]}) else: return HttpResponse(json.dumps({'aaData':data['data']['client_mobiles']})) def getTollFree(request, clientId): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = {"staff_id":staff_id,"client_id":clientId} if 'id' in request.GET: if request.GET['id'] != '0': params['client_toll_free_id'] = request.GET['id'] else: return render(request, 'portal/account/tabs/toll_free_detail.html', {'toll_free':{'client_id':clientId}}) params = json.dumps(params) r = Request() r = r.get(params, 'clients/getTollFree', request.session['user_data']['tokens']['access_token']) data = r.json() if 'id' in request.GET: # mobile detail.html return render(request, 'portal/account/tabs/toll_free_detail.html', {'toll_free':data['data']['toll_free'][0]}) elif 'type' in request.GET and request.GET['type'] == 'dropdown': return render(request, 'portal/account/dropdown_list.html', {'data':data}) else: return HttpResponse(json.dumps({'aaData':data['data']['toll_free']})) def getStandingCharges(request, clientId): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) params = {"staff_id":staff_id,"client_id":clientId} # send request to api if 'standing_charge_id' in request.GET: if request.GET['standing_charge_id'] != '0': params['standing_charge_id'] = request.GET['standing_charge_id'] else: return render(request, 'portal/account/tabs/st_charges_detail.html', {'standing_charges':{'client_id':clientId}}) r = Request() r = r.get(json.dumps(params), 'clients/getStandingCharges', request.session['user_data']['tokens']['access_token']) data = r.json() if 'standing_charge_id' in request.GET: # mobile detail.html return render(request, 'portal/account/tabs/st_charges_detail.html', {'standing_charges':data['data']['standing_charges'][0]}) else: return HttpResponse(json.dumps({'aaData':data['data']['standing_charges']})) def getWhitelabel(request, clientId): staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) params = {"staff_id":staff_id,"client_id":clientId} # send request to api r = Request() if request.GET['wl_enabled'] and request.GET['wl_enabled'] == 'False': if 'action' in request.GET and request.GET['action'] == 'read': return render(request, 'portal/account/controls_sidebar/wl_form.html') r = r.post(json.dumps(params), 'prices/getDefaultPrices', request.session['user_data']['tokens']['access_token']) data = r.json() data['data']['prices_default']['client_id'] = clientId return render(request, 'portal/account/controls_sidebar/enable_wl.html', {'white_label':data['data']['prices_default']}) r = Request() r = r.get(json.dumps(params), 'clients/getWhitelabel', request.session['user_data']['tokens']['access_token']) data = r.json() if 'action' in request.GET and request.GET['action'] == 'read': return render(request, 'portal/account/controls_sidebar/wl_form.html', {'white_label':data['data']['white_label']}) else: return render(request, 'portal/account/controls_sidebar/enable_wl.html', {'white_label':data['data']['white_label']}) @csrf_exempt def createOneOffCharges(request, clientId): if request.method == "POST": staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) post_data = request.POST params = '{"staff_id":'+staff_id+', "client_id":'+clientId+', "data":'+json.dumps(post_data)+'}' if 'other_charges_transaction_id' in post_data and post_data['other_charges_transaction_id'] != '': url = 'clients/updateOneOffCharges' else: url = 'clients/createOneOffCharges' r = Request() r = r.post(params, url, request.session['user_data']['tokens']['access_token']) data = r.json() if 'other_charges_transaction_id' in post_data and post_data['other_charges_transaction_id'] != '': if data['data']['one_off_charge']['charge_updated']: msg = 'One-Off Charge updated' data = {'alert':'success','message':msg} else: data = {'alert':'error','message':'One-Off Charge not updated'} else: if data['data']['one_off_charge']['charge_created']: msg = 'One-Off Charge created' data = {'alert':'success','message':msg} else: data = {'alert':'error','message':'One-Off Charge not creaded'} return HttpResponse(json.dumps(data)) @csrf_exempt def createContact(request, clientId): if request.method == "POST": staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) post_data = request.POST params = '{"staff_id":'+staff_id+', "client_id":'+clientId+', "data":'+json.dumps(post_data)+'}' if 'contact_id' in post_data and post_data['contact_id'] != '': url = 'clients/updateContact' else: url = 'clients/createContact' r = Request() r = r.post(params, url, request.session['user_data']['tokens']['access_token']) data = r.json() if 'contact_id' in post_data and post_data['contact_id'] != '': if data['data']['contact']['contact_updated']: msg = 'Contact Updated' data = {'alert':'success','message':msg} else: data = {'alert':'error','message':'Contact not updated'} else: if data['data']['contact']['contact_created']: msg = 'Contact created' data = {'alert':'success','message':msg} else: data = {'alert':'error','message':'Contact not creaded'} return HttpResponse(json.dumps(data)) @csrf_exempt def createPhone(request, clientId): if request.method == "POST": staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) post_data = request.POST params = '{"staff_id":'+staff_id+', "client_id":'+clientId+', "data":'+json.dumps(post_data)+'}' if 'client_to_phone_id' in post_data and post_data['client_to_phone_id'] != '': url = 'clients/updatePhone' else: url = 'clients/createPhone' r = Request() r = r.post(params, url, request.session['user_data']['tokens']['access_token']) data = r.json() if 'client_to_phone_id' in post_data and post_data['client_to_phone_id'] != '': if data['data']['phone']['phone_updated']: msg = 'Phone Updated' data = {'alert':'success','message':msg} else: data = {'alert':'error','message':'Phone not updated'} else: if data['data']['phone']['phone_created']: msg = 'Phone created' data = {'alert':'success','message':msg} else: data = {'alert':'error','message':'Phone not creaded'} return HttpResponse(json.dumps(data)) @csrf_exempt def createTollfree(request, clientId): if request.method == "POST": staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) post_data = request.POST params = '{"staff_id":'+staff_id+', "client_id":'+clientId+', "data":'+json.dumps(post_data)+'}' if 'client_toll_free_id' in post_data and post_data['client_toll_free_id'] != '': url = 'clients/updateTollfree' else: url = 'clients/createTollfree' r = Request() r = r.post(params, url, request.session['user_data']['tokens']['access_token']) data = r.json() if 'client_toll_free_id' in post_data and post_data['client_toll_free_id'] != '': if data['data']['tollfree']['tollfree_updated']: msg = 'Tollfree Updated' data = {'alert':'success','message':msg} else: data = {'alert':'error','message':'Tollfree not updated'} else: if data['data']['tollfree']['tollfree_created']: msg = 'Tollfree created' data = {'alert':'success','message':msg} else: data = {'alert':'error','message':'Tollfree not creaded'} return HttpResponse(json.dumps(data)) @csrf_exempt def createStandingCharges(request, clientId): if request.method == "POST": staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) post_data = request.POST params = '{"staff_id":'+staff_id+', "client_id":'+clientId+', "data":'+json.dumps(post_data)+'}' if 'standing_charge_id' in post_data and post_data['standing_charge_id'] != '': url = 'clients/updateStandingCharges' else: url = 'clients/createStandingCharges' r = Request() r = r.post(params, url, request.session['user_data']['tokens']['access_token']) data = r.json() if 'standing_charge_id' in post_data and post_data['standing_charge_id'] != '': if data['data']['standing_charges']['st_charges_updated']: msg = 'Standing charges Updated' data = {'alert':'success','message':msg} else: data = {'alert':'error','message':'Standing charges not updated'} else: if data['data']['standing_charges']['st_charges_created']: msg = 'Standing charges created' data = {'alert':'success','message':msg} else: data = {'alert':'error','message':'Standing charges not creaded'} return HttpResponse(json.dumps(data)) @csrf_exempt def createWhiteLabel(request, clientId): if request.method == "POST": staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) post_data = request.POST params = '{"staff_id":'+staff_id+', "client_id":'+clientId+', "data":'+json.dumps(post_data)+'}' if 'wl_client_id' in post_data and post_data['wl_client_id'] != '': url = 'clients/updateWhiteLabel' else: url = 'clients/createWhiteLabel' r = Request() r = r.post(params, url, request.session['user_data']['tokens']['access_token']) data = r.json() if 'wl_client_id' in post_data and post_data['wl_client_id'] != '': if data['data']['white_label']['whitelabel_updated']: msg = 'Client White Label Updated' data = {'alert':'success','message':msg,'action':'createWl'} else: data = {'alert':'error','message':'Client White Label not updated'} return HttpResponse(json.dumps(data)) # partner page def maintainPartnerView(request, partner_id=""): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # send request to api params = '{"staff_id":'+staff_id+', "partner_id":'+partner_id+'}' r = Request() r = r.get(params, 'staff/getStaff', request.session['user_data']['tokens']['access_token']) data = r.json() if data['isSuccess']: context = {'user_data': request.session['user_data']['user_info'],'data':data} return render(request, 'portal/partner_account/maintain.html', context) return HttpResponseRedirect("/login") @csrf_exempt def editPartner(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) post_data = request.POST # send request to api params = '{"staff_id":'+staff_id+', "data":'+json.dumps(post_data)+'}' r = Request() r = r.post(params, 'staff/editStaff', request.session['user_data']['tokens']['access_token']) data = r.json() if 'staff_and_agents_id' in post_data and post_data['staff_and_agents_id'] != '': if data['data']['staff']['staff_updated']: msg = 'Staff Updated' data = {'alert':'success','message':msg} else: data = {'alert':'error','message':'Staff not updated'} else: if data['data']['staff']['staff_created']: msg = 'Staff created' data = {'alert':'success','message':msg} else: data = {'alert':'error','message':'Staff not creaded'} return HttpResponse(json.dumps(data)) @csrf_exempt def searchPartner(request): if request.method == "POST": if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # user search string search_str = request.POST['search_str'] params = '{"staff_id":'+staff_id+', "limit":"20", "search_str":"'+search_str+'"}' r = Request() r = r.get(params, 'staff/getAllStaffs', request.session['user_data']['tokens']['access_token']) data = r.json() return render(request, 'portal/components/search_result.html',{'data':data}) def getClients(request, partner_id=""): staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) # user search string params = '{"staff_id":'+staff_id+', "partner_id":'+partner_id+'}' r = Request() r = r.get(params, 'clients/getClients', request.session['user_data']['tokens']['access_token']) data = r.json() return HttpResponse(json.dumps({'aaData':data['data']['clients']})) def getcreateAccountPage(request): return render(request, 'portal/account/create_content.html') def logout(request): try: if(request.session['user_data']): del request.session['user_data'] return HttpResponseRedirect("/login") except: return HttpResponseRedirect("/login") def checkUserType(userType): if (userType == '3'): return True else: return False def checkUserSession(request): if 'user_data' not in request.session : return HttpResponseRedirect("/login") staff_id = str(request.session['user_data']['user_info']['staff_and_agents_id']) <file_sep># Ufone Operation Portal API Integrations - [Vumeda API](https://vumeda.devoli.com) Custom Developed API ACL: Role base user login, Ufone database management, excel reports generation ## Getting Started Before start, please note this portal is using the django-API(another repo here) - so it'll run in-conjuction with Django-API ### Prerequisites As prerequisites you must have installed python 3.6 and a package to create virtual environment like pipenv ### Installing Git clone the repositry or download the zip file. Go into the project folder and create virtual enviornment - pipenv shell Outside shell, inside project folder ,install all required packages and add them to pip file - pipenv install <pkg name> Finally, launch shell - pipenv shell Run django server - python manage.py runserver ## Built With * [Django](https://docs.djangoproject.com/en/2.1/) - The web framework used ## Authors * **Creativetech Solutions** - [Creativetech](https://github.com/Creativetech-Solutions/)
e3d869da424af6ee596b88e9412104695d6132e7
[ "Markdown", "HTML", "Python" ]
6
Markdown
Creativetech-Solutions/Django-Portal
9fe6dc469398d935d79d450d070fd9aa1c973551
9d77743a9d1653fe922793619b3b817ca6259f0c
refs/heads/master
<repo_name>AJacobsonRed3/NAV_FieldOptionNumbers<file_sep>/100 - Build NAVFieldNames NAVFieldOptions.py # Example Using Python 3.x import zlib, sys, struct import xml.etree.ElementTree as ET import numpy as np import pandas as pd import pyodbc import sqlalchemy as sa # 1.3.6 import urllib # 1.25.3 import xml.etree.ElementTree as ET def ParseXML(): print("Processing " + str(TableNo) + " " + TableName) dfNAVFieldNames = pd.DataFrame(columns=['TableNo','TableName','FieldNo', 'FieldName']) dfNAVFieldOptions = pd.DataFrame(columns=['TableNo','TableName','FieldNo', 'FieldName','OptionNo','OptionName']) tree = ET.fromstring(output.decode("utf-8")) # root = tree.getroot() for child in tree.iter('{urn:schemas-microsoft-com:dynamics:NAV:MetaObjects}Field'): # print(child.attrib.get("ID")) dfNAVFieldNames = dfNAVFieldNames.append( {'TableNo' : TableNo, 'TableName' : TableName, 'FieldNo' : child.attrib.get('ID'), 'FieldName' : child.attrib.get('Name')},ignore_index=True) OptionString = child.attrib.get('OptionString') if (OptionString is not None): # print(OptionString.split(",")) OptionNo = 0 for Option in OptionString.split(","): dfNAVFieldOptions = dfNAVFieldOptions.append( {'TableNo' : TableNo, 'TableName' : TableName, 'FieldNo' : child.attrib.get('ID'), 'FieldName' : child.attrib.get('Name'), 'OptionNo' : OptionNo, 'OptionName' : Option},ignore_index=True) OptionNo += 1 dfNAVFieldNames.to_sql("NAVFieldNames",con=engine,schema=Schema,if_exists="append",index=False) dfNAVFieldOptions.to_sql("NAVFieldOptions",con=engine,schema=Schema,if_exists="append",index=False) # 1 -Create a connection string Driver = "ODBC Driver 17 for SQL Server" Server = "ADAM2019" Database = "NAVReportingTest" Schema = "dbo" ConnectionString = "Driver={" + Driver + "};Server="+Server+";Database="+Database+";Trusted_Connection=yes;" params = urllib.parse.quote_plus(ConnectionString) engine = sa.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params, fast_executemany=True) # 2 - The query we want to use SQLQuery = """ SELECT meta.[Object ID] AS TableNo, obj.Name AS TableName, meta.Metadata FROM NAVDemo.dbo.[Object Metadata] meta JOIN NAVDemo.dbo.Object obj ON meta.[Object Type] = obj.Type AND meta.[Object ID] = obj.ID WHERE obj.Type = 1 --aND meta.[Object ID] <= 40 ORDER BY obj.ID""" # 2A - the dataframes that will actually store all the output # From our parsing of the Metadata # Creating empty dataframe one for each table we will eventually write # 3 -Load the Data From NAV to a Python Pandas Dataframe ObjectMetaData = pd.read_sql(sql=SQLQuery,con=engine)#,params=params) # 4 - loop throught the output (Note - in the initial test I have # limited this to just table 15) for Name, TableNo, TableName, MetaData in ObjectMetaData.itertuples(): MetaDataToDecompress = bytearray(MetaData) # we need to skip the first four characters MetaDataToDecompress = MetaDataToDecompress[4:] # now we decompress the data output = zlib.decompress(MetaDataToDecompress,-15) # we are going to take the output data and pass it to our python function ParseXML() <file_sep>/210 - Parse the XML and write to SQL.py import xml.etree.ElementTree as ET import numpy as np import pandas as pd import pyodbc # 4.0.26 import sqlalchemy as sa # 1.3.6 import urllib # 1.25.3 # Creating empty dataframe one for each table we will eventually write dfNAVFieldNames = pd.DataFrame(columns=['TableNo','TableName','FieldNo', 'FieldName']) dfNAVFieldOptions = pd.DataFrame(columns=['TableNo','TableName','FieldNo', 'FieldName','OptionNo','OptionName']) with open('NAVTable-3.xml', 'r') as xml_file: tree = ET.parse(xml_file) root = tree.getroot() TableNo = 3 TableName = "Payment Terms" # this gets me all the field level attributes from the XML. It creates row in our # dataframe. One row for each distinct field name and one row for each option for child in root.iter('{urn:schemas-microsoft-com:dynamics:NAV:MetaObjects}Field'): dfNAVFieldNames = dfNAVFieldNames.append( {'TableNo' : TableNo, 'TableName' : TableName, 'FieldNo' : child.attrib.get('ID'), 'FieldName' : child.attrib.get('Name')},ignore_index=True) OptionString = child.attrib.get('OptionString') if (OptionString is not None): # print(OptionString.split(",")) OptionNo = 0 for Option in OptionString.split(","): dfNAVFieldOptions = dfNAVFieldOptions.append( {'TableNo' : TableNo, 'TableName' : TableName, 'FieldNo' : child.attrib.get('ID'), 'FieldName' : child.attrib.get('Name'), 'OptionNo' : OptionNo, 'OptionName' : Option},ignore_index=True) OptionNo += 1 # the below just show examples print(dfNAVFieldNames.head()) print(dfNAVFieldOptions.head()) # We have our Dataframe and we want to load them into SQL server # Create Our Connection String- Driver="ODBC Driver 17 for SQL Server" # Update your parameters for your database Server = "ADAM2019" Database = "NAVReportingTest" ConnectionString = "Driver={" + Driver + "};Server="+Server+";Database="+Database+";Trusted_Connection=yes;" Schema = "dbo" params = urllib.parse.quote_plus(ConnectionString) engine = sa.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params, fast_executemany=True) # here we take our dataframes and put them into SQL dfNAVFieldNames.to_sql("NAVFieldNames",con=engine,schema=Schema,if_exists="append",index=False) dfNAVFieldOptions.to_sql("NAVFieldOptions",con=engine,schema=Schema,if_exists="append",index=False) <file_sep>/201 - Simple Parse of XML.py import xml.etree.ElementTree as ET with open('NAVTable-36.xml', 'r') as xml_file: tree = ET.parse(xml_file) root = tree.getroot() for child in root.iter('{urn:schemas-microsoft-com:dynamics:NAV:MetaObjects}Field'): #print(child.attrib) # uncomment the next lines to see a few columns print(child.attrib.get('ID'), child.attrib.get('Name'), child.attrib.get('Datatype'), child.attrib.get('OptionString')) <file_sep>/200 - Read NAV and Create Decompressed File.py # Example Using Python 3.x import zlib, sys, struct import xml.etree.ElementTree as ET import numpy as np import pandas as pd import pyodbc # 1 -Create a connection string Driver = "ODBC Driver 17 for SQL Server" Server = "ADAM2019" Database = "NAVReportingTest" ConnectionString = "Driver={" + Driver + "};Server="+Server+";Database="+Database+";Trusted_Connection=yes;" conn = pyodbc.connect(ConnectionString) # 2 - The query we want to use SQLQuery = """ SELECT meta.[Object ID] AS TableNo, obj.Name AS TableName, meta.Metadata FROM NAVDemo.dbo.[Object Metadata] meta JOIN NAVDemo.dbo.Object obj ON meta.[Object Type] = obj.Type AND meta.[Object ID] = obj.ID WHERE obj.Type = 1 AND meta.[Object ID] = 15 ORDER BY obj.ID""" # 3 -Load the SQL to a Python Pandas Dataframe ObjectMetaData = pd.read_sql(sql=SQLQuery,con=conn)#,params=params) # 4 - loop throught the output (Note - in the initial test I have # limited this to just table 15) for Name, TableNo, TableName, MetaData in ObjectMetaData.itertuples(): MetaDataToDecompress = bytearray(MetaData) # we need to skip the first four characters MetaDataToDecompress = MetaDataToDecompress[4:] # now we decompress the data output = zlib.decompress(MetaDataToDecompress,-15) # We can print it to the screen print(output.decode("utf-8")) # we can write it to an xml file OutputFileName = "NAVTable-" + str(TableNo) + ".xml" OutputFile = open(OutputFileName,"w+") OutputFile.write(output.decode("utf-8")) OutputFile.close()<file_sep>/README.md # NAV_FieldOptionNumbers Get NAv Field and Option Numbers into a SQL Table for query use I've written a detailed blog post which goes through this step by step. Please note: The programs (other than the simple SQL to build the table) are written in Python. I am working with Python 3.7. You must make sure that you have access to the following on Python numpy pandas pyodbc sqlalchemy I believe that everything else I reference comes with the standard install. To build the NAVFieldNames and NAVFieldOptions 1) Create the two new tables in your reporting database. The script is 010 - Tables to Store Field and Option Data.sql. 2) Run: 100 - Build NAVFieldNames NAVFieldOptions.py in Python. The other scripts here can be used to better understand how everything works. Please read the blog post for more information. <file_sep>/010 - Tables to Store Field and Option Data.sql CREATE TABLE dbo.NAVFieldNames (TableNo INT NOT NULL, TableName VARCHAR(30) NOT NULL, FieldNo INT NOT NULL, FieldName VARCHAR(30) NOT NULL, CONSTRAINT PK_NAVFieldNames PRIMARY KEY CLUSTERED (TableNO, FieldNo) ) GO CREATE TABLE dbo.NAVFieldOptions (TableNo INT NOT NULL, TableName VARCHAR(30) NOT NULL, FieldNo INT NOT NULL, FieldName VARCHAR(30) NOT NULL, OptionNo TINYINT NOT NULL, OptionName VARCHAR(30) NOT NULL, CONSTRAINT PK_NAVFieldOptions PRIMARY KEY CLUSTERED (TableNo, FieldNo, OptionNo) ) GO <file_sep>/205 - Parse the XML.py import xml.etree.ElementTree as ET import numpy as np import pandas as pd # Creating an empty Dataframe with column names only dfNAVFieldNames = pd.DataFrame(columns=['TableNo','TableName','FieldNo', 'FieldName']) dfNAVFieldOptions = pd.DataFrame(columns=['TableNo','TableName','FieldNo', 'FieldName','OptionNo','OptionName']) tree = ET.parse("NAVTable-15.xml") root = tree.getroot() # this gets me all the field level attributes from the XML. It creates row in our # dataframe. One row for each distinct field name and one row for each option for child in root.iter('{urn:schemas-microsoft-com:dynamics:NAV:MetaObjects}Field'): dfNAVFieldNames = dfNAVFieldNames.append( {'TableNo' : 15, 'TableName' : 'G/L Account', 'FieldNo' : child.attrib.get('ID'), 'FieldName' : child.attrib.get('Name')},ignore_index=True) OptionString = child.attrib.get('OptionString') if (OptionString is not None): # print(OptionString.split(",")) OptionNo = 0 for Option in OptionString.split(","): dfNAVFieldOptions = dfNAVFieldOptions.append( {'TableNo' : 15, 'TableName' : 'G/L Account', 'FieldNo' : child.attrib.get('ID'), 'FieldName' : child.attrib.get('Name'), 'OptionNo' : OptionNo, 'OptionName' : Option},ignore_index=True) OptionNo += 1 # the below just show examples print(dfNAVFieldNames.head()) print(dfNAVFieldOptions.head())
3d8992d1f4856aae971718f26d54fc06915b3a63
[ "Markdown", "TSQL", "Python" ]
7
Markdown
AJacobsonRed3/NAV_FieldOptionNumbers
6144d362b27aa505cd73cdaeff57bdd28be324d2
cfdc174efc2ecbed1d480141bb073bbdbc3314f0
refs/heads/master
<repo_name>ammarwa/MicroProject<file_sep>/MicroProject/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MicroProject { public partial class Form1 : Form { int TableKey = 0; string[] lines; DataTable Memory = new DataTable(); DataTable Registers = new DataTable(); Dictionary<String, String> instructionFunction; Dictionary<String, String> instructionOpcode; int clockCycle; string writeRegister = ""; public Form1() { InitializeComponent(); } } }
ee2f6a01bf971a0774217015cd742a8d1eb8d5fc
[ "C#" ]
1
C#
ammarwa/MicroProject
345e761c20ebf5cb45b722e93b0b4e7e4ac26bee
cb72a6367d6686a0abab041144a0ac4249af29a4
refs/heads/master
<repo_name>Rymurphy12/twitter-analytics-v2<file_sep>/build.sbt name := "twitter-analytics" organization := "com.github.rymurphy12" version := "0.0.1-SNAPSHOT" scalaVersion := "2.12.4" // Also supports 2.11.x val http4sVersion = "0.18.0" // Only necessary for SNAPSHOT releases resolvers ++=Seq(Resolver.sonatypeRepo("snapshots"), Resolver.sonatypeRepo("releases"), Resolver.typesafeIvyRepo("releases") ) libraryDependencies ++= Seq( "org.http4s" %% "http4s-dsl" % http4sVersion, "org.http4s" %% "http4s-blaze-server" % http4sVersion, "org.http4s" %% "http4s-blaze-client" % http4sVersion, "org.http4s" %% "http4s-circe" % http4sVersion, "io.circe" %% "circe-generic" % "0.9.1", "io.circe" %% "circe-literal" % "0.9.1", "com.typesafe" % "config" % "1.3.1", "com.vdurmont" % "emoji-java" % "3.3.0", "com.github.nscala-time" %% "nscala-time" % "2.18.0" ) scalacOptions ++= Seq("-Ypartial-unification") addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full) <file_sep>/src/main/scala/com/github/rymurphy12/analyzer/TwitterMetrics.scala package com.github.rymurphy12.analyzer import org.http4s._ import org.http4s.client.blaze._ import org.http4s.client.oauth1 import cats.effect._ import fs2.{Stream, StreamApp} import fs2.StreamApp.ExitCode import fs2.io.stdout import fs2.text.{lines, utf8Encode} import jawnfs2._ import io.circe.Json import com.typesafe.config.ConfigFactory import org.joda.time.DateTime import com.vdurmont.emoji._ import com.github.nscala_time.time.Imports._ object TWStream extends TWStreamApp[IO]{ } abstract class TWStreamApp[F[_]: Effect] extends StreamApp[F]{ implicit val f = io.circe.jawn.CirceSupportParser.facade def sign(consumerKey: String, consumerSecret: String, accessToken: String, accessSecret: String)(req: Request[F]): F[Request[F]] = { val consumer = oauth1.Consumer(consumerKey, consumerSecret) val token = oauth1.Token(accessToken, accessSecret) oauth1.signRequest(req, consumer, callback = None, verifier = None, token = Some(token)) } def jsonStream(consumerKey: String, consumerSecret: String, accessToken: String, accessSecret: String)(req: Request[F]): Stream[F, Json] = for { client <- Http1Client.stream[F]() sr <- Stream.eval(sign(consumerKey, consumerSecret, accessToken, accessSecret)(req)) res <- client.streaming(sr)(resp => resp.body.chunks.parseJsonStream) } yield res override def stream(args: List[String], requestShutdown: F[Unit], consumerKey: String, consumerSecret: String, accessToken: String, accessSecret: String): Stream[F, ExitCode] = { val req = Request[F](Method.GET, Uri.uri("https://stream.twitter.com/1.1/statuses/sample.json")) val s = jsonStream(consumerKey, consumerSecret, accessToken, accessSecret)(req) s.map(_.spaces2).through(lines).through(utf8Encode).to(stdout) >> Stream.emit(ExitCode.Success) } }
d74a8fb4107978b93e074c99867ab2bfe1a89afd
[ "Scala" ]
2
Scala
Rymurphy12/twitter-analytics-v2
3a44628734c73eb080e88715170d4b0dc4935290
03174b79509f1eb518bb295a94d655529cdba2aa
refs/heads/master
<repo_name>knut0815/OpenCL-path-tracing-tutorial-2-Part-2-Path-tracing-spheres<file_sep>/README.md # OpenCL-path-tracing-tutorial-2-Part-2-Path-tracing-spheres Tutorial on how to use OpenCL for path tracing a simple scene of spheres Details on https://raytracey.blogspot.com/2016/11/opencl-path-tracing-tutorial-2-path.html This code produces the following images: ![Image description](https://github.com/straaljager/OpenCL-path-tracing-tutorial-2-Part-2-Path-tracing-spheres/blob/master/opencl_pathracer_spheres.png) ![Image description](https://github.com/straaljager/OpenCL-path-tracing-tutorial-2-Part-2-Path-tracing-spheres/blob/master/opencl_raytracer_2000samps.png)
69baf016e2b82b733d178a1f6c235f7027effb31
[ "Markdown" ]
1
Markdown
knut0815/OpenCL-path-tracing-tutorial-2-Part-2-Path-tracing-spheres
a09948384591d202dfe5c3c81db7158cc8677471
d0719a20476cc694499ae6aef77b4a537c2382ce
refs/heads/master
<repo_name>anandology/vizag-hackathon<file_sep>/README.md # vizag-hackathon List of projects done at Citizen Centric Services Hacathon - Visakhapatnam ## Projects ### illuminaTeam <https://github.com/praveensvsrk/CCSHackathon_illuminaTeam> ### Get Me a Doctor <https://github.com/ramsankarpeesa/get-me-a-doctor> ### renewme <https://github.com/rasagnavarma/renewme> ### FAT BOY FAMILY <https://github.com/RAVURISREESAIHARIKRISHNA/Hackathon2017> ### e-democracy <https://github.com/anaganisk/e-democracy> ### Helping Hands - Blood Drive <https://github.com/Harikamadeti/blooddrive> ### rythuandhra <https://github.com/sandeepvenkat7/rythuandhra> ### tech toots - c2g <https://github.com/manikanta44/c2g> ### Agro Services <https://github.com/sarvanis/ccsh_agroservices>
12c9735237e5c4b07e79ed8a17a28ea7a773479b
[ "Markdown" ]
1
Markdown
anandology/vizag-hackathon
af6a993c724257cc69336e85e3c3bcba22d9f90d
e62716dfa922e0fbc4294e9e6fc00ab786b19a6c
refs/heads/master
<file_sep>package com.example.login_application; import java.io.IOException; import javax.servlet.RequestDispatcher; 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 com.example.login_application.dto.User; import com.example.login_application.service.LoginService; /** * Servlet implementation class LoginServlet */ @WebServlet(description = "A simple login servlet.", urlPatterns = { "/login" }) public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); LoginService loginService = new LoginService(); boolean result = loginService.authenticate(username, password); if(result) { User user = loginService.getUser(username); // request.getSession().setAttribute("user", user); // response.sendRedirect("success.jsp"); /* * Another way to the above stuff * We are gonna use Request Dispatcher Object * The same request and response as of the current page * is forwarded to the redirecting page as well */ request.setAttribute("user", user); RequestDispatcher requestDispatcher = request.getRequestDispatcher("success.jsp"); requestDispatcher.forward(request, response); return; }else { response.sendRedirect("login.jsp"); return; } } } <file_sep># JSP and Servlets ### References [Java Brains - JSPs and Servlets](https://www.youtube.com/playlist?list=PLE0F6C1917A427E96) ### Setting Up [Click Here](https://youtu.be/b42CJ0r-1to) A problem you might face in the newer versions of eclipse - the servers option will not show up in the Show View menu. You will need to download the Enterprise Edition version of eclipse for that. ### Some Full Forms * MVC - Model View Controller * DTO - Data Transfer Objects * JSTL - Java Standard Tag Library<file_sep># Simple Servlet Project ### Important Links * [Understanding the servlet](https://youtu.be/YxuCG0f14hM) * [init, service and ServletConfig](https://youtu.be/ji_N8pspwn0) ### How to write a servlet 1. The servlet class need to extend the `HttpServlet` class. 2. We need to create the WebServlet annotation with the required URL pattern. ### Three important objects 1. Requests 2. Sessions 3. Contexts ### MVC Model View Controller ### MVC Ingredients 1. Controller 2. Business Service 3. Model 4. View<file_sep><%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import="com.example.login_application.dto.User" %> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Success</title> </head> <body> <h1>Login Successful!</h1> <% // User user = (User) session.getAttribute("user"); // User user = (User) request.getAttribute("user"); %> <jsp:useBean id="user" class="com.example.login_application.dto.User" scope="request"> </jsp:useBean> Hello <%=user.getName() %> Hello <jsp:getProperty property="name" name="user"/> </body> </html><file_sep># Login Application ### Reference [Java Brains](https://youtu.be/QOUIVsBN82Q)
06a5282ad53676246715cca6848170d090115b59
[ "Java", "Markdown", "Java Server Pages" ]
5
Java
thevipulsharma/jsp-servlets
f35be7dc3cc5e726f8e2de8a051ead2847e0b350
e6199dc1c7011f685ff6998218abadef37334bcb
refs/heads/master
<repo_name>jasonjlam/60_wrapBinarySearch<file_sep>/README.md # implement List.indexOf `while`-style and recursive implementations at the top of OrderedList_inArraySlots.java [Java API on the `indexOf` method](https://docs.oracle.com/javase/10/docs/api/java/util/List.html#indexOf(java.lang.Object)) based on [solutionsHolmes/5D_genericTypes/OrderedList_inArraySlots_v2/](https://github.com/stuyvesant-cs/solutionsHolmes/tree/master/5D_genericTypes/OrderedList_inArraySlots_v2) as of 2019-04-10 04:48 Logarithms The term y = log(2)(x) refers to the idea that 2 raised to y is equal to x. The graph begins as a concave down curve that slowly decreases in slope to 0. The problem is finding the index in a sorted list of n length. When I am asked to find the index of an object in a sorted list of n length, the recursive abstraction can find the index of an object in a sorted list of n/2 length. Boolean: When the lowest index is greater than the highest index Base case: When the lowest index is equal to the highest index Recursive case: There are two recursive cases; If the index is lower then search from the lowest index to the current index - 1 If the index is higher then search from the current index + 1 to the highest index There is no concatenation involved. There are also no leftovers. All that matters is the check for if the current index is equal to the item being searched for.
726d0baf6893d5c1bbf5a5d8d9c20c70aae44b26
[ "Markdown" ]
1
Markdown
jasonjlam/60_wrapBinarySearch
939ffb92cda5ff4ce506ca3262ca3e8bafe4dcf9
e9f0e58cfa2241f3ca24ad603fd903def4aecf1f
refs/heads/master
<repo_name>DivyaPuttur/unix-workbench-project<file_sep>/README.md # unix-workbench-project Project Title is Guessing Game The date and time at which make run: Thurs Aug 13 12:49:53 GMT 2020 The number of linesof code contained in guessinggame.sh: 23
1d2aeeab6944667d028d65e8d7a2c932909bb42e
[ "Markdown" ]
1
Markdown
DivyaPuttur/unix-workbench-project
700cd75afed3195f4226e19985a448e3bc9f6213
9eb76b386c6e41535b1ecbfccce717169cc0c490
refs/heads/master
<file_sep># Battle-Ship-game Project is developed by java 8 version
9724ea9838c1e1da16d4c77f67b44aa175f61715
[ "Markdown" ]
1
Markdown
manoharswamy9/Battle-Ship-game
e3729e852908fb05acee3b203020c96137529baa
e0112b75482be73dd6d224491562cae73468f859
refs/heads/master
<repo_name>Mechachleopteryx/Beef<file_sep>/README.md # Beef Lathe-based myco-bacterial meats.
29547b8ff7ff3854327c54e745aa4ce3609ff7e4
[ "Markdown" ]
1
Markdown
Mechachleopteryx/Beef
e1b58f7a671950ce170c11356ff931b711a1febe
2a3ace31635f98f3a5d0fc649929fdea0944bebd
refs/heads/master
<file_sep># Geo URI Handler Open `geo:` URIs in your preferred maps website Supported destination map sites: * OpenStreetMap * Google Maps (planned) * Bing Maps (planned) Supported URI examples: * `geo:latitude,longitude` * `geo:latitude,longitude?z=zoom` * `geo:latitude,longitude;z=zoom` * `geo:latitude,longitude?q=search+query` * Combinations of `z` and `q` are allowed with either `?` and `&` (Android/deprecated) or `;` (new) delimiters Ignored parameters: * `crs` (always treated as wgs84) * `u` (always ignored) * `geo:latitude,longitude,altitude` (altitude is ignored) Supported browsers: * Firefox 59+ * Android already natively [partially supports `geo:` URIs](https://developer.android.com/guide/appendix/g-app-intents.html) Licenses: * Code: MIT (see LICENSE file) * Icon: [Globe](https://thenounproject.com/search/?q=globe&i=1368249) by [Randomhero](https://thenounproject.com/rahedesigns) from the [Noun Project](https://thenounproject.com/) 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.
74c4b9ed7b647770cc64786d8035c9cd4104ceff
[ "Markdown" ]
1
Markdown
chriso1977/geo-handler
05566fcda2e33b2cfc50d69a0f3300a798261945
506a4257b30dc83b7467610b39b48862466d8476
refs/heads/master
<file_sep>Muniti - Cryptocurrency of Malta RPC Port: 3519
e09d39023748872ec8a047512fd5085b86cd0780
[ "Markdown" ]
1
Markdown
muniti/muniti
8c088a4f907f5daf269e8ba0a9280e85028becb7
51fb2680b0300018189276c0549ba25e287c8533
refs/heads/master
<file_sep># mapCoord.R #' Populate a GeneData list with functions for mapping coordinates from chromosome to gene #' #' \code{mapCoord.R} populates map elements of a GeneData list with a #' corresponding function closure that maps chromosomal coordinates to #' gene coordinates. #' The populated GeneData list is saved to an .rds file. #' #' @section Mapping function closure: #' The mapping function that \code{mapCoord.R} creates and populates a GeneData #' list which takes a chromosomal coordinate as input and returns the #' corresponding gene coordinate if the chromosomal coordinate occurs in an #' exon of the gene. #' If the input is in an intron, the function returns 0. #' If the input is out-of-bounds of the gene or invalid, the function #' returns \code{NULL}. #' #' @param geneData the GeneData formatted resource list with at least strand, #' start, end, exonStart, exonEnd elements populated #' @param outFile File where the populated GeneData list is stored #' (default: "geneData.rds") #' @param dropExonBoundaries logical. Populated GeneData list has exonStart #' and exonEnd elements dropped iff \code{TRUE}. (default: \code{TRUE}) #' @param silent logical. Console is suppressed iff silent is \code{TRUE}. #' (default: \code{FALSE}) #' @param writeLog logical. Log file is written iff \code{TRUE}. #' (default: \code{TRUE}) #' #' @export mapCoord <- function(geneData, outFile = "geneData.rds", dropExonBoundaries = TRUE, silent = FALSE, writeLog = TRUE){ #========================== Parameter validation =========================== cR <- character() cR <- c(cR, .checkArgs(geneData, like = list())) cR <- c(cR, .checkArgs(outFile, like = character())) cR <- c(cR, .checkArgs(dropExonBoundaries, like = logical(1), checkSize = TRUE)) cR <- c(cR, .checkArgs(silent, like = logical(1), checkSize = TRUE)) cR <- c(cR, .checkArgs(writeLog, like = logical(1), checkSize = TRUE)) if(length(cR) > 0) { stop(cR) } # Parameter validation for geneData lapply(geneData, function(x) { cRGeneData <- character() cRGeneData <- c(cRGeneData, .checkArgs(x$start, like = integer(1), checkSize = TRUE)) cRGeneData <- c(cRGeneData, .checkArgs(x$end, like = integer(1), checkSize = TRUE)) cRGeneData <- c(cRGeneData, .checkArgs(x$strand, like = "+", checkSize = TRUE)) cRGeneData <- c(cRGeneData, .checkArgs(x$exonStart, like = integer())) cRGeneData <- c(cRGeneData, .checkArgs(x$exonEnd, like = integer())) if(length(cRGeneData) > 0) { stop(cRGeneData) } }) #=============== Mapping function for a single gene model ================== makeMap <- function(ucscMod) { # Check if the number of exons listed in start and end match if(length(ucscMod$exonStart) != length(ucscMod$exonEnd)) { stop("Corrupt gene model") } # Prepare the environment (exon matrix, start, end, strand) exons <- cbind(ucscMod$exonStart, ucscMod$exonEnd) start <- ucscMod$start end <- ucscMod$end reverse <- FALSE if (ucscMod$strand == "-") { reverse <- TRUE } # Check if the exons and start stop points are validly ordered if(is.unsorted(c(start, as.vector(t(exons)), end))) { stop("Corrupt gene model") } # Generate cumulative sums exons <- cbind(exons, cumsum(exons[,2] - exons[,1] + 1)) # Return the mapping function return( function(x) { # Check if input is numeric if (length(.checkArgs(x, like = integer(1), checkSize = TRUE)) > 0) { stop("Non-numeric input") } # Check if out-of-range if (x < start | x > end) { return(NULL) } # Determine the exon our coordinate is located in iEx <- which(x >= exons[ , 1] & x <= exons[ , 2]) # Check if intron if(length(iEx) != 1){ return(0) } # Exon bases to the left (toward 5', + strand gene start) of x total <- exons[iEx, 3] - (exons[iEx, 2] - x) if (reverse) { #Exon bases to the right (toward 3', - strand gene start) of x total <- exons[nrow(exons), 3] - total + 1 } return(total) } ) } #====================== "Function manufacturing" =========================== geneData <- lapply(geneData, function(x) { x$map = makeMap(x) return(x) }) if (dropExonBoundaries) { geneData <- lapply(geneData, function(x) { x$exonStart <- NULL x$exonEnd <- NULL return(x) }) } saveRDS(geneData, file = outFile) #============================== Write log ================================== if(writeLog) { myTitle <- "mapCoord" # Compile function call record myCall <- character() myCall[1] <- "mapCoord(" myCall[2] <- "geneData, " myCall[3] <- sprintf("outFile = \"%s\", ", outFile) myCall[7] <- sprintf("dropExonBoundaries = %s, ", as.character(dropExonBoundaries)) myCall[8] <- sprintf("silent = %s, ", as.character(silent)) myCall[9] <- sprintf("writeLog = %s)", as.character(writeLog)) myCall <- paste0(myCall, collapse = "") # indicate input object name(s) myInput <- "geneData" # Record progress information myNotes <- sprintf("Generated %s mapping function closures", length(geneData)) # indicate output object name(s) myOutput <- "geneData" # send info to log file logEvent(eventTitle = myTitle, eventCall = myCall, input = myInput, notes = myNotes, output = myOutput) } } # [END] <file_sep># testMapCoord.R # # context("GeneData mapping function generator") # ==== BEGIN SETUP AND PREPARE ================================================= # Randomly generate a valid geneData structure of valid gene models generateGeneData <- function() { geneData <- list() geneSymbols <- list("abcD", "efgH", "ijkL", "mnoP", "qrsT", "uvwX") # Convert a sorted even-sized list with a random number of random numbers # within an interval into a "gene model" for (i in 1:length(geneSymbols)) { lG <- 2 * sample(2:10, 1) preMod <- sample(1:10000, size=lG) preMod <- sort(preMod) plusmin <- c('+', '-') geneMod <- list(start=preMod[1], end=preMod[lG], strand=plusmin[sample(1:2, 1)]) geneMod$exonStart <- c(preMod[2:(lG-1)])[c(TRUE, FALSE)] geneMod$exonEnd <- c(preMod[3:(lG)])[c(TRUE, FALSE)] geneData[[as.character(geneSymbols[i])]] <- geneMod } return(geneData) } # Build a new gene model based on running the mapFunctions on every coordinate # If the mapping function was correct, the same gene model should be rebuilt rebuildGeneModel <- function(mapFunction) { expGeneMod <- list() # Loop through all bases in the gene previous <- NULL counter <- 1 for (i in 0:10001) { current <- mapFunction(i) if (is.null(previous) & !is.null(current)) { expGeneMod$start <- i } else if (!is.null(previous) & is.null(current)) { expGeneMod$end <- i - 1 } else if (!is.null(previous) & !is.null(current)) { if (previous == 0 & current != 0) { expGeneMod$exonStart[counter] <- i } else if (previous != 0 & current == 0) { expGeneMod$exonEnd[counter] <- i - 1 counter <- counter + 1 } } previous <- current } return(expGeneMod) } # ==== END SETUP AND PREPARE =================================================== test_that("parameter errors are correctly handled by mapCoord", { # Try setting each of the parameters to be NULL # Try setting "geneData" to a list with zero length lists expect_error(mapCoord()) expect_error(mapCoord(NULL)) expect_error(mapCoord(list(list(), list(), list()))) gd <- generateGeneData() expect_error(mapCoord(gd, outFile = NULL)) expect_error(mapCoord(gd, outFile = 42)) expect_error(mapCoord(gd, dropExonBoundaries = NULL)) expect_error(mapCoord(gd, dropExonBoundaries = "abcD")) expect_error(mapCoord(gd, silent = NULL)) expect_error(mapCoord(gd, silent = list())) expect_error(mapCoord(gd, writeLog = NULL)) expect_error(mapCoord(gd, writeLog = "42")) }) test_that("a corrupt input does not lead to corrupted output for mapCoord", { # Generate geneData with generateGeneData and corrupt it. # Try corrupted "geneData": # Exon starts and ends do not match # Gene start and end do not match # Types do not match wrongType <- generateGeneData() wrongType$abcD$exonEnd <- "Hello!" expect_error(mapCoord(wrongType)) mismatchedExonsSingle <- generateGeneData() mismatchedExonsSingle$efgH$exonStart <- 1L expect_error(mapCoord(mismatchedExonsSingle)) mismatchedExonsMulti <- generateGeneData() mismatchedExonsMulti$efgH$exonEnd <- 1:10 expect_error(mapCoord(mismatchedExonsmismatchedExonsMulti)) mismatchedStart <- generateGeneData() mismatchedStart$start <- 10001L expect_error(mapCoord(mismatchedStart)) mismatchedEnd <- generateGeneData() mismatchedEnd$end <- 1L expect_error(mapCoord(mismatchedEnd)) }) test_that("parameter errors are correctly handled by the map functions produced by mapCoord", { # Generate geneData with generateGeneData and apply mapCoord to it # Try setting the map function parameters to NULL, non-ints gd <- generateGeneData() mapCoord(gd, writeLog = FALSE) gd <- readRDS("geneData.rds") for (name in names(gd)) { fx <- gd[[name]]$map expect_error(fx(NULL)) expect_error(fx("42")) expect_error(fx(list())) } }) test_that("the functions produced by mapCoord accurately map all coordinates", { # Generate geneData with generateGeneData # Check that mapCoord returns functions where the outputs of all the # coordinates can rebuild the correct gene model gd <- generateGeneData() mapCoord(gd, writeLog = FALSE) mappedGD <- readRDS("geneData.rds") for (name in names(gd)) { model <- gd[[name]] reModel <- rebuildGeneModel(mappedGD[[name]]$map) expect_equal(model$start, reModel$start) expect_equal(model$end, reModel$end) expect_equal(model$exonStart, as.vector(reModel$exonStart)) expect_equal(model$exonEnd, as.vector(reModel$exonEnd)) } }) test_that("mapCoord drops exon boundaries iff dropExonBoundaries is TRUE", { # Generate geneData with generateGeneData # Test that dropExonBoundaries drops boundaries when TRUE, and default # Test that dropExonBoundaries does not drop boundaries when FALSE gd <- generateGeneData() mapCoord(gd, writeLog = FALSE) defaultDrop <- readRDS("geneData.rds") expect_equal(defaultDrop$abcD$exonStart, NULL) expect_equal(defaultDrop$abcD$exonEnd, NULL) mapCoord(gd, dropExonBoundaries = TRUE, writeLog = FALSE) trueDrop <- readRDS("geneData.rds") expect_equal(trueDrop$efgH$exonStart, NULL) expect_equal(trueDrop$efgH$exonEnd, NULL) mapCoord(gd, dropExonBoundaries = FALSE, writeLog = FALSE) falseDrop <- readRDS("geneData.rds") expect_false(is.null(falseDrop$uvwX$exonStart)) expect_false(is.null(falseDrop$uvwX$exonEnd)) }) # ==== BEGIN TEARDOWN AND RESTORE ============================================== if (file.exists("geneData.rds")) { file.remove("geneData.rds") } # ==== END TEARDOWN AND RESTORE =============================================== # [END]
928f6663df27bf7b6b23c07b91963fa94695e1f1
[ "R" ]
2
R
Sabrina-Ge/rete
e2c897bc58c555ce1b4ba92882671cc3623e57da
7880e9015e51ee465c1b46a0654ce389d7e9b6cc
refs/heads/master
<repo_name>featurist/browser-pdf-support<file_sep>/readme.md # Can I has PDF? A tiny NPM module that determines if the browser can render PDFs, either with built-in support like Safari, Chrome and Firefox, or with Adobe Acrobat in Internet Explorer. The module is expected to be used with [the amazing browserify](https://github.com/substack/node-browserify). var pdfSupport = require('browser-pdf-support'); if (pdfSupport()) { console.log('we has PDF!'); } else { console.log('oh dear, you'll need to download acrobat or a real browser...'); } ## We're Hiring! Featurist provides full stack, feature driven development teams. Want to join us? Check out [our career opportunities](https://www.featurist.co.uk/careers/). <file_sep>/index.js module.exports = function() { function hasAcrobatInstalled() { function getActiveXObject(name) { try { return new ActiveXObject(name); } catch(e) {} } return getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl') } function isIos() { return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream } return navigator.mimeTypes['application/pdf'] || hasAcrobatInstalled() || isIos() };
cdf254927f91bc976342818cb0afe1314948bff1
[ "Markdown", "JavaScript" ]
2
Markdown
featurist/browser-pdf-support
da43b33d0fda26815b23c655b76fff4669f7aa02
30199f5f603c74c2d062e57e68cdf0e99edeeb59
refs/heads/main
<file_sep># Where-There-is-a-will-There-s-a-way It tells people not to give up, but continue till they achieve their dreams and goals. Furthermore, this proverb highlights the importance of will power, hard work and determination to reach success.
7788401993021fe589abcc6f6e13d07246decd22
[ "Markdown" ]
1
Markdown
Aishu808/Where-There-is-a-will-There-s-a-way
3e2eff667f057854d13c9f302fb5a559652a4afd
8efcc621908e02f61ba2510353ef66c94b885e9e
refs/heads/master
<repo_name>assertlab/assertlab.github.io<file_sep>/_posts/2014-04-17-assert-at-wp2p-sbrc2014.md --- layout: post title: "ASSERT at WP2P+ (SBRC’2014)" categories: Artigos tag: conferencia --- ASSERT will be present at the [Workshop on P2P Networks, Dynamics, and Social Content-Oriented (WP2P+)](http://www.sbrc2014.ufsc.br/?pg=workshops&id=5){:target="_blank"} in conjunction with the [Brazilian Symposium on Computer Networks and Distributed Systems (SBRC’2014)](http://www.sbrc2014.ufsc.br/?pg=apresentacao){:target="_blank"} to be held in Florianópolis (Santa Catarina) 5-9 May 2014. This activity is part of the project “[Social Machines and Research Team - SMaRT](http://www.ines.org.br/?p=502){:target="_blank"}” and is one of the results of the research being done by **ASSERT Lab**. The paper is entitled “**_Cloud Disk Drive - Uma abordagem para a criação de discos virtuais de baixo custo utilizando redes p2p_**” by <NAME>, <NAME>, <NAME> and <NAME>. A brief summary of the paper is following: > Este trabalho apresenta uma proposta para a disponibilização de unidades virtuais para armazenamento de dados em nuvem, através da associação de tecnologias e conceitos, tais como: ISCSI e redes P2P. Desta forma, os arquivos podem ser distribuídos em nós conectados a rede,permitindo a oferta de armazenamento em disco de maneira compartilhada e a redução de custos pelo ofertante do serviço.<file_sep>/_posts/2014-09-23-cloudam-2014-notification.md --- layout: post title: "CloudAM 2014 notification" categories: Artigos tag: conferencia --- É com prazer que informo que o artigo “**A Service-Oriented Architecture and a DSL for Billing Resources in IaaS Cloud Platforms**” de autoria de <NAME>, <NAME>, <NAME>, <NAME>, <NAME> e <NAME> foi aceito para publicação no [International Workshop on Clouds and (eScience) Applications Management (CloudAM)](http://cloudam2014.lncc.br/). O evento ocorrerá em Londres nos dias 8 a 11 de Dezembro de 2014. Parabéns aos autores!<file_sep>/_posts/2011-08-25-six-steps-to-develop-a-good-survey.md --- layout: post title: "Six Steps to Develop a Good Survey" categories: Educacao tag: pesquisa --- Often, we researchers and scientists have to understand, evaluate, and learn different methods, processes, techniques, technologies, and so on. We [discussed previously the importance of empirical studies in the area](http://worldofreuse.blogspot.com/2008/07/empirical-studies-on-software-and.html). On the other hand, another important and probable the most used research method are Surveys. If you take look, we are often asked to participate in surveys in our life, in different roles such as: electors, consumers, service user, and so on. Doing research, many times we have to design a survey to understand and characterize some particular phenomena. However, in some situations, we forget that there is a bunch of important material about it published in other sciences and, specially, in the software engineering area. I am designing a survey to characterize the state of reuse measurement based on expert opinion and the series of paper published by [<NAME>](http://shari.pfleeger.com/) and her colleagues were and are being extremely valuable. Thus, if you need to understand, design, construct, and evaluate a survey, I strongly recommending these papers [[P1](http://portal.acm.org/citation.cfm?doid=505532.505535), [P2](http://portal.acm.org/citation.cfm?doid=566493.566495), [P3](http://portal.acm.org/citation.cfm?doid=511152.511155), [P4](http://portal.acm.org/citation.cfm?id=638574.638580&coll=GUIDE&dl=GUIDE), [P5](http://portal.acm.org/citation.cfm?id=571686), [P6](http://portal.acm.org/citation.cfm?id=638758)]. These papers gathered experience in the field during the last years and are extremely important for someone interested in this activity. Regarding to reuse are, I recommend for example two papers in this direction [[P1](http://portal.acm.org/citation.cfm?doid=505532.505535), [P2](http://portal.acm.org/citation.cfm?doid=566493.566495)]. The [second one](http://worldofreuse.blogspot.com/2007/09/rise-publishes-survey-about-software.html) presents the state of software reuse in Brazil conducted by RiSE. *Artigo originalmente publicado por [<NAME>](http://viniciusgarcia.me/education/a-biblioteca-do-desenvolvedor-de-software-dos-dias-de-hoje/)*<file_sep>/_posts/2014-02-05-uma-arquitetura-para-sistemas-de-file-cloud.md --- layout: post title: "Uma Arquitetura para Sistemas de File Cloud Storage" categories: Pesquisa tag: mestrado --- Desde o advento da Internet, o volume de dados armazenado por usuários tem crescido de forma exponencial. De acordo com um estudo realizado pela International Data Corporation (IDC) [Gantz 2011], o volume global de dados em 2011 era de 1.8 zetabytes e dobra a cada dois anos. Outro fator importante é a popularização dos dispositivos portáteis, em que o usuário deseja armazenar e acessar seus dados de forma umbíqua. Nessa nova era, chamada de Era do Zettabyte, surgem alguns desafios importantes para a área de Tecnologia da Informação. Tais como sincronizar dispositivos diferentes, manter dados com garantia, buscar dados dentro desse volume, entre outros. Os chamados sistemas de File Cloud Storage vêm a resolver esse tipo de problema. São sistemas baseado no modelo de serviço Storage as a Service utilizados para armazenar arquivos. Entretanto, construir um sistema de File Cloud Storage torna-se um grande desafio tecnológico, pois alguns requisitos funcionais não são fáceis de atender. Para construir a arquitetura, temos que definir um conjunto de requisitos funcionais e não funcionais. Esses requisitos foram levantados observando os principais sistemas de file cloud storage do mercado, assim como foram observadas algumas características de bancos de dados relacionais e não relacionais. A Tabela 1 mostra os requisitos funcionais para aplicação. Basicamente, são requisitos relacionados com a operação de arquivos em um sistema de arquivo, com exceção dos requisitos RF7 e RF8, que estão relacionados com a administração do sistema. ![]({{ BASE_PATH }}/images/2014-02-05-uma-arquitetura-para-sistemas-de-file-cloud/tabela1.png) Na Tabela 2 é mostrada a relação dos requisitos não funcionais. A maioria deles é comum a requisitos de bancos de dados pois, de certa forma, os mesmos também são storage engines. ![]({{ BASE_PATH }}/images/2014-02-05-uma-arquitetura-para-sistemas-de-file-cloud/tabela2.png) Com a definição dos dados, podemos listar algumas decisões arquiteturais. A Tabela 3 mostra as principais decisões arquiteturas que foram tomadas durante o desenvolvimento da arquitetura. ![]({{ BASE_PATH }}/images/2014-02-05-uma-arquitetura-para-sistemas-de-file-cloud/tabela3.png) Na arquitetura, podemos agrupar os serviços em três camadas: Serviços básicos, serviços importantes e serviços desejáveis. Através dos serviços básicos, podemos compor uma storage engine que armazena e recupera dados no formato chave-valor. Garantindo a durabilidade, disponibilidade, integridade e consistência dos dados. Com a adição dos serviços importantes, podemos compor um File Cloud Storage propriamente dito, realizando operações sobre arquivos. Por fim, adicionando os serviços desejáveis, podemos adicionar algumas features adicionais ao sistema de cloud storage. A Figura 1 mostra a composição dos serviços em camadas. ![]({{ BASE_PATH }}/images/2014-02-05-uma-arquitetura-para-sistemas-de-file-cloud/figura1.png) A Figura 2 mostra a visão geral do sistema. Temos uma DHT formada por vários nós de armazenamento que estão organizados formando um anel, em uma estrutura semelhante ao DynamoDB (DeCandia, 2007) com o serviço de armazenamento de dados e de metadados provendo uma interface para serviços. No nível do Cluster de serviços são implementados os serviços básicos, utilizando o Basic Storage tanto como armazenamento de dados como também de metadados. O serviço de Gerenciamento de usuários armazena todos os dados sobre os usuários e seu sistema de arquivo virtual. O serviço de autenticação permite que os usuários se identifiquem para o sistema, garantindo assim um acesso seguro. O serviço de gerenciamento de arquivos é o disco virtual do usuário propriamente dito, onde é possível fazer operações semelhantes a um sistema de arquivos em disco. Para facilitar o controle de operações como replicação, armazenamento e recuperação, os arquivos são repartidos em pedaços menores denominados chunks. O serviço de Chunk é responsável pelo armazenamento e recuperação dos chunks que compõem cada arquivo. O serviço de segurança utiliza um sistema de chave pública e privada para garantir a confidencialidade e segurança dos dados, assim como permitir também o compartilhamento entre usuários. Para garantir que a arquitetura de fato, resolva o problema proposto, será necessário desenvolver uma avaliação arquitetural, em que pessoas com experiência comprovada na área possam avaliar e propor melhorias na arquitetura do sistema. ![]({{ BASE_PATH }}/images/2014-02-05-uma-arquitetura-para-sistemas-de-file-cloud/figura2.png) Referências * <NAME>. (2011). The 2011 digital universe study: Extracting value from chaos. * <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Dynamo: amazon’s highly available keyvalue store. Proceedings of twenty-first ACM SIGOPS symposium on Operating systems principles, 205-220, 2007 Texto escrito por <NAME> (tjs at cin.ufpe.br)<file_sep>/_posts/2013-06-10-assert-at-11th-international-conference-on.md --- layout: post title: "ASSERT at 11th International Conference on Privacy, Security and Trust (PST'2013)" categories: Artigos tag: conferencia --- The paper “**How People Care about Their Personal Data Released on Social Media**“ authored by <NAME>, <NAME> <NAME> and <NAME> has been accepted for publication at [11th International Conference on Privacy, Security and Trust](http://unescoprivacychair.urv.cat/pst2013/). The conference is being held in Tarragona, Catalonia, July 10-12, 2013. A brief overview of the paper is given next. _Content sharing services become immensely&nbsp;popular on the Web. More than 1 billion people use this kind of&nbsp;services to communicate with friends and exchange all sorts of&nbsp;information. In this new context, privacy guarantees are essential:&nbsp;guarantees about the potential release of data to unintended&nbsp;recipients and the use of user data by the service provider.&nbsp;Although the general public is concerned about privacy questions&nbsp;related to unintended audiences, data usage by service providers&nbsp;is still misunderstood. In order to further explore this level of&nbsp;misunderstanding, this work presents the results of a survey&nbsp;conducted among 900 people with the aim of discovering how&nbsp;people care about the use of their personal data by service&nbsp;providers in terms of social media. From the results, we found&nbsp;that: (i) in general people do not read license terms and do not&nbsp;know very much about service policies, and when presented with&nbsp;these policies people do not agree with them; (ii) a good number&nbsp;of people would support alternative models such as paying for&nbsp;privacy or selling their personal data; and (iii) there are some&nbsp;differences between generations in relation to how they care&nbsp;about their data._<file_sep>/_posts/2013-07-22-open-data-smart-cities-campus-party-recife.md --- layout: post title: "Open Data & Smart Cities @ Campus Party Recife 2013" categories: Pesquisa tag: evento --- Nesta última semana, especificamente no dia 19/07, ocorreu o Fórum Open Data &amp; Smart Cities na Campus Party Recife e contou com a participação dos professores <NAME> e <NAME>, membros do grupo ASSERT. O prof. Kiev foi o mediador do fórum enquanto o professor Vinicius estava responsável por tratar dos aspectos tecnológicos viabilizadores, ou não, das soluções e desafios para tratar do tema do fórum. Maiores informações: Fórum "Open Data &amp; Smart Cities" Descrição: Dados abertos, ou "open data", significam que certos dados devem estar publicamente disponíveis para uso comum, sem restrições ou mecanismos de controle. Com a lei de acesso à informação, a disponibilização de dados se tornou obrigatória no Brasil. Entretanto, essa novidade traz uma séria de perguntas importantes: que dados realmente interessam aos cidadãos? Como disponibilizá-los e armazená-los? O que poderíamos fazer com eles e, principalmente, como eles podem tornar a cidade mais inteligente? Palestrantes: <NAME>: Administradora de empresas, Pós-graduada em Comércio e Marketing Internacional, Mestre e Doutoranda em Internacionalização de Empresas. Experiência profissional no Brasil, Europa e EUA. Professora universitária. Consultora e gestora regional do Fundo Criatec no Estado do Ceará (fundo de investimento de Capital Semente, iniciativa do BNDES com co-investimento do BNB, para fomentar a geração de “startups” de base tecnológica no Brasil). <NAME>: Professor de Engenharia de Software do Centro de Informática (UFPE), evangelizador de reúso de software, entusiasta da computação em nuvem, empreendedor por formação, inovador por DNA e semeador (provocador?) de conhecimento por paixão. <NAME>: Professor do curso de administração do CCSA-UFPE e editor do blog Acerto de Contas <NAME> (mediador): Atuou alguns anos no mercado de Tecnologia da Informação brasileiro, posteriormente ingressando na carreira acadêmica. Obteve o doutorado em Ciência da Computação pela Université de Grenoble, França (2011), e atualmente é professor adjunto do Centro de Informática da Universidade Federal de Pernambuco (CIn-UFPE). <iframe width="560" height="315" src="https://www.youtube.com/embed/_ZvmaAv90pA" frameborder="0" allowfullscreen></iframe><file_sep>/_posts/2018-06-26-o-que-eh-arquitetura-serverless.md --- layout: post title: "O que é arquitetura Serverless (sem servidor)?" categories: Desenvolvimento tag: - Serverless - Engenharia de Software - Desenvolvimento - boas práticas - Function as a Service - Function - Lambda --- Sem servidor ou *Serverless*, a mais nova _buzzword_ do momento (tá, nem tão nova assim dependendo de quão *early adopter* você é) vem ganhando muita atenção dos profissionais e estudantes no mundo (indústria e academia) de Tecnologia da Informação. Em parte devido à forma como os fornecedores/provedores de nuvem, como a [AWS](https://aws.amazon.com/pt/serverless/) e [Microsoft Azure](https://azure.microsoft.com/en-us/services/functions/), majoritariamente, fizeram o _hype_ da arquitetura, de conferências a _meetups_, a posts de blogs e artigos em quase todos os lugares. Além disso, novos projetos pipocam o tempo todo (nota: vale à pena conferir o [Fn](https://github.com/fnproject/fn)). Mas serverless não é apenas sobre o _hype_, ele promete também a possibilidade de implementações de negócios do "jeito ideal" e que, em um primeiro momento, soa bastante agradável para os ouvidos e, provavelmente, lança uma luz sobre os custos e o orçamento também. O lema no universo Serverless é > _“Focus on your **application**, not the **infrastructure**”_ Temos que reconhecer, é um lema reconfortante, principalmente sabendo que muitas das nossas horas do dia são dedicadas a implementar, manter, depurar e monitorar a nossa infraestrutura. Com toda essa carga na infraestrutura fora do nosso caminho, de fato poderíamos nos concentrar nos tão sonhados **objetivos de negócios** (ou _business drivers_) que nossas aplicações devem atender. Neste contexto, muitos esforços poderiam ser direcionados para onde os resultados são realmente mais importantes, e valiosos. Claro, soa como mais uma [bala de prata](http://www.cs.nott.ac.uk/~pszcah/G51ISS/Documents/NoSilverBullet.html), mas se você pensar bem, é asism que as coisas deveriam ser desde o princípio né? Pelo menos para aqueles que não podem gastar tanto esforço (tempo e dinheiro) presos nas ais diversas complexidades de infraestrutura (principalmente nos dias de hoje, com [as mais modernas complexidades](https://cloudplatform.googleblog.com/2018/06/Time-to-Hello-World-VMs-vs-containers-vs-PaaS-vs-FaaS.html)). ## E então, o que é Serverless? Serverless é um modelo de execução de computação em nuvem no qual o provedor de nuvem gerencia **dinamicamente** a **alocação** e o **provisionamento** de servidores para atender a uma computação (execução, função). Uma aplicação Serverless é executada em [contêineres](https://www.docker.com/what-container) _stateless_ (sem estado) que são disparados por evento (_event-triggered_), **efêmeros** (podem durar por uma chamada) e totalmente gerenciados pelo provedor de nuvem. O preço é baseado no número de execuções, e não na capacidade de computação pré-adquirida. > Serverless applications are event-driven cloud-based systems where application development rely solely on a combination of **third-party services**, **client-side logic** and cloud-hosted remote procedure calls (**Functions as a Service**). A maioria dos provedores de nuvem investiram pesado em serverless. Com essa promoção maciça e a oferta realista, podemos seguramente assumir que serverless será um dos serviços em nuvem mais usados nos próximos anos. Aqui estão alguns dos serviços em nuvem atualmente disponíveis: * [AWS Lambda](https://aws.amazon.com/lambda/) * [Google Cloud Functions](https://cloud.google.com/functions/) * [Azure Functions](https://azure.microsoft.com/en-us/services/functions/) * [IBM OpenWhisk](https://www.ibm.com/cloud-computing/bluemix/openwhisk) * [Alibaba Function Compute](https://www.alibabacloud.com/product/function-compute) * [Iron Functions](http://open.iron.io/) * [Auth0 Webtask](https://webtask.io/) * [Oracle Fn Project](https://fnproject.io/) * [Kubeless](https://kubeless.io/) ## Arquitetura Tradicional vs Serverless [![]({{ BASE_PATH }}/images/2018-06-26-o-que-eh-arquitetura-serverless/1_x_v5NRC3TTMt1MaYl1gMUg.png)](https://www.gocd.org/2017/06/26/serverless-architecture-continuous-delivery/) Fonte: <https://www.gocd.org/2017/06/26/serverless-architecture-continuous-delivery/> Durante anos, as aplicações eram executadas em servidores que sempre necessitavam de correções, atualizações além de uma dedicação contínua (madrugadas à fio) para mantê-los em operação. Desta forma, **TODA** responsabilidade do funcionamento deles estava em **você**. Serverless tende a ser diferente dessa situação, onde você não precisa mais se preocupar com os servidores subjacentes. Eles já não são mais gerenciados por você e com o gerenciamento fora do quadro, a responsabilidade recai sobre os fornecedores de nuvem. Mas, independentemente dos recursos interessantes do Serverless, em alguns casos, a arquitetura tradicional o supera. ### Preço Uma das principais vantagens de usar Serverless é o **custo reduzido**. O modelo de custo do Serverless é baseado em **execução**: você é cobrado pelo número de execuções. Você recebe um certo número de **segundos de uso** que varia de acordo com a **quantidade de memória necessária**. Da mesma forma, o preço por MS (milissegundos) varia com a quantidade de memória necessária. Obviamente, funções de execução mais curtas são mais adaptáveis a esse modelo, com um pico de tempo de execução de 300 segundos para a maioria dos fornecedores de nuvem. O vencedor aqui é a arquitetura Serverless. ### Networking A desvantagem é que as funções Serverless são acessadas apenas como **APIs privadas**. Para acessá-los, você deve configurar um **gateway de API**. Isso não afeta seu preço ou processo, mas significa que você não pode acessá-los diretamente por meio do IP habitual. O vencedor aqui é a arquitetura tradicional. ### Dependências de terceiros A maioria, se não todos os projetos, têm dependências externas. Eles dependem de bibliotecas que não estão embutidas na linguagem ou framework que você usa. Desenvolvedores costumam usar bibliotecas com funcionalidades que incluem criptografia, processamento de imagens, etc., e essas bibliotecas podem ser muito pesadas. Sem acesso no nível do sistema, a solução é empacotar essas dependências na própria aplicação. > Reinventar a roda **nem sempre** é uma boa ideia. O vencedor aqui é baseado no contexto. Para aplicações simples com **poucas dependências**, o Serverless é o vencedor; para qualquer coisa **mais complexa**, a arquitetura tradicional é a vencedora. ### Ambientes Configurar ambientes diferentes para Serverless é tão fácil quanto configurar um ambiente único. Como se trata de pagamento por execução, temos aqui uma grande melhoria em relação aos servidores tradicionais, já que desta forma não há mais a necessidade de configurar máquinas de desenvolvimento, teste e produção, por exemplo. O vencedor aqui é a arquitetura Serverless. ### Timeout Com a computação Serverless, há um limite de timeout de **300 segundos**. Funções muito complexas ou de **longa duração** não são boas para Serverless, mas ter um timeout rígido impossibilita a realização de determinadas tarefas. Um limite rígido nesse tempo torna o Serverless inutilizável para aplicações que possuem tempos de execução variáveis e para determinados serviços que requerem informações de uma fonte externa. O vencedor claro aqui é a arquitetura tradicional. ### Escala O processo de escalonamento para Serverless é automático e contínuo, mas há falta de controle ou total ausência de controle. Embora o dimensionamento automático seja ótimo, é difícil não conseguir resolver e atenuar erros relacionados a novas instâncias Serverless. Temos um empate técnico entre a arquitetura Serverless e a tradicional. ## Functions as a Service (FaaS) O FaaS é uma implementação de arquiteturas Serverless onde os desevnolvedores podem implantar uma função individual ou uma parte da lógica de negócios. Eles começam em milissegundos (~ 100 ms para o [AWS Lambda](https://aws.amazon.com/lambda/)) e processam solicitações individuais em um intervalo de tempo - no geral - de 300 segundos - imposto pela maioria dos fornecedores de nuvem. ### Princípios do FaaS * Gerenciamento completo de servidores * Cobrança baseada em invocação * Orientado a eventos e instantaneamente escalonável ### Propriedades chave do FaaS * **Funções lógicas independentes do lado do servidor:** Os FaaS são semelhantes às funções que você está acostumado a escrever em linguagens de programação. Unidades de lógica **pequenas**, separadas, que recebem argumentos de entrada, operam na entrada e retornam o resultado. * **Sem estado:** Com o Serverless, **tudo é sem estado**, você não pode salvar um arquivo no disco em uma execução da sua função e esperar que ela esteja lá na próxima. Quaisquer duas invocações da mesma função podem ser executadas em contêineres completamente diferentes sob o teto. * **Efêmero:** FaaS são projetados para iniciar rapidamente, fazer seu trabalho e depois desligar novamente. Eles não permanecem sem uso. Contanto que a tarefa seja executada, os contêineres subjacentes são descartados. * **Disparados por evento:** Embora as funções possam ser chamadas diretamente, elas geralmente são acionadas por eventos de outros serviços de nuvem, como solicitações HTTP, novas entradas de banco de dados ou notificações de mensagens de entrada. FaaS são frequentemente usados e considerados como a cola entre serviços em um ambiente de nuvem. * **Escalonável por padrão:** Com as funções _stateless_, vários contêineres podem ser inicializados, permitindo que tantas funções sejam executadas (em paralelo, se necessário), conforme necessário, para atender continuamente a todas as solicitações recebidas. * **Totalmente gerenciado por um fornecedor de nuvem:** O [AWS Lambda](https://aws.amazon.com/lambda/), [Azure Functions](https://azure.microsoft.com/en-us/services/functions/), [IBM OpenWhisk](https://www.ibm.com/cloud-computing/bluemix/openwhisk) e o [Google Cloud Functions](https://cloud.google.com/functions/) são as soluções FaaS mais conhecidas disponíveis atualmente. Cada oferta suporta tipicamente uma variedade de linguagens e tempos de execução, i.e. Node.js, Python, .NET Core, Java. ## Aplicação Serverless (um exemplo da AWS) Uma solução Serverless consiste em um servidor Web, funções Lambda (FaaS), serviço de token de segurança (STS), autenticação do usuário e banco de dados. [![]({{ BASE_PATH }}/images/2018-06-26-o-que-eh-arquitetura-serverless/1_TIrjN7EjLUVJmJ6YvHR7Dg.png)](http://blog.tonyfendall.com/2015/12/serverless-architectures-using-aws-lambda/) Fonte: <http://blog.tonyfendall.com/2015/12/serverless-architectures-using-aws-lambda/> * **Aplicação Cliente** - A UI da sua aplicação é renderizada no lado do cliente em algum framework frontend javascript, que nos permite usar um servidor web simples e estático. * _Servidor Web_ - O Amazon S3 fornece um servidor Web robusto e simples. Todos os arquivos HTML, CSS e JS estáticos para nossa aplicação podem ser fornecidos a partir do S3. * **Funções Lambda (FaaS)** - São os principais facilitadores na arquitetura Serverless. Os serviços da aplicação para efetuar login e acessar dados serão criados como funções Lambda. Estas funções irão ler e escrever a partir do seu banco de dados e fornecer respostas JSON. * **Security Token Service (STS)** - Gera credenciais temporárias da AWS (chave de API e chave secreta) para os usuários da aplicação. Essas credenciais temporárias são usadas pela aplicação cliente para chamar a API da AWS (e, portanto, chamar o Lambda). * **Autenticação do usuário** - O AWS Cognito é um serviço de identidade integrado ao AWS Lambda. Com o Amazon Cognito, você pode adicionar facilmente a inscrição do usuário e o login em suas aplicações Web e móveis. Ele também tem as opções para autenticar usuários através de provedores de identidade social como Facebook, Twitter ou Amazon, com soluções de identidade SAML ou usando seu próprio sistema de identidade. * **Banco de dados** - O AWS DynamoDB fornece um banco de dados NoSQL totalmente gerenciado. O DynamoDB não é essencial para uma aplicação Serverless, mas é usado como um exemplo aqui. ## Benefícios da arquitetura Serverless ### Da perspectiva de negócios * O custo gerado por uma aplicação Serverless é baseado no número de execuções da função, medido em milissegundos em vez de horas. * Agilidade do processo: Unidades implantáveis menores resultam em entrega mais rápida de recursos ao mercado, aumentando a capacidade de adaptação à mudança. * O custo de contratação de engenheiros de infraestrutura de backend cai. * Custos operacionais reduzidos. ### Da perspectiva do desenvolvedor * Responsabilidade reduzida, sem infraestrutura de backend a ser gerida. * Zero administração do sistema. * Gerenciamento operacional mais fácil. * Promove a adoção de Nanoservices, Microservices, Princípios SOA. * Configuração mais rápida. * Escalável, não precisa se preocupar com o número de solicitações simultâneas. * Monitorando fora da caixa. * Promove a inovação. ### Da perspectiva do usuário * Se as empresas estão usando essa vantagem competitiva para enviar recursos mais rapidamente, os clientes estão recebendo novos recursos mais rapidamente do que antes. * É possível que os usuários possam fornecer mais facilmente seu próprio backend de armazenamento (ou seja, Dropbox, Google Drive). * É mais provável que esses tipos de aplicações ofereçam armazenamento em cache no lado do cliente, o que proporciona uma melhor experiência offline. ## Desvantagens da arquitetura Serverless ### Da perspectiva de negócios * Controle total reduzido. * O temido bloqueio de fornecedor (_vendor lock-in_) exige mais confiança para um provedor terceirizado. * Exposição adicional ao risco requer mais confiança para um provedor terceirizado. * Risco de segurança. * Risco de Recuperação de Desastres. * Todos esses inconvenientes podem ser mitigados com alternativas de código aberto, mas à custa dos benefícios de custo mencionados anteriormente. ### Da perspectiva do desenvolvedor * A tecnologia imatura resulta em fragmentação de componentes, melhores práticas não são claras. * Complexidade arquitetônica. * A disciplina necessária contra a expansão de funções. * A multilocação (_multi-tenancy_) significa que é tecnicamente possível que as funções vizinhas possam sobrecarregar os recursos do sistema nos bastidores. * Testar localmente se torna complicado. * Restrições significativas no estado local. * A duração da execução é limitada. * Falta de ferramentas operacionais. ### Da perspectiva do usuário * A menos que seja arquitetado corretamente, uma aplicação pode fornecer uma experiência ruim ao usuário como resultado do aumento da latência da solicitação. ## Serverless Frameworks Plataformas Serverless precisam de infraestruturas onde possam ser executadas. Estruturas independentes de provedores fornecem uma maneira independente de plataforma para definir e implantar código Serverless em várias plataformas de nuvem ou serviços comerciais. * [Serverless Framework](https://serverless.com/) (Javascript, Python, Golang) * [Apex](http://apex.run/) (Javascript) * [ClaudiaJS](https://claudiajs.com/) (Javascript) * [Sparta](https://gosparta.io/) (Golang) * [Gordon](https://github.com/jorgebastida/gordon) (Javascript) * [Zappa](https://www.zappa.io/) (Python) * [Up](https://github.com/apex/up) (Javascript, Python, Golang, Crystal) ## Resumo A arquitetura Serverless é certamente muito interessante, mas ainda possui uma série de limitações. Vale ressaltar que a validade e o sucesso das arquiteturas de software dependem muito mais dos requisitos do negócio e do que das tecnologias. Da mesma forma, Serverless pode se destacar quando usado em local/contexto adequado. Aqui estão alguns links para você começar sua jornada sem Serverless. * [Serverless Examples](https://github.com/serverless/examples) – A collection of boilerplates and examples of serverless architectures built with the Serverless Framework and AWS Lambda. * [Awesome Serverless](https://github.com/anaibol/awesome-serverless) - A curated list of awesome services, solutions and resources for serverless / nobackend applications. Este post foi baseado nos seguintes artigos: ["The Benefits of Serverless Computing and its Impact on DevOps"](https://hackernoon.com/the-benefits-of-serverless-computing-and-its-impact-on-devops-e75d82c47ac4), ["Comparing PubNub Functions vs. AWS Lambda Functions"](https://www.pubnub.com/blog/comparing-pubnub-functions-vs-aws-lambda-functions/), ["Time to “Hello, World”: VMs vs. containers vs. PaaS vs. FaaS"](https://cloudplatform.googleblog.com/2018/06/Time-to-Hello-World-VMs-vs-containers-vs-PaaS-vs-FaaS.html) e ["What is Serverless Architecture? What are its Pros and Cons?"](https://hackernoon.com/what-is-serverless-architecture-what-are-its-pros-and-cons-cc4b804022e9). Artigo originalmente publicado em [O que é arquitetura Serverless (sem servidor)?](http://viniciusgarcia.me/development/o-que-eh-arquitetura-serverless/) :: [viniciusgarcia.me](http://viniciusgarcia.me/) <file_sep>/_posts/2015-03-15-assert-ieee-internet-computing-magazine.md --- layout: post title: "ASSERT @ IEEE Internet Computing Magazine" categories: Artigos tag: periodico --- A paper by ASSERT Members was published in the [IEEE Internet Computing Magazine](http://ieeexplore.ieee.org/xpl/RecentIssue.jsp?reload=true&punumber=4236), vol. 19, 2015. The paper is entitled "**An Architecture and Guiding Framework for the Social Enterprise**", by <NAME>, <NAME> and <NAME>. In this paper, the authors suggest ways to help integrate social technologies into enterprise operations. In fact, with the widespread adoption of social technologies like social networks, blogs, and wikis, there is a growing interest in looking into how enterprises should capitalize on these technologies. The social enterprise is the one that on top of having an online presence on the Internet, strives to open up new communication channels with stakeholders using social technologies. Building upon previous works on social business processes and on practical experiences on adopting such technologies in different Brazilian companies, this paper suggests an architecture and guiding framework for the social enterprise in terms of how to bridge the gap between the business world and social world and how to integrate social technologies into the enterprise's day-to-day operations. <file_sep>/_posts/2014-04-03-assert-member-website-is-the-first-prize-winner-of.md --- layout: post title: "ASSERT member website is the First-Prize Winner of Recife Application Contest, “Cidadão Inteligente”" categories: Pesquisa tag: premio --- Last Monday (March 31, 2014), the website [Cidadão Recifense](http://www.cidadaorecifense.com.br){:target="_blank"}, part of Ph.D efforts of the assertlab member **<NAME>**, won the **First Prize of Recife City Application Contest**, [Cidadão Inteligente](http://www.cidadaointeligente.rec.br){:target="_blank"}. The application contest was launched in July 2013, the same release month of the **city open-data portal**. Its objective was to incentivize developers “_to build applications or conceptual projects that enhance life in Recife_”, and developers were instructed to use Recife’s open-data portal, which contains initially 31 datasets. Applications could be sent until December 2013, and city hall committed almost **US$15,000** in two categories prizes: conceptual projects and developed apps. A total of 23 applications and 34 conceptual projects had been submitted, and 5 of each category was selected to be presented on a final workshop on March 31. At the end, each of them was judged by a specialist comitee and final results of application category is: * 1st Prize - Cidadão Recifense - Author: <NAME> (<www.cidadaorecifense.com.br>) * 2nd Prize - Doe Recife - Authors: <NAME> e <NAME> (<https://play.google.com/store/apps/details?id=br.com.doe>) * 3th Prize - PeerSquare Recife - Author: <NAME> (<http://dmesquita.github.io/>) AssertLab congratulates all participants for the quality of their projects. More information can be found (in portuguese) at contest website: <http://cidadaointeligente.rec.br/>.<file_sep>/_posts/2014-06-26-ensinando-engenharia-de-software-na-pratica-parte-ii.md --- layout: post title: "Ensinando Engenharia de Software na Prática, Parte II" categories: Educacao tag: software engineering --- Depois de alguns meses entretido com outros desafios, minhas atenções voltaram para a construção da nova abordagem de abordar _Educação em Engenharia de Software_ ou_ Como formar Capital Humano **EFICIENTE** em Produção de Software._ No primeiro post da série, tratei do que eu considero como [A biblioteca do Desenvolvedor de Software dos dias de hoje](https://viniciusgarcia.com/2014/02/14/a-biblioteca-do-desenvolvedor-de-software-dos-dias-de-hoje/). Diversos temas (ou verticais) foram destacados com algumas sugestões de bons (ótimos?) livros que abordam estes problemas de maneira didática, prática e objetiva. No segundo post da série, comecei a tratar do desafio [Ensinando Engenharia de Software na Prática, Parte I](https://viniciusgarcia.com/2014/02/19/ensinando-engenharia-de-software-na-pratica-parte-i/). Nele fiz uma contextualização das experiências e desafios que vivi tentando ensinar/vivenciar a engenharia de software na academia, ou melhor, tentando levar o **estado da arte para o estado da prática**. Adicionalmente, as bases desta nova abordagem que estou desenhando para a formação de capital humano em engenharia de software começaram a ser estabelecidas. Depois destas discussões o desafio foi conseguir estruturar um ciclo de vida do conhecimento a ser apresentado e evoluído dentro de um período de um semestre letivo, que na prática são uns 4 meses. Estes meses frequentemente sofrem interrupções na sua continuidade devidos a feriados, catástrofes naturais (aqui em Recife temos sérios problemas com chuvas), Copa do Mundo (como neste ano) e por aí vai. Mas até que nada disso compromete, efetivamente, a continuidade e sobrevivência do curso em si. Isso tudo passa, inicialmente, pela (re)definição da ementa do curso. Segundo a [Wikipedia](http://pt.wikipedia.org/wiki/Ementa), **Ementa** é > (do latim ementum, “pensamento”, “ideia”, de e e mens, “juízo”, “razão”, “mente”) é um termo aplicado de modo geral, para indicar uma espécie de apontamento ou anotação tomada para lembrança, a fim de que, por aí, se produza depois o documento escrito, para que se faça e se execute o ato nela lembrado. Por exemplo, é a decisão resumida das matérias e suas cargas horárias dadas numa faculdade. > Uma ementa universitária, em geral, apresenta muito sucintamente as idéias gerais que serão abordadas ao longo da disciplina, como forma de um fichamento (frases soltas, de forma bem sintética). A apresentação mais detalhada dos assuntos que serão estudados, ponto a ponto, é dada no programa de curso. A ementa atual do curso (até 2014.1) é a que se segue: > Engenharia de Software não é só desenvolvimento de software. Ou seja, não é somente a atividade de programar e conhecer linguagens e ferramentas de apoio à programação. Existem uma série de processos envolvidos que colaboram na “construção” de um produto de software, desde a especificação do projeto, seu planejamento de execução, desenvolvimento, testes, manutenção e evolução. Portanto, Engenharia de Software claramente não se trata apenas de programação, uma atividade que pode ser desenvolvida de forma independente de outras pessoas, mas sim de um conjunto de atividades, tarefas e mais ainda, papéis que requerem trabalho em equipe (social) e capacidade de comunicação (socialização). Neste curso, vamos estudar princípios da Engenharia de Software, seus objetivos, atividades, papéis, recursos, como planejar um projeto, descobrir requisitos, abstrair uma proposta de construção de um produto de software e apresentar uma solução que será construída de forma iterativa, bem como a continuidade da vida útil deste produto. Analisando-a friamente, ela é até bem mais adequada do que _**MUITAS**_ ementas encontradas por aí… o que não é surpresa, dado o caráter diferencial da forma como a disciplina é vivenciada. Entretanto, conforme já foi discutido até então, uma **_reengenharia_** no curso se mostrou necessária e, consequentemente, a ementa foi revista. A nova ementa é > Hoje a Engenharia de Software não é só desenvolvimento de software ou de um **Software as a Service** (**SaaS**). Ou seja, não é somente a atividade de programar e conhecer linguagens e ferramentas de apoio à programação. Existem uma série de processos envolvidos que colaboram na “construção” de um produto de software, desde a especificação do projeto, seu planejamento de execução, desenvolvimento, testes, manutenção e evolução porque um software ou SaaS não tem vida curta. Portanto, Engenharia de Software claramente não se trata apenas de programação, uma atividade que pode ser desenvolvida de forma independente de outras pessoas, mas sim de um conjunto de atividades, tarefas e mais ainda, papéis que requerem trabalho em equipe (social) e capacidade de comunicação (socialização). Neste curso, vamos estudar princípios da Engenharia de Software através de técnicas ágeis altamente produtivas para desenvolver sistemas de informação na forma de SaaS. Espera-se que os alunos se deparem e compreendam os novos desafios e oportunidades de SaaS versus software empacotados por meio da aplicação de técnicas de desenvolvimento fundamentais para a concepção, análise, projeto, implementação, teste e implantação de um sistema de informação SaaS simples. É importante ressaltar que esta é uma das **poucas** disciplinas do curso de SI que possibilita ao aluno **um contato mais próximo e prático** com as disciplinas relacionadas ao **desenvolvimento de software propriamente dito**, uma clara carência não só deste curso mas uma necessidade real do mercado de TI nacional e com muitas posições de trabalho em aberto o que demonstra uma clara carência de capital humano especializado. É sabido que uma imersão **prática** em Engenharia de Software em um curso semestral (em torno de 15 semanas) com _Exercícios Escolares _intercalados, necessidades de aulas práticas de monitoria, revisões e um significativo projeto em times com data limite para conclusão é uma meta bastante ambiciosa. Neste contexto, espera-se que os estudantes, para cursar esta disciplina com sucesso, estejam confortáveis com _pelo menos uma linguagem de programação Orientada a Objetos_ e com os _conceitos básicos da Orientação a Objetos_ (classes, herança, polimorfismo, sobrecarga, entre outros) e _conceitos básicos de abstração e estrutura de dados_ (abstração de dados, abstrações de procedimentos / funções de alta ordem, recursão, tipos abstratos de dados, entre outros). Antes desta disciplina, é importante ressaltar que os alunos de SI do CIn cursam “_IF966 INTRODUÇÃO AOS SISTEMAS DE INFORMAÇÃO_” (pré-requisito) que introduz os alunos aos principais conceitos e fundamentos dos Sistemas de Informação e da Tecnologia da Informação e Comunicação; “_IF968 PROGRAMAÇÃO 1_” (pré-requisito) que aborda os conceitos básicos de algoritmos, estruturas de dados dinâmicas, técnicas de construção de algoritmos e alguns breves conceitos de complexidade de algoritmos, usualmente em Java mas com experiências feitas utilizando Python (são duas turmas, onde a turma com os “reprovados” trabalham com Python como uma experiência em verificar qual o impacto de já iniciar com Java e suas complexidades atrapalha na absorção do conteúdo); e, “_IF969 ALGORITMOS E ESTRUTURA DE DADOS_” (obrigatória do curso) utilizando Java que conforme o nome diz, trata dos algoritmos e estruturas de dados. A IF968 e a IF969 são as únicas disciplinas do curso que tratam de algoritmos e programação e juntamente com a IF977 formam a trilha de disciplinas obrigatórias para trabalhar o desenvolvimento de software propriamente dito. Existem ainda disciplina (co)relacionadas como: - “IF976 – BANCO DE DADOS” - “IF979 – PLANEJAMENTO E GERENCIAMENTO DE PROJETOS” - “IF978 – GESTÃO DE PROCESSOS DE NEGÓCIO” No próximo post tratarei do projeto propriamente dito do curso, ou seja, o programa da disciplina. Quais os principais temas, como eles serão tratados, o ciclo de vida do conhecimento dentro do framework do curso e o que eu imagino enfrentar de desafios e os riscos envolvidos! Espero não demorar tanto para o próximo post, mesmo porque o semestre atual está no fim e a disciplina tem que ficar pronta logo! _Artigo originalmente publicado por [<NAME>](http://viniciusgarcia.me/education/ensinando-engenharia-de-software-na-pratica-parte-ii/)_<file_sep>/_posts/2019-01-12-quem-eh-o-culpado-pela-queda-nas-vendas-de-smartphones.md --- layout: post title: "Quem é o culpado pela queda nas vendas de smartphones?" categories: Negócios tag: - startup - smartphone - mobile - innovation --- Primeiro, não tem ninguém indo à falência nem tampouco endividadas, não estão dando nem prejuízo. Continuam dando lucro mas, de acordo com seus relatórios financeiros, devem dar menos lucro do que o que estava previsto para os próximos meses. E isso por quê? Aqui vão alguns motivos: 1. **Falta de novidades**. Porém, de acordo com dados do IDC, há três problemas maiores: alta penetração, saturação de mercado e preços galopantes. 1. **Estagnação do mercado**. Todo ano, as fabricantes tentam te convencer a mudar de smartphone, pois uma novíssima tecnologia está disponível e vai melhorar incrivelmente sua vida, uma hora isso ia estagnar. 1. **Preços cada vez mais altos**. Sabemos que topos de linha são caros, já até que nos acostumamos a desembolsar bem mais pelo que há de melhor. Mas há limites, e eles estão sendo ultrapassados. 1. **Mais concorrentes forçam a diminuição da fatia do bolo**. Há bons smartphones de outras fabricantes, como Oppo, Huawei, Xiaomi, Vivo e outras (isso apenas na China). 1. Sim, também é política e problemas que acontecem entre nações, também pela Globalização, influenciam sim em vendas E você, o que acha? Artigo originalmente publicado em [Quem é o culpado pela queda nas vendas de smartphones?](http://viniciusgarcia.me/business/quem-eh-o-culpado-pela-queda-nas-vendas-de-smartphones/) :: [viniciusgarcia.me](http://viniciusgarcia.me/) <file_sep>/_posts/2017-08-25-defesa-de-dissertacao-de-mestrado-n-1727.md --- layout: post title: "Defesa de Dissertação de Mestrado Nº 1.727" categories: Defesa tag: mestrado --- ## Pós-Graduação em Ciência da Computação – UFPE ### Defesa de Dissertação de Mestrado Nº 1.727 **Aluno**: <NAME> **Orientador**: Prof. <NAME> **Título**: _**Uma Arquitetura para Orquestração da Distribuição de Água no Semiárido Brasileiro Baseada em Internet das Coisas e Computação em Nuvem**_ **Data**: 29/08/2017 **Hora/Local**: 10h – Centro de Informática – Sala E423 Banca Examinadora: * Prof. <NAME> (UFPE / Centro de Informática) * Prof. <NAME> (UFRN / DIMAp) * Prof. <NAME>(UFPE / Centro de Informática) RESUMO: > Na região Semiárida brasileira o regime de chuvas é caracterizado por períodos longos de estiagem com secas prolongadas, fazendo com que no ano de 2016 fossem gastos mais de um bilhão de Reais em programas de distribuição de água à população carente dessa região, dos quais cerca de 14% desse recurso foi gasto em fiscalização. A forma de fiscalização atual não contempla nenhuma maneira de mensurar a quantidade ou a qualidade da água recebida e várias notícias de fraudes publicadas pela mídia em geral indicam que essa fiscalização é um processo caro e propício a erro. O problema então é como melhorar o monitoramento e fiscalização na distribuição de água, ampliando a transparência e a eficiência de programas federais de distribuição deste recurso. Sistemas de Internet das Coisas (IoT) são capazes de transmitir informações sobre volume e qualidade da água, estas informações podem ser usadas de forma integrada com os sistemas de tomada de decisão para fins de gestão. No entanto, as limitações dos dispositivos IoT requerem uma Tecnologia como Computação em Nuvem para complementar suas aplicações, dado que a Computação em Nuvem possui capacidades praticamente ilimitadas em termos de armazenamento e processamento. Motivado pela importância do programa de distribuição de água para o Semiárido brasileiro e pela necessidade de definição de um framework para permitir a integração de soluções parciais para fiscalização destes tipos de programas, este trabalho apresenta uma arquitetura baseada em IoT e Computação em Nuvem que disponibiliza serviços para orquestrar a distribuição de água no Semiárido brasileiro. Para atingir os objetivos deste trabalho foi realizado um mapeamento das principais tecnologias empregadas em Sistemas de Gerenciamento de Recursos Hídricos que utilizam IoT e foi realizada uma análise do emprego da Tecnologia da Informação como instrumento de apoio à fiscalização do programa de distribuição de água. Apoiado nestes conhecimentos foi especificada, projetada e implementada uma arquitetura de referência. Por fim, a partir de uma avaliação pôde-se mensurar o quão a Arquitetura Proposta está apta para ser implantada em um contexto real. Palavras-chave: Internet das Coisas, Computação em Nuvem, Engenharia de Software Baseada em Evidência, Segurança, Arquitetura de Software, Distribuição de Água, Seca.<file_sep>/resultados.md --- layout: page title: Resultados tagline: Ferramentas e Projetos de Pesquisa & Desevnolvimento & Inovação permalink: /resultados.html --- # [Projetos](#projetos) ## Uma proposta baseada em Representação Textual Simplificada para minimizar ataques de Phishing Direcionados `Metade dos golpes relacionados a cartões de crédito são aplicados através de ataques de phishing, e protagonizados em ambientes de e-commerce. Através da engenharia social, o atacante traça perfis de suas vítimas com base em características inerentes ao contexto, como termos ou palavras-chave de uma determinada marca, para registrar domínios com erros tipográficos propositais. Todavia, existem estudos que norteiam suas heurísticas com base na ausência de detalhes textuais, ou seja, quanto menor a fidedignidade do phishing, maiores as chances de sucesso na detecção. Na mesma linha, a detecção é comprometida à medida que o phishing tem maior fidedignidade, sendo um raciocínio semelhante ao crivo humano. Diante disso, o presente estudo tem como motivação apresentar uma heurística sustentada à medida que o phishing tem maior riqueza em detalhes baseados na fidedignidade. Diante o exposto, esse projeto propõe utilizar Natural Language Processing (NLP), especificamente o modelo estatístico Latent Dirichlet Allocation (LDA) ou baseado em Deep Learning, como estratégia para representação simplificada da recuperação de informações. A abordagem sugere que certos termos sejam previamente relacionados a um conjunto de palavras semanticamente relacionadas. A proposta é oferecer um mecanismo capaz de identificar ataques de phishing considerando eventos sazonais e suas relações tipográficas a uma determinada marca. EDITAL FACEPE 11/2020 CONCESSÃO DE BOLSAS DE PÓS-GRADUAÇÃO STRICTO SENSU (2º SEMESTRE/2020), PBPG-1218-1.03/20 (R$36.600,00).` ## Pesquisa de um Método de Investigar as estratégias de Transformação Digital [2020 - Atual] **Projeto certificado pela empresa THE DIGITAL STRATEGY COMPANY (TDS Company) em 01/04/2020.** `É inegável o crescimento da transformação digital dos mais diferentes domínios de negócios no mundo todo e, no Brasil, não é diferente. Entretanto, nenhuma transformação é trivial. É preciso repensar as bases do negócio. Dar um salto das plataformas analógicas para as digitais, o novo e ainda pouco entendido substrato, para competir nos mercados contemporâneos deixa diversos pontos em aberto, nessa imensa jornada de tomadas de decisão. Muitas vezes, essas transformações são conduzidas pela experiência de times de consultoria, com muitas horas de esforço e dedicação, individual em cada projeto de transformação, considerando inúmeras variáveis relacionadas ao negócio, competidores, processos de aquisição de insumos, relacionamentos com os clientes, fornecedores e colaboradores, cultura organizacional, cultura dos mercado, dos clientes, entre tantas outras facilmente mapeadas e outras extremamente difíceis e complexas de se mapear. Em função deste quadro, as empresas estão investindo cada vez mais em tecnologia e em soluções que promovam tanto a melhor experiência para as empresas que necessitam passar por uma transformação digital - seja por questões de sobrevivência ou antecipação frente aos concorrentes - seus consumidores, e todo ecossistema ao seu redor com o objetivo de ter um aumento efetivo dos resultados do seu desempenho ? como negócio - neste meio digital. Entendendo este cenário e a necessidade das organizações encararem a jornada da transformação (ou adaptação) digital, este projeto tem por objetivo investigar o estado-da-arte e da prática sobre estratégias, metodologias, processos, mecanismos e ferramentas podem ajudar a alavancar as teorias e estratégias de transformação digital e realizar experimentos que possam alavancar a capacidade da TDS Company neste tema.` ## Expeditus: Investigação e experimentação de estratégias de busca para a aumentar a eficiência dos resultados em sistemas de e-commerce [2019 - 2019] **Projeto certificado pela empresa Centro de Estudos e Sistemas Avançados do Recife em 07/04/2020.** `As empresas estão investindo cada vez mais em tecnologia e em soluções que promovam tanto a melhor experiência para seus consumidores, como também, um aumento efetivo dos resultados de vendas neste meio digital. Um dos fatores que mais podem contribuir para a experiência do usuário e aumento da receita de empresas é um sistema de busca apurado que possa não só trazer o resultado esperado pelo cliente, como também sugerir produtos que tenham relação com o que o usuário está buscando. Nos últimos anos diversas soluções surgiram com o objetivo de atacar o armazenamento, manipulação, indexação e análise de grandes volumes de dados. E é nesse grupo que se encontra o Elasticsearch, um mecanismo distribuído de pesquisa e análise RESTful capaz de solucionar um número crescente de casos de uso no domínio de buscas.` ## Uma arquitetura de microsserviços de suporte à computação em névoa com ênfase no offloading de processamento e dados contextuais [2018 - 2021] `Fog Computing is defined as a scenario where a huge number of heterogeneous (wireless and sometimes autonomous), ubiquitous and decentralized devices communicate and potentially cooperate among themselves and with the network to perform storage and processing tasks without the intervention of third parties. These tasks may support basic network functions or new services and applications that run in a sandboxed environment. Fog Computing presents several challenges. One of them includes the management of complex tasks that are not well-supported by resource-constrained devices. In fact, this problem is not restricted to computing tasks only, but it can also comprises data that should not be stored in some IoT nodes. A promising technique to address this issue is offloading, an approach to increase performance and reduce the energy consumption by migrating processing or data from constrained devices into other infrastructure, with greater computing power and storage. In this project, we address this research topic and propose n an architecture to support data and computing offloading in Fog environments based on the microservices architectural style.` ## Mangue: Uma Plataforma de Computação em Nuvem para o Gerenciamento e Implantação de Aplicações Científicas e Industriais [2018 - 2019] `Aplicações científicas e industriais têm que lutar com uma enorme quantidade de dados provenientes de várias fontes e em uma taxa que excede muitas vezes a própria capacidade de gerir, manter, analisar e partilhar. Adicionalmente, a diversidade em ambientes para implantação e gerenciamento destas aplicações, ou serviços, dificulta e onera substancialmente os custos de desenvolvimento e manutenção destas aplicações. As taxas de dados e demandas de processamento, capacidades de armazenamento, memória, leitura e escrita, enfim, de recursos computacionais, podem variar ao longo do tempo e por aplicação, fazendo da natureza sob demanda (elástica) da computação em nuvem o paradigma adequado para estas aplicações. Plataformas em nuvem têm demonstrado a capacidade de fornecer um conjunto escalável de serviços que podem ser facilmente, e a baixo custo, utilizados para combater as demandas de processamento e cargas de trabalho das empresas. Nesta proposta, pretende-se demonstrar que o paradigma de computação em nuvem também é apropriado para aplicações científicas e industriais caracterizadas pela agilidade em seu gerenciamento, implantação, necessidade de aquisição, armazenamento, manipulação e compartilhamento de grandes massas de dados (i.e. aplicações de big data). No entanto, as atuais infraestruturas de nuvem não são projetadas para suportar aplicações de uso intensivo de grandes massas dados e de maneira ágil, produtiva e até certo ponto transparente para o usuário. O objetivo deste projeto é investigar e propor o desenvolvimento de uma plataforma de nuvem, fornecendo apoio para implantação e gerenciamento de aplicações de maneira ágil e produtiva.` ## UM AMBIENTE SMART (Social Machine Architecture for Real Time) PARA ORGANIZAÇÕES [2017 - 2021] `A evolução tecnológica e o aparecimento das novas mídias, têm sido a base das alterações de pensamento e de adaptação das sociedades. À medida que esses meios começaram a convergir, surgiram novas formas de interatividade, mecanismos de comunicação, possibilidades de criação colaborativa do conteúdo, disseminação de informações em tempo real, como também uma nova maneira de desenvolver software. Dentro deste cenário, a próxima geração de software fará mais do que conectar pessoas que de forma inconsciente orquestram processos, nos ajudarão a alcançar um patamar de relacionamento e conectividade que anteriormente imaginávamos impossível. O termo máquina social não se refere necessariamente a aplicações sociais ou redes sociais. Neste contexto, o termo possui um significado bem mais amplo. Uma Máquina social ou Software social, significa que software foi concebido e construído desde seu início para atender a três objetivos: (i) publicar suas funcionalidades centrais para o seu ambiente; (ii) permitir de modo fácil a criação de outras aplicações sociais; e (iii) estar ciente sobre suas relações com outros softwares, alterando seu comportamento quando necessário. Mediante exposto, este projeto se relaciona perfeitamente com os principais objetivos do INES 2.0, tendo em vista que indivíduos e organizações podem ser vistas como agentes/entidades que se relacionam por meio de SMART APIs abrindo novos canais de comunicação entre as partes interessadas, permitindo a descoberta, seleção e composição eficaz de sistemas de informação, criando novas aplicações com a utilização de serviços existentes, e com isso, gerar um grande volume de dados. Vale ressaltar que ao tratamos de Internet das Coisas, podemos considerar que organizações ? entidades complexas ? podem não somente ser consideradas como ?coisas? como também produzem, manipulam, compartilham grandes volumes de dados, informações e processos entre si, de/para sensores e, principalmente, de/para pessoas. O fulcro determinante deste levantamento será entender o panorama atual de arquiteturas SMART, a fim de especificar regras e limitações que ocorrem durante o processo de estabelecer relações entre as diferentes Máquinas Sociais considerando as restrições baseadas em recurso, visibilidade e qualidade.` ## Uma Abordagem Prática para Integração Eficaz de Conceitos e Práticas no Ensino da Engenharia de Software [2017 - 2019] `O objetivo deste trabalho é definir uma proposta prática para o ensino da engenharia de software no Centro de Informática (CIn), a partir do estudo das principais referências curriculares para a área, levando em consideração as principais metodologias de ensino, as características das práticas de ensino-aprendizagem utilizadas nas disciplinas de engenharia de software ministradas no CIn e as necessidades do mercado. Os principais benefícios esperados são: Definir práticas de ensino que foquem nos tópicos considerados relevantes para a formação profissional dos alunos das disciplinas de engenharia de software, além de definir uma abordagem de ensino mais voltada para o desenvolvimento de habilidades e competências profissionais, a fim de aumentar a aprendizagem destes tópicos e formar profissionais mais preparados para atender às demandas do mercado de software.` ## BIGStore - Evolução da plataforma Ustore para Armazenamento, Manipulação e Experimentação de Grandes Volumes de Dados [2015 - 2018] **Projeto certificado pela empresa UstoRe em 26/01/2017.** `Este projeto tem por objetivo principal evoluir tecnologicamente a primeira plataforma 100% nacional para armazenamento, compartilhamento, manipulação e governança de dados em ambientes privados, de maneira distribuída, a PLATAFORMA USTORE, apoiando efetivamente as iniciativas do governo brasileiro na adoção da computação em nuvem e nas políticas nacionais de segurança e proteção aos dados e informações estratégicas. Uma das possíveis evoluções tecnológicas de uma plataforma de armazenamento e distribuição de dados e computação em nuvem é auxiliar os usuários a processar e extrair informações úteis de uma massa complexa de dados desestruturados. Para seguir essa trilha, deve-se adicionar informações semânticas aos dados armazenados e quatro pontos devem ser abordados: (i) Definir uma Arquitetura de Referência de Segurança (ARS) para sistemas de armazenamento em nuvem; (ii) Implementar uma ARS na plataforma de armazenamento Ustore; (iii) Criar um modelo padronizado para o enriquecimento dos dados de diferentes fontes (diferentes tipos de provedores de serviços na nuvem); e, (iv) Aplicar tecnologias semânticas como recurso para garantir um melhor compartilhamento dos dados criando informações acessíveis (SIN-0199-1.03/15, R$155.520,00).` ## Engenharia de Software para Cidades Inteligentes (PRONEX FACEPE/CNPq) [2014 - 2018] `Este projeto visa pesquisar, avaliar e aplicar técnicas, ferramentas e processos de engenharia de software para lidar com desafios associados ao contexto de cidades inteligentes. Em particular, pretendemos pesquisar aspectos como variabilidade, modularidade, e a especificação e teste de sistemas distribuídos. Todos esses aspectos serão avaliados e utilizados para o desenvolvimento de uma plataforma aberta de serviços de software urbanos, resultado prático do projeto e que será a base de um modelo de ecossistema de negócios voltado para cidades inteligentes. Esta plataforma visa permitir que terceiros possam consumir e fornecer serviços de software fortemente baseados em dados urbanos. Diferentes tipos de aplicações e serviços poderão ser criados, com a possibilidade de monetizar sobre estas soluções. Contrário à tendência dos grandes fornecedores de soluções, este formato permitirá a participação de diferentes fornecedores, estimulando o mercado local no setor de TIC (APQ-0388- 1.03/14).` ## Smart City Data Mediation [2013 - 2016] `Este projeto tem como objetivo a criação de um middleware de integração e mediação de dados oriundos de sistemas que coletam dados no contexto de cidades inteligentes. A proposta envolve a construção do middleware Smart City DAM (DAta Mediation), numa alusão a uma represa (dam, em inglês) que armazena dados. Dentre os objetivos específicos podem ser citados a especificação e implementação da arquitetura proposta; o projeto da arquitetura visando escalabilidade e considerando como ambiente de execução uma plataforma de Cloud Computing; a utilização de bancos de dados não convencionais para persistência dos dados; especificação de API de adaptação para facilitar integração com mecanismos de análise dos dados; especificação e implementação de camada de serviços fornecendo acesso aos dados. Edital MCTI/CNPq Nº 14/2013, R$14.000,00.` ## Uma Arquitetura de Referência para Softwares Baseados em Máquinas Sociais [2013 - 2015] `Este projeto tem como objetivo geral a promoção de pesquisa, desenvolvimento e inovação na área de Cloud Computing/Sistemas Distribuídos com o objetivo de desenvolver conhecimento sobre arquiteturas em Máquinas Sociais. Desta forma uma questão interessante a ser discutida é entender os conceitos arquiteturais que veem sendo trabalhados neste paradigma de SMs e propor um modelo arquitetural de referência. Ainda, a proposta sugere a elaboração de um processo bem definido, que torne possível documentar as decisões arquiteturais das SMs. De fato, mais do que explicar o ecossistema atual de SM na web, este trabalho visa auxiliar na construção da nova geração de aplicativos, serviços e sistemas que emerge na web. O trabalho será conduzido em 5 fases: (i) revisão sistemática da literatura, (ii) proposta da solução (processo e arquitetura de referencia), (iii) avaliação da proposta (experimentos), (iv) aplicação em empresas do Porto Digital e (v) disseminação dos resultados (publicações). Edital FACEPE 17/2012, número IBPG-0719-1.03/12, R$28.80,00.` ## Um Ambiente como Serviço para Gerenciamento de Implantação Ágil de Aplicações na Nuvem [2012 - 2014] `Uma das questões mais importantes e atuais na engenharia de software é a disponibilização de software como serviço, do inglês SaaS - Software as a Service, o que parece ser um dos fatores chave para lidar com os custos, disponibilidade e qualidade desses sistemas. Para cumprir estes objetivos, é necessário desenvolver sistemas de forma ágil, flexível e que possuam certo grau de autonomia em relação a manutenção e gerenciamento. Em particular, uma questão importante é estabelecer métodos e definir ferramentas que possuam as principais abordagens, os casos de fracasso e, principalmente, as demandas atuais para a indústria de software: Ambientes como Serviço, do inglês EaaS - Environment-as-a-Service. Neste contexto, este projeto se propõe a investigar a utilização de sistemas autônomos de gerenciamento de bancos de dados em ambientes orientados a serviço e propor modelos, técnicas e ferramentas que permitam ampliar as características autônomas nesses ambientes na computação em nuvem (Edital FACEPE 11/2011, número IBPG-0499-1.03/11, R$86.400,00).` ## Uso de DSL Como Abordagem Para Agilizar o Desenvolvimento e Implantação de Sistemas em Ambientes de Cloud Computing [2012 - 2014] `A recente incursão de grandes empresas como Amazon, Google, IBM, Microsoft, entre outras na plataforma da Cloud Computing nos leva a um cenário onde as empresas não são mais obrigadas a possuir uma conjunto mínimo de infra-estrutura e aplicativos próprios. Cloud computing, ou computação nas nuvens, é um modelo que permite acesso ubíquo, conveniente e sob demanda, para a rede ou a um pool de recursos computacionais (rede, armazenamento, servidor, aplicações, serviços) que podem ser rapidamente provisionados e disponibilizados com um esforço mínimo de gerenciamento do provedor de serviços. Falhas na manutenção da implantação das aplicações pode levar a um aumento considerável nos custos e tempo de execução do projeto, além de causar a degradação da qualidade do software. Neste contexto, o objetivo deste projeto de pesquisa é investigar e definir uma abordagem para apoiar o desenvolvimento e implantação de aplicações em ambientes de cloud computing, reduzindo os riscos, custos e aumentando a possibilidade de sucesso em projetos de desenvolvimento de software baseados na plataforma de Cloud Computing. (Edital FACEPE 11/2011, número IBPG-0483-1.03/11, R$28.80,00).` ## EUBrazilOpenBio: EU-Brazil Open Data and Cloud Computing e-Infrastructure for Biodiversity [2011 - 2013] `Um projeto colaborativo de 2 anos que irá lançar as bases de uma infra-estrutura de acesso livre a dados, permitindo que os parceiros do Brasil e da União Europeia consigam detectar padrões e tendências de mudanças na biodiversidade. Essa e-infraestrutura de dados, ferramentas e serviços resultará da federação e integração das principais iniciativas de infraestruturas de dados, nuvens e grids da Europa e do Brasil, focadas no domínio da biodiversidade e taxonomia. A infraestrutura EUBrazilOpenBio e a disponibilização aberta de seus recursos viabilizará uma gama de aplicações em ambientes interdisciplinares de pesquisa virtual de alta relação custo-benefício, abrindo caminhos para a sua adoção e uso em larga escala pela comunidade científica mundial. O objetivo do projeto é realizar dois estudos de caso com foco em: (1) integração de taxonomias regionais e globais; e (2) usabilidade de dados de ocorrência de espécies e modelagem de nicho ecológico. A realização destes estudos de caso envolve a avaliação de mecanismos de Interoperabilidade das infraestruturas existentes: hardware e facilidades computacionais, portais e plataformas, infraestruturas de dados e conhecimento científicos. Contrato número ICT-288754, financiamento total: EUROPE €1.253.555,00 ; BRAZIL R$ 2.299.939,13. Web site: http://www.eubrazilopenbio.eu.` ## Uma Abordagem para Rastreabilidade de Variabilidades entre Requisitos e Arquiteturas de Software Orientadas a Serviços [2011 - 2013] `A recente incursão de grandes empresas como Amazon, Google, IBM, Microsoft, entre outras na plataforma da Cloud Computing nos leva a um cenário onde as empresas não são mais obrigadas a possuir uma conjunto mínimo de infra-estrutura e aplicativos próprios. Isto somente é possível através da utilização de técnicas de Service-Oriented Architecture (SOA). SOA é um estilo de arquitetura de software cujo princípio fundamental prega que as funcionalidades implementadas pelas aplicações devem ser disponibilizadas na forma de serviços. Para apoiar um desenvolvimento de software consistente e eficiente, qualquer mudança nos artefatos do ciclo de desenvolvimento devem ser controladas (rastreadas). Falhas na manutenção da rastreabilidade dos requisitos pode levar a um aumento considerável nos custos e tempo de execução do projeto, além de causar a degradação da qualidade do software. Neste contexto, o objetivo deste projeto de pesquisa é investigar e definir uma abordagem para apoiar a rastreabilidade entre requisitos e arquiteturas orientadas a serviços, reduzindo os riscos, custos e aumentando a possibilidade de sucesso em projetos de desenvolvimento de software baseados na plataforma de Cloud Computing (FACEPE Edital 20/2010, número IBPG-0398-1.03/10 - R$ 28.800,00).` ## JiT Clouds - Uma proposta para ampliar a elasticidade de provedores de computação em nuvem baseada na federação de recursos computacionais amortizados [2011 - 2013] `O paradigma da computação em nuvem permite o fornecimento de Tecnologia da Informação (TI) sob a forma de um serviço adquirido sob demanda. Entre os vários benefícios providos por esse novo paradigma, a elasticidade, que habilita o cliente a aumentar ou diminuir a capacidade de sua infraestrutura de TI sem qualquer custo adicional, é um dos mais importantes. Essa característica faz com que o ônus dos custos e riscos associados ao planejamento da capacidade da infraestrutura de TI passem do cliente para o provedor do serviço. O estado-da-prática em provimento de infraestrutura como um serviço (IaaS) impõe um limite a essa elasticidade, para que se possa garantir uma disponibilidade suficientemente elevada para os serviços e, ao mesmo tempo, manter os custos operacionais em um nível aceitável. Isso restringe o escopo das aplicações que poderiam se beneficiar do paradigma de computação em nuvem. Nesse projeto nós iremos investigar uma arquitetura alternativa para a construção de provedores de IaaS, onde os mesmos apenas incorrem em custos de propriedade quando os recursos usados para prover a sua infraestrutura são demandados pelos seus clientes, permitindo uma ampliação de algumas ordens de magnitude no limite que precisa ser imposto aos clientes. Além das questões relacionadas com o provimento de IaaS, serão estudadas questões relacionadas com o acoplamento com os outros níveis de computação em nuvem (RNP, CTIC - R$1.880.000,00). Web site: http://jitclouds.lsd.ufcg.edu.br/` ## UbiStructure - Uma infra-estrutura de desenvolvimento e execução de aplicações ubíquas [2011 - 2013] `O objetivo desse novo projeto, denominado UbiStructure, é utilizar as ideias que foram propostas durante o projeto MobiLine e criar um ambiente de desenvolvimento e execução para aplicações móveis e sensíveis ao contexto utilizando Linhas de Produtos de Software, que contemple os vários ciclos propostos no MobiLine. Para isso, muitas questões não tratadas anteriormente serão exploradas e tem enfoque nos aspectos de dependabilidade, qualidade de software, aquisição de contexto e de configuração otimizada de um produto (EDITAL UNIVERSAL - CNPq 14/2011, processo número 481417/2011-7 - R$ 109.730,56).` ## RiSE-APF: Um Framework de Processos para Adoção Incremental de Reuso Sistemático de Software [2010 - 2012] `Este projeto propõe um Modelo para Adoção Incremental de Reuso no Processo de Desenvolvimento de Software. O modelo tem por objetivo prover uma abordagem sistemática para adoção de reuso no processo de desenvolvimento de software das organizações, de uma forma incremental e customizável, por meio de uma série de diretrizes, atividades (tarefas) e ferramentas. O modelo é baseado na análise do estado da arte na área, incluindo modelos de reuso, processos para engenharia de domínio e para linhas de produto, e ferramentas e ambientes para o reuso de software. O ponto chave deste modelo é a combinação de diretrizes, métricas de reuso, aspectos econômicos e um conjunto de requisitos para uma adoção incremental de reuso de software (Edital Programa Primeiros Projetos PPP/FACEPE/CNPq - 10/2010, APQ-1044-1.03/10 - R$ 18.278,30).` # [Ferramentas](#ferramentas) ## Piracema.io : um sistema especialista baseado em heurística direcionada por características estáticas e dinâmicas para a detecção gradual de phishing direcionados Não é incomum encontrar estudos que investigaram abordagens que analisam características estáticas (i) e dinâmicas (ii) de uma página Web para detectar ataques de phishing através de predição. Em (i), as características não consideram aspectos como tempo ou de terceiros envolvidos, o que propõem benefícios em termos de desempenho, contudo, tem baixa precisão devido ao escopo ser limitado porque não considera a página em execução. Diante disso, estudos são impulsionados a adotarem uma abordagem (ii) que considera aspectos temporais e contexto da atuação do phishing, oferecendo maior eficiência nas soluções anti-phishing. Todavia, a análise em (ii) tem limitações devido a mudança contínua de conteúdo. Não obstante, alguns phishing, a exemplo dos direcionados a uma marca específica, possuem um alto grau de fidedignidade com a página genuína, portanto, ao mesmo tempo que aumentam a exploração da suscetibilidade do usuário final, a riqueza em detalhes dificulta a predição de algo malicioso. Há também o desafio em identificar quais características são mais e menos relevantes devido as novas tendências, considerando o cenário dinâmico de atuação do phishing. Diante disso, o estudo faz uma investigação sobre a relevância, relação e similaridade entre (i) e (ii) através de uma regressão logística sobre amostras de phishing reais. O intuito é contribuir com os rumos para novas abordagens baseadas em predição, considerando aspectos como fidedignidade, ofuscação, propagação, sazonalidade e volatilidade, que podem dificultar a identificação dos padrões em páginas maliciosas. A proposta apresenta-se como uma solução complementar, ou seja, atuar em conjunto com soluções já existentes que são baseadas em lista de bloqueio. Adicionalmente, também é pretendido disponibilizar um mecanismo de lista de permissão baseado em um protocolo de autenticação e autorização para fortalecer a proposta contra falsos positivos. O presente estudo propõe um sistema especialista como mecanismo anti-phishing baseado em regras. Sua detecção é tida como gradual porque sua máquina de inferência processa as regras em profundidade gradativa, visando reduzir o custo computacional e ser menos invasivo no contexto da privacidade durante o processamento da predição. A proposta demonstra maior eficiência em phishing com maior riqueza em detalhes, e com isso, se caracterizando como uma alternativa de proteção de marcas. Como prova de conceito (PoC), o estudo faz uma avaliação de possíveis falsos positivos e negativos da proposta quando a mesma é submetida à amostras reais de phishing e de páginas genuínas. Também é pretendido avaliar o caráter complementar da proposta com as soluções nativas em navegadores Web e também avaliar os impactos positivos atingidos pela análise gradual da proposta. Como resultado, além dos dados quantitativos, essa pesquisa também realizou uma análise qualitativa da proteção, identificando contribuições e limitações. Atualmente, foi firmada uma parceria técnica e autoral do projeto com a [Tempest Security Intelligence](https://www.tempest.com.br/). ## professorqrbot: Um Chatbot para auxílio no ensino de engenharia de software Durante o curso de uma disciplina, os alunos usam uma série de ferramentas para obter as informações necessárias para ter um bom desempenho escolar. Cada professor, que é responsável pelo fornecimento dessas informações, também faz uso de algumas ferramentas, sejam elas digitais ou não, para torná-las acessíveis aos alunos. O objetivo principal deste trabalho é criar uma plataforma de distribuição dessas informações, que podem ser referentes a turma em si, como notas e cronograma, ou relacionadas ao conteúdo de Engenharia de Software. Para isso, foi desenvolvido um Chatbot ([@professorqrbot](https://web.telegram.org/#/im?p=@professorqrbot)) que simula um professor online. Além disso, também foi necessário uma [interface de abastecimento de informações](https://github.com/renatodeyvson/professorqr-dashboard), para que o professor possa alimentar o sistema e a sua [API de back-end](https://github.com/renatodeyvson/professorqr-api). ## Mangue.io Mangue é uma plataforma para orquestração e gerenciamento de clusters [Kubernetes](https://kubernetes.io/). O Mangue possibilita a criação de um ambiente diversificado, atuando sobre a tecnologia [_contaners_](https://www.docker.com/what-container), fornece a possibilidade de migração de aplicações entre infraestruturas distintas independente do hardware. Além disso fornece uma informação granularizada sobre o consumo e custo a nível de aplicação em tempo real, possibilitando o gestor a escalar sob demanda e reduzir custos. Na perspectiva da equipe de desenvolvimento o Mangue serve como um ambiente para facilitar o processo de [DevOps](https://techcrunch.com/2015/05/15/what-is-devops/) (continuos integration e continuos delivery), permitindo, por exemplo, o _deploy_ e _rollback_ de versões e consequentemente a redução de _time-to-market_. ## Jacroid Plugin [[github](https://github.com/assertlab/jacroid){:target="_blank"}] `Plugin para IDE Eclipse com o objetivo de apoiar o desenvolvimento de aplicativos na plataforma Android, dentro do domínio de pessoas como sensores.` ## EVA: An Environment for Virtual Assistant [[github](https://github.com/assertlab/eva){:target="_blank"}] `EVA tem como objetivo auxiliar os estudantes quanto ao que estaá acontecendo no Centro de Informaática da Universidade Federal de Pernambuco, no que diz respeito a dúvidas relacionadas a horários, localizações, processos e eventos, sendo capaz de entendê-las e respondê-las de forma natural. Para isso, foram desenvolvidos modelos para a classificação de intenções e para o reconhecimento de entidades em textos, utilizando Aprendizado de Maáquina e Processamento de Linguagem Natural. Se-guem as principais funcionalidades implementadas: Part-Of-Speech Tagger (POS), para a classificacção gramatical de palavras, treinado com CRF; Inside-Outside-Begin Tagger (IOB), para executar o reconhecimento de entidades, treinado com CRF; Um Classificador de Intenções, treinado com SVM; Uma interface para classificar intençõ̃es, identificar entidades e retornar a entrada de modo estruturado.` ## UsainBots! [[github](https://github.com/eva-lab/usainbots){:target="_blank"}] `Uma aplicação de gerenciamento de bots desenvolvido por meio de técnicas de inteligência artificial. Este projeto representa um esforço inicial para a busca e o desenvolvimento de bots por meio de um serviço web. Tem por objetivo desenvolver um serviço web que possibilite desenvolvimento e gerenciamento simplificado de bots com uma abstração inicial de reapresentação de conhecimento baseado em um sistema de recuperação da informação.` ## Django Multi-Tenant [[github](https://github.com/assertlab/django-multi-tenant){:target="_blank"}] `Nos últimos anos o modelo de entrega de software como serviço, ou Software as a Service (SaaS), surgiu trazendo softwares mais flexíveis e reutilizáveis. Este modelo provê suporte a diversos usuários sobre uma mesma infra-estrutura configurável, oferecendo funcionalidades sob demanda. Multi-Tenancy, ou multi-inquilino, é uma abordagem organizacional do modelo SaaS. Características de uma arquitetura multi-tenant são: compartilhamento de recursos de hardware, alto grau de configurabilidade e bancos de dados compartilhados. Alguns benefícios da utilização desta arquitetura são: maior utilização dos recursos de hardware, manutenção da aplicação facilitada e mais barata e redução nos custos globais do sistema. Tomando como base as características desta arquitetura, esta pesquisa propõe uma biblioteca open source para transformar projetos Django em um projeto multi-tenant, com o intuito de facilitar seu desenvolvimento. Assim, os desenvolvedores podem focar seus esforços na regra de negócio e não com a arquitetura, já implementada pela biblioteca.` ## BDD Plugin for Mantis (BDDPM) [[bitbucket](https://bitbucket.org/alvaromagnum/bdd-plugin/overview){:target="_blank"}] `BDD Plugin for Mantis (BDDPM) é uma ferramenta cujo objetivo é facilitar a adoção do BDD em projetos de desenvolvimento de software. Para avaliar o plugin quanto ao cumprimento dos objetivos, foi utilizada uma técnica denominada GQM (Goal/Question/Metric), que permite, através de objetivos bem estabelecidos, planejar e mensurar métricas de avaliação. O BDDPM foi avaliado com sucesso dentro de um ambiente de produção real, uma autarquia do Governo do Estado da Paraíba: a Paraíba Previdência.` ## Extractviewer project [[github](https://github.com/assertlab/extractviewer_project){:target="_blank"}] `A ExtractViewer tem por objetivo acelerar e apoiar a execução das atividades do processo de mapeamento sistemático, além de diminuir a propensão à erros, naturalmente advindos de processos manuais e repetitivos. O conjunto de features inicialmente desenvolvidos da ferramenta permite: (i) importar os resultados do processo de busca, (ii) acessar facilmente os arquivos dos estudos, (iii) aplicar os critérios de inclusão e exclusão, (iv) identificar conflitos e resolvê-los e (vi) extrair dados da pesquisa. A ferramenta foi concebida de modo a permitir que todas estas atividades possam ser realizadas de forma distribuída, proporcionando mais velocidade na conclusão desta etapa do estudo. São disponibilizados, além do acesso aos arquivos dos estudos, todas as informações de metadados obtidos, de forma a assitir o processo de seleção: título, autor, ano, resumo, confe- rência e engenho de busca. Também é permitido aos revisores registrar todas as observações que julgem relevantes durante suas análises, o que posterioremente apóia a resolução de conflitos e análise dos estudos.` ## Hadoop-Analyzer [[github](https://github.com/assertlab/hadoop-analyzer){:target="_blank"}] `Hadoop-Analyzer is a tool for analysing Hadoop execution logs. This tool relies on Apache Rumen to extract raw data from collected Hadoop logs and generate structured information about jobs execution, which are processed and shown as graphs.` ## PuzzlEdu (Software Educacional) [[Google Code Archive](https://code.google.com/archive/p/puzzledu/){:target="_blank"}] `O PuzzlEdu é um software educacional para apoiar o ensino/aprendizagem de lógica de programação no paradigma da orientação a objetos. Sua arquitetura foi proposta para ser executada na nuvem computacional, inicialmente da Google (App Engine). Foi construído utilizando Google Web Toolkit (GWT) com Java. Faz parte da dissertação de mestrado de <NAME>, da Universidade Federal de Pernambuco (UFPE).` <file_sep>/_posts/2016-03-17-assert-at-sbsi2016.md --- layout: post title: "ASSERT @ SBSI'2016" categories: Artigos tag: conferencia --- É com prazer que informamos que o artigo “_**Modelos de Negócios Inovadores na Era da Computação em Nuvem**_”, de autoria de <NAME>, <NAME>, <NAME> e <NAME> foi aceito para apresentação como minicurso e para publicação como capítulo de livro [XII Simpósio Brasileiro de Sistemas de Informação (SBSI’2016)](http://sbsi2016.ufsc.br/){:target="_blank"}. O resumo do artigo diz que: > Modelos de negócios passam uma imagem inicial de algo complexo e trabalhoso, visto por muitos como desnecessário. Os modelos de negócios se tornaram uma ferramenta fundamental para empreendedores. Com a evolução tecnológica, surgiram diversos negócios baseado na Internet, parte desses negócios estão ou são baseados em nuvem. Este minicurso apresenta uma série de conceitos, tais como: Computação em Nuvem, Lean Startup, Modelo de Negócio Canvas e uma série de estratégias que podem ajudar o empreendedor a criar um Produto Mínimo Viável (MVP) de seu negócio, de modo a maximizar as chances de sucesso em um novo negócio. <file_sep>/_posts/2015-11-25-algoritmos-de-deteccao-de-resistencia-a-drogas-do.md --- layout: post title: "Algoritmos de detecção de resistência a drogas do HIV e porquê devemos otimizá-los" categories: Pesquisa tag: doutorado --- A manipulação de dados biomoleculares pode apresentar características tratadas em computação como problemas de Big Data. Estes, são comumente armazenados em grandes bases de dados estruturadas ou não, apresentam certo grau de complexidade e as técnicas tradicionais de gerenciamento e processamento desses dados podem não ser muito úteis. Sobretudo para os casos em que existem inconsistências e a possibilidade de combinações imprevisíveis. Segundo Prajapati (2013), a caracterização enquanto Big Data vem dos requisitos de volume, velocidade e variedade. Essas características são encontradas na interpretação de resistência a drogas do Vírus da Imunodeficiência Humana (HIV). Existem diversos algoritmos que se propõem a fazer essa interpretação de resistência a drogas para o HIV. O [HIValg](https://hivdb.stanford.edu/hivalg/by-sequences/){:target="_blank"}, mantido pela Universidade de Stanford, permite que sequencias de código genético viral sejam avaliadas quanto a resistência a drogas pelos algoritmos HIVdb (da própria Standford), Rega e ANRS. Essa análise é feita a partir da manipulação de uma sequência de 9181 caracteres que é cortada e comparada com milhares de sequências de mesmo tamanho presentes nas bases de dados desses algoritmos. Partimos da premissa de que a performance desses algoritmos é satisfatória para a análise de apenas uma sequência genética por vez. No entanto, o mesmo não acontece de forma escalável para a análise de várias sequências ao mesmo tempo devido à natureza de alto consumo de recursos computacionais da realização de operações com grandes cadeias de caracteres e dado o contínuo aumento dessas bases de dados com de códigos genéticos do HIV. O objetivo de nossa pesquisa é otimizar o tempo e o consumo de recursos computacionais do algoritmo de interpretação de resistência a drogas Rega, utilizando técnicas de manipulação e gerenciamento de Big Data. Considerando como recursos computacionais a o consumo de tempo de processamento e memória RAM, observando para que não haja prejuízo da corretude das análises. Os benefício dessa otimização é uma provável redução de tempo e custo para a realização de pesquisas científicas sobre a resistência a drogas do HIV. Essa resistência tem aumentado o número de mortes por AIDS em 14% para pacientes em tratamento. O índice de resistência às drogas utilizadas como terapia inicial tem sido de 9% na Polônia (Parczewski, 2014), 11.7% na França (Frange, 2015), de até 64% na Libéria (Loubet, 2015) e de 35% do Brasil (De Souza, 2015). Um provável caminho para se chegar a esta otimização é a utilização de tecnologias como o Apache Hadoop, que é um framework para pesquisa e processamento de Big Data em clusters de servidores. A segunda versão deste framework deixa o gerenciamento de recursos e o apontamento de responsabilidades para ferramentas como YARN e Mesos. Outra ferramenta útil a este contexto é o Spark, que provê um engine de execução para o processamento de grandes quantidades de dados manipulados em memória de forma paralela utilizando diversas linguagens de programação. **Referências** * <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2015). High frequency of dolutegravir resistance in patients failing a raltegravir-containing salvage regimen. Journal of Antimicrobial Chemotherapy, 70(3), 926–929. <http://doi.org/10.1093/jac/dku439> * <NAME>., 1, 2, * <NAME>., 3, <NAME>., 4, 5, … <NAME>. (2015). HIV-1 subtype B-infected MSM may have driven the spread of transmitted resistant strains in France in 2007– 12: impact on susceptibility to first-line strategies ´, (February), 2084–2089. <http://doi.org/10.1093/jac/dkv049> * <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., … <NAME>. (2015). Prevalence of HIV-1 drug resistance among patients failing first-line ART in Monrovia, Liberia: a cross-sectional study. Journal of Antimicrobial Chemotherapy, (February), 1881–1884. <http://doi.org/10.1093/jac/dkv030> * <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., … <NAME>. (2014). Transmitted HIV drug resistance in antiretroviral-treatment-naive patients from Poland differs by transmission category and subtype. Journal of Antimicrobial Chemotherapy, 70(1), 233–242. <http://doi.org/10.1093/jac/dku372> * <NAME>. (2013). Big data analytics with R and Hadoop. Packt Publishing Ltd.<file_sep>/_posts/2012-10-15-whassup-dude-episodio-01.md --- layout: post title: "WHASSUP DUDE, Episódio 01" categories: Pesquisa tag: seminario --- ![]({{ BASE_PATH }}/images/2012-10-15-whassup-dude-episodio-01/figura1.png) Nesta sexta-feira, dia 19/10/2012 teremos de volta as apresentações dos trabalhos em andamento do grupo, mostrando os avanços obtidos ao longo do semestre, os impedimentos e problemas, riscos e maneira de mitigá-los e, claro, os próximos passos. É uma ótima oportunidade para ver pontos em comum, ou melhor, de convergência de interesses e mais ainda, oportunidades de trabalhos em parceria! Desta forma, convidamos a todos os interessados para aparecerem na sala A014 do Centro de Informática (UFPE) para assistir às seguintes apresentações, que tem como tema principal o artigo [The Emerging Web of Social Machines](http://arxiv.org/abs/1010.3045): **15:00, <NAME>**, "_[A framework to redefine the meaning of “Social”, online, once and for all](https://docs.google.com/open?id=0Bxt1VZoj3lGuM3FhUTJyMkhoUEk)_" > A ideia principal deste projeto de pesquisa é que qualquer um e qualquer coisa na atual Web pode ser representado por uma [Máquina Social](http://arxiv.org/abs/1010.3045) (do inglês, Social Machine). Seja uma pessoa, uma empresa, um dispositivo, um sensor… > > Neste contexto, estas entidades devem possuir toda informação necessária para poder consumir e prover comportamentos, que pode/devem ser manipulados por meio do que hoje vemos como serviços (destas&nbsp;[Máquinas Sociais](http://arxiv.org/abs/1010.3045)). > > Estes serviços podem ser acessados, ou consumidos, e manipulados por outras&nbsp;[Máquinas Sociais](http://arxiv.org/abs/1010.3045)&nbsp;(e seus serviços/comportamentos). Desta forma, temos uma relação entre estas entidades que deve ser composta dentro de um conjunto de regras (Entidades vs Serviços vs Regras/Leis). **16:00, <NAME>**, "_[Uma Arquitetura para a Auto-Implantação de Máquinas Sociais](https://docs.google.com/open?id=0Bxt1VZoj3lGuYnkyMENvTm5XTnM)_" > O processo de implantação de software é uma das fases mais importantes do processo de desenvolvimento do software. Esta processo consiste na alocação do software no ambiente de execução, onde muitas atividades estão envolvidas nesta fase, tais como: configuração, instalação, ativação, desativação, atualização de reconfiguração, e desinstalação. Este processo está propenso a erros devido à quantidade de atividades que devem ser executadas. Neste trabalho procura-se resolver problemas de implantação em ambientes Cloud, tais como: quantidade de parâmetros a serem definidos, ambientes heterogêneos e portabilidade (que se refere à implantação em múltiplos provedores de Cloud de forma simplificada, sem ter que executar procedimentos manuais e complexos). Para isto, este trabalho visa propor uma solução para facilitar o processo de implantação em múltiplas infraestruturas Clouds de forma transparente para o desenvolvedor e/ou usuário e sem precisar que estes tenham muito conhecimento de tecnologias específicas de diversos provedores.<file_sep>/_posts/2013-05-14-assert-no-ix-simposio-brasileiro-de-sistemas-de.md --- layout: post title: "ASSERT no IX Simpósio Brasileiro de Sistemas de Informação (SBSI'2013)" categories: Artigos tag: conferencia --- Três trabalhos foram aprovados no [IX&nbsp;Simpósio Brasileiro de Sistemas de Informação](http://sbsi2013.dce.ufpb.br/pt-br/start) (SBSI'2013). O primeiro foi o "**Br-SCMM: Modelo Brasileiro de Maturidade para Cidades Inteligentes**" de autoria de <NAME>,&nbsp;<NAME>,&nbsp;<NAME>, <NAME> e <NAME>&nbsp;Garcia. Resumo do artigo:&nbsp;_As Cidades Inteligentes estão emergindo frente às necessidades da nova&nbsp;sociedade&nbsp;da&nbsp;tecnologia&nbsp;e informação que surgiu neste&nbsp;século. Atualmente não existe&nbsp;um modelo&nbsp;de&nbsp;maturidade&nbsp;que&nbsp;possa&nbsp;medir o quão inteligente uma sociedade pode ser com base em indicadores sociais ou&nbsp;tecnológicos.&nbsp;Criar&nbsp;um &nbsp;modelo&nbsp;de&nbsp;maturidade pressupõe levantar requisitos, analisá-los e definir quais serão transformados em indicadores. Este trabalho visa apresentar o nível inicial de um Modelo de maturidade aplicado às cidades inteligentes._ Esse artigo é resultante dos estudos conduzidos por <NAME> no seu Doutorado e de&nbsp;<NAME> e&nbsp;<NAME> nos seus respectivos Mestrados. O segundo trabalho é o "**Desenvolvendo aplicativos peer-to-peer (p2p) no contexto de data storage para ambientes de Cloud Computing**", que é um minicurso de autoria de <NAME>, <NAME>, <NAME>, &nbsp;<NAME>&nbsp;Garcia, <NAME>,&nbsp;<NAME>, <NAME> Silva e <NAME>. Resumo do minicurso: _O objetivo deste minicurso é abordar de forma teórica, o conceito da computação em nuvens (características, modelos de implantação, serviços), em conjunto com as tecnologias relacionadas às redes peer-to-peer (características, arquitetura e funcionamento), exemplificando sua aplicabilidade à abordagem p2p-storage cloud no contexto de STaS (Storage a Service) e DaaS (Data as Service). O curso apresentará tecnologias relacionadas à construção de redes peer-to-peer, apresentando tendeˆncias e aplicações de mercado. Por fim, será apresentado um caso real de implementação de p2p-storage cloud na indústria, detalhando sua arquitetura, bem como, a resolução de requisitos não-funcionais e desafios encontrados na construção deste._ Este minicurso é resultantes dos esforços desenvolvidos por esta equipe nos projetos de pesquisa relacionados aos mestrados de&nbsp;<NAME>, <NAME>, <NAME>, <NAME> e Silva e do doutorado de&nbsp;<NAME> e Silva, bem como dos projetos de P&amp;D&amp;I conduzidos pelo grupo. O terceiro trabalho é o "**SafeMash: Uma Plataforma como Serviço para a Composição Segura e Colaborativa de Mashups**", aprovado no&nbsp;[VI Workshop de Teses e Dissertações em Sistemas de Informação](http://sbsi2013.dce.ufpb.br/pt-br/wtdsi/start) (que acontece dentro do SBSI), de autoria de&nbsp;<NAME> e <NAME> e é o resultado dos estudos para a construção da proposta de mestrado de <NAME>. Resumo do artigo:&nbsp;_Este artigo descreve o projeto SafeMash, uma plataforma como&nbsp;serviço que proporciona um ambiente para a construção segura e&nbsp;padronizada de Mashups. A plataforma oferece aos seus usuários recursos&nbsp;que promovem boas práticas, como tratamento das entradas, além de&nbsp;inspecionar a integridade das políticas de segurança estabelecidas pelas API&nbsp;de terceiros que atuam como provedores de conteúdo. Estes recursos são&nbsp;baseados nas abordagens de Segurança especificadas por organizações como&nbsp;OWASP, CSA, OpenMashup e OpenAjax Alliance._ O simpósio acontecerá no período de 22 a 24 de Maio de 2013 em João Pessoa.<file_sep>/_posts/2012-08-28-nasceu-o-assert.md --- layout: post title: "Nasceu o ASSERT!" categories: Pesquisa tag: assert --- No dia de ontem nasceu oficialmente o&nbsp;**ASSERT**, um grupo de&nbsp;_pesquisa + desenvolvimento + inovação_focado em resolver problemas reais da engenharia de software e sistemas. O ASSERT, acrônimo para&nbsp;**_Advanced System and Software Engineering Research Technologies Lab_**, já nasce grande, com um grupo comprometido com resultados&nbsp;**práticos**&nbsp;e**intensivos**&nbsp;em&nbsp;**pesquisa de qualidade**. O que pretendemos com a formação&nbsp;deste&nbsp;grupo é ajudar na criação de soluções para os principais problemas que o mercado, e as empresas, de TI (inicialmente .BR) enfrentam nas novas plataformas de mercado, negócios e tecnologias. Atualmente temos nos deparado com uma série de desafios voltados para enfrentar os&nbsp;[LSCITS](http://lscits.cs.bris.ac.uk/ "Large-scale complex IT systems"). De acordo com&nbsp;[Ian Sommerville](http://www.software-engin.com/ "I<NAME>"), LSCITS são sistemas organizacionais utilizados por um grande número, ou conjunto, de stakeholders com diferentes objetivos, visões, eventualmente culturas, e propósitos. Como bem disse Sommerville, essa escala e complexidade significa que eles podem apresentar comportamentos e desempenho inesperado e a evolução destes sistemas normalmente é difícil, custosa e de consequências quase imprevisíveis. No cenário atual de desenvolvimento e vivência de software (sim, vivência, todos vivemos imersos em software!) os LSCITS estão cada vez mais inseridos no dia-a-dia das pessoas comuns e não mais apenas nos grandes Centros de Tecnologia. Isso acarreta em uma série de aspectos técnico-sócio-econômicos que são fortemente influenciados por fatores humanos, sociais, organizacionais, tecnológicos, culturais e mercadológicos. Além disso, as plataformas de atuação, negociação, interação e desenvolvimento mudou para a rede, ou usando uma buzzword, para a Nuvem! A evolução para essa nova Web (conhecida por&nbsp;[Web 3.0](http://techcrunch.com/2008/08/01/welcome-to-web-30-now-your-other-computer-is-a-data-center/)) adiciona uma complexidade acidental a engenharia de software e sistemas antes nunca imaginado. Neste contexto, e inspirados pelos desafios discutidos por Sommerville em&nbsp;[Large-scale Complex it systems](http://dl.acm.org/citation.cfm?id=2209268), publicado na&nbsp;Communications of the ACM,&nbsp;Volume 55, Issue 7, páginas&nbsp;71-77&nbsp;em Julho de 2012, iniciamos nossos trabalhos, oficialmente, levantando os 11 principais desafios da nossa primeira agenda de trabalho: > _1. How can we design, develop, model and simulate the interactions between independent systems (SaaS or SaSM - Systems as&nbsp;[Social Machines](http://dx.doi.org/10.1109/COMPSAC.2011.12))?_ > > _2. How can we monitor coalitions or federations of [SaaS or SaSM] and what are the warning signs of problems?_ > > _3. How can [SaaS or SaSM] be designed to recover from failure?_ > > _4. How can we integrate socio-technical factors into [SaaS or SaSM] and software engineering methods?_ > > _5. To what extent can coalitions of [SaaS or SaSM] be self-managing?_ > > _6. How can we manage complex, dynamically changing [SaaS or SaSM] configurations? And intra and/or inter&nbsp;federations of&nbsp;[SaaS or SaSM]?_ > > _7. How can we support the agile engineering of coalitions or federations of [SaaS or SaSM]?_ > > _8. How should coalitions or federations of [SaaS or SaSM] be regulated and certified?_ > > _9. How can we do ‘probabilistic verification’ of [SaaS or SaSM]?_ > > _10. How should shared knowledge in a coalition federation of [SaaS or SaSM] be represented?_ > > _11. How can we prepare system and software engineers to build single,&nbsp;coalitions or federations of [SaaS or SaSM]?_ Por SaaS estamos falando de sistemas (que eventualmente envolvem SaaS, PaaS e IaaS) para plataformas de cloud computing. Tem interesse em responder alguma dessas perguntas? Tem as suas próprias perguntas? Então junte-se a nós!<file_sep>/_posts/2014-02-19-ensinando-engenharia-de-software-na-pratica-parte-i.md --- layout: post title: "Ensinando Engenharia de Software na Prática, Parte I" categories: Educacao tag: software engineering --- Dando continuidade no tema de _Educação em Engenharia de Software_ ou_ Como formar Capital Humano **EFICIENTE** em Produção de Software_, vem o segundo post da série. O primeiro você pode conferir aqui: [A biblioteca do Desenvolvedor de Software dos dias de hoje](https://viniciusgarcia.com/2014/02/14/a-biblioteca-do-desenvolvedor-de-software-dos-dias-de-hoje/). Eu sou professor de Engenharia de Software há alguns anos… especificamente no [Centro de Informática](http://www.cin.ufpe.br/) da [UFPE](http://www.ufpe.br/), desde o primeiro semestre de 2012. A primeira experiência pode ser vista neste [link](https://viniciusgarcia.com/courses/if977/). Aqui a ideia já veio de experiências prévias em disciplinas na UPE, no Mestrado Profissional do [CESAR.EDU](http://www.cesar.edu.br/newsite/) e de apoio a disciplinas da pós-graduação do CIn, em especial: - IN0953 – Engenharia de Software, junto com o prof. <NAME> - IN1163 – Tópicos Avançados em Desenvolvimento de Software de Código Aberto, conduzida com o pessoal do [RiSE](https://wordpress.dcc.ufba.br/riselabs/) A experiência nestas disciplinas foi plenamente prática, com um esforço na implantação de técnicas baseadas em PBL ([_Problem-Based Learning_](http://en.wikipedia.org/wiki/Problem-based_learning)). Na primeira experiência de ES no curso de Sistemas de Informação, a intenção foi a mesma, com foco na resolução de problemas ao invés de _um monte_ de slides com teorias, puramente. Todos os tópicos teóricos do curso giravam em torno da execução de um projeto em equipe que devia ser desenvolvido em iterações (quatro para ser mais exato). Para começar, era feito uma imersão nos conceitos básicos e fundamentais da Engenharia de Software, mais especificamente no que é Software, o que é Engenharia, como se dá a Engenharia de algo tão complexo e diferente que é o Software e tudo o que cerca esse processo produtivo. Uma das perguntas que faço sempre aos alunos é: _como eu defino o preço do meu software?_ Em seguida, uma discussão acerca das Fábricas de Software, desde as clássicas até os modelos mais “diversos” existentes hoje… como se dão, o que são, por que são… qual o princípio e necessidade de existir uma comunidade ao redor desse ciclo de desenvolvimento, onde entra o software livre… Claro, a leitura e discussão do clássico [The Cathedral and the Bazaar](http://catb.org/~esr/writings/cathedral-bazaar/cathedral-bazaar/) é obrigatória! A definição do projeto, contra a minha real vontade, sempre ficou a cargo dos alunos. Como era difícil conseguir projetos reais ou mais próximos do mundo real (por uma série de questões, mas a principal é falta de tempo do professor – entidade única envolvida na disciplina, uma vez que os monitores são apoio e normalmente são alunos que acabaram de cursar a disciplina) a abordagem era estimular a descoberta de oportunidades de negócios, aproveitando todo o caráter inovador e empreendedor que o CIn tem em seu DNA. Tivemos excelentes resultados e resultados nem tão significativos… mas acredito que no final o saldo é positivo. A partir da segunda rodada da disciplina, ou seja, de 2012.2 resolvemos promover duas integrações, digamos assim. A primeira foi **horizontal** e teve por objetivo tratar o currículo de Engenharia de Software que acreditamos ser o ideal no CIn. Então por uma iniciativa dos professores de ES dos três cursos de graduação do centro (Ciência da Computação, Engenharia da Computação e Sistemas de Informação) tentamos encontrar o que seria o _core_ de ES e compartilhamos tudo referente a este núcleo. A metodologia, critérios, artefatos e _templates_, políticas e métodos de avaliações, enfim, buscamos montar um framework para somente acrescentarmos o que seria específico e necessário em cada curso. Daí nasceu essa primeira integração, disponível neste site: [Engenharia de Software e Sistemas](https://sites.google.com/a/cin.ufpe.br/if682/). A segunda integração ocorreu de maneira **vertical**, ou seja, dentro do curso de Sistemas de Informação e buscamos uniformizar o conhecimento, a metodologia, os tópicos cobertos e até mesmo os projetos que deveriam ser executados nas disciplinas intimamente relacionadas: - [IF977 – Engenharia de Software](http://www.cin.ufpe.br/~if977) - [IF976 – Banco de Dados](http://www.cin.ufpe.br/~if976) - IF979 – Planejamento e Gerenciamento de Projetos Até o presente momento estas três disciplinas tem rodado ainda desta forma. Não ocorreram mais conversas ou atualizações horizontais entre as disciplinas de Engenharia de Software. Após estes 4 semestres ministrando a disciplina e vendo as deficiências deste modelo, pontos de melhoria e a carência do [Arranjo Produtivo Local](http://www.portodigital.org/), num primeiro momento, e a carência nacional e mão de obra em produção de software, me senti motivado a fazer uma reengenharia desta disciplina e é esta reengenharia que eu vou ir apresentando aos poucos aqui. Para começar, resolvi me inspirar no curso [CS 169 Software Engineering](https://sites.google.com/site/ucbsaas/) da [UC Berkeley](http://www.berkeley.edu/index.html). O curso tem um formato também já focado na prática, que gira em torno do uso das próprias metodologias ágeis na condução do curso em si bem como da aplicação de conceitos e tópicos da ES em um projeto executado por pequenos times formados pelos alunos. Além disso, ele está plenamente de acordo com as novas plataformas de software e serviços, utiliza conceitos e recursos de _Software as a Service_ e [_Cloud Computing_](http://www.nist.gov/itl/cloud/) e preocupações com o projeto, atenção aos objetivos de negócios, entrega de [MVP](http://en.wikipedia.org/wiki/Minimum_viable_product) e exercitar mais uma vez a prática da programação, que no caso do curso de Sistemas da Informação é um pouco deficiente, na minha humilde opinião. O cerne do curso vai continuar sendo o [Software Engineering Body of Knowledge (SWEBOK)](http://www.computer.org/portal/web/swebok) mas as novas tecnologias, metodologias e eventualmente ferramentas vão fazer parte do convívio dos alunos no curso. A intenção principal é trabalhar a lacuna existente entre o que a **academia acredita** que deveriam ser cobertos em cursos de ES e o que a **indústria quer** ver nos alunos formados por estes cursos. As empresas não querem que as universidades se transformem em escolas profissionalizantes que ensinam tecnologias, ferramentas, linguagens ou _frameworks_ específicos; elas querem habilidades que transcendem estas “_coisas_“, incluindo lidar com código legado e trabalhar em equipe para atender a um cliente que não fala o “_computês_“. Nos próximos posts vou apresentando este novo projeto que espero servir de estímulo para mais reengenharia em disciplinas de Engenharia de Software em outras instituições. *Artigo originalmente publicado por [<NAME>](http://viniciusgarcia.me/education/ensinando-engenharia-de-software-na-pratica-parte-i/)*<file_sep>/_posts/2019-01-14-oito-tendencias-para-empreendedores-em-2019.md --- layout: post title: "Oito tendências para empreendedores em 2019" categories: Empreendedorismo tag: - startup - innovation - mercado - empreendedorismo - inovação - empreender - lean - sebrae - pme - abstartups --- Segundo informações da **Associação Brasileira de Startups (Abstartups)**, instituição sem fins lucrativos que mapeia startups do país, o Brasil fechou o ano de 2018 com **10 mil startups em atividade**. Todo ano surgem novas formas de interagir com os clientes e entregar novos serviços e valores, o que cada vez mais dá origem às mais diversas possibilidades de novos negócios e expansão de mercado. Para ajudar os empreendedores a entenderam as mudanças, o Sebrae/PR preparou o Caderno de tendências 2018/2019, analisando o mercado atual e com ênfase nas PMEs. Confira oito dessas tendências e empresas inseridas nesse contexto. ##1. Cliente no controle O jovem consumidor contemporâneo tem visto a publicidade on-line como uma inconveniência, preferindo ter o controle daquilo que consome no ambiente online. Por isso, compreender esse público, direcionando a criação de conteúdos ou ações a ele, tem se tornado essencial para o êxito de qualquer negócio. Novas formas de anúncio, de se comunicar e interagir de forma mais efetiva com seus potenciais clientes é fundamental.Novas abordagens como big data analytics para o setor de comunicação e marketing, ajuda a monitorar seus concorrentes em diferentes vertentes. ##2. Consumidores investigativos Estudos recentes indicam que 70% dos consumidores procuram saber mais sobre as empresas que consomem. Se as organizações não fornecem dados, certamente o consumidor irá procurar tais informações na internet. Para ajudar nessa busca, muitas startups criaram tecnologias capazes de melhorar na pesquisa por informações verdadeiras sobre as marcas no ambiente online. ##3. Cultura de aprendizagem As diversas mudanças no século XXI também resultaram no surgimento de uma preocupação quanto à construção de uma cultura de aprendizagem, inclusive no campo corporativo. Pesquisas apontam que empresas que exercem uma mentalidade de crescimento ao estimularem a educação e a capacitação de seus funcionários podem se tornar três vezes mais lucrativas. ##4. Compradores imediatistas Os tipos de serviço criados para facilitar e agilizar a entrega de produtos e serviços para o consumidor fizeram com que eles se acostumassem ao ritmo imediato e à "pronta-entrega". Já habituados ao mundo digital, os clientes estão se tornando cada vez mais impacientes, fazendo com que empresas surgissem para responder a essa demanda. ##5. Consumo on-the-go Hoje, o consumidor tem buscado otimizar seu tempo, por meio da utilização aplicativos nas mais diversas ocasiões, desde o agendamento de entrega das compras de supermercado a domicílio à marcação de consultas online. Trazer mais praticidade e conveniência aos seus consumidores, oferecendo uma variedade de produtos de serviços bem como gerindo melhor os horários e as formas de entrega, por exemplo, da forma que for mais conveniente para o cliente, tem trazido ganhos e destaque. ##6. Caça ao desconto Encontrar os melhores preços para itens de desejo é o que o consumidor mais procura na internet. Desde a recessão de 2008, que impactou a economia mundial, as pessoas têm buscado por ofertas baseadas em preços baixos, refletindo diretamente no crescimento de negócios baseados em descontos. ##7. Espaço integrados e sociais O mercado autônomo tem se desenvolvido em todo mundo. Por isso, a demanda por espaços de coworking, e de convivência em condomínios residenciais, também devem aumentar, assim como, a flexibilização dos espaços de trabalho para colaboradores. ##8. Cocriação Seja por meio de recursos físicos ou digitais, as marcas agora podem tornar suas relações com os clientes cada vez mais íntimas, informais e, consequentemente, reveladoras. Conhecer o seu cliente e saber com qual a frequência que ele vai até a sua loja, são informações importantes para melhorar a sua experiência de compra. Artigo originalmente publicado em [Kubernetes 1.10: Estabilizando armazenamento, segurança e rede](http://viniciusgarcia.me/development/kubernetes-1-10/) :: [viniciusgarcia.me](http://viniciusgarcia.me/) <file_sep>/_posts/2014-01-29-aquecendo-os-motores.md --- layout: post title: "Uma abordagem para o balanceamento de carga de servidores de busca em sistemas de armazenamento de dados P2P JXTA" categories: Pesquisa tag: doutorado --- antes de iniciarmos a principal discussão que motiva este blog, precisamos entender quais as tecnologias, componentes e coisas que apoiarão este trabalho. o primeiro deles inicia-se com algo não tão novo conhecido como [redes peer-to-peer (p2p)](http://bit.ly/1bGQGDD){:target="_blank"} e outras coisas mais… napster, kazaa, torrent, gnutella, … todos possuem um modelo de comunicação em comum, alguns totalmente puros e outros nem tanto [hibridos], alguns se deram bem por um tempo, outros, continuam até hoje em pleno funcionamento. para se criar estas redes no braço, existem frameworks que abstraem a implementação baixo nível, conhecidos como p2p overlay networks. em java, no início do milênio, foi criado um desses de nome jxta, sob a orientação de dois caras: [bill jow e mark clark](http://bit.ly/1awHQJ1){:target="_blank"}. outros frameworks para desenvolver aplicações em redes de p2p e um comparativo sob as duas categorias: estruturadas e não-estruturadas podem ser vistas [aqui](http://bit.ly/1iDsFWC){:target="_blank"}. então o objetivo inicial deste blog é apresentar uma proposta onde por meio da utilização de computadores conectados, sem um servidor, em um modelo totalmente descentralizado, seja possível doar espaço ocioso para alguém armazenar arquivos. até agora isso não é novidade alguma, tem gente que doa o tempo ocioso do seu computador para curar doenças, estudar o aquecimento global, o caso do [BOINC](http://bit.ly/1iDrMgB){:target="_blank"}. o nome desta proposta: an architectural proposal for a decentralized p2p cloud storage framework. ok, mas existem diversas empresas vendendo este produto: [cloud storage](http://bit.ly/KqZ58I){:target="_blank"}, aqui tem as 10 melhores, mas, quem garante que seus dados estão seguros lá? [vale lembrar que](http://bit.ly/1hofqZs){:target="_blank"} você pode não ser o dono dos seus dados, mesmo que você cancele o serviço. caiu na net!!! pra finalizar, tem uns caras há algum tempo [fazendo p2p cloud storage](http://bit.ly/1exRAFU){:target="_blank"}, uns tempos atrás no modelo p2p, depois, em modo mais centralizado. por que eles desistiram da primeira opção, vamos verificar mais lá na frente. fora eles, [quem brinca com essa abordagem hoje](http://bit.ly/19V9QsN){:target="_blank"}, p2p híbrido, com alta disponibilidade e baixo consumo de recursos. isso foi o esquente... Texto escrito por [<NAME>](https://andersonfonseka.blogspot.com.br/){:target="_blank"}.<file_sep>/_posts/2013-08-30-defesa-de-dissertacao-de-mestrado-n-1324.md --- layout: post title: "Defesa de Dissertação de Mestrado Nº 1.324" categories: Defesa tag: mestrado --- ## Pós-Graduação em Ciência da Computação – UFPE ### Defesa de Dissertação de Mestrado Nº 1.324 * Aluno: <NAME> * Orientador: Prof. <NAME> * Co-orientador: Prof <NAME> (DIMAP/UFRN) * Título: DYMOS: Uma abordagem para suporte a variabilidades dinâmicas em Linhas de Produto de Software Orientado a Serviços e Sensível ao Contexto * Data: 30/08/2013 * Hora/Local: 13h – Sala D226 Banca Examinadora: * Prof. <NAME> &nbsp;(UFPE / CIn) * Profa. <NAME> (UFC / Departamento de Computação) * Prof. <NAME> &nbsp;(UFPE / CIn) RESUMO: _É notório o surgimento de ambientes cada vez mais dinâmicos, exigindo sistemas mais flexíveis, de forma que componentes possam ser plugados ou desplugados durante o seu ciclo de vida, inclusive em tempo de execução. Para atender estes requisitos, é necessário que decisões sobre possíveis adaptações e variações do produto possam ser tomadas em tempo de execução. Sistemas Sensíveis ao Contexto (SSC’s) atendem a esse propósito, sendo capazes de adaptar-se em tempo de execução de acordo com mudanças no ambiente, obedecendo um conjunto de regras._ _Quando técnicas de Linha de Produto de Software (LPS) são aplicadas no desenvolvimento de sistemas adaptativos, tais decisões podem resultar na configuração de um novo produto. Em uma LPS tradicional, um produto é derivado de acordo com sua configuração, que ocorre na fase de design e consiste na seleção de features que irão compor o produto, remoção das features que não farão parte do produto e ligação dos pontos de variação._ _Linhas de Produto de Software Dinâmicas (LPSD’s) extendem o conceito convencional de Linhas de Produto de Software abordando aspectos dinâmicos, provendo uma abordagem para tratar variabilidades que precisam ser manipuladas em tempo de execução._ _Quando alinhamos paradígmas como Sistemas Sensíveis ao Contexto, Arquitetura Orientada a Serviços (AOS) e LPS, podemos enfrentar alguns desafios. O sistema derivado de uma LPS é composto por features e pontos de variação. Considerando que o modelo de AOS segue o padrão arquitetural Cliente-Servidor, podemos ter um cenário em que as features que compõem o produto no lado cliente podem endereçar uma composição de serviços. Dessa forma, os pontos de variação podem sofrer variabilidades de acordo com mudanças no contexto, exigindo a execução de reconfigurações nos serviços de modo a atender tais variabilidades. As abordagens propostas atualmente não oferecem um suporte para esse tipo de problema ou são inscipiente, estando em fases iniciais de pesquisa._ _Neste trabalho é apresentado um estudo sobre variabilidades dinâmicas em Linha de Produto de Software Orientado a Serviços e Sensível ao Contexto, investigando especificamente situações quando features que endereçam um ou mais serviços são reconfiguradas, requerendo reconfigurações no lado servidor._ Palavras-chave: sistemas adaptativos, arquitetura orientada a serviços, linhas de produto de software dinâmicas, reconfiguração dinâmica, variabilidade dinâmica<file_sep>/pesquisa.md --- layout: page title: Pesquisa tagline: Tópicos de pesquisa permalink: /pesquisa.html --- ## Lista de Targets A lista de periódicos e conferências de interesse do grupo estão listadas neste [link](https://docs.google.com/spreadsheets/d/117YhIc-GKw8Cv4lBT2WupQskvKbqn4gdmfHfGB9er_A/edit#gid=0){:target="_blank"} ## Principais tópicos de pesquisa #### Site Reliability Engineering `Continuous Integration, Continuous Delivery, Containerization, Virtualization, DevOps, Container Orchestration` #### Cloud Computing `Software as a Service (SaaS), Platform as a Service (PaaS), Infrastructure as a Service (IaaS), Everything as a Service (XaaS), Billing and Monitoring, Storage as a Service (STaaS), Open Data` #### Social Machines `Web-based Information System, Federation of Social Machines, Data Privacy Policy, People as a Social Machines` #### Software Architecture `Service Oriented Architecture, Dynamic Architectures, Architecture Description Languages (ADL), Design Patterns, Microservices, Serverless, Function as a Service (FaaS), Sky Computing` #### Smart Cities and Internet of Things `Smart Citizen, Smart City Maturity Model, Smart City Architecture Framework, Internet of Things (IoT)` #### Software Language Engineering `Domain Specific Languages (DSL), Domain-Specific Modeling Languages (DSML), Generative Programming, Model Driven Engineering` #### Software Evolution `Software Test, Software Maintenance, Software Evolution, technical Debt, Software Configuration` #### Software Product Lines `Variability Management, Variability Quality Assurance, Dynamic SPL, Context-Sensitive SPL, Service-Oriented SPL, Traceability between features and other artifacts` #### Software, Systems and Information Safety and Security `Security, Software Safety, Information security, Cybersecurity, Phishing, Privacy` #### Data Science and Learning Analytics `Learning Analytics (LA), Data Science, Data-driven organizations, Data Strategies` <file_sep>/_posts/2014-02-14-a-biblioteca-do-desenvolvedor-de-software-dos-dias-de-hoje.md --- layout: post title: "A biblioteca do Desenvolvedor de Software dos dias de hoje" categories: Educacao tag: software engineering --- Desde que comecei a me envolver com a Engenharia de Software, sempre foi difícil definir ou classificar os “_skills_” necessários a um engenheiro de software. E esse tipo de discussão sempre me levava para a área de saúde, mais especificamente para a medicina. Afinal de contas, são tantas especializações, tantos “_microuniversos_” que se assemelhava muito ao que vemos na Engenharia de Software (ES). A ES é um bicho estranho, muito estranho. Primeiramente por conta do produto principal gerado por ela: o tal do software, conhecido por alguns por SISTEMA. É… esse mesmo sistema que “_resolve_” sair do “_ar_” justamente quando chega a sua vez de ser atendido no banco ou logo depois de passar longos 47 minutos no telefone esperando pela atendente da sua empresa de telefonia móvel. Mas como assim “_saiu do ar_“? Desde quando ele voa? Software é um produto **intangível** e muito difícil de **mensurar** o valor, ou melhor, de _precificar_ e de calcular o **retorno no investimento** da sua construção, manutenção e evolução. Por ser intangível, ele também tende a viver mais do que os que o construíram. Outro ponto de muito investimento, por parte tanto da academia quanto da indústria é justamente a construção do software. Alguns pregam que a depender do “tipo” do software, as técnicas, ferramentas, processos e papéis envolvidos mudam. Por tipo quero dizer: software empacotado, o tradicional, também conhecido por _shrink-wrapped software_; software como serviço (_SaaS_); sistemas críticos; de tempo real; larga escala; sistemas operacionais; aplicativos móveis; _mainframe_; entre tantos outros. A quantidade de disciplinas envolvidas na ES é muito grande e vai desde disciplinas puramente técnicas da Ciência da Computação até questões mais humanas, envolvendo Psicologia, passando por questões legais e tributárias. O mundo é software hoje em dia e tudo é software! Absolutamente tudo! Conforme disse <NAME>: [Program or Be Programmed](http://youtu.be/kgicuytCkoY). Com este cenário bastante diversificado de emoções, desafios, ações, papéis e pessoas envolvidas, eu comecei a pensar no que seria um conjunto de perfis que poderiam ser trabalhados por alguém que quer ser um bom profissional neste mundo da Engenharia de Software, que entenda das peculiaridades que envolvem a construção do software (ou serviço, ou aplicativo, ou seja lá o que for, desde que seja programável). Já via que existem algumas listas e partilho de boa parte das opiniões delas. A que mais gostei foi a de [<NAME>](http://stevewedig.com/2014/02/03/software-developers-reading-list/), que eu utilizei como inspiração e base para sugerir a minha. Também separei, inicialmente, por tópicos que acho importantes e dentro deles sugeri alguns livros que podem ajudar neste entendimento. Adicionei às sugestões de Steve, as versões em português ou versões “alternativas” para os tópicos propostos. Além disso, trouxe alguns livros que tratam de tecnologias específicas, mas que as técnicas abordadas neles, podem ser levadas para outras tecnologias Eu dividiria a disciplina de desenvolvimento de software em verticais, que seriam: - Primeiros Passos na Programação de Software (_First Steps in Software Programming_) - [Code Complete](http://amzn.to/1kRMKuk) ou [Um Guia Prático para Construção de Software](http://www.buscape.com.br/code-complete-um-guia-pratico-para-a-construcao-de-software-steve-mcconnell-8536305045.html?pos=2#precos) - [Structure and Interpretation of Computer Programs](http://amzn.to/1cO2iVR) - [Teach Yourself Programming in 10 years](http://norvig.com/21-days.html) - [The Pragmatic Programmer](http://amzn.com/020161622X) ou [O Programador Pragmático](http://www.ciadoslivros.com.br/programador-pragmatico-o-p379143/) - Técnicas Fundamentais de Criação de Software (_Core Software Creation Techniques_) - TDD: [Growing Object-Oriented Software, Guided By Tests](http://amzn.to/1mwt5hE) ou [TDD: Desenvolvimento Guiado por Testes](https://www.goodreads.com/book/show/29742940-tdd-desenvolvimento-guiado-por-testes) - Refactoring: [Refactoring](http://amzn.to/1e9iAMM) ou [Refatoração: Aperfeiçoando o Projeto de Código Existente](https://indicalivros.com/pdf/refatoracao-aperfeicoando-o-projeto-de-codigo-existente-martin-fowler) - BDD: [The Cucumber Book: Behaviour-Driven Development for Testers and Developers * ](http://amzn.com/1934356808) - Conceitos de Projeto de Software (_Software Design Concepts_) - Code Design: [Clean Code](http://amzn.to/1mwsAUU) ou [O Codificador Limpo](http://www.livrariacultura.com.br/scripts/resenha/resenha.asp?nitem=29802936) - Structural Design: [Design Patterns](http://amzn.com/0201633612) ou [Padrões de Projeto](http://www.livrariasaraiva.com.br/produto/436822?PAC_ID=25371) - Analysis Design: [Applying UML and Patterns](http://amzn.com/0131489062) ou [Utilizando UML e Padrões](http://www.buscape.com.br/utilizando-uml-e-padroes-craig-larman-8560031529) - Component Design: [Object Design: Roles, Responsibilities, and Collaborations](http://amzn.to/1mwsH2P) - Service Design: [Service Design Patterns](http://amzn.com/032154420X) - Domain Design: [Domain Driven Design](http://amzn.to/1bEZApL) ou [Domain Driven Design (pt-br)](http://www.altabooks.com.br/domain-drive-design-atacando-as-complexidades-no-coracao-do-software.html) - System Design: [Software Systems Architecture](http://amzn.to/1f0S8pS) ou [Software Architecture](http://www.softwarearchitecturebook.com/) - System Design (Availability): [Release It!](http://amzn.to/1e82joE) - System Design (Security): [Foundations of Security](http://amzn.to/1hbp8et) - Legacy Code: [Working Effectively With Legacy Code](http://amzn.to/19IQKZd) ou [Trabalho Eficaz com Código Legado](http://www.grupoa.com.br/livros/engenharia-de-software-e-metodos-ageis/trabalho-eficaz-com-codigo-legado/9788582600320) - User Experience Design: [Designing Interfaces](http://amzn.to/1bepv3D) - Conceitos de Engenharia de Software (_Software Engineering Concepts_) - [Object Oriented Software Engineering](http://amzn.com/0201544350) - [Engineering Long-Lasting Software](https://www.amazon.com/Engineering-Long-Lasting-Software-Approach-Computing/dp/0984881212/ref=sr_1_1?ie=UTF8&qid=1505915363&sr=8-1&keywords=Engineering+Long-Lasting+Software) - [Software Reuse](http://amzn.com/0201924765) - [Software Engineering](http://amzn.com/0137035152) (clássico) ou [Engenharia de Software](https://www.saraiva.com.br/engenharia-de-software-9-ed-2011-3648635.html) - [Software Engineering: Theory and Practice](http://amzn.com/0136061699) – ou [Engenharia de Software – Teoria e Prática](http://wps.prenhall.com/br_pfleeger_engsoftware_2/) - Conceitos de Entrega de Software (_Software Delivery Concepts_) - Lean Systems: [Leading Lean Software Development](http://amzn.to/1jiPwHc) ou [Implementando o Desenvolvimento Lean de Software](http://www.grupoa.com.br/livros/engenharia-de-software-e-metodos-ageis/implementando-o-desenvolvimento-lean-de-software/9788577807567) - Agile Team Organization: [Essential Scrum](http://amzn.to/1aEY0U2), [The Agile Samurai](http://amzn.com/B00AYQNR5K), [The Scrum Field Guide](http://amzn.com/0321554159) ou [Desenvolvimento de Software com Scrum](https://www.skoob.com.br/desenvolvimento-de-software-com-scrum-185738ed207233.html) - Requirements Design: [User Stories Applied](http://amzn.to/1dUtfvC) - Testing Products & Services: [Agile Testing](http://amzn.to/1bF22g2) ou [Lessons Learned in Software Testing](http://amzn.com/0471081124) - Continuous Integration: [Continuous Integration](http://amzn.com/0321336380) - Continuous Delivery: [Continuous Delivery](http://amzn.to/1bepwoh), [Lean Enterprise](http://amzn.com/1449368425) ou [A Entrega Contínua](http://www.grupoa.com.br/livros/engenharia-de-software-e-metodos-ageis/entrega-continua/9788582601037) - Customer Development: [Lean Startup](http://amzn.to/LxoXQ8), [Lean Software Development](http://amzn.com/0321150783) ou [A Startup Enxuta](https://www.amazon.com/Startup-Enxuta-Em-Portuguese-Brasil/dp/8581780040) Os livros com * são de alguma tecnologia específica, mas que as técnicas podem ser utilizadas em qualquer linguagem, por exemplo. Alguma sugestão para complementar a lista? _Artigo originalmente publicado por [<NAME>](http://viniciusgarcia.me/education/a-biblioteca-do-desenvolvedor-de-software-dos-dias-de-hoje/)_<file_sep>/_posts/2015-12-24-uma-meta-analise-sobre-ameacas-a-seguranca-no.md --- layout: post title: "Uma Meta-Análise sobre Ameaças à Segurança no Ecossistema Web" categories: Pesquisa tag: mestrado --- Não há dúvidas que nos dias atuais a Web se consagra como um dos mecanismos computacionais mais preciosos para a humanidade. Seus usuários, através de um computador pessoal, smartphone ou smart tv, que uma vez munido de um navegador Web, é capaz de consumir serviços como e-mail, e-commerce, redes sociais e transações online, seja para fins de lazer ou negócios, beneficiando pessoas ou organizações, caracterizando assim o ecossistema Web. Um ecossistema por definição padrão é tido como um conjunto que designa a observação do comportamento e interação entre diferentes indivíduos em um mesmo ambiente. A interação entre o conjunto de usuários, navegadores Web, redes sociais, dispositivos, aplicações e demais serviços na Web é o que definimos como o ecossistema Web, conforme a Figura 1. ![]({{ BASE_PATH }}/images/2015-12-24-uma-meta-analise-sobre-ameacas-a-seguranca-no/figura1.png) Contudo, apesar dos benefícios, podemos afirmar que esse ecossistema é um ambiente hostil diante aos casos cada vez mais frequentes de ataques que resultam na violação dos dados sensíveis de seus usuários ou serviços [1]. Nos repositórios acadêmicos, há exatamente 21 anos, desde o início de 1994 até final de 2014, nosso estudo identificou artigos que abordam sobre essa problemática. O que podemos perceber é a notória necessidade de catalogar esses incidentes no intuito de inventariar os comportamentos relacionados, facilitando na identificação e prevenção de vulnerabilidades decorrentes. Um bom exemplo são organizações como MITRE e OWASP que mantêm periodicamente catálogos destas ameaças, auxiliando a manutenção e desenvolvimento de aplicações projetadas para o ecossistema Web [2] [3]. Diante disso, a problemática abordada por este estudo pretende considerar violação de dados sensíveis oriundas de aplicações ou serviços Web, bem como mecanismos como o navegador Web, além de aspectos relacionados ao comportamento humano nesse ecossistema, a exemplo da engenharia social. Segundo [4], um dado sensível é um ativo do usuário, pois é uma informação que tem valor agregado para o mesmo. Além disso, o acesso e armazenamento desse dado devem ser restritos ao seu proprietário. Uma vez que o dado sensível seja visualizado, modificado ou indisponível, sem a devida autorização do seu proprietário, é reproduzida uma violação. Este estudo tem como objetivo identificar os ataques mais emergentes na literatura que estão relacionados à violação de dados sensíveis no ecossistema Web. A meta-análise está estruturada da seguinte forma: (i) Descrevemos a contextualização da problemática, onde apresentamos conceitos, atores, riscos e impactos sobre os dados sensíveis. (ii) Desenvolvemos uma metodologia baseada em três etapas que propõe uma análise dos principais ataques no contexto do ecossistema Web. Essa análise visa responder alguns questionamos acerca da problemática do estudo, tendo como base para as respostas as publicações da literatura. (iii) Identificamos estudos correlatos na literatura e descrevemos nossos pontos chaves que diferem dos demais. E por fim, (IV) descrevemos nossas conclusões e trabalhos futuros a serem explorados durante a evolução deste estudo. 1. Secunia, 2014. “Secunia Vulnerability Review”. Disponível em: <http://goo.gl/6nqBAQ> 2. MITRE, 2014. “Common Weakness Enumeration”. Disponível em: <http://cwe.mitre.org/> 3. OWASP, 2013. “Top Ten 2013”. Disponível em: <https://goo.gl/qRgSkl> 4. Allen, 2001. “The CERT guide to system and network security practices Series in software engineering” Addison-Wesley.<file_sep>/index.md --- # # Here you can change the text shown in the Home page before the Latest Posts section. # # Edit cayman-blog's home layout in _layouts instead if you wanna make some changes # See: https://jekyllrb.com/docs/themes/#overriding-theme-defaults # layout: home --- O **ASSERT Lab** é um grupo de pesquisa que tem por objetivo investigar e desenvolver soluções, técnicas e processos para melhorar os níveis de produtividade e qualidade em ambientes de TI de larga escala e complexidade sem comprometer os fatores de qualidade de software e da vida humana envolvida. Somos um grupo multi-institucional e distribuído formado por pesquiadores e diversos centros e instituições de pesquisa e desenvolvimento. Somos parte do [**Instituto Nacional** de Ciência e Tecnologia **para Engenharia de Software** (INES)](http://www.ines.org.br/){:target="_blank"}. <file_sep>/_posts/2018-03-29-kubernetes-1-10.md --- layout: post title: "Kubernetes 1.10: Estabilizando armazenamento, segurança e rede" categories: Desenvolvimento tag: - Container - Engenharia de Software - Desenvolvimento - boas práticas - DevOps - Kubernetes - Pod --- Foi anunciado no dia 26 de Março de 2018 o [lançamento do Kubernetes 1.10](http://blog.kubernetes.io/2018/03/kubernetes-1.10-stabilizing-storage-security-networking.html), apenas algumas semanas desde sua [graduação da incubação da CNCF](https://cloudplatform.googleblog.com/2018/03/from-open-source-to-sustainable-success-the-Kubernetes-graduation-story.html). Como membro fundador da [CNCF](https://www.cncf.io/) e um dos principais autores do Kubernetes, o Google continua a ser o maior contribuidor do projeto, bem como revisor de contribuições e mentor para membros da comunidade. Esta nova versão estabiliza os recursos em três áreas principais, incluindo armazenamento, segurança e rede. Como novidades interessantes nesta versão podemos citar a introdução de provedores de credenciais kubectl externos (alfa), a capacidade de alternar o serviço DNS para CoreDNS no tempo de instalação (beta) e a transformação da [*Container Storage Interface* (CSI)](https://github.com/container-storage-interface/spec/blob/master/spec.md) e volumes locais persistentes para **beta**. ## Container storage plugins Esta é uma versão impactante para o [*Storage Special Interest Group* (SIG)(https://github.com/kubernetes/community/tree/master/sig-storage), marcando o ponto culminante de seu trabalho em vários recursos. A [implementação Kubernetes](https://github.com/kubernetes/features/issues/178) da [*Container Storage Interface* (CSI)](https://kubernetes.io/docs/concepts/storage/volumes/#csi) passa para beta nesta versão: instalar novos plug-ins de volume agora é tão fácil quanto implantar um pod. Isso, por sua vez, permite que provedores de armazenamento terceirizados desenvolvam suas soluções independentemente do código do Kubernetes. Isso colabora de maneira fundamental para a extensibilidade no ecossistema do Kubernetes. O [gerenciamento de armazenamento local durável (não compartilhado)](https://github.com/kubernetes/features/issues/121) também progrediu para beta nesta versão, tornando o armazenamento anexado localmente (não conectado à rede) disponível como uma fonte de volume persistente. Isso significa um maior desempenho e menor custo para sistemas de arquivos distribuídos e bancos de dados. [<NAME>](https://github.com/saad-ali) (presidente da SIG-Storage) é um dos principais autores da especificação CSI e da implementação da especificação pelo Kubernetes. _"O Kubernetes fornece um poderoso [sistema de plugins de volume](https://kubernetes.io/docs/concepts/storage/volumes/#types-of-volumes) que facilita o consumo de diferentes tipos de armazenamento em block e file"_, explica ele (em tradução livre). "No entanto, adicionar suporte a novos plugins de volume foi um desafio. Com a adoção da [*Container Storage Interface*](https://github.com/container-storage-interface/spec/blob/master/spec.md), a camada de volume do Kubernetes está se tornando **verdadeiramente extensível**. "Usuários Kubernetes podem agora escrever e implementar plugins expondo novos sistemas de armazenamento na plataforma sem precisar tocar no código dela. Em última análise, isso dará aos usuários do Kubernetes e do [Kubernetes Engine](https://cloud.google.com/kubernetes-engine) mais opções para armazenamento" (em tradução livre). Esta versão também inclui muitas atualizações para Volumes Persistentes. Agora, o Kubernetes pode impedir [automaticamente a exclusão de *Persistent Volume Claims*](https://github.com/kubernetes/features/issues/498) que estão sendo usadas por um pod (beta) e impedir a [exclusão de um Volume Persistente que esteja vinculado a uma *Persistent Volume Claim* (beta)](https://github.com/kubernetes/features/issues/499). Essas evoluções ajudam a garantir que os objetos da API de armazenamento sejam excluídos na ordem correta. ## Security - External credential providers (alpha) O Kubernetes, que já é altamente extensível, ganha outro ponto de extensão na versão 1.10 com [provedores de credenciais kubectl externos (alfa)](https://github.com/kubernetes/features/issues/541). Os provedores de nuvem, fornecedores e desenvolvedores agora podem liberar plugins para lidar com autenticação de serviços IAM de provedores de nuvem específicos ou que se integram a sistemas de autenticação internos, como o Active Directory. Essa característica complementa o [Cloud Controller Manager](https://kubernetes.io/docs/tasks/administer-cluster/running-cloud-controller/) adicionado na versão 1.9. ## Networking - CoreDNS as a DNS provider (beta) A capacidade de [alternar o serviço DNS](https://github.com/kubernetes/features/issues/427) para o CoreDNS no [momento da instalação](https://kubernetes.io/docs/tasks/administer-cluster/coredns/) está agora na versão beta. O CoreDNS tem menos partes móveis: é um único executável e um único processo e suporta casos de uso adicionais. Cada Grupo de Interesse Especial (_Special Interest Group_, SIG) dentro da comunidade continua a fornecer os aprimoramentos, correções e funcionalidades mais solicitados para suas respectivas áreas de especialidade. Para uma lista completa de inclusões pela SIG, maiores informações no [release notes](https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG-1.10.md#110-release-notes). ## Availability O Kubernetes 1.10 está disponível para [download no GitHub](https://github.com/kubernetes/kubernetes/releases/tag/v1.10.0). Para começar a entender e usar o Kubernetes, recomendo estes [tutoriais interativos](https://kubernetes.io/docs/tutorials/). ## Destaques De acordo com uma [pesquisa recente da CNCF](https://www.cncf.io/blog/2018/03/26/cncf-survey-china/), mais de 49% dos entrevistados na Ásia usam o Kubernetes em produção, com outros 49% avaliando-o para uso em produção. Organizações globais estão usando o [Kubernetes em produção](https://kubernetes.io/case-studies/) em escala maciça. Histórias de usuários recentemente publicadas da comunidade incluem: - A **Huawei**, maior fabricante de equipamentos de telecomunicações do mundo, [transferiu seus aplicativos internos do departamento de TI para serem executados no Kubernetes](https://kubernetes.io/case-studies/huawei/). Esta mudança resultou em ciclos globais de implantação que diminuíram de uma semana para alguns minutos, e a eficiência da entrega de aplicativos melhorou em dez vezes. - A **Jinjiang Travel International**, uma das cinco maiores empresas OTA e de hotéis, usa o Kubernetes para [acelerar a velocidade de lançamento de software de horas para apenas alguns minutos](https://www.linux.com/blog/managing-production-systems-kubernetes-chinese-enterprises). Além disso, eles utilizam o Kubernetes para aumentar a escalabilidade e a disponibilidade de suas cargas de trabalho on-line. - O **Haufe Group**, empresa de mídia e software da Alemanha, utilizou o Kubernetes para [entregar um novo lançamento em meia hora, em vez de dias](https://kubernetes.io/case-studies/haufegroup/). A empresa também pôde reduzir para metade da capacidade computacional à noite, economizando 30% em custos de hardware. - A **BlackRock**, a maior administradora de ativos do mundo, conseguiu se movimentar rapidamente usando o Kubernetes e criou um aplicativo da web para pesquisa com investidores desde a sua [concepção até a entrega em menos de cem dias](https://kubernetes.io/case-studies/blackrock/). Mais informações nos artigos ["Kubernetes 1.10: an insider take on what's new"](https://cloudplatform.googleblog.com/2018/03/Kubernetes-1-10-an-insider-take-on-whats-new.html) e ["Kubernetes 1.10: Stabilizing Storage, Security, and Networking"](http://blog.kubernetes.io/2018/03/kubernetes-1.10-stabilizing-storage-security-networking.html). Artigo originalmente publicado em [Kubernetes 1.10: Estabilizando armazenamento, segurança e rede](http://viniciusgarcia.me/development/kubernetes-1-10/) :: [viniciusgarcia.me](http://viniciusgarcia.me/)<file_sep>/_posts/2017-12-04-estudos-empiricos-na-engenharia-de-software.md --- layout: post title: "Estudos Empíricos na Engenharia de Software" categories: Educacao tag: pesquisa --- No dia 01/12/2017 (sexta-feira), às 8 horas na sala E423 do [Centro de Informática](http://www.cin.ufpe.br) ocorreu a defesa de doutorado de <NAME> **Neto**, cujo o tema tratava da construção de uma ferramenta [CASE](https://pt.wikipedia.org/wiki/Ferramenta_CASE) para auxiliar na execução de experimentos envolvendo codificação ne Engenharia de Software. Durante a leitura da tese de Nto, me deparei com um breve resumo, ou melhor, uma suscinta explicação sobre os principais métodos, por assim dizer, da Engenharia da Software Experimental. A pesquisa em Engenharia de Software (ES) investiga eventos do mundo real para promover o desenvolvimento de novos mecanismos (como tecnologias, processos, métodos, técnicas e ferramentas) para apoiar suas atividades. Visa melhorar a qualidade dos produtos de software e aumentar a produtividade do processo de desenvolvimento ([WEYUKER, 2011](http://ieeexplore.ieee.org/document/6092548/)). Resumidamente, a pesquisa em engenharia de software está preocupada em investigar como funcionam os mecanismos, entender seus limites e propor soluções. Neste contexto, os métodos empíricos fornecem uma maneira consistente para validar o fenômeno da ES, gerando evidências mais precisas e facilitando a transferência de tecnologia para a indústria ([SJOBERG; DYBA; JORGENSEN, 2007](http://ieeexplore.ieee.org/document/4221632/)). Por outro lado, a ES é fortemente influenciada por fatores humanos (da mesma forma que ciências como as ciências sociais e comportamentais). Portanto, os fatores humanos têm um impacto significativo no processo de desenvolvimento de software e na qualidade do software produzido. Além disso, apesar dos esforços de atividades relacionadas à produção de software, a ES ainda depende da influência humana ([ROBSON, 2016](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118531507.html)). Como resultado, a SE e os estudos empíricos enfrentaram várias dificuldades relacionadas a fatores humanos. Conforme foi bem pontuado por Neto em sua tese, os fatores humanos têm uma importância fundamental na ES. Portanto, os métodos empíricos mais apropriados são aqueles de disciplinas relacionadas ao estudo do comportamento humano, como a psicologia (quanto ao nível individual do comportamento humano) ou a sociologia (em relação à equipe e aos níveis organizacionais). Métodos adaptados para essas disciplinas têm falhas conhecidas, e cada uma só pode fornecer evidências limitadas e qualificadas sobre os fenômenos em estudo. No entanto, cada método é falho de forma diferente, e as estratégias de pesquisa viáveis usam métodos múltiplos, escolhidos de forma tal que o uso de métodos complementares abordem as fraquezas de cada método ([EASTERBROOK et al., 2008](https://link.springer.com/chapter/10.1007%2F978-1-84800-044-5_11)). A seguir, Neto fez um resumo de cada um dos métodos, para esclarecer onde cada um atua e suas princiais características. ## Experimentos Um **experimento** (ou experimento controlado) é uma pesquisa sobre uma hipótese testável onde uma ou mais variáveis são gerenciadas para medir seu efeito em uma ou mais variáveis dependentes. Uma condição prévia para a experimentação é uma hipótese clara. A hipótese (e qualquer teoria a partir da qual ela é desenhada) conduzem todas as etapas do projeto experimental, incluindo decidir quais variáveis devem ser cobertas e como mensurá-las. ## Estudos de Caso [Yin (2013)](https://www.amazon.com/Case-Study-Research-Methods-Applied/dp/1452242569) define **estudo de caso** como "_uma pesquisa empírica que investiga um fenômeno contemporâneo em seu contexto da vida real, especialmente quando os limites entre fenômeno e contexto não são evidentes_". Além disso, estudos de caso oferecem uma compreensão aprofundada de **como** e **por que** ocorrem certos fenômenos. Uma condição prévia para realizar um estudo de caso é uma pergunta de pesquisa clara relacionada com a forma ou por que certos fenômenos ocorrem. ## Survey **Survey** é usado para identificar características de uma grande população. Está mais intimamente ligado aos questionários para a coleta de dados. No entanto, surveys também podem usar entrevistas estruturadas ou técnicas de registro de dados. As principais características de uma pesquisa por survey são (i) a seleção de uma amostra representativa de uma população, e (ii) as técnicas de análise de dados utilizadas para generalizar os resultados da amostra para a sua população. Uma condição prévia para a realização de um survey é uma questão de pesquisa clara que exige informações sobre a natureza de uma população alvo específica. ## Etnorafias A **etnografia** é uma estratégia empírica concentrada na sociologia do significado através da observação de campo. O objetivo é investigar uma comunidade de pessoas para entender como seus membros interagem. Na ES, a etnografia geralmente é adotada para examinar como as comunidades técnicas desenvolvem uma cultura de práticas e estratégias de comunicação que lhes permitem executar uma tarefa de forma colaborativa. As condições prévias para um estudo etnográfico incluem questões de pesquisa focadas em aspectos culturais de uma determinada comunidade ou acesso a membros dessa comunidade. ## Pesquisa-ação Na **pesquisa-ação**, os pesquisadores tentam resolver um problema do mundo real enquanto investigam simultaneamente a experiência de resolver esse problema. Embora a maioria dos métodos de pesquisa empírica procure observar o mundo tal como existe atualmente. Os pesquisadores de ação buscam interceder em situações estudadas com o propósito explícito de melhorar a situação. Uma condição prévia para a pesquisa-ação de um problema, é que as pessoas envolvidas tenham vontade de colaborar para identificar um problema e resolvê-lo seguindo uma abordagem empírica. ## Métodos combinados Além dos métodos anteriormente mencionados, [Easterbrook et al. (2008)](https://link.springer.com/chapter/10.1007%2F978-1-84800-044-5_11) citam outra abordagem combinando esses métodos. A escolha de cada método depende de pré-requisitos de investigação, objetivo da pesquisa, recursos disponíveis e como os dados devem ser coletados e analisados. [Easterbrook et al. (2008)](https://link.springer.com/chapter/10.1007%2F978-1-84800-044-5_11) apresenta mais detalhes sobre essa abordagem. Não obstante as perspectivas associadas à **Engenharia de Software Empírica**, estudos obtiveram uma baixa avaliação empírica na ES, dificultando seu progresso como ciência e adiando a adoção de novas tecnologias ([TICHY, 1998](http://ieeexplore.ieee.org/document/675631/); [JURISTO; VEGAS, 2009](http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=5463362&filter%3DAND%28p_IS_Number%3A5463276%29); [SJØBERG et al., 2005](http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=1514443); FALCAO , 2016). Além disso, [<NAME> (2013)](http://www.springer.com/br/book/9780792379904) apresenta alguns argumentos citados contra o uso de métodos empíricos: falta de treinamento nesses métodos do lado dos profissionais, dificuldades em entender e analisar dados empíricos; estudos empíricos realizados para verificar idéias de outros não são frequentemente publicados. Neste contexto, [SJØBERG et al. (2005)](http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=1514443) identificaram uma discrepância entre o número de experiências e o número de novas tecnologias que surgem na ES. [Wohlin & Aurum (2015)](https://link.springer.com/article/10.1007/s10664-014-9319-7) cita outros fatores que se tornam pesquisas empíricas em ES especialmente desafiadoras. Por exemplo, além de estudar o uso da tecnologia, também é necessário investigar os processos sociais e cognitivos associados às atividades humanas. Neste contexto, os pesquisadores devem ter uma base sólida ao escolher métodos e diretrizes para realizar um estudo empírico ([WOHLIN; AURUM, 2015](https://link.springer.com/article/10.1007/s10664-014-9319-7)). ## References * <NAME>., <NAME>., <NAME>., <NAME>. (2008) Selecting Empirical Methods for Software Engineering Research. In: <NAME>., <NAME>., <NAME>. (eds) Guide to Advanced Empirical Software Engineering. Springer, London * FALCÃO, <NAME>. Analysis of Human-Centric Software Engineering Experiments: a systematic mapping study. 2016. Dissertação (Mestrado em Ciência da Computação) — Center of Informatics - Federal University of Pernambuco, Recife - Brazil. * <NAME> and <NAME>. 2009. Using differences among replications of software engineering experiments to gain knowledge. In Proceedings of the 2009 3rd International Symposium on Empirical Software Engineering and Measurement (ESEM '09). IEEE Computer Society, Washington, DC, USA, 356-366. doi: [10.1109/ESEM.2009.5314236](http://dx.doi.org/10.1109/ESEM.2009.5314236) * <NAME> & <NAME>. Basics of software engineering experimentation. [S.l.]: Springer Science & Business Media, 2013. * <NAME>, K. Real world research. [S.l.]: <NAME> & Sons, 2016. * <NAME> et al., "A survey of controlled experiments in software engineering," in IEEE Transactions on Software Engineering, vol. 31, no. 9, pp. 733-753, Sept. 2005. doi: [10.1109/TSE.2005.97](http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1514443&isnumber=32435) * <NAME>, <NAME> and <NAME>, "The Future of Empirical Methods in Software Engineering Research," Future of Software Engineering, 2007. FOSE '07, Minneapolis, MN, 2007, pp. 358-378. [doi: 10.1109/FOSE.2007.30](http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4221632&isnumber=4221601) * <NAME>, "Should computer scientists experiment more?," in Computer, vol. 31, no. 5, pp. 32-40, May 1998. doi: [10.1109/2.675631](http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=675631&isnumber=14870) * <NAME>, "**Empirical Software Engineering Research - The Good, The Bad, The Ugly**," 2011 International Symposium on Empirical Software Engineering and Measurement, Banff, AB, 2011, pp. 1-9. doi: [10.1109/ESEM.2011.66](http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=6092548&isnumber=6092538) * <NAME>. & <NAME>. Empir Software Eng (2015) 20: 1427. https://doi.org/10.1007/s10664-014-9319-7 * <NAME>. Case study research: design and methods. [S.l.]: Sage publications, 2013. Artigo originalmente publicado em [Estudos Empíricos na Engenharia de Software :: viniciusgarcia.me](vinicius3w.github.io/research/estudos-empiricos-na-engenharia-de-software/) <file_sep>/_posts/2015-07-21-trabalhando-com-rna.md --- layout: post title: "Trabalhando com RNA" categories: Pesquisa tag: doutorado --- Você não leu o título errado. Este é o primeiro post de uma série tendo Bioinformática como temática central. Daqui para frente este será um tema recorrente no blog do Assert Labs como uma forma esboçar uma série de estudos introdutórios que nos tem ajudado a imergir neste novo mundo. O objetivo deste post em específico é apresentar ferramentas para a busca de moléculas de RNA na Internet, a predição da estrutura secundária da molécula de RNA e encontrar RNAs não codificantes. ## Estruturas secundárias Uma molécula de RNA de estrutura simples não estará estável enquanto algumas das suas bases nitrogenadas não estiverem protegidas de contato com seu solvente natural - a água. A maneira mais efetiva de fazer isso é unindo as bases nitrogenadas em pares. Esta ligação entre pares de bases é mais efetiva quando uma guanina (G) é ligada a uma citosina (C) em comparação com uma ligação entre uma uracila (U) ligada com uma adenina (A). O emparelhamento dessas bases forma a estrutura secundária do RNA. Quando uma molécula de RNA possui dois longos trechos complementares, ela “dobra“ para formar os pares de bases resultando em uma haste de ligações estáveis. Estas hastes podem ser imperfeitas e conter regiões arredondadas de bases não pareadas (ver figura abaixo). ![]({{ BASE_PATH }}/images/2015-07-21-trabalhando-com-rna/figura1.png) Existe uma tendência natural para a molécula de RNA buscar ter a estrutura secundária mais estável a partir do melhor conjunto de ligações de bases possível de ser formado. O conceito _lowest-energy model_ (modelo de menor quantidade de energia) preconiza que as estruturas de RNA estáveis sempre possuem um valor energético negativo em Kcal/mol. Portanto, para “desdobrar” uma sequencia de RNA desfazendo as ligações entre as bases nitrogenadas é necessário prover energia (calor) a essas moléculas. A estabilidade de um RNA dobrado depende não só da quantidade de ligações GC (GC content), mas da quantidade de ligações de uma maneira geral e do tamanho das regiões arredondadas, também chamadas de regiões de loop. Algoritmos sofisticados como o mfold podem levar essas especificidades em conta para predizer qual seria uma dobra de estabilidade ótima dada a estrutura primária do RNA. Infelizmente essas predições da forma secundária do RNA não são totalmente confiáveis. Essa predição exige que se pressuponha que o RNA dobre-se em si mesmo dentro de uma célula, o que nem sempre é verdade uma vez que existe interações terciárias e efeitos de determinadas proteínas, íons, outros RNAs e outros elementos químicos sobre a dobra. Essas interações terciárias que afetam a estabilidade da dobra do RNA incluem _pseudo-knotes_ que são longas sequencias de ligações entre um loop e uma outra porção da molécula de RNA. Por conta disto, nem sempre é verdade que a predição de uma estrutura secundária esteja totalmente correta. A regra geral é que as características mais energeticamente estáveis tendam a ser razoavelmente próximas da verdade quando passam pelo processo de predição. ## Tipos de RNA Os RNAs podem ser divididos em dois grupos: 1. RNAs que podem ser transformados em proteínas devido ao trabalho dos ribossomos e 2. RNAs que são utilizados diretamente pelas células. RNAs não codificantes auxiliam as células nos processos de transcrição, seccionamento e e replicação e outras atividades. Com exceção do RNA ribossomal esses RNAs tendem a ser curtos e pobremente conservados. Um integrante deste grupo é o tRNA (transport RNA) responsável pela montagem de proteínas a partir do transporte de aminoácidos. Existe ao menos um tipo de tRNA para cada aminoácido. O fenômeno conhecido como _RNA inference_ (RNAi) em células eucariontes ocorre quando pequenas porções de RNA não codificantes interferem no RNA codificante prevenindo a expressão de ao menos um gene. Um tipo de RNA que provoca esse fenômeno é o _silencing RNA_ (siRNA), descoberto inicialmente em plantas que tem a habilidade de inativar (silenciar) um gene. A descoberta do siRNA abriu as portas para a observação de outras pequenas porções de RNA que são chamadas de _micro-RNA_ (miRNA). Pouco se sabe a respeito do miRNA e sua função nas células e a busca e identificação destes é bastante difícil devido ao seu tamanho reduzido em comparação com o genoma. Sabe-se apenas que o siRNA diferencia-se por ter uma cadeia dupla e o miRNA possui cadeia simples. ## Mfold [Mfold](http://rothlab.ucdavis.edu/genhelp/mfold.html){:target="_blank"} é uma implementação do algoritmo de Zuker que tem a função de prever a estrutura secundária energeticamente ótima de um RNA. Para tanto, o algoritmo utiliza um modelo que leva em conta características físicas, como pH e temperatura, que afetam a dobra do RNA. Este modelo energético ignora interações 3-D ou interações entre proteínas e RNA que podem tornar estáveis uma dobra considerada como não ótima. Para ajudar no processo de decisão o mfold oferece como resultado modelos não ótimos e deixa na mão do especialista o julgamento da estabilidade da dobra ótima. É possível ainda, a partir dessa implementação, forçar uma interação que é dada como correta. O mfold pode ser encontrado [neste endereço](http://unafold.rna.albany.edu/?q=mfold/download-mfold){:target="_blank"} tanto para download quanto para uso on-line. Em ambos os casos ele recebe como parâmetros para a predição da estrutura secundária do RNA a sequência de bases nitrogenadas no formato fasta e os parâmetros do modelo energético. ## tRNAScan e PatScan tRNAs são difíceis de serem encontrados em um genoma. Todos os genomas bacteriais e de eucariontes contém tRNA. Mas por serem pequenos necessitam de ferramentas de pesquisa em bases de dados mais sofisticadas que o BLAST. Uma ferramenta que pode ser utilizada para o propósito de busca de tRNAs em genomas é o [tRNAScan](http://lowelab.ucsc.edu/tRNAscan-SE/){:target="_blank"}. tRNAScan é ótimo para pesquisas interessadas em tRNAs de uma maneira geral. No entanto, se o interessa da pesquisa está em uma família específica de tRNA que permita a busca por estrutura secundária a ferramenta PatScan é mais adequada. Outra alternativa é utilizar o RNAmot que tem as mesmas funcionalidade que o PatScan.<file_sep>/_posts/2015-11-11-program-synthesis.md --- layout: post title: "A very brief overview of Program Synthesis" categories: Pesquisa --- Reproduzo aqui o [post](https://fernandocastor.github.io/general/2015/11/10/program_synthesis.html) que o prof. [<NAME>](https://fernandocastor.github.io/{:target="_blank"}) fez sobre o seminário apresentado pelo prof. <NAME> acerca sobre seus trabalhos com Métodos Formais. Estes seminários fazem parte de uma iniciativa do Laboratório de Engenharia de Software do CIn-UFPE. * * * Starting a couple of months ago, [CIn](http://www.cin.ufpe.br/){:target="_blank"}-[UFPE](http://www.ufpe.br/){:target="_blank"}’s Software Engineering Laboratory started organizing seminars given by its members. The goal is to make laboratory members aware of work being conducted by other members. So far, I’ve greatly enjoyed these seminars. In one of them, I learned a bit about cloud computing and also about electronic government (which seems to be an area of research that sits between Computer Science and Political Science) from Prof. [<NAME>](http://viniciusgarcia.me/){:target="_blank"}. Last week we had one given by Prof. [<NAME>](https://sites.google.com/site/acmrecife/){:target="_blank"}. One of the things I admire about Alexandre is that he is a hard core Formal Methods guy with a remarkable track record of collaboration with industry. ![](https://raw.githubusercontent.com/fernandocastor/fernandocastor.github.io/master/images/alexandre.jpg) Alexandre’s talk started with an overview of formal methods. According to Alexandre, formal methods are a combination of notations, tools, and a semantics based on mathematics. Their use can help developers to ascertain that there is no ambiguity, imprecision, inconsistency, and (for some systems) incompleteness in a system specification. This is the **good** side of formal methods. The **bad** side is that, to get from a specification to a correct system, there is a myriad different paths and each one of them is tough to traverse. And this is assuming that a formal specification exists. Going from an informal specification to a formal one is a very difficult problem in and of itself. It requires a thorough validation and the assistance of specialists. Alexandre also discussed the process of program refinement, going from a formal specification to executable code in a way that guarantees that the generated code satisfies the specification. According to him, there are two paths to go from formal specification to a correct system: (i) by data and operation refinement; and (ii) by [refinement calculus](http://www.cs.ox.ac.uk/publications/books/PfS/){:target="_blank"} (using a set of refinement rules). In the former approach, we’re transitioning from a specification _S0_ to a specification _S1_ and _S1_ is not determined by pre-established laws. One needs to propose and verify each refinement. It is possible to apply more broad-scoped transformations using this approach. In the latter, the transformations one can apply to the specification are constrained by the laws one is using. This is good because the proof obligations are relatively straightforward. The bad part is that it is more constraining and requires very experienced engineers. The “search” in refinement calculus may never end. Both approaches require searching for the specifications and for the theorems that must be proved. It is a search problem and leads us to the problem of program synthesis. After presenting a (critical) view of formal methods, he narrowed down the scope of his talk, focusing more on the subject of program synthesis. The problem of program synthesis can be summarized as follows: Build a system that, given a specification and optionally a set of program fragments, produces as output a program that satisfies (refines?) the given specification and also includes the given program fragments. Program synthesis is a search problem because a large part of the work performed by a program synthesis system consists of searching through a space of candidate programs and checking whether they satisfy the specification. This problem is tough. In fact, part of it usually involves solving [SAT](https://en.wikipedia.org/wiki/Boolean_satisfiability_problem){:target="_blank"}, the most famous [NP-complete](https://en.wikipedia.org/wiki/NP-completeness){:target="_blank"} problem. “Usually” because, when one is using a probabilistic approach for program synthesis, this is not the case. The area of program synthesis started a long time ago, before computers. In 1932, famous soviet mathematician [<NAME>](https://en.wikipedia.org/wiki/Andrey_Kolmogorov){:target="_blank"} already talked about algorithms with proofs that come from constructive mathematics. This is very distant from what is currently discussed as program synthesis. A particularly important system in this area, which appeared much latter, was the [Kestrel Interactive Development System](http://www.kestrel.edu/home/projects/kids/){:target="_blank"} (KIDS). KIDS supported program synthesis from a complex program specification by means of a series of manually applied refinement steps (maybe it couldn’t be strictly called a program systhesis system) and, according to its homepage, has been used to develop many applications in such diverse areas as scheduling, combinatorial design, sorting and searching, computational geometry, pattern matching, and mathematical programming. KIDS came close to a commercial breakthrough, which is impressive. According to Alexandre, there are three main approaches to program synthesis: * **Synthesizers that are specialized in a particular domain**. An example of such approaches is the use of the VHDL language to describe digital and mixed-signal systems. These approaches are scalable but constrained to specific kinds of systems. * **Synthesizers that translate a particular language into SAT/SMT language**. This is a general purpose approach, but it usually focuses on specific problems, such as security. According to Alexandre, the Sketch system is one of the most proeminent examples of this approach. Given specification and a code fragment, Sketch fills in the code that the programmer did not provide. An example of the kind of fragment the Sketch receives is the following: {% highlight c %} harness void doubleSketch(int x){ int t = x + ?? assert t = x + x; } {% endhighlight %} * **Synthesizers that take as input a general purpose high-level specification**. This is the line of work that Alexandre and his colleagues, such as [<NAME>](http://www.cin.ufpe.br/~jmi/){:target="_blank"} (also from CIn-UFPE), pursue. In this case, program synthesis takes as input the specification of the program to be synthesized and an optional set of code fragments and produces as a result a program in a language that has a formal semantics. The latter part is particularly relevant because, as long as a language has formal syntax and semantics, it can be combined with this approach. They proposed an approach and a tool implementing it, named PSAtCIn, that currently combines a DSL targeting C# code, [Alloy*](http://alloy.mit.edu/alloy/hola/){:target="_blank"}, and a formal specification language in an Ecplise Plugin that is already capable of producing code from general-purpose specifications. Here’s a very simple example of the kind of thing one can do with PSAtCIn. Given a specification: {% highlight csharp %} Vars x, y requires: x > 1 and y > 1 ensures: x' = gcd(x, y) sketch: while * != * * {% endhighlight %} it can generate the program {% highlight csharp %} while (x != y) { if (x > y) x = x - y else y = y - x {% endhighlight %} In the specification part, ```gcd``` is a logical predicate. Alexandre explained that this approach is currently capable of generating simple programs that include loops, e.g., it was capable of generating [Euclid’s algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm){:target="_blank"} for the greatest common divisor. This is a promising result, since loops are a common stumbling point for program synthesis and verification techniques. PSAtCIn also supports sketching (similarly to Sketch) and it is extensible for other languages that have formal syntax and semantics. Finally, Alexandre discussed some current challenges. The one that caught my attention was the recommendation of scopes for search. Since PSAtCIn uses Alloy* under the hood, it also performs bounded scope search when verifying whether a program satisfies its intended properties (pre and postconditions). In Alloy*, users must specify the bounds for the search scope. Alexandre hopes that, in the near future, PSAtCIn will be able to provide this kind of information automatically in program synthesis.<file_sep>/_posts/2014-05-22-assert-meeting-10-may-2014-post-mortem.md --- layout: post title: "ASSERT Meeting (10-May-2014) Post Mortem" categories: Pesquisa tag: seminario --- No último sábado, 10/05/2014, ocorreu no [**Centro de Informática**](http://www.cin.ufpe.br){:target="_blank"} da UFPE o primeiro de uma série de seminários sobre os projetos que estão sendo desenvolvidos pelos membros do ASSERT Lab. Inaugurando a série, o <NAME> apresentou o status do seu trabalho, discutindo as publicações recentes [1][2][3] e apresentando a previsão das próximas etapas de sua pesquisa. Os slides usados na apresentação podem ser consultados em <http://pt.slideshare.net/kellytonbrito/assert-workshop-dados-abertos>. Após a apresentação, houve uma rica discussão envolvendo os presentes, aos quais o autor agradece a presença e as contribuições. Em seguida, o mestrando <NAME> apresentou o estado atual de sua pesquisa, orientada pelo professor <NAME>, mas que também conta com valiosas contribuições dos professores <NAME> e <NAME>. A pesquisa parte da premissa de que o desempenho de sistemas intensivos em E/S pode ser aumentado significativamente explorando-se as oportunidades que estes sistemas costumam oferecer para a execução concorrente de operações de E/S. Apesar deste enorme potencial, operações de E/S são executadas concorrentemente apenas em sistemas altamente especializados, tais como aqueles que efetuam computações científicas. Isto acontece porque programar a execução concorrente de operações de E/S a partir dos mecanismos mais difundidos para tal (primitivas síncronas de E/S com programação multithreaded e primitivas assíncronas) é significativamente mais difícil do que programar a execução sequencial destas operações. O primeiro resultado obtido pela pesquisa é um framework para a linguagem Java chamado Afluentes (disponível em <https://github.com/afluentes>), que permite ao programador coordenar a execução tanto de métodos síncronos quanto a de métodos assíncronos através da composição de métodos, facilitando o desenvolvimento de sistemas que executam operações de E/S concorrentemente. Afluentes foi avaliado através de experimentos realizados em um sistema web que interage com um banco de dados relacional. Nestes experimentos, o tempo gasto pelo sistema para responder a uma requisição foi mensurado com o sistema submetendo consultas ao banco de dados sequencialmente e também concorrentemente. Os resultados obtidos são animadores, mostrando que, de fato, a execução concorrente de operações de E/S aumenta significativamente o desempenho de sistemas intensivos em E/S. Ao final da apresentação, o público teceu críticas e sugestões ao estado atual da pesquisa, contribuindo para delinear seus próximos passos. Mais informações podem ser obtidas em [4] e os slides da apresentação estão disponíveis em: <http://www.slideshare.net/saulomaraujo/afluentes-concurrent-io-made-easy-with-lazy-evaluation>. 1. Experiences Integrating Heterogeneous Government Open Data Sources to Deliver Services and Promote Transparency in Brazil. Artigo aceito para publicação na 38ª Annual International Computers, software & Applications Conference Special Sessions 2014 (COMPSAC), em Västerås, Sweden 21–25 Jul, 2014; 2. Using Parliament Brazilian Open Data to Improve Transparency and Public Participation in Brazil. Artigo aceito para publicação na International Digital Government Research Conference (2014), em Aguascalientes City - Mexico, 18–21 Jun, 2014; 3. Brazilian Government Open Data: Implementation, Challenges, and Potential Opportunities. Artigo também aceito para publicação na International Digital Government Research Conference (2014), em Aguascalientes City - Mexico, 18–21 Jun, 2014; 4. Araujo, <NAME>, <NAME>, <NAME>, and <NAME>. “Afluentes Concurrent I/O Made Easy with Lazy Evaluation.” In Parallel, Distributed and Network-Based Processing (PDP), 2014 22nd Euromicro International Conference on, pp. 279-287. IEEE, 2014.<file_sep>/_posts/2013-03-03-profiling-distributed-applications-through-network.md --- layout: post title: "Profiling Distributed Applications Through Network Traffic Analysis" categories: Pesquisa tag: mestrado --- This is the research conducted by <NAME>, which studies techniques for profiling distributed applications at runtime, with low intrusion, high accuracy and fast results. Distributed systems has been adopted for building modern Internet services and cloud computing infrastructure, in order to obtain services with high performance, scalability and reliability. Cloud computing SLAs require low time to identify, diagnose and solve problems in a cloud computing production infrastructure, in order to avoid problem impacts into the quality of service provided for its clients. ![image]({{ BASE_PATH }}/images/2013-03-03-profiling-distributed-applications-through-network/figura1.png) The detection of error causes, diagnose and reproduction of errors are challenges that motivate efforts to the development of less intrusive mechanisms for monitoring and debugging distributed applications at runtime. ![image]({{ BASE_PATH }}/images/2013-03-03-profiling-distributed-applications-through-network/figura2.png) Network traffic analysis is one option to the distributed systems measurement, although there are limitations on capacity to process large amounts of network traffic in short time, and on scalability to process network traffic where there is variation of resource demand.&nbsp; The goal of this research is to evaluate the processing capacity problem for profiling distributed systems through network traffic analysis, in order to evaluate distributed applications at a data center, using commodity hardware and cloud computing services, in a minimally intrusive way. We proposed a new approach based on MapReduce, for deep inspection of distributed application traffic, in order to evaluate the behavior of distributed systems at runtime, using commodity hardware. In this research we evaluated the effectiveness of MapReduce for a deep packet inspection algorithm, its processing capacity, completion time speedup, processing capacity scalability, and the behavior followed by MapReduce phases, when applied to deep packet inspection for extracting indicators of distributed applications. ![image]({{ BASE_PATH }}/images/2013-03-03-profiling-distributed-applications-through-network/figura3.png) With our proposed approach, it is possible to measure the network traffic behavior of distributed applications with intensive network traffic generation, through the offline evaluation of information from the production environment of a distributed system, making it possible to use the information from the evaluated indicators, to diagnose problems and analyse performance of distributed systems. We showed that MapReduce programming model can express algorithms for DPI, as the algorithm implemented to extract application indicators from the network traffic of a JXTA-based distributed application. We analysed the completion time scalability achieved for different number of nodes in a Hadoop cluster composed of virtual machines, with different size of network traffic used as input. We showed the processing capacity and the completion time scalability achieved, and also was showed the influence of the number of nodes and the data input size in the processing capacity for DPI using virtual machines of Amazon EC2. We evaluated the performance of MapReduce for packet level analysis and DPI of applications traffic, using commodity hardware, and showed how data input size, block size and cluster size cause relevant impacts into MapReduce phases, job completion time, processing capacity scalability and in the speedup achieved in comparison against the same execution by a non distributed implementation. The results showed that although MapReduce presents a good processing capacity using cloud services or commodity computers for dealing with massive application traffic analysis, but it is necessary to evaluate the behaviour of MapReduce to process specifics data type, to understand its relation with the available resources and the configuration of MapReduce parameters, and to obtain an optimal performance for specific environments. We showed that MapReduce processing capacity scalability is not proportional to number of allocated nodes, and the relative processing capacity decreases with node addition. We showed that input size, block size and cluster size are important factors to be considered to achieve better job completion time and to explore MapReduce scalability, due to the observed variation in completion time provided by different block size adopted. Also, in some cases, the processing capacity does not scale with node addition into the cluster, what highlights the importance of allocating resources according with the workload and input data, in order to avoid wasting resources. We verified that packet level analysis and DPI are Map-intensive jobs, due to Map phase consumes more than 70\% of the total job completion time, and shuffle phase is the second predominant phase. We also showed that using whole block as input for Map functions, was achieved a poor completion time than the approach which splits the block into records. We published the papers below about this research: <http://bit.ly/WDryaG> <http://bit.ly/WDrGXr> If you want to know more about our research, contact me at **tpbv at cin dot ufpe dot br**.<file_sep>/_posts/2015-03-04-international-journal-of-e-planning-research.md --- layout: post title: "ASSERT @ International Journal of E-Planning Research (IJEPR) notification" categories: Artigos tag: periodico --- A paper from ASSERT Members has been accepted for publication in the [International Journal of E-Planning Research](http://www.igi-global.com/journal/international-journal-planning-research-ijepr/44994) (IJEPR). The paper is entitled "I**s Brazilian Open Government Data Actually Open Data? An Analysis of the Current Scenario**", by <NAME>, <NAME>, <NAME> and <NAME>. A brief summary of the paper is following: _Open Government Data (OGD) hold great promise for transforming the efficiency and effectiveness of public services through the ease of publishing and access to government public information or through the offer of new kinds of services, such as smart city services and applications. In this work, we analyze the Brazilian OGD current scenario and the main difficulties and challenges of developing applications using that data. First, we performed an analysis of three Brazilian OGD repositories according to OGD definitions. Then, we interviewed the developers of two similar applications that use the OGD of two main Brazilian cities, were submitted to different cities’ application contests, and were well evaluated in both. Based on the analysis, this work concludes that Brazilian OGD initiatives have to resolve some issues before being considered truly open data for use in application development at large._<file_sep>/_posts/2012-12-06-assert-and-ines-at-28th-symposium-on-applied.md --- layout: post title: "ASSERT and INES at 28th Symposium On Applied Computing (SAC’2013)" categories: Artigos tag: conferencia --- The paper “**Smart Cities Software Architectures: A Survey**”&nbsp;authored by <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and&nbsp;<NAME>&nbsp;has been accepted for publication in the&nbsp;[Software Architecture: Theory, Technology, and Applications (SA-TTA)&nbsp;Technical Track](http://dinamico2.unibg.it/sa-tta/ "SAC 2013 Track on Software Architecture: Theory, Technology, and Applications (SA-TTA)")&nbsp;at the&nbsp;[28th Symposium On Applied Computing (SAC’2013)](http://www.acm.org/conferences/sac/sac2013/ "28th Symposium On Applied Computing"). The conference will be held in March 18 - 22, 2013 at&nbsp;[Institute of Engineering of the Polytechnic Institute of Coimbra (ISEC-IPC)](http://www.isec.pt/en/),&nbsp;Coimbra, Portugal. This activity is part of the project “[Social Machines and Research Team - SMaRT](http://www.ines.org.br/?p=502)” and is one of the results of the MSc research being done by&nbsp;<NAME> and <NAME> and PhD research being done by <NAME>. A brief overview of the paper is given next > The smart cities concept arises from the need to manage, automate, optimize and explore all aspects of a city that could be improved. For this purpose it is necessary to build a robust architecture that satisfies a minimal number of requirements such as distributed sensing, integrated management and flexibility. > > Several architectures have been proposed with different goals, but none of them met satisfactorily the needs that permeate smart cities. > > In this work various architectures are discussed, highlighting the main requirements that they aim to fulfill. Furthermore, based on different architectures with the most varied purposes, a set of requirements for the implementation of a smart city is presented and discussed.<file_sep>/_posts/2018-03-20-chegou-o-spring-boot-2.md --- layout: post title: "Chegou o Spring Boot 2.0" categories: Desenvolvimento tag: - programação - Engenharia de Software - desenvolvimento - boas práticas - microservices - spring boot --- Neste semestre estou ministrando pela primeira uma disciplina inteiramente focada em investigar o desenvolvimento de aplicações "nativas de nuvem" com arquitetura baseada em microservises (mais informações aqui: [Desenvolvimento de Aplicações com Arquitetura Baseada em Microservices](https://github.com/vinicius3w/if1007-Microservices). Como ferramenta adotei o [Spring Boot](https://projects.spring.io/spring-boot/) dado o conjunto de facilidades e benefícios acelerados que teria com o seu uso. O foco ficaria muito mais nos conceitos e decisões de projetos do que em questões de codificação, digamos assim. Estratégia também adotada na disciplina de Engenharia de Software (maiores informações aqui: [ Engenharia de Software (if977)](https://sites.google.com/a/cin.ufpe.br/if977/)), que também ministro, e motivou a escolha da suite de ferramentas pra ela. Bem, o Spring Boot 2 acabou de ser lançado e a comunidade já está pronta para vê-lo em ação nos próximos meses. Este lançamento coroa o ciclo de 17 meses de trabalho e mais de 6800 commits por 215 colaboradores diferentes. Existem algumas características realmente interessantes neste lançamento, e vou tentar abordar aqui. ## História Antes de tratar do que há de novo, é interessante contextualizar um pouco a história do framework Spring Boot. Em uma publicação num blog publicada em agosto de 2013, [<NAME> anunciou o lançamento do primeiro marco de um novo projeto chamado Spring Boot](https://spring.io/blog/2013/08/06/spring-boot-simplifying-spring-for-everyone/). > Spring Boot aims to make it easy to create Spring-powered, production-grade applications and services with minimum fuss. It takes an opinionated view of the Spring platform so that new and existing users can quickly get to the bits they need. You can use it to create stand-alone Java applications that can be started using ‘java -jar’ or more traditional WAR deployments. Cerca de 9 meses depois, em abril de 2014, o Spring Boot 1.0 foi lançado. Desde então, houveram inúmeros lançamentos menores e evluções até alcançarmos o estágio atual, conforme pode ser conferido neste post do [Dan Vega](http://therealdanvega.com/blog/2018/03/01/what-is-new-spring-boot-2?utm_content=educational&utm_campaign=2018-03-20&utm_source=email-sendgrid&utm_term=554668&utm_medium=760202). ## O que há de novo no Spring A primeira grande evolução é a atualização para o [Spring Framework 5](https://springframework.guru/what-is-new-with-spring-framework-5/), lançado em setembro de 2017. O Spring Framework 5 apresenta uma longa lista de novos recursos, mas vamos destacar apenas alguns. ### O que há de novo no Spring Framework 5 - **Java 8+ Baseline**: Para criar aplicações baseadas Spring Framework daqui pra frente, o requisito mínimo é o Java 8. Inicialmente pode até parecer uma ótima mudança para os desenvolvedores, mas, de fato, é ainda maior para a equipe Spring. Isso deu a eles a chance de fazer algumas mudanças importantes que tornaram viável atualizar a base de código para todos os novos recursos no Java 8, como Lambdas e streams. Isso não apenas melhora a legibilidade do código, mas também oferece algumas melhorias de desempenho no núcleo do framework. - **Suporte ao Java 9**: Se você pretende usar o Java 9, terá que se atualizar para o Spring Framework 5 e, portanto, precisa atualizar para o Spring Boot 2. Provavelmente muitos não estão utilizando em produção, ainda, a última versão do Java, mas essa pode ser considerada uma ótima chance para começar a brincar com as novas funcionalidades desses dois frameworks. - **Spring MVC**: Por enquanto o Spring MVC não é o personagem principal desta história, mas houveram algumas atualizações agradáveis. Não vamos abordá-las aqui, mas dá para conferir na documentação do [Spring Framework 5](https://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-Spring-Framework-5.x#spring-web-mvc). - **Spring Webflux**: The reactive stack is our main character in the story of Spring Framework 5. This is a different way of thinking but fortunately for us, we don’t have to learn a whole new way of writing applications. Spring WebFlux is a fully asynchronous and non-blocking web framework built from the ground up allowing us to handle a massive number of concurrent connections. While this is a complete paradigm shift it is really easy to get started. ![]({{ BASE_PATH }}/images/2018-03-20-chegou-o-spring-boot-2/reactive_stack.png) - **Kotlin**: O suporte a Kotlin foi adicionado ao <http://start.spring.io>, mas no Spring Framework 5 há suporte dedicado para a linguagem. Com o suporte dedicado, surgiram alguns novos recursos interessantes que podem ser vistos em detalhes [aqui](https://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-Spring-Framework-5.x#kotlin-support). - **Testes**: A maior mudança na área de testes é o suporte completo para o modelo de programação e extensão Jupiter do JUnit 5. Quando criamos uma nova aplicação Spring Boot 2, ainda estamos usando JUnit 4 por padrão, porém é uma mudança simples migrar para JUnit 5. ### O que há de novo no Spring Boot 2 #### Atualizações de bibliotecas de terceiros Com a nova versão do Spring Boot, a equipe Spring teve a oportunidade de atualizar várias "dependências". - Thymeleaf 3 (O Thymeleaf starter agora inclui ``thymeleaf-extras-java8time``) - Jetty 9.4 - Tomcat 8.5 - Hibernate 5.2 - Flyway 5 - Gradle 4 #### Reactive Spring Data & Spring Security Como o Spring WebFlux, o Spring Data também fornece suporte para aplicações reativas. Atualmente, Cassandra, MongoDB, Couchbase e Redis possuem suporte a APIs reativas. O Spring Boot inclui starter-POMs para todos eles, o que deve facilitar demais. Também há a possibilidade agora de usar o Spring Security 5.0 nas aplicações reativos. Quando o Spring Security está no classpath, a configuração automática é fornecida para aplicativos WebFlux. #### Actuator O Spring Boot Actuator não é nenhuma novidade, mas foi completamente reescrito. O Actuator expõe os _endpoints_ automaticamente para obter informações sobre esse status de sua aplicação. O Actuator foi escrito para dar suporte aos novos requisitos e funcionalidades providas pelo stack reativo. Algumas das mudanças no Actuator: - Redesign para trabalhar tanto com servlet & reactive - Status & health (todos os detalhes) foram separados - Modelo de segurança simplificado - Migração para o micrometer (tipo o SLF4J mas para métricas) - Melhoria nas Estruturas JSON - Processo simplificado para a criação de Endpoints definidos pelo usuário - @Endpoint - @WebEndpoint - @JmxEndpoint Esta pode ser uma área em que as pessoas tenham problemas para atualizar por causa das mudanças no modelo de segurança. Por padrão, todos os endpoints da web estão disponíveis abaixo do caminho ``/actuator`` com URLs na forma ``/actuator/{id}``. O caminho base do ``/actuator`` pode ser configurado usando a propriedade ``manage.endpoints.web.base-path``. Existe um documento detalhado para a Spring Boot Actuator Web API Endpoints [disponível aqui](https://docs.spring.io/spring-boot/docs/2.0.x/actuator-api/html/). #### Segurança Simplificada No Spring Boot 2.x, um dos principais objetivos foi simplificar a configuração de segurança e facilitar a segurança personalizada. Por padrão, tudo está seguro, incluindo recursos estáticos e os pontos finais do Actuator. Se o Spring Security estiver no classpath, o Spring Boot irá adicionar a anotação @EnableWebSecurity e contar com a negociação de conteúdo do Spring Security para decidir qual mecanismo de autenticação usar. Uma vez que os desenvolvedores decidam que querem adicionar uma segurança personalizada, a configuração de segurança padrão fornecida pelo Spring Boot será desativada completamente. Neste ponto, os desenvolvedores precisam definir explicitamente todos os bits que desejam proteger. Isso significa que a configuração de segurança está agora em um só lugar e evita qualquer tipo de problemas com os ``WebSecurityConfigurerAdapters`` existentes. #### Suporte a HTTP/2 É difícil de acreditar, mas a especificação HTTP 1.1 foi lançada em **1996**. Não precisamos nem dizer isso, mas a web de hoje em dia é **muito** diferente. Se você quiser habilitar o HTTP/2 em suas aplicaçõess Spring MVC ou WebFlux, você pode usar a seguinte propriedade. ```java server.http2.enabled=true ``` Claro que isso também depende do servidor web escolhido e do ambiente da aplicação, já que esse protocolo não é suportado "_out-of-the-box_" a pelo JDK8. [Verifique a documentação para obter mais detalhes](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/howto-embedded-web-servers.html#howto-configure-http2). #### Configuration Properties No Spring Boot 1.x, essa noção de ligação relaxada ("_relaxed binding_") foi suportada e tudo isso significava que havia várias maneiras de criar um nome de propriedade (_camel case, underscore, hyphen_) e todos se vinculariam à mesma propriedade. Isso ainda funciona da mesma forma, mas o que eles apertaram foi a maneira como você lê variáveis em seu próprio código. A anotação @Value é um recurso de contêiner central e não fornece os mesmos recursos que as propriedades de configuração type-safe. ![]({{ BASE_PATH }}/images/2018-03-20-chegou-o-spring-boot-2/2018-02-28_07-12-58.png) <https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/boot-features-external-config.html#boot-features-external-config-relaxed-binding> #### Métricas As métricas do Spring Boot foram substituídas por Micrometer, que está sendo desenvolvido pela Pivotal. O Spring Boot Actuator fornece gerenciamento de dependência e configuração automática para Micrometer, uma fachada de métricas de aplicações que oferece suporte a vários sistemas de monitoramento, incluindo: * [Atlas](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/production-ready-metrics.html#production-ready-metrics-export-atlas) * [Datadog](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/production-ready-metrics.html#production-ready-metrics-export-datadog) * [Ganglia](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/production-ready-metrics.html#production-ready-metrics-export-ganglia) * [Graphite](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/production-ready-metrics.html#production-ready-metrics-export-graphite) * [Influx](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/production-ready-metrics.html#production-ready-metrics-export-influx) * [JMX](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/production-ready-metrics.html#production-ready-metrics-export-jmx) * [New Relic](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/production-ready-metrics.html#production-ready-metrics-export-newrelic) * [Prometheus](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/production-ready-metrics.html#production-ready-metrics-export-prometheus) * [SignalFx](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/production-ready-metrics.html#production-ready-metrics-export-signalfx) * [Simple (in-memory)](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/production-ready-metrics.html#production-ready-metrics-export-simple) * [StatsD](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/production-ready-metrics.html#production-ready-metrics-export-statsd) * [Wavefront](https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/production-ready-metrics.html#production-ready-metrics-export-wavefront) ![]({{ BASE_PATH }}/images/2018-03-20-chegou-o-spring-boot-2/2018-02-28_06-59-52.png) Mais informações sobre o Micrometerm visite <https://micrometer.io/> #### Quartz Scheduler O Spring Boot 2 fornece suporte para o Quartz Scheduler que pode ser usado através do iniciador dedicado ``spring-boot-starter-quartz``. Tanto no armazenamento na memória quanto JDBC podem ser configurados. ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> ``` #### HikariCP Connection Pool O pool de conexão padrão mudou do Tomcat para HikariCP. Se antes era utilizado ``spring.datasource.type`` para forçar o uso do Hikari em uma aplicação baseado no Tomcat, agora não há mais necessidade. Da mesma forma, se preferir ficar com o pool de conexão do Tomcat, basta adicionar o seguinte à sua configuração: ```java spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource ``` ### Dev Tools Por padrão, cada vez que a aplicação é reiniciada, um relatório que mostra o delta de avaliação de condição é registrado. O relatório mostra as mudanças na configuração automática da sua aplicação à medida que ocorrem as alterações como, por exemplo, adicionar ou remover beans e definir propriedades de configuração. Para desativar o registro do relatório, defina a seguinte propriedade: ```java spring.devtools.restart.log-condition-evaluation-delta=false ``` #### JUnit 5 Conforme já dito anteriormente, o padrão para um aplicativo Spring Boot é ainda usar o JUnit 4. Se quiser mudar para o JUnit 5, será preciso excluir JUnit 4 do teste de inicialização inicial do spring boot e adicionar as dependências necessárias. ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>junit</groupId> <artifactId>junit</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-surefire-provider</artifactId> <version>${junit-platform.version}</version> </dependency> </dependencies> </plugin> </plugins> </build> ``` Este é um post baseado no artigo publicado pelo [<NAME>](http://therealdanvega.com/blog/2018/03/01/what-is-new-spring-boot-2?utm_content=educational&utm_campaign=2018-03-20&utm_source=email-sendgrid&utm_term=554668&utm_medium=760202). Artigo originalmente publicado em [Chegou o Spring Boot 2.0](http://viniciusgarcia.me/development/chegou-o-spring-boot-2/) :: [viniciusgarcia.me](http://viniciusgarcia.me/) <file_sep>/_posts/2014-01-22-dymos-qos.md --- layout: post title: "Dymos QoS" categories: Pesquisa tag: mestrado --- Neste post pretendo descrever em linhas gerais a minha proposta de Mestrado em Ciência da Computação e o seu respectivo andamento. Antes de prosseguir gostaria de falar a respeito do cenário que motiva essa pesquisa. Imaginemos uma aplicação para dispositivos móveis que tem como uma de suas funcionalidades exibir vídeos que o usuário. Esses vídeos não estão armazenados no aparelho e são acessados via Internet no momento em que o usuário os requisita à aplicação, sem que o mesmo saiba necessariamente de onde vêm esses vídeos. Assumindo que os vídeos são transmitidos para a aplicação a partir de um web service chamado “VideoWS1″, o que aconteceria se este serviço ficasse indisponível? É evidente que a aplicação móvel não poderia transmitir o vídeo ao usuário por não poder atender a sua requisição em tempo de execução. Um estudo anterior[1] resolve este problema selecionando arbitrariamente um outro serviço (“VideoWS2″) na ausência do “VideoWS1″ para transmitir os vídeos sem que isso seja perceptível ao usuário. No entanto, nesta abordagem proposta (em [1]) não é possível utilizar atributos de qualidade para avaliar qual seria o melhor serviço para substituir o web service indisponível. Muito menos diferenciar a qualidade do serviço prestado em níveis de serviço distintos com custos, benefícios, níveis de confiabilidade e disponibilidade distintos. O Dymos QoS tem por objetivo oferecer ao usuário e ao desenvolvedor do aplicativo móvel a possibilidade de negociar dentre um conjunto pré-definido de web services qual melhor atende as expectativas do usuário em tempo de execução. Para tanto o Dymos QoS armazena informações contextuais referentes aos web services permitindo que a aplicação selecione para a exibição do conteúdo um serviço que esteja dentro de um nível de serviço desejado comparando-o e relacionando o seu benefício (tempo de resposta), confiabilidade e disponibilidade em uma proporção com o custo. Assumimos, em consonância com os estudo de Yu[2], que quanto maior for o número de requisições em um instante de tempo t1 para um determinado web service maior será o tempo de resposta para um nova requisição feita a este. Sendo assim definimos como benefício a proporção inversa do valor da carga de requisições em um web service em um instante de tempo t1 para um determinado nível de serviço. O custo de um web service em um instante de tempo t1 para um determinado nível de serviço é adquirido através da soma do custo do serviço em si e do custo de transmissão do mesmo. Os valores de confiabilidade e disponibilidade são adquiridos a partir de dados históricos onde a disponibilidade é a proporção entre a quantidade de tempo que um serviço está disponível pela quantidade de tempo no qual este serviço foi monitorado dentro de um determinado nível de serviço. A confiabilidade de um web service em um nível de serviço é a proporção entre o número de requisições respondidas com sucesso e o total de requisições. O Dymos QoS está estruturado para trabalhar com arquiteturas orientadas à serviço e foi construído para ser utilizado em linhas de produto de software dinâmicas e orientadas à serviço. O seu processo de avaliação está em fase de treinamento e será realizado com uma linha de produto de software de guias de visitas móveis. Referências 1. <NAME>. – Uma Abordagem para Suporte a Variabilidades Dinâmicas em Linhas de Produto de Software Orientado a Serviços e Sensível ao Contexto, Recife, Agosto de 20013 2. <NAME>., & <NAME>. (2005). Service selection algorithms for Web services with end-to-end QoS constraints. Information Systems and e-Business Management, 3(2), 103–126. doi:10.1007/s10257-005-0052-z Texto originalmente publicado por [<NAME>](https://jacksonsplace.wordpress.com/2014/01/02/dymos-qos/){:target="_blank"}.<file_sep>/_posts/2017-11-16-novo-livro-publicado.md --- layout: post title: "Membros do ASSERT Lab publicam novo livro" categories: Noticias tag: livro --- Acabou de ser publicado o livro "[**UMA INVESTIGAÇÃO SOBRE AS DIFICULDADES DE PLANEJAMENTO DE TI EM INSTITUIÇÕES PÚBLICAS BRASILEIRAS: UMA ABORDAGEM COM TEORIA FUNDAMENTADA EM DADOS**](https://www.amazon.com.br/INVESTIGA%C3%87%C3%83O-DIFICULDADES-PLANEJAMENTO-INSTITUI%C3%87%C3%95ES-BRASILEIRAS-ebook/dp/B077GBLBQ3/ref=sr_1_1?ie=UTF8&qid=1510830571&sr=8-1&keywords=vinicius+cardoso+garcia)" de autoria de <NAME> e <NAME>. O livro é resultado de dois anos de pesquisa executados durante o Mestrado Profissional de Plínio, sob oretação do prof. Vinicius, no Centro de Informática de UFPE. Plínio defendeu o seu mestrado em 2016 e no último ano trabalhou para consolidar o conhecimento no livro que acaba de ser publicado. Durante seu mestrado, a demanda pelos resultados foi grande, principalmente por parte de instituições públicas, o que motivou a ideia da publicaçào como livro. Eis o resumo do mesmo. _Assim como em organizações privadas, os órgãos públicos devem realizar processos de planejamento para cumprir seus objetivos. O governo brasileiro determina que as instituições federais elaborem um Plano Diretor de TI (PDTI), importante instrumento de planejamento das atividades de TI. O PDTI permite que a instituição tenha controle sobre os recursos gastos com tecnologia da informação, melhore o alinhamento estratégico e minimize os riscos relacionados aos ativos de TI. Contudo, relatórios do Tribunal de Contas da União (TCU) apresentam índices preocupantes com relação à adoção do PDTI. Apesar de seus conhecidos benefícios e de ser obrigatório nos órgãos da administração pública federal, o PDTI não está sendo adotado por um número considerável de instituições. Além disso, pouco mais da metade dos órgãos que possuem PDTI fazem o vínculo das ações de TI com os objetivos estratégicos da instituição, ou seja, apresentam deficiências de alinhamento estratégico. Esta obra busca compreender de forma abrangente as dificuldades que resultam nos números insatisfatórios apresentados pelo TCU. O objetivo principal da pesquisa que originou este livro consistiu em elaborar teoria fundamentada em dados que apresente uma relação de causa e consequência entre os elementos que restringem a elaboração do PDTI. Os resultados apresentam duas teorias, a primeira, com as razões da ausência do PDTI em algumas instituições e, a segunda, com as causas das dificuldades encontradas durante a elaboração do PDTI. Utilizando o mesmo método, Grounded Theory, foi possível relacionar os elementos das teorias fundamentadas com um conjunto de 5 processos e 48 melhores práticas de planejamento de TI. Desta forma, este trabalho apresenta uma forma de minimizar os problemas encontrados na elaboração do PDTI._<file_sep>/_posts/2012-10-31-in1163-inicio-da-3a-sprint.md --- layout: post title: "[in1163] Início da 3ª sprint" categories: Educacao tag: in1163 --- Semana passada (sexta-feira, 26/10/2012) e nesta quarta-feira (31/10/2012) tivemos as apresentações dos resultados da segunda sprint, conduzida dentro das disciplinas [in1163] Tópicos Avançados em Desenvolvimento de Software de Código Aberto e [in1184] Trabalho Individual em Engenharia de Software de forma casada. Obtivemos os seguintes resultados. **Sexta-feira, 26/10/2012** * _**<NAME>**_, [Um Agente Inteligente Para Recomendação em Cloud Storage](https://docs.google.com/open?id=0Bxt1VZoj3lGuTzVXdG5RWGhZNnc) * _**<NAME>**_, [A Cognitive Privacy Framework to a Smart City Architecture based on People as Sensors](https://docs.google.com/open?id=0Bxt1VZoj3lGuampyN3U5LTdPNFU) * _**<NAME>**_, [Uma arquitetura para Smart Cities baseada na Internet of Things](https://docs.google.com/open?id=0Bxt1VZoj3lGueXJCS2Y2T01pb1E) * _**<NAME>**_, [Uma Arquitetura de Referência para Data Cloud Storage](https://docs.google.com/open?id=0Bxt1VZoj3lGuLW43S3RRblV1ZG8) * _**<NAME>**_, [SafeMash: um framework para detecção de falhas de segurança em Cloud-based mashups](https://docs.google.com/open?id=0Bxt1VZoj3lGuSEppUU5Eb1dtd0E) * _**<NAME>**_, [Uma Abordagem Restful para Prover as Funcionalidades Ideais para Sistemas de Cloud Storage](https://docs.google.com/open?id=0Bxt1VZoj3lGuT09vdWNvd0w3MGM) **Quarta-feira, 31/10/2012** * _**<NAME>**_, [Uma DSL para Composição Segura de Software em SPL Sensíveis ao Contexto](https://docs.google.com/open?id=0Bxt1VZoj3lGuRElHQUdYSzZ5eVk) * _**<NAME>**_, [Abordagem de monitoramento e definição de SLA para Cloud Storage em uma arquitetura P2P](https://docs.google.com/open?id=0Bxt1VZoj3lGudGVCVUpLczRhNDQ) * _**<NAME>**_, [Melhoria de Performance para cloud storage P2P](https://docs.google.com/open?id=0Bxt1VZoj3lGuTlYxOTg5ZEgwdFk) * _**<NAME>**_, [eme.io](https://docs.google.com/open?id=0Bxt1VZoj3lGuWXpXWVNuSGcxTG8) * _**<NAME>**_, [SCMM (Smart City Maturity Model)](https://docs.google.com/open?id=0Bxt1VZoj3lGuV0dXNlp3TjAxenM) * _**<NAME>**_, [Avaliação de abordagens de derivação de produtos para SPLs sensíveis a contexto e com arquitetura orientada a serviços](https://docs.google.com/open?id=0Bxt1VZoj3lGuZzNpdlNWRElzVmM) [[brienfing atualizado](https://docs.google.com/open?id=0Bxt1VZoj3lGuR1NzTmY5d29JSGM)] Parabéns a todos pelos resultados alcaçados! Agora é manter o foco e se empenhar ainda mais para fecharmos os trabalhos nesta terceira e última sprint!<file_sep>/_posts/2012-11-27-assert-apresenta-artigos-no-icsea2012.md --- layout: post title: "ASSERT apresenta artigos no ICSEA'2012" categories: Artigos tag: conferencia --- ![Vista panorâmica Lisboa](http://www.cin.ufpe.br/~lmn2/icsea2012/lisbon.jpg) Assim como foi divulgado no post do dia 24/10/2012 ([link](http://assertlab.com/post/34227137391/assert-no-icsea2012-e-no-icpads2012)), o pesquisador <NAME> esteve presente na Seventh International Conference on Software Engineering Advances -&nbsp;[ICSEA’2012](http://www.iaria.org/conferences2012/ICSEA12.html "ICSEA") para apresentação dos dois artigos intitulados: “**_A Systematic Mapping Study on Domain-Specific Languages_**” (artigo completo [aqui](http://www.thinkmind.org/index.php?view=article&amp;articleid=icsea_2012_7_30_10390 "Nascimento et al.")), de autoria do próprio <NAME> com <NAME>, <NAME>, <NAME>, <NAME> e <NAME> e “**_Evaluating performance of distributed systems with MapReduce and application traffic analysis_**” (artigo completo [aqui](http://www.thinkmind.org/index.php?view=article&amp;articleid=icsea_2012_25_30_10419 "Vieira et al.")), de autoria de <NAME>, <NAME>, <NAME>, <NAME> e <NAME>. A conferência começou no dia 18/11 com a apresentação intitulada “**_IBM Test Overview and Best Practices_**” seguida do coquetel de abertura. No dia 19/11, iniciaram-se propriamente as apresentações dos artigos aprovados na ICSEA, após apresentação do [Prof. <NAME>](http://www.iaria.org/speakers/PetreDini.html), membro sênior da IARIA. Oito sessões de 4 ou 5 artigos seguiam-se durante o dia inteiro em dois auditórios. Pela manhã duas sessões ocorriam em paralelo em cada auditório e à tarde mais seis sessões ocorriam, sendo duas simultaneamente em três horários distintos. No dia 20/11, o Prof. <NAME> apresentou o seu trabalho que trazia um estudo de mapeamento sistemático sobre a área de linguagens específicas de domínio. Após mostrar brevemente como um mapeamento sistemático deve ser executado, os resultados foram explanados para a audiência e, infelizmente, poucas perguntas foram levantadas, provavelmente por ter sido uma das últimas apresentações. Uma das perguntas que surgiram diziam respeito à forma do trabalho e à quantidade de estudos levantados Já que havia um número expressivo de artigos catalogados (1440 no total), um ouvinte gostaria de saber como todo esse material tinha sido catalogado e se poderia ser disponibilizado publicamente. A resposta do Prof. Leandro foi: “Todas as referências foram gerenciadas com através de planilhas com dados alimentados a partir de arquivos BiBTeX que foram processados usando-se um script em Java. Tal material pode sim ser disponibilizado” e um e-mail de contato foi deixado para quem se interessasse. No dia seguinte, o segundo artigo foi apresentado. Este artigo tratava de uma abordagem para avaliação de sistemas distribuídos utilizando-se _MapReduce_ e análise de tráfego de dados da aplicação com _deep packet inspection_ (DPI). Para tal avaliação, foram usados os dados de uma ferramenta de armazenamento em _cloud _através de uma arquitetura P2P. Dois ouvintes mostraram-se interessados pelo trabalho. Uma pergunta surgiu justamente para entender melhor a diferença entre a abordagem de avaliação de desempenho em sistemas distribuídos e a ferramenta de armazenamento em _cloud_. Todas as apresentações seguiram-se até o dia 22/11. Conforme Prof. Leandro, duas apresentações chamaram sua atenção. Um artigo intitulado “_Architecture Centric Tradeoff - A Decision Support Method for COTS Selection and Life Cycle Management_” e a palestra intitulada “_Envisioning the Next Software Development Era_”, do Prof. [<NAME>](http://www.iaria.org/fellows/RoyOberhauser.pdf), Aalen University, Germany. Além das apresentações, houve diversas oportunidades de conhecer um pouco de Lisboa e Portugal como um todo tanto no Jantar de Gala, no dia 21/11 quanto no city tour, no dia 23/11, ambos os eventos organizados pela própria conferência. A ICSEA aconteceu em paralelo com outras conferências e teve um considerável número de participantes, seguindo a tendência de centralização de algumas conferências que tratam de tópicos relacionados para serem realizadas no mesmo local e permitir maior troca de experiências entre os participantes.<file_sep>/_posts/2013-06-03-assertlab-na-www2013.md --- layout: post title: "AssertLab na WWW2013" categories: Artigos tag: conferencia --- ![image]({{ BASE_PATH }}/images/2013-06-03-assertlab-na-www2013/foto1.jpg?raw=true) Durante o período de 13 a 17 de Maio de 2013, dois pesquisadores do AssertLab, [<NAME>](http://bit.ly/19DICGd) e [<NAME>](http://bit.ly/1aYlobC), estiveram presentes numa das maiores e mais relevantes conferências sobre o tema “Internet” de uma forma geral: a WWW (World Wide Web) Conference, edição 2013, que ocorreu na cidade do Rio de Janeiro, Brasil. A conferência contou com nomes de peso como [<NAME>](http://bit.ly/12qjXES), mundialmente conhecido com inventor da Web, e Dr. [<NAME>](http://bit.ly/15wAUKJ), responsável por projetos de pesquisa ligados à computação realizada pelo cérebro humano. A conferência contou com a participação de mais de 800 pessoas, com diversas sessões separadas por tema e workshops envolvendo pesquisadores e especialistas de várias partes do mundo. Nos dois primeiros dias, 13 e 14, a conferência foi composta por workshops envolvendo temas diversos. Um dos workshops intitulado “_Social Machines (SOCM)_” contou com a participação de <NAME>, membro do AssertLab e pesquisador da UFPE, que teve sua publicação abrindo a sessão e gerando discussões interessantes. Mais detalhes sobre o SOCM Workshops serão mostrados em [outro post](http://bit.ly/133Ytsp), detalhado pelo próprio Vanilson. Nos três dias consecutivos, 15 a 17, o evento iniciou-se com as palestras de _Keynote Speakers_ seguindo-se das sessões de pesquisa. No dia 15, a primeira palestra do professor da Universidade <NAME> e empreendedor [<NAME>](http://bit.ly/11SLai0) abordou a questão do empreendedorismo de forma bastante simples. <NAME> é o criador do projeto Captcha e CEO da duolingo e apresentou em detalhes este último projeto. O professor compartilhou com todos suas experiências empreendedoras e como ideias simples podem se tornar poderosas ferramentas na atual mundo conectado. Em seguida, <NAME> sentou em uma sessão privada de perguntas direcionada para empreendedores. Dentre diversas perguntas e respostas, uma bastante curiosa dizia: “Qual o segredo para descobrir projetos que vão dar certo?” e a resposta do professor seguiu o seguinte raciocínio “Olhe para o mercado americano, se algo estiver funcionando lá e ninguém ainda trouxe para seu país/região, então copie-o. As chances de dar certo são grande uma vez que deram certo nos EUA”. No mesmo dia, uma sessão de perguntas e respostas foi realizada entre <NAME> e os estudantes. No dia seguinte, <NAME> abriu o evento como Keynote Speaker numa palestra intitulada “_Computing with Brain Circuits_”. A palestra mostrou toda a saga do pesquisador brasileiro, residente na Carolina do Norte, EUA e professor da Duke Universisty, responsável por diversos projetos de pesquisas que envolvem a computação com o cérebro. Muitos resultados da sua pesquisa mostram uma forma de predizer os pensamentos de primatas ou mover braços mecânicos apenas com a força do pensamento. Um de seus projetos mais audaciosos está relacionado com a Copa de 2014 e irá tentar fazer com que um ser humano que perdeu os movimentos das pernas consiga controlar um exoesqueleto para chutar realizar o primeiro chute da competição apenas com a força do pensamento. No último dia da conferência, o professor [<NAME>](http://bit.ly/11Aw5vr) da Cornell University apresentou uma palestra intitulada “_Computational Perspectives on Social Phenomena in On-Line Networks_”. A apresentação retratou o crescente fenômeno de acúmulo de dados sobre o comportamento coletivo e interações sociais de milhões de pessoas através das redes sociais. A análise desses dados oferece insights sobre questões fundamentais das ciências sociais envolvendo as interações dinâmicas entre indivíduos. Um dos pontos interessantes a se ressaltar no evento como todo foi sua organização. Os locais e horários das sessões foram organizados de tal forma que, durante os intervalos do café, as pessoas se encontravam num hall central, com vários stands de grandes organizações, como Google, Microsoft, Facebook, Red Hat, Globo.com, entre outras. Cada stand exibia as questões relevantes de pesquisa que vinham sendo tocadas em cada empresa e permitiam a interação dos participantes com os pesquisadores diretamente. A WWW2013 foi um evento único de grande porte que contou com a presença do AssertLab e trouxe muitos contatos para parcerias futuras.<file_sep>/_posts/2013-04-09-assert-and-ines-at-15th-international-conference.md --- layout: post title: "ASSERT and INES at 15th International Conference on Enterprise Information Systems (ICEIS)" categories: Artigos tag: conferencia --- Two papers has been accepted for publication as Short Paper in the [15th International Conference on Enterprise Information Systems](http://www.iceis.org/Home.aspx) (ICEIS). The first is entitled “**Smart Cities Architectures: A Systematic Review**" and second is "**Synaptic City: An architectural approach using an OSGI Infrastructure and GMaps API to build a City Simulator**". Both papers are authored by <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. The conference will be held in July 4 - 7, 2013 at ESEO, Angers Loire Valley, France. This activity is one result of the MSc research being done by <NAME> and <NAME>. A brief overview of the two paper is given next: “Smart Cities Architectures: A Systematic Review" :&nbsp; _The smart cities concept arises from the necessity of manage several problems caused by the unbridled population growth at urban centers. To make a city become "smart" it is needed employ Information Technology and Communication (ICT) to access, process and deliver information according to the urban context. This information can be employed to mitigate several urban issues, such as jams, high natural resource consumption, epidemic, sustainability, waste management, low quality and life expectation of citizens, among others. Thus, the need arises to create architecture able to interact with the Internet of Things, i.e., several built-in devices, appliances, sensors and actuators embedded in each urban context. This work is a systematic review regarding proposals for such architectures. After selecting the relevant approaches, we have identified a set of issues that these approaches aim to solve and some architectural patterns employed._ "Synaptic City: An architectural approach using an OSGI Infrastructure and GMaps API to build a City Simulator" _Big cities have noticeable problems resulting from poor management of urban services. Monitoring a city gives some parameters to evaluate the performance of urban services, allowing to identify their flaws, and elaborate strategic plains to correct them. Smart cities architectures are intended to propose Information and Communication Technologies (ICTs) solutions to increase service efectiveness. Considering that to establish a ICT infrastructure to support a smart city architecture is very expensive, once you have got the data and you know what urban service you will attend to, you can use a city simulator to test how the architecture will behave when facing the city's problems. In this context we propose the Synaptic City architecture, together with a city simulator, with which we modeled a Brazilian city, Recife, Pernambuco, in order to discuss its main problems._<file_sep>/sobre.md --- layout: page title: Sobre tagline: Algumas palavras sobre o nascimento deste grupo de pesquisa permalink: /sobre.html --- # Nasceu o ASSERT! No dia de ontem nasceu oficialmente o **ASSERT**, um grupo de *pesquisa + desenvolvimento + inovação* focado em resolver problemas reais da engenharia de software e sistemas. O ASSERT, acrônimo para *Advanced System and Software Engineering Research Technologies Lab*, já nasce grande, com um grupo comprometido com resultados **práticos** e **intensivos** em **pesquisa de qualidade**. O que pretendemos com a formação deste grupo é ajudar na criação de soluções para os principais problemas que o mercado, e as empresas, de TI (inicialmente .BR) enfrentam nas novas plataformas de mercado, negócios e tecnologias. Atualmente temos nos deparado com uma série de desafios voltados para enfrentar os [LSCITS](http://www.lscits.org/){:target="_blank"}. De acordo com [<NAME>](http://www.software-engin.com/){:target="_blank"}, LSCITS são sistemas organizacionais utilizados por um grande número, ou conjunto, de stakeholders com diferentes objetivos, visões, eventualmente culturas, e propósitos. Como bem disse Sommerville, essa escala e complexidade significa que eles podem apresentar comportamentos e desempenho inesperado e a evolução destes sistemas normalmente é difícil, custosa e de consequências quase imprevisíveis. No cenário atual de desenvolvimento e vivência de software (sim, vivência, todos vivemos imersos em software!) os LSCITS estão cada vez mais inseridos no dia-a-dia das pessoas comuns e não mais apenas nos grandes Centros de Tecnologia. Isso acarreta em uma série de aspectos técnico-sócio-econômicos que são fortemente influenciados por fatores humanos, sociais, organizacionais, tecnológicos, culturais e mercadológicos. Além disso, as plataformas de atuação, negociação, interação e desenvolvimento mudou para a rede, ou usando uma buzzword, para a Nuvem! A evolução para essa nova Web (conhecida por [Web 3.0](https://techcrunch.com/2008/08/01/welcome-to-web-30-now-your-other-computer-is-a-data-center/){:target="_blank"}) adiciona uma complexidade acidental a engenharia de software e sistemas antes nunca imaginado. Neste contexto, e inspirados pelos desafios discutidos por Sommerville em [Large-scale Complex it systems](https://dl.acm.org/citation.cfm?id=2209268){:target="_blank"}, publicado na Communications of the ACM, Volume 55, Issue 7, páginas 71-77 em Julho de 2012, iniciamos nossos trabalhos, oficialmente, levantando os 11 principais desafios da nossa primeira agenda de trabalho: 1. How can we design, develop, model and simulate the interactions between independent systems (SaaS or SaSM - Systems as [Social Machines](http://ieeexplore.ieee.org/document/6032321/){:target="_blank"})? 1. How can we monitor coalitions or federations of [SaaS or SaSM] and what are the warning signs of problems? 1. How can [SaaS or SaSM] be designed to recover from failure? 1. How can we integrate socio-technical factors into [SaaS or SaSM] and software engineering methods? 1. To what extent can coalitions of [SaaS or SaSM] be self-managing? 1. How can we manage complex, dynamically changing [SaaS or SaSM] configurations? And intra and/or inter federations of [SaaS or SaSM]? 1. How can we support the agile engineering of coalitions or federations of [SaaS or SaSM]? 1. How should coalitions or federations of [SaaS or SaSM] be regulated and certified? 1. How can we do ‘probabilistic verification’ of [SaaS or SaSM]? 1. How should shared knowledge in a coalition federation of [SaaS or SaSM] be represented? 1. How can we prepare system and software engineers to build single, coalitions or federations of [SaaS or SaSM]? 1. Por SaaS eu estou falando de sistemas (que eventualmente envolvem SaaS, PaaS e IaaS) para plataformas de cloud computing. Tem interesse em responder alguma dessas perguntas? Tem as suas próprias perguntas? Então junte-se a nós!<file_sep>/_posts/2015-09-17-assert-sbti2015.md --- layout: post title: "ASSERT @WTD WebMedia 2015" categories: Artigos tag: conferencia --- É com prazer que informamos que o artigo "_**SCiAl: Usando Dados Públicos para Agrupar Cidades Inteligentes Alagoanas**_“, de autoria de <NAME>, <NAME> e <NAME>, foi aceito para apresentação no [IV Simpósio Brasileiro de Tecnologia da Informação (SBTI)](http://www.sbti2015.com.br/){:target="_blank"} que vai ser realizado entre os dias 14 a 16 de Outubro em Aracaju.A apresentação do artigo no evento permitirá que ele seja publicado na (RBADM) Revista Brasileira de Administração Científica. > Resumo: O conceito de Cidades Inteligentes surgiu frente às necessidades da nova sociedade da tecnologia e informação em identificar formas de otimizar recursos. Atualmente existem modelos para comparar e medir os domínios dessas cidades, sobretudo modelos americanos e europeus. Entretanto, estes modelos se mostram ineficazes ou incompatíveis com as necessidades de pequenas e médias cidades, cujas preocupações ainda residem nos domínios de infraestrutura e oferta de serviços públicos básicos. Este trabalho apresenta o resultado da mineração de dados abertos públicos e a comparação de indicadores que permitiu criar um agrupamento de cidades inteligentes (SCiAl – Smart Cities Alagoas) por semelhanças de características regionais.<file_sep>/_posts/2013-03-05-defesa-de-dissertacao-de-mestrado-n-1253.md --- layout: post title: "Defesa de Dissertação de Mestrado Nº 1.309" categories: Defesa tag: mestrado --- ## Pós-Graduação em Ciência da Computação – UFPE ### Defesa de Dissertação de Mestrado Nº 1.253 Aluno: [**<NAME>**](http://lattes.cnpq.br/6100546713818163) Orientador: **Prof. <NAME>** Título: **_Monext: An Accounting Framework for Federated Clouds_** Data: 27/02/2013 Hora/Local: 10:00h – Sala D226 Banca Examinadora: * Prof. [<NAME>](http://lattes.cnpq.br/4220236737158909) &nbsp;(UFPE / CIn) * Prof. [<NAME>](http://lattes.cnpq.br/5957855817378897) (UFCG / Departamento de Sistemas e Computação) * Prof. [<NAME>](http://lattes.cnpq.br/6613487636748832) (UFPE / CIn) Apresentação disponível [aqui](http://pt.scribd.com/doc/128372634/Monext-An-Accounting-Framework-for-Federated-Clouds-Apresentacao) [[MORE]] **RESUMO:** _A Computação na Nuvem se tornou um paradigma consumado para executar serviços em infraestruturas externas, onde de uma forma virtual a capacidade praticamente ilimitada pode ser alocada dinamicamente. Este paradigma estabelece um novo cenário para a implantação de aplicações e serviços de TI. Neste modelo, desde aplicações completas até infraestrutura de máquinas são ofertadas a usuários, que são cobrados apenas pelo uso dos recursos consumidos. Desta forma, os bens de consumo da nuvem são ofertados através de abstrações de serviços, onde atualmente são citadas três principais categorias: Software como Serviço (SaaS), Plataforma como Serviço (PaaS) e Infraestrutura como Serviço (IaaS). No caso do IaaS são oferecidos recursos computacionais na forma de Máquinas Virtuais para o cliente final. Para atingir o aspecto ilimitado de recursos é necessário distribuir estas Máquinas Virtuais por vários Data Centers. Esta distribuição dificulta atender uma série de requisitos como Segurança, Confiabilidade, Disponibilidade e a Tarifação pelos recursos consumidos. A Tarifação refere-se a como os recursos são registrados, contabilizados e cobrados. Mesmo no caso de um único provedor esta tarefa não é nada fácil e existe um contexto que esta dificuldade se torna ainda maior, conhecida como Federação de Computação na Nuvem ou também chamadas de Nuvens Federadas. Nuvens Federadas ocorrem quando um provedor de Computação na Nuvem terceiriza recursos dinamicamente para outros provedores em resposta à variação da demanda. Desta forma ocorre um aglomerado de nuvens, porém seus recursos são heterogêneos, acarretando num maior esforço para gerenciar os recursos distribuídos e por consequência para a Tarifação. Neste contexto foram identificadas pesquisas nesta área sobre plataformas para Nuvens Federadas que não abordam o requisito de Tarifação. Esta dissertação apresenta um framework voltado à tarifação de Infraestrutura como Serviço com foco em Nuvens Federadas. Objetivando colher informações sobre esta área e consequentemente gerar insumos para fundamentar as decisões na construção do framework, foi aplicado um Estudo de Mapeamento Sistemático. Esta dissertação também apresenta uma validação inicial da ferramenta, através de um estudo de caso, mostrando indícios de que os requisitos gerados pelo Mapeamento Sistemático foram atendidos, bem como será viável a aplicação da solução por provedores de serviços de nuvem em um cenário real._ **Palavras-chave**: _Computação na Nuvem, Infraestrutura como Serviço, Tarifação, Con-tabilidade, Nuvens Federadas, Linguagem Específica de Domínio_<file_sep>/_posts/2012-10-24-assert-e-ines-no-dsm2012-o-artigo-eseml.md --- layout: post title: "ASSERT e INES no DSM'2012" categories: Artigos tag: conferencia --- O artigo&nbsp;[ESEML - Empirical Software Engineering Modeling Language](http://www.dsmforum.org/events/DSM12/Papers/Cartaxo.pdf), de autoria de <NAME> e <NAME>, membros do grupo ASSERT, em parceria com <NAME>, <NAME>,&nbsp;[<NAME>](http://www.cin.ufpe.br/~alms/),&nbsp;[<NAME>](http://www.cin.ufpe.br/~scbs/)&nbsp;publicaram um artigo no &nbsp;[12th Workshop on Domain-Specific Modeling - DSM 2012](http://www.dsmforum.org/events/DSM12/)&nbsp;que ocorre&nbsp;em conjunto com o&nbsp;[SPLASH’2012 (ACM Conference on Systems, Programming, Languages, and Applications: Software for Humanity)](http://splashcon.org/2012/). <iframe width="560" height="315" src="https://www.youtube.com/embed/fqhvt2Ppojw" frameborder="0" allowfullscreen></iframe> O abstract do artigo relata... > _New processes, patterns, structures, tools, languages, and practices are being proposed for software development, but technology transfer is hard to achieve. One of the objectives of empirical studies is easing technology transfer from academy to industry. On the other hand, there are a number of issues that hinder the application of empirical studies, more specifically, controlled experiments. This paper defines a visual DSL for modeling controlled experiments supporting researchers that are not experts in such study. By using the language, the researcher is guided to define the elements of an experimental plan and connections, which is automatically generated, resulting a complete document of experimental plan. The proposed environment assists the definition of controlled experiments, increasing empirical evaluation of the proposed technologies. More specifically, the current version of our proposal generates the experimental plan from the experiment model defined using the DSL._ [A apresentação do artigo](http://youtu.be/fqhvt2Ppojw)&nbsp;foi feita pelo professor <NAME>, com colaboração de <NAME>, que foram participar do evento. Parabéns aos autores, em especial a Sérgio pela brilhante apresentação!<file_sep>/_posts/2014-03-10-defesa-de-tese-de-doutorado-n-206.md --- layout: post title: "Defesa de Tese de Doutorado Nº 206" categories: Defesa tag: doutorado --- ## Pós-Graduação em Ciência da Computação – UFPE ### Defesa de Tese de Doutorado Nº 206 **Aluno**: <NAME> **Orientador**: Prof. <NAME> **Título**: _**SMADL – The Social Machines Architecture Description Language**_ **Data**: 11/03/2014 **Hora/Local**: 8h à Sala D001 (Bloco D – Térreo) – Centro de Informática Banca Examinadora: * Prof. <NAME> (CIn/UFPE) * Prof. <NAME> (CIn / UFPE) * Prof. <NAME> (Departamento de Computação / UFSCar) * Prof. <NAME> (Departamento de Computação / UFSCar) * Prof. <NAME> (DEINFO / UFRPE) **RESUMO**: > Nós estamos experimentando um alto crescimento no número de aplicações web sendo desenvolvidas. Isto está acontecendo principalmente porque a web está entrando em uma nova fase, chamada web programável, onde diversos sistemas baseados na web estão disponibilizando suas APIs publicamente. Com o objetivo de lidar com a complexidade dessa web emergente, nós definimos a noção de uma Máquina Social (SM) e vislumbramos uma linguagem que permite descrever redes de tais máquinas. >Para começar, nós definimos uma Máquina Social como sendo “um componente conectável e programável que encapsula (WI) um sistema de processamento de informação (IPS) e define um conjuntos de serviços requeridos (RS) e providos (PS), dinamicamente disponível sob certas restrições ©, as quais são determinadas por, dentre outras coisas, seus relacionamentos (Rel) com terceiros”. > Para que seja possível a aplicação prática do conceito de Máquina Social previamente mencionado, nós definimos SMADL, a linguagem para descrição arquitetural de máquinas sociais, como uma tentativa de ser uma forma completamente diferente de se programar a web, misturando conceitos de linguagens de descrição arquitetural (ADLs) e linguagens específicas de domínio (DSLs). Como uma ADL, a linguagem permite a descrição de máquinas sociais (e redes de tais) em termos de relacionamentos (Rel) como abstrações de alto nível, sem a necessidade de se especificar os detalhes de comunicação (protocolos) e/ou métodos de autenticação. Como uma DSL, ela permite a implementação e integração de serviços web usando uma sintaxe de tipos dinâmicos, completamente integrada à máquina virtual Java e a IDE Eclipse. Cada elemento do conceito de uma máquina social é diretamente mapeado na linguagem. > Em poucas palavras, SMADL pode ser definida como uma linguagem dirigida a relacionamentos que pode ser usada para descrever interações entre qualquer número de máquinas de inúmeras formas, como um meio de representar máquinas interagindo na web realmente, tais como, Twitter rodando em cima da Amazon AWS, mashups construídos usando o Google Maps, jogos rodando em cima de Facebook e, obviamente, como um meio de representar interações com outras máquinas sociais também. > Vários outros esforços já foram feitos para definir ADLs e alguns deles foram, de alguma forma, aplicados no domínio da web. Entretanto, há uma clara falta de base fundamental que provenha abstrações de alto nível tais como o modelo de máquinas sociais provê. Nossos resultados preliminares mostram que SMADL é uma linguagem prática, escalável, extensível e de fácil aprendizado para implementar máquinas sociais. **Palavras-Chave**: Architecture description language, programmable web, web 3.0, social machines.<file_sep>/_posts/2015-09-30-rastreabilidade-de-artefatos-heterogeneos-de.md --- layout: post title: "Rastreabilidade de Artefatos Heterogêneos de Software – Um Mapeamento Sistemático" categories: Pesquisa tag: mestrado --- O aluno **<NAME>** entrou no mestrado em 2013 e vem estudando a rastreabilidade de artefatos heretogêneos de software, em programas de desenvolvimento. A rastreabilidade tem sido reconhecida como uma tarefa importante no desenvolvimento de sistemas de software. As relações de rastreabilidade podem reduzir custos, o tempo de desenvolvimento e melhorar a qualidade do produto. Diferentes tipos de artefato podem ser rastreados, em níveis variáveis de granularidade e em quantidade. Complexidades são introduzidas pelo fato de que as ligações de rastreio devem ser criadas e mantidas através de artefatos heterogêneos que podem residir em uma variedade de ferramentas de terceiros. Com isso, estabelecer a infraestrutura tecnológica, promover o planejamento estratégico e o desenvolvimento de novas técnicas de ligação e visualização dos vínculos de rastreabilidade para apoiar a integração de dados através de uma ampla variedade de ferramentas e formatos de dados são alguns dos desafios atuais da área. Estes desafios continuam a ser um pesadelo devido à falta de ferramentas adaptáveis de domínio específico e soluções que apoiam a manutenção de vínculos de rastreabilidade de forma automática durante o ciclo de vida dos processos da engenharia de software. Muitos pesquisadores tem se dedicado a este tema e publicado os seus estudos ao longo dos anos. Portanto, este estudo tem como objetivo investigar o estado atual das pesquisas sobre rastreabilidade de software em artefatos heterogêneos, fornecendo como resultado uma compreensão sobre a abordagem utilizada, as relações estabelecidas, o contexto de uso, as tecnologias, ferramentas e indicadores de desempenho obtidos. A quantidade de estudos primários envolvidos até o momento foi de 603 no total. Onde foi realizada pesquisa manual limitado às publicações de uma dos mais importantes eventos da área TEFSE (Traceability in Emerging Forms of Software Engineering), e pesquisa automática utilizando o motor de busca do Scopus. Este número foi reduzido na primeira sessão de triagem, que consistiu em avaliar o título, resumo e palavras-chave, deixando apenas 140 estudos primários potencialmente relevantes. Depois da segunda fase, que consistiu na leitura e análise de todo o estudo, foi definido o conjunto final de documentos. O conjunto final resumiu em 7 estudos primários. Pode-se perceber que a maioria dos estudos trata apenas da criação dos links de rastreabilidade, onde em sua totalidade utiliza uma abordagem semiautomática, onde envolve ações manuais para o estabelecimento e recuperação das ligações. Os artefatos mais frequentemente relacionados envolvem as áreas de requisitos e design de software. No total, 7 temas diferentes foram exploradas pela estudos primários. Os tópicos foram identificados com base na descrição dada pelos autores dos estudos primários. Em geral, os autores não são muito claros ao descrever o contexto, a impressão obtida é que o fato da rastreabilidade ser empregada em diversos cenários dificulta a limitação ou especificação do contexto específico da aplicação. Dentre os desafios relatados estão à integração do processo de gestão e manutenção dos links de rastreabilidade ao processo de desenvolvimento de software, a granularidade do links em relação aos artefatos, a escalabilidade, a redução de esforços humanos e aumento da precisão e recall dos vestígios.<file_sep>/_posts/2013-03-05-dissertacao-de-mestrado-n-1265.md --- layout: post title: "Defesa de Dissertação de Mestrado Nº 1.309" categories: Defesa tag: mestrado --- ## Pós-Graduação em Ciência da Computação – UFPE ### Defesa de Dissertação de Mestrado Nº 1.265 Aluno: [**<NAME>**](http://lattes.cnpq.br/9213156996136744) Orientador: **Prof. <NAME>** Co-orientador: **Prof. &nbsp;<NAME>** Título: _**An Approach for Profiling Distributed Applications Through Network Traffic Analysis**_ Data: 05/03/2013 Hora/Local: 14:00h – Sala &nbsp;D224 Banca Examinadora: * Prof. [<NAME>](http://lattes.cnpq.br/2887736963561252) &nbsp;(UFPE / CIn) * Prof. [<NAME>](http://lattes.cnpq.br/0353331129592565) &nbsp;(IFPB / Coinfo) * Prof. [<NAME>](http://lattes.cnpq.br/6613487636748832) &nbsp;(UFPE / CIn)[[MORE]] **RESUMO**: _Distributed systems has been adopted for building modern Internet services and cloud computing infrastructure, in order to obtain services with high performance, scalability and reliability. Cloud computing service level agreements (SLA) require low time to identify, diagnose and solve problems in its production infrastructure, in order to avoid problem impacts into quality of service provided for its clients. Thus, the detection of error causes, diagnosing and reproduction of errors are challenges that motivate efforts to the development of less intrusive mechanisms for monitoring and debugging distributed applications at runtime. Network traffic analysis is one option to the distributed systems measurement, although there are limitations on capacity to process large amounts of network traffic in short time, and on scalability to process network traffic where there is variation of resource demand._ _The goal of this dissertation is to solve the processing capacity problem for measuring distributed systems through network traffic analysis, in order to evaluate distributed systems at a data center, using commodity hardware and cloud computing services, in a minimally intrusive way._ _We proposed a new approach based on MapReduce, for deep inspection of distributed application traffic, in order to evaluate the behavior of distributed systems at runtime, using commodity hardware. In this dissertation we evaluated the effectiveness of MapReduce for a deep packet inspection algorithm, its processing capacity, completion time speedup, processing capacity scalability, and the behavior followed by MapReduce phases, when applied to deep packet inspection, for extracting indicators of distributed applications._ **Palavras-chave**: Distributed Application Measurement, Profiling, MapReduce, Network Traffic Analysis, Packet Analysis, Deep Packet Inspection<file_sep>/_posts/2014-02-13-assert-at-the-theory-and-practice-of-social.md --- layout: post title: "ASSERT at The Theory and Practice of Social Machines (SOCM2014) co-located with 23rd International World Wide Web Conference (WWW2014)" categories: Artigos tag: conferencia --- Two papers from ASSERT Members and UFPE PhD students have been accepted for the [International World Wide Web Conference (WWW’2014)](http://www2014.kr/){:target="_blank"} to be held in Seoul, South Korea, on April 2014. <NAME>, author of both papers, will attend the conference and present both papers. The first paper is entitled “_**A New Architecture Description Language for Social Machines**_” by <NAME>, <NAME>, <NAME> and <NAME>. A brief summary of the paper is following: > “The term ‘Social Machine’ (SM) has been commonly used as a synonym for what is known as the programmable web or web 3.0. Some definitions of a Social Machine have already been provided and they basically support the notion of relationships between distributed entities. The type of relationship molds which services would be provided or required by each machine, and under certain complex constraints. In order to deal with the complexity of this emerging web, we present a language that can describe networks of Social Machines, named SMADL – the Social Machine Architecture Description Language. In few words, SMADL is as a relationship-driven language which can be used to describe the interactions between any number of machines in a multitude of ways, as a means to represent real machines interacting in the real web, such as, Twitter running on top of Amazon AWS or mashups built upon Google Maps, and obviously, as a means to represent interactions with other social machines too.” The second one is entitled “**_Personal APIs as an Enabler for Designing and Implementing People as Social Machines_**” by <NAME>, <NAME>, <NAME> and <NAME>. The paper abstract is following: > “In this paper, we extend our initial classication scheme for Social Machines (SM) by including Personal APIs as a new SM-related topic of research inquiry. Personal APIs basically refer to the use of Open Application Programming Interfaces (Open APIs) to programmatically access information about a person (e.g., personal basic info, health-related statistics, busy data) and/or trigger his/her human capabilities in a standardized way. Here, we provide an overview of some existing Personal APIs and show how this approach can be used to enable the design and implementation of people as individual SMs on the Web. A proof-of-concept system that demonstrates these ideas is also outlined in this paper.” These papers will be soon available on **ACM Digital Library**. A new post will be done after the conference, presenting our impressions of the event and the feedback from research community about the work.<file_sep>/_posts/2015-03-17-assert-webist-2015.md --- layout: post title: "ASSERT @WEBIST 2015" categories: Artigos tag: conferencia --- Com prazer informamos que o artigo “_**Convertview: A Tool for Conversion and Visualization of Open Heterogenic Governmental Data to the Rdf Standard**_”, de autoria de <NAME>, <NAME>, <NAME> e <NAME> foi aceito como poster para apresentação no [11th International Conference on Web Information System and Technologies (WEBIST'2015)](http://www.webist.org/?y=2015){:target="_blank"}. O resumo do artigo diz que: > The diversity and relevance of the information made available by many governments, using the principles defined by the open data manifest, creates an opportunity for the populations aid in many fields of governmental administration, such as security, transportation, health care and education. However, most of this information was generated in unstructured digital files, making them hard to use. This paper presents an approach for the structuring of data, improving the processing and extraction of information. Thus, we created a tool based on a cloud computing environment, which has high processing and storage ability, to create files in a homogeneous and structured format, allowing for ominous and specific queries; contributing to the access of the information.<file_sep>/_posts/2015-03-16-assert-medinfo-2015.md --- layout: post title: "ASSERT @ Medinfo 2015" categories: Artigos tag: conferencia --- Com prazer informamos que o artigo “_**Br-SCMM - Brazilian Smart City Maturity Model: A Perspective from the Health Domain**_”, de autoria de <NAME>, <NAME>, <NAME>, <NAME> e <NAME> foi aceito como poster para apresentação no [15th World Congress on Health and Biomedical Informatics (Medinfo'2015)](http://www.sbis.org.br/medinfo2015/medinfo2015.html){:target="_blank"}. O resumo do artigo diz que: > The term definition “Smart City” still allows various interpretations, and this causes some difficulty in establishing parameters to measure how smart the cities can be. On the other hand, create intangible indicators can discourage small and medium cities to seek solutions that make them more competitive, sustainable and optimized, just like domain of Health. This paper presents a Maturity Model that uses a set of minimum domains and indicators that aim to encourage cities of different sizes to identify their potential and improve processes and public policies. To validate this model, we used data collected in public Big Data Systems from Brazilian cities.<file_sep>/_posts/2013-03-13-assert-lab-and-ines-at-17th-international.md --- layout: post title: "Assert Lab and INES at 17th International Conference on Evaluation and Assessment in Software Engineering (EASE 2013)" categories: Artigos tag: conferencia --- The paper “**Cloud Testing Framework**”&nbsp;authored&nbsp;by <NAME> (DCC-UFBA and IFBA), and <NAME> (CIn-UFPE), has been accepted for publication at the&nbsp;[17th International Conference on Evaluation and Assessment in Software Engineering](http://cin.ufpe.br/~ease2013/index.html)&nbsp;(EASE’2013). The conference will be held in April 14 - 16, 2013 at Porto de Galinhas, Brazil. This activity is part of the project “[Social Machines and Research Team - SMaRT](http://www.ines.org.br/?p=502)” at [INES](http://www.ines.org.br/ "INES") and is one of the results of the research being done by&nbsp;[ASSERT Lab](http://assertlab.com/). A brief overview of the paper is given next _Cloud-based testing introduces a new set of challenges. While many companies are approaching cloud computing with cautious, testing appears to be next area of growing interest. This paper propose the development of a new framework focusing on cloud testing. We intend to define the activities, roles, techniques, and tools that will be used in an integrated framework. A research methodology containing all the steps that will be executed during the proposal implementation was defined. A schedule was suggested in order to allow the research development. We propose a new Cloud Testing framework and we present the research methodology and schedule that will be used to implement the proposal._<file_sep>/_posts/2014-04-08-assert-at-international-digital-government.md --- layout: post title: "ASSERT at International Digital Government Research Conference (dg.o 2014)" categories: Artigos tag: conferencia --- Two papers from ASSERT Members have been accepted for the [International Digital Government Research Conference (dg.o 2014)](https://dgsociety.org/conference/2014){:target="_blank"} to be held in Aguascalientes City, Mexico, on June 2014. <NAME>, author of both papers, will attend the conference and present both papers. The first paper is entitled “_**Brazilian Government Open Data: Implementation, Challenges, and Potential Opportunities**_” by <NAME>, <NAME>, <NAME> and <NAME>. A brief summary of the paper is following: > “Technological advances and real-time worldwide communications hold great promise for transforming the efficiency and effectiveness of public services through the ease of publishing and access to government public information or through the offer of new kinds of services. In this paper, we describe two initiatives, Rio Inteligente (Smart Rio) and Cidadão Recifense (Recife Citizen), which are based on Brazilian open-data repositories from the cities of Rio de Janeiro and Recife and deliver services for citizens and tourists, mainly (i) a health-unit finder based on user location and (ii) an online vaccination card. Based on the development experience of these two similar applications that use completely independent open-data repositories, this paper discusses the current state of Brazilian open-data initiatives, their challenges and difficulties, and draws some considerations towards a framework to build applications based on government data.” The second one is entitled “_**Using Parliament Brazilian Open Data to Improve Transparency and Public Participation in Brazil**_“ by <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. The paper abstract is following: > “Government concerns about transparency date from 1957, but current technological advances and real-time worldwide communications hold promise to transform accountability, transparency, citizen participation and collaboration, in addition to offering better public services, by increasing efficiency and effectiveness and decreasing corruption in government. With these goals in mind, this paper describes Meu Congresso Nacional (My National Congress), a first prize winner application developed during the First Brazilian Parliament Hackathon focused on parliamentarians transparency by obtaining and analyzing data from several sources and displaying them on a user-friendly website. In addition, based on this development experience, this paper discusses the difficulties and challenges of developing applications based on Brazilian government data.” These papers will be soon available on [ACM Digital Library](https://dl.acm.org/){:target="_blank"}. A new post will be done after the conference, presenting our impressions of the event and the feedback from research community about the work.<file_sep>/_posts/2015-10-15-uma-maquina-para-publicacao-dos-dados.md --- layout: post title: "Uma máquina para publicação dos dados governamentais" categories: Pesquisa tag: doutorado --- A primeira legislação sobre transparência e liberdade da informação data do século 18, sendo a Suécia o pioneiro ao criar esta legislação em 1776. Dois séculos depois, nos anos após a segunda guerra mundial, os Estados Unidos começaram a discutir o “direito de saber” (_the right to know_) e aprovaram sua legislação em 1966, sendo seguido por inúmeros países. Assim, no final do século 20 as leis de acesso a informação já eram populares na maioria dos países democráticos. Com o surgimento da Web 2.0 e das novas tecnologias de publicação e consumo de dados esse movimento resurgiu como Governo Aberto, levando a iniciativas de Dados Abertos Governamentais (OGD - do inglês _Open Government Data_), iniciando a “segunda onda” de transparência. Porém, apesar de muitos governos ao redor do mundo lançarem portais de OGD, os mesmos tem sido muito criticados principalmente por falharem em cumprir os requisitos básicos de OGD, além de alguns críticos considerarem que “…muitos governos focam no desenvolvimento de um portal nacional de dados abertos governamentais como se isso fosse mais prioritário do que desenvolver a infraestrutura técnica para abertura dos dados para uso por terceiros…”. Nesse contexto, em sua tese de doutorado **<NAME>** considera que os governos deveriam basear a publicação dos seus dados a partir de um modelo mais abstrato, como um modelo de máquinas computacionais. O que leva a uma questão principal: existe um modelo computacional abstrato e genérico capaz de descrever os dados governamentais e possível de ser implementado como um sistema de informação na forma de um portal de dados abertos governamental? Com o objetivo de responder a esta questão, Kellyton definiu a **MAGDA - MAchine for Government Data** (Máquina para Dados Governamentais), um modelo abstrato e genérico de máquina computacional que satisfaz os requisitos do domínio de OGD, e usou esse modelo para projetar, desenvolver e disponibilizar portais de dados abertos, usando dados reais publicados pelos governos, como os dados dos parlamentares federais e de todas as 270 mil escolas do Brasil. Posteriormente, de forma a validar a utilidade da proposta, foram desenvolvidos aplicativos utilizando os dados desse portais. Estes aplicativos, além de demonstrarem a viabilidade e benefícios da proposta, receberam diversos prêmios de órgãos oficiais, como a Câmara dos Deputados e o Ministério das Comunicações. Além disso, também demonstraram ser de grande utilidade pública. Como exemplo, em uma pesquisa realizada durante o período das Eleições 2014, 58% dos respondentes que visitaram um desses aplicativos, o Meu Congresso Nacional (<www.meucongressonacional.com>) afirmaram que sua visita ao mesmo teve muita ou extrema influência na sua decisão de voto.<file_sep>/_posts/2015-03-16-assert-dgo-2015.md --- layout: post title: "ASSERT @ dg.o 2015" categories: Artigos tag: conferencia --- Com prazer informamos que o artigo “_**Assessing the Benefits of Open Government Data: The Case of Meu Congresso Nacional in Brazilian Elections 2014**_”, de autoria de <NAME>, <NAME>, <NAME> e <NAME> foi aceito como full paper para apresentação oral e publicação na [16th International Digital Government Research Conference (dg.o 2015)](http://dgo2015.dgsociety.org/){:target="_blank"}. O resumo do artigo diz que: > Open Government Data (OGD) and transparency has been recognized as having the potential to provide many benefits for the society at all, including governmental, scientific, commercial and political domains. However, much of the existing research discusses benefits on a high-level basis, and more empirical analysis is needed in order to analyze and assess the real impact of these initiatives. The objective of this paper is to analyze the benefits perceived by the general population of the use of applications based on OGD, especially the Meu Congresso Nacional, a website based on political OGD and broadly used by Brazilian citizens in the Brazilian elections in 2014. The analysis was based on a survey conducted with website visitors and concludes that, despite this kind of application not yet being popular, people consider them more useful than official government websites, able to help reduce corruption and even influence voting decisions.<file_sep>/_posts/2013-05-14-assert-at-1st-workshop-on-high-performance-and.md --- layout: post title: "ASSERT at 1st Workshop on High Performance and Programmable Networking (HPPN’13)" categories: Artigos tag: conferencia --- The paper "**Evaluating MapReduce for Profiling Application Traffic**"&nbsp;authored by&nbsp;<NAME>, <NAME> and <NAME>&nbsp;has been accepted for publication at the&nbsp;[1st Workshop on High Performance and Programmable Networking](http://www.grid.unina.it/HPPN2013/) (HPPN’13), co-located with [22nd&nbsp;International Symposium on High-Performance Parallel and Distributed Computing](http://www.hpdc.org/2013/) (HPDC).&nbsp;The conference will be held in June 17-21, 2013 at New York City. A brief overview of the paper is given next. _The use of MapReduce for distributed data processing has been growing and achieving benefits with its application for different workloads. MapReduce can be used for dis- tributed traffic analysis, although network traces present characteristics which are not similar to the data type com- monly processed through MapReduce. Motivated by the use of MapReduce for profiling application traffic and due to the lack of evaluation of MapReduce for network traffic analysis and the peculiarity of this kind of data, this paper evaluates the performance of MapReduce in packet level analysis and DPI, analysing its scalability, speed-up, and the behavior of MapReduce phases. The experiments provide evidences for the predominant phases in this kind of job, and show the impact of input size, block size and number of nodes, on MapReduce completion time and scalability._<file_sep>/_posts/2012-10-04-assert-lab-apresenta-artigo-na-sle2012-alemanha.md --- layout: post title: "ASSERT Lab apresenta artigo na SLE'2012, Alemanha" categories: Artigos tag: conferencia --- Entre os dias 25 e 28 de Setembro de 2012, o pesquisador <NAME> apresentou o artigo intitulado "_SMADL - The Social Machines Architecture Description Language_" de sua autoria juntamente com <NAME> e <NAME>, na&nbsp;_5th International Conference on Software Language Engineering_ (SLE) 2012. O evento aconteceu na&nbsp;cidade de Dresden, Alemanha. Em paralelo e no mesmo local ocorriam os eventos GPCE (_Generative Programming and Component Engineering_) e FOSD (_Feature-Oriented Software Development_). ![Technische Universität Dresden - Faculty of Computer Science]({{ BASE_PATH }}/images/2012-10-04-assert-lab-apresenta-artigo-na-sle2012-alemanha/faculty.jpg) O artigo foi apresentando especificamente no Simpósio de Doutorado da SLE, o qual apresentava o seguinte formato: durante um dia inteiro, 8 sessões de apresentações aconteceram. Cada sessão era composta da apresentação do artigo propriamente dito e uma discussão realizada por um autor de outro artigo aceito para o simpósio. Desta forma, havia pelo menos uma pessoa, além do próprio autor do artigo, que tinha lido o artigo de outra pessoa e montado uma crítica seguindo um padrão estabelecido pelo Chair da sessão. Como intermediador (chair) de todos os artigos estava o&nbsp;Prof. Dr. <NAME>, um dos autores do conceituado livro "_Generative Programming: Methods, Tools, and Applications_". O professor provocava perguntas sobre o trabalho de cada estudante e trazia todos da audiência para a discussão. Neste contexto, as discussões de todos os artigos foram bem ricas e fizeram com que a opinião sobre todos os trabalhos servisse como ponto de apoio para melhorias e trabalhos futuros. ![Simpósio de Doutorado]({{ BASE_PATH }}/images/2012-10-04-assert-lab-apresenta-artigo-na-sle2012-alemanha/presentation.jpg) Os comentários sobre o trabalho apresentado (SMADL) trouxeram à tona a seguinte pergunta: "Você acredita que seu trabalho é realmente uma linguagem de descrição arquitetural (ADL) ou uma linguagem específica de domínio (DSL) para o domínio de aplicações Web?". A resposta para tal pergunta será melhor respondida quando criarmos um exemplo prático usando a SMADL, mas de antemão, acredita-se que temos em mãos uma ADL, pois a mesma deve descrever os sistemas Web num nível de abstração alto o suficiente para aproximar-se da arquitetura de tais sistemas. Além disso, comparações foram feitas entre os trabalhos gerando discussões entre os autores de uma forma rica e interativa. No mais, outros artigos das conferências que aconteciam em paralelo chamaram a atenção, principalmente aqueles que tratavam diretamente das ferramentas chamadas&nbsp;_Language Workbenches_. Um exemplo foi o artigo apresentado no GPCE intitulado: "_Xbase: Implementing Domain-Specific Languages for Java_". A participação no evento proporcionou uma experiência única, tanto do lado acadêmico e científico, quanto cultural, pois a cidade de Dresden apresenta uma história única que foi apresentada por um guia turístico local, agendado pela própria organização da conferência no dia 27, após as apresentações.<file_sep>/_posts/2012-10-22-in1163-final-da-2a-sprint-e-apresentacao-dos.md --- layout: post title: "[in1163] Final da 2ª sprint e apresentação dos resultados" categories: Educacao tag: in1163 --- De acordo com [nosso cronograma](https://docs.google.com/spreadsheet/pub?key=<KEY>&amp;output=html), nesta quarta, dia 24 de Outubro de 2012, é o dealine para entrega do release da **2ª Sprint** dos projetos do ASSERT Framework que estão sendo desenvolvidos na disciplina da pós-graduação do Centro de Informática da UFPE [in1163] Tópicos Avançados em Desenvolvimento de Software de Código Aberto. Assim como no [final da 1ª Sprint](http://assertlab.com/post/32754449032/in1163-final-da-1-sprint-e-apresentacao-dos) a entrega será feita por email para o professor da disciplina, <NAME> (vcg) e seu _shepherd_, e na plataforma de acompanhamento de projeto [Trello](http://www.trello.com), dentro dos respectivos boards, na forma de **um card para o release**. Lembrando que o release é formado por **TODOS** os artefatos desenvolvidos (evoluídos) na 2ª Sprint (código, documento, imagens, organogramas, modelos, entre outros), que ocorreu entre os dias 03 e 24 de Outubro de 2012. A novidade é que as apresentações, que se iniciam na sexta-feira, dia 26 de Outubro de 2012 e terminam na quarta-feira dia 31 de Outubro de 2012, ocorrerão por **sorteio**. Portanto, **TODOS** devem vir preparados para apresentar. Adicionalmente, atendendo a pedidos, o tempo de apresentação agora é no formato **10+5 minutos**. Por favor, respeitem o tempo! * O que: Apresentação dos resultados da 2ª Sprint * Data/Hora: 26 de Outubro de 2012, 15:00 e&nbsp;31 de Outubro de 2012, 10:00 * Formato: 10 + 5 minutos * Local: Sala A014, Centro de Informática, UFPE Nos vemos lá!<file_sep>/_posts/2013-06-03-assert-at-international-journal-of-computer.md --- layout: post title: "ASSERT at International Journal of Computer Science and Information Security (IJCSIS)" categories: Artigos tag: periodico --- The paper “**Systematic Mapping Study On Security Threats in Cloud Computing**“ authored by <NAME>, <NAME>, <NAME>, <NAME> and <NAME> has been accepted for publication at [International Journal of Computer Science and Information Security (IJCSIS)](http://www.doaj.org/doaj?func=openurl&amp;issn=19475500&amp;genre=journal). A brief overview of the paper is given next. _Today, Cloud Computing is rising strongly, presenting itself to the market by its main servisse models, known as IaaS, PaaS and SaaS, that offer advantages in operational investments by means of on-demand costs, where consumers pay by resources used. In face of this growth, security threats also rise, compromising the Confidentiality, Integrity and Availability of the services provided. Our work is a Systematic Mapping where we hope to present metrics about publications available in literature that deal with some of the seven security threats in Cloud Computing, based in the guide entitled "Top Threats to Cloud Computing" from the Cloud Security Alliance (CSA). In our research we identified the more explored threats, distributed the results between fifteen Security Domains and identified the types of solutions proposed for the threats. In face of those results, we highlight the publications that are concerned to fulfill some standard of compliance._<file_sep>/_posts/2019-01-08-a-nuvem-se-movera-para-o-blockchain.md --- layout: post title: "A nuvem se moverá para o blockchain?" categories: Computação em Nuvem tag: - cloud - cloudcomputing - blockchain - tic - nuvem - computação em nuvem - bitcoin - ethereum - aws - azure - google - consensys - kaleido --- A chamada **Cloud 2.0** se concentra no dimensionamento do ecossistema blockchain para desenvolver novas oportunidades no espaço da nuvem. Em 2018, as principais empresas de nuvem do mundo mostraram um grande interesse em torno do blockchain. Amazon Web Services (AWS), Google Cloud e Microsoft Azure, deixaram claro que a tecnologia de contabilidade digital distribuída está se tornando um ingrediente-chave para o futuro da computação em nuvem. A ConsenSys, um dos principais players do blockchain, operando como estúdio de produção de risco e consultoria de desenvolvimento de software blockchain, fez um grande avanço para a indústria de nuvem através de uma parceria entre a Kaleido (parte da ConsenSys) e AWS. A empresa pretende oferecer aos clientes da AWS um “botão fácil” para entrar na mesma tecnologia que sustenta as criptomoedas e os d-apps. Vem mais um hype por aí? Artigo originalmente publicado em [A nuvem se moverá para o blockchain?](http://viniciusgarcia.me/cloud%20computing/a-nuvem-se-movera-para-o-blockchain/) :: [viniciusgarcia.me](http://viniciusgarcia.me/) <file_sep>/_posts/2013-04-06-assert-lab-and-ines-at-the-12th-international.md --- layout: post title: "Assert Lab and INES at the 12th International Symposium on Parallel and Distributed Computing (ISPDC 2013)" categories: Artigos tag: conferencia --- The paper "**Monext: An Accounting Framework for Infrastructure Clouds**" authored by <NAME>, <NAME>, <NAME>, <NAME> and <NAME>, has been accepted for publication at the [12th International Symposium on Parallel and Distributed Computing](http://ispdc.hpc.pub.ro/) (ISPDC 2013). The conference will be held in Jun 27-30, 2013 at Bucharest, Romania. This activity is part of the project "[JiTCloud - Highly scalable IaaS](http://jitclouds.lsd.ufcg.edu.br/site/)" and is one of the results of the MSc research developed by Francisco Airton. A brief overview of the paper is given next _Cloud Accounting refers to how cloud usage is recorded and charged. Even in the case of a single cloud provider this task is hard and there is a context which it becomes even worse, known as federated cloud. It happens when a cloud provider dynamically outsources resources to other providers in response to demand variation. In this context, we identified some research addressing this area which developed platforms for federated clouds, however without addressing the accounting requirement. This work presents the Monext, an accounting framework for Infrastructure as a Service, focused on federated clouds. It is based on a standard accounting process; follows a set of principles specified by previous research; and offers a Domain Specific Language (DSL) to define charging policies. We evaluated the framework under a federated cloud platform called JiTCloud. The results provided evidences that Monext can be considered feasible under many aspects, such as flexibility, reliability and efficiency._<file_sep>/_posts/2013-07-10-assert-apresenta-artigo-no-ispdc13.md --- layout: post title: "ASSERT apresenta artigo no ISPDC’13" categories: Artigos tag: conferencia --- Entre os dias 27 e 30 de junho o estudante de doutorado Francisco Airton participou do [12th International Symposium on Parallel and Distributed Computing – ISPDC 2013](http://ispdc.hpc.pub.ro/) na cidade de Bucareste na Romênia. O evento ;(patrocinado pela IEEE) é classificado como Qualis B2 de acordo com a CAPES, e na ocasião representando os autores Francisco Airton, <NAME>, <NAME>, <NAME> e <NAME>, apresentou o trabalho entitulado “_Monext: An Accounting Framework for Infrastructure Clouds_” que é parte dos resultados do seu mestrado. Este trabalho é financiado pelo ;Centro de Pesquisa e Desenvolvimento em Tecnologias Digitais para Informação e Comunicação (CTIC) do Ministério de Ciência e Tecnologia do Brasil (MCT), processo número 68/2011. Adicionalmente, este trabalho é apoiado pelo [Instituto Nacional de Ciência e Tecnologia (INCT) para Engenharia de Software (INES)](http://www.ines.org.br/), financiado pelo CNPq e FACEPE, processos número 573964/2008-4 and APQ-1037-1.03/08. O evento é bem multidisciplinar e abordou temas relacionados à computação distribuída e paralela no tocante a seis trilhas: 1. Task Scheduling and Load Balancing 2. Performance Management in Parallel and Distributed Systems 3. Cloud and Mobile Computing 4. Distributed Software Components 5. Collaborative Computing 6. Parallel Programming Francisco apresentou o framework Monext na trilha “Task Scheduling and Load Balancing”. Essa ferramenta visa realizar tarifação de IaaS em nuvens privadas ou públicas aplicando políticas próprias fazendo uso de uma linguagem específica de domínio. Para saber mais sobre o trabalho acesse a [página da ferramenta](http://cin.ufpe.br/~faps/monext/). Na ocasição a platéia se interessou mais pela DSL indagando sobre a sua extensibilidade. ![image]({{ BASE_PATH }}/images/2013-07-10-assert-apresenta-artigo-no-ispdc13/foto1.jpg) Na trilha "Cloud and Mobile Computing" o professor pesquisador <NAME> da universidade de Bucareste apresentou o estado da arte e futuras direções em Mobile Cloud (linha de pesquisa na qual Francisco visa seguir atualmente) e defendeu a ideia de que todas as técnicas de evolução de aplicações mobile que interagem com nuvens devem tentar ser direcionadas à melhoria da experiência do usuário, delimitando métricas que transpareçam a satisfação do mesmo. Esta apresentação foi de suma importância para Francisco, pois pôde discutir posteriormente com Grigoras possíveis facetas de pesquisa a serem exploradas. Neste ambiente, Francisco também conheceu de perto o trabalho em Mobile Cloud realizado por <NAME>, estudante PhD em fase final de trabalho em que como pesquisador desenvolve estudos na subárea denominada offloading de aplicações e como professor aplica uma metodologia de ensino de programação através da construção de apps mobile. Na foto abaixo, um grupo de alunos de graduação que estavam participando de um escola de verão em mobile programming na semana da conferência. ![image]({{ BASE_PATH }}/images/2013-07-10-assert-apresenta-artigo-no-ispdc13/foto2.jpg) Dentre as keynotes, duas chamaram mais a atenção por correlação ao trabalho de Francisco, a primeira ministrada por <NAME> por incluir mecanismos de monitoramento de infraestrutura e a segunda de <NAME> por ter uma certa relação com o projeto [JiTCloud](http://jitclouds.lsd.ufcg.edu.br/site/index.php/en/) (no qual teve construção participativa do grupo ASSERT). <NAME> é um engenheiro pesquisador no Instituto de Tecnologia da Califórnia desde 1998, trabalhou muitos anos envolvendo física e energia nuclear, sendo que atualmente coordena uma série de projetos de software em computação distribuída. No ISPDC Iosif apresentou um keynote entitulado "Monitoring and Control of Large Scale Distributed Systems" onde ele chama de [MonALISA ](http://monalisa.caltech.edu/monalisa.htm) um framework que fornece um sistema de serviço distribuído capaz de controlar e otimizar aplicações de larga escala e dados intensivos. Seu campo inicial de atuação são os sistemas de rede, suporte de processamento e análise de dados. A estratégia do trabalho dele é tentar satisfazer as demandas de aplicações de uso intensivo de dados tornando mais sinérgicas as interações entre os aplicativos, computação, armazenamento e infra-estrutura de rede. <NAME> é um professor de computação na universidade de Amsterdam na Holanda. Ele investiga sistemas de larga escala focando em clusters, clouds e grids. No ISPDC ele falou sobre um trabalho mais relacionado ao o que Francisco trabalhou no mestrado que é tarifação, porém focando em custo. Kielmann apresentou o keynote entitulado "Cost-efficient Task Farming with ConPaaS". [ConPaas](http://www.conpaas.eu/) permite aos usuários executar "sacos de tarefas" (Bags of Tasks) de acordo com um orçamento definido pelo usuário. Usando uma amostra de tarefas, ConPaas estima os custos para executá-las em diferentes ofertas de nuvem (provedores). O serviço oferece ao usuário uma escolha de opções antes da execução e agenda horários para isto de acordo com as preferências do usuário. O serviço não exige a priori informações sobre o tempo de conclusão da tarefa. Este trabalho open-source se mostrou bastante maduro e pode ser usado tanto na Amazon EC2 quanto no OpenNebula atualmente. Foi notado que pode-se fazer uma relação do ConPass com o trabalho JiTCloud uma vez que o objetivo de ambos é trabalhar com bags of tasks de forma elástica, no entanto o ConPaaS apenas dá um direcionamento de onde e quando executar limitado a algumas nuvens e o JiTCloud é uma nuvem por si só que procura executar estas tarefas em nuvens privadas (a princípio).<file_sep>/_posts/2017-03-13-defesa-de-tese-de-doutorado-n-352.md --- layout: post title: "Defesa de Tese de Doutorado Nº 352" categories: Defesa tag: doutorado --- ## Pós-Graduação em Ciência da Computação – UFPE ### Defesa de Tese de Doutorado Nº 352 **Aluno**: <NAME> **Orientador**: Prof. <NAME> **Título**: _**SMARTCLUSTER: A METAMODEL INDICATORS FOR SMART AND HUMAN CITIES**_ **Data**: 13/03/2017 **Hora/Local**: 9h – Centro de Informática – Sala A14 Banca Examinadora: * Prof. <NAME>(UFPE / CIn - Centro de Informática) * Prof. <NAME>(UFPE / CIn - Centro de Informática) * Prof. <NAME>(UFPE / Arquitetura e Urbanismo) * Prof. <NAME>(UFSCAR / DC) * Prof. <NAME>(UFRPE / DEINFO) Abstract: > Currently, there are several works on smart cities and the advances offered to the routine of its inhabitants and optimization of resources, however, there is still no consensus on the definition of the term “Smart Cities”, nor their domains and indicators. The lack of a clear and widely usable definition, as well as the delimitation of domains and indicators makes it impossible to compare or measure cities in this context. This work presents a proposal for a metamodel called SmartCluster, which was developed to allow uniformity in intelligent city models so that they can be used in any context and can be expanded at any time. The use of this metamodel will allow indicators drawn from public databases to serve to assist municipal managers in measuring, comparing and managing resources of smart cities. Keywords: Smart Cities, e-Government, Metamodel, Ontology Resumo: > Atualmente, existem vários trabalhos sobre cidades inteligentes e os avanços oferecidos à rotina de seus habitantes e otimização de recursos, no entanto, ainda não há consenso sobre a definição do termo “Cidades Inteligentes”, nem seus domínios e indicadores. A falta de uma definição clara e amplamente utilizável, bem como a delimitação de domínios e indicadores torna impossível comparar ou medir as cidades neste contexto. Este trabalho apresenta uma proposta para um metamodelo chamado SmartCluster, que foi desenvolvido para permitir a uniformidade em modelos de cidades inteligentes para que eles possam ser usados em qualquer contexto e podem ser expandidos a qualquer momento. A utilização deste metamodelo permitirá que indicadores elaborados a partir de bases de dados públicas sirvam para auxiliar os gestores municipais na medição, comparação e gestão de recursos das cidades inteligentes. Palavras-chave: Cidades Inteligentes, Governo Eletrônico, Metamodelo, Ontologia<file_sep>/_posts/2012-11-26-in1163-final-da-3a-sprint-e-apresentacao-dos.md --- layout: post title: "[in1163] Final da 3ª sprint e apresentação dos resultados" categories: Educacao tag: in1163 --- De acordo com&nbsp;[nosso cronograma](https://docs.google.com/spreadsheet/pub?key=<KEY>&amp;output=html), nesta quarta e sexta, dias 28 e 30 de Novembro de 2012, é o dealine para apresentação do release da&nbsp;**3ª Sprint**&nbsp;dos projetos do ASSERT Framework que estão sendo desenvolvidos na disciplina da pós-graduação do Centro de Informática da UFPE [in1163] Tópicos Avançados em Desenvolvimento de Software de Código Aberto. Assim como no&nbsp;[final da 2ª Sprint](http://assertlab.com/post/34108540631/in1163-final-da-2-sprint-e-apresentacao-dos)&nbsp;(e da [1ª sprint](http://assertlab.com/post/32754449032/in1163-final-da-1-sprint-e-apresentacao-dos))&nbsp;a entrega será feita por email para o professor da disciplina, <NAME> (vcg) e seu respectivo&nbsp;_shepherd_, e na plataforma de acompanhamento de projeto&nbsp;[Trello](http://www.trello.com/), dentro dos respectivos boards, na forma de&nbsp;**um card para o release**. Lembrando que o release é formado por&nbsp;**TODOS**&nbsp;os artefatos desenvolvidos (evoluídos) na 3ª Sprint (código, documento, imagens, organogramas, modelos, entre outros), que ocorreu entre os dias 31 de Outubro e 25 de Novembro de 2012. Nesta fase repetiremos a abordagem do final da sprint passada onde as apresentações ocorrerão por&nbsp;**sorteio**. Portanto,&nbsp;**TODOS**&nbsp;devem vir preparados para apresentar. Mais uma vez o tempo de apresentação é no formato&nbsp;**10+5 minutos**. Por favor, respeitem o tempo! * O que: Apresentação dos resultados da 2ª Sprint * Data/Hora: 28 de Novembro de 2012, 10:00 e&nbsp;30 de Novembro de 2012, 15:00 * Formato: 10 + 5 minutos * Local: Sala A014, Centro de Informática, UFPE Nos vemos lá!<file_sep>/_posts/2014-02-26-defesa-de-dissertacao-de-mestrado-n-1363.md --- layout: post title: "Defesa de Dissertação de Mestrado Nº 1.363" categories: Defesa tag: mestrado --- ## Pós-Graduação em Ciência da Computação – UFPE ### Defesa de Dissertação de Mestrado Nº 1.363 **Aluno**: <NAME> **Orientador**: Prof. <NAME> **Co-Orientador**: Prof. <NAME> (UFBA) **Título**: _**RecCloud: Um Modelo de Recomendação para Sistemas de Armazenamento em Nuvem**_ **Data**: 27/02/2014 **Hora/Local**: 8h – Centro de Informática – Sala D224 Banca Examinadora: * Profa. <NAME> (UFPE / CI * Prof. <NAME> (UFRPE / Estattistica e Informática) * Prof. <NAME>(UFPE / CIn) **RESUMO**: > O desenvolvimento tecnológico vivenciado nos últimos anos, proporcionou o crescimento do universo digital de forma exponencial. Este crescimento gerou um grande volume dados e segundo o relatório publicado pela EMC Corporation em 2005, a previsão é que em 2015 chegue a quase 8 zettabytes. A filtragem de conteúdo em meio a essa imensidão de dados torna-se cada vez mais complexa. O armazenamento em nuvem é apontado por Zeng et al. em 2009 [44] como uma das possíveis soluções para lidar com o problema de armazenamento para a imensidão de dados gerados a cada dia. Grande parte dos sistemas de armazenamento em nuvem existentes não oferecem ferramentas que permitam que o usuário faça a filtragem de conteúdo de forma simples como por exemplo, levando em consideração o conteúdo dos arquivos, a relevância dos arquivos na rede ou fatores que proporcionem a melhor utilização dos recursos da nuvem, por exemplo, a disponibilidade. Este cenário torna cada vez mais complexa a tarefa de filtrar conteúdo relevante em meio a imensidão de dados disponíveis na nuvem. Diante deste contexto, sistemas de recomendação (SR) se tornam uma alternativa para auxiliar os usuários na tomada de decisão por qual arquivo escolher e a filtrar informações relevantes de acordo com suas preferências. Nesta pesquisa, propomos um modelo de recomendação baseado em características da nuvem, associadas à técnica de recomendação baseada em conteúdo. Com uma aplicabilidade prática para ambientes de armazenamento de dados na nuvem, que proporcionem a melhor utilização dos recursos da nuvem e atenda as preferências dos usuários. **Palavras-chave**: Sistemas de recomendação, modelo de recomendação, computação em nuvem, sistemas de armazenamento em nuvem.<file_sep>/_posts/2013-05-27-assert-apresenta-artigo-no-ccgrid13.md --- layout: post title: "ASSERT apresenta artigo no CCGrid'13" categories: Artigos tag: conferencia --- ![image]({{ BASE_PATH }}/images/2013-05-27-assert-apresenta-artigo-no-ccgrid13/figura1.png) Entre os dias 13 e 16 o estudante de doutorado Francisco Airton participou do [13th IEEE/ACM International Symposium on Cluster, Cloud and Grid Computing (CCGrid)](http://www.pds.ewi.tudelft.nl/ccgrid2013)&nbsp;na cidade de Delft na Holanda. O evento&nbsp;(patrocinado pela IEEE e ACM)&nbsp;é classificado como Qualis A1 de acordo com a CAPES, e na ocasião representando os autores Francisco Airton, <NAME>, <NAME>, <NAME> e <NAME>, apresentou o trabalho entitulado “Accounting Federated Clouds based on the JiTCloud Platform” que é parte dos resultados do seu mestrado. ![image]({{ BASE_PATH }}/images/2013-05-27-assert-apresenta-artigo-no-ccgrid13/foto1.jpg) Este artigo do tipo pôster foi apresentado em duas etapas, na primeira, uma sessão de “introdução” onde cada autor fez uma pequena apresentação sobre o trabalho no auditório principal a fim de motivar as pessoas a buscarem informações na sessão seguinte onde efetivamente o autor explicou detalhes sobre a pesquisa em um salão de exposição para os interessados. Apresentação do tipo pôster é uma ótima oportunidade que permite uma interação mais pessoal e com menos restrição de tempo com as pessoas. No caso Francisco Airton pôde discutir detalhes do trabalho com pesquisadores de renome na área de computação na nuvem como o professor <NAME>a que o ajudou a identificar possíveis melhorias e soluções para a evolução do estudo. O artigo tratou da aplicação de um framework de tarifação de IaaS em uma plataforma de nuvens federadas chamada JiTCloud. Boa parte das perguntas focaram na adequação do framework a diferentes contextos ou provedores de serviço. Muitos questionaram sobre o projeto JiTCloud e sua similaridade com outras propostas como o Reservoir. No primeiro dia do evento o estudante participou de um minicurso com o professor <NAME> abordando o tema “Market-Oriented Cloud Computing” onde iniciou com os paradigmas da computação como utilidade, passando por aspectos mais comerciais da prestação de serviços nas nuvens e terminando com as principais características do gerenciamento de recursos computacionais em data centers se preocupando com riscos e monitoramento de Acordos de Nível de Serviços (SLA). Ele apresentou o software [Aneka](http://www.manjrasoft.com/products.html), um sistema para desenvolvimento e deploy de aplicações na nuvem (pública ou privada). No fim ele terminou defendendo a convergência dos paradigmas relacionados a nuvem buscando a cooperação de diferentes tipos de serviços e níveis de entrega. ![image]({{ BASE_PATH }}/images/2013-05-27-assert-apresenta-artigo-no-ccgrid13/foto2.jpg) Em relação às apresentações os trabalhos mais relacionados ao o que Francisco vêm pesquisando abordaram SLA's (três em especial). O primeiro: “**Towards QoS-Oriented SLA Guarantees for Online Cloud Services” **apresenta um modelo de nuvem chamado SLAaaS que permite uma integração sistemática dos níveis de QoS e SLA para a nuvem. Ele é ortogonal a outros modelos de nuvem, como SaaS ou PaaS e podem ser aplicadas a qualquer um deles; O segundo: “**Negotiation-based Flexible SLA Establishment with SLA-oriented Resource Allocations in Cloud Computing**” já era do seu conhecimento, quando Francisco encontrou o autor do artigo em uma outra conferência no ano passado (evento GCA), Seokho Son estuda a negociação automática de SLA utilizando agentes inteligentes que permite a economia na contratação de serviços e trata também da alocação de recursos em nuvem baseado em métricas monitoradas de SLA; O terceiro trabalho: “**Automated SLA Negotiation Framework for Cloud Computing**” de autoria de <NAME> trata do mesmo tema do anterior só que focado em SaaS. Além de SLA outros trabalhos chamaram sua atenção. “**Autoflex: Service Agnostic Auto-scaling Framework for IaaS Deployment Models**” de autoria de <NAME> da UFCG em cooperação com a Hewlett-Packard (HP). &nbsp;O trabalho desenvolvido propõe um framework para provisionamento automático de recursos não intrusivo, ou seja, que não necessita de informações específicas da aplicação, apenas informações de utilização de recursos no nível de máquina virtual.&nbsp; Para mais informações sobre o evento contacte&nbsp;Francisco Airton – http://cin.ufpe.br/~faps<file_sep>/_posts/2015-11-18-uma-metodologia-de-recomendacao-hibrida-para.md --- layout: post title: "Uma Metodologia de Recomendação Híbrida Para Sistemas de Armazenamento em Nuvem" categories: Pesquisa tag: mestrado --- Um estudo realizado pela KPMG International apontou que cerca de 50% das empresas participantes optam por armazenar dados em nuvem. Com essa crescente utilização de armazenamento em nuvem, são formados grandes volumes de dados. Essa propagação do uso de sistemas de armazenamento em nuvem teve como resultado a migração de grandes volumes de dados para esses sistemas. A escassez de informação disponível deu lugar a uma imensa massa de dados ao alcance de todos. Entretanto, esta inversão também acabou gerando um problema: como encontrar dados relevantes em meios a uma grande massa de dados? A filtragem de conteúdo relevante em meio a essa imensidão de dados é complexa, demanda tempo e recursos computacionais. Outro ponto a ser considerado neste cenário é como proporcionar aos usuários a melhor utilização dos recursos em nuvem, na enfadonha tarefa de filtrar conteúdo relevante em meio a grandes massas de dados. Um forma de amenizar esses problemas pode ser o uso de técnicas de recomendação. Para isto, é necessário informações sobre o indivíduo alvo da recomendação ou sobre o ambiente que influenciará na geração da recomendação. A partir destas informações, um sistema de recomendação poderá recomendar arquivos que apresentem maior semelhança com as preferências do usuário alvo [2]. Nesse contexto, este trabalho tem como proposta de pesquisa propor uma metodologia de recomendação de arquivos para sistemas de armazenamento em nuvem, utilizando as técnicas de recomendação mais utilizadas e características de ambientes de armazenamento em nuvem. O objetivo deste modelo é recomendar aos usuários arquivos que sejam similares a suas preferências e em paralelo proporcionar uma melhor utilização dos recursos do ambiente em nuvem. Como resultado, no desenvolver deste trabalho serão propostos dois modelos de recomendação e uma metodologia híbrida (conjunto de boas praticas para recomendação de arquivos em sistemas de armazenamento em nuvem). Serão utilizadas as técnicas de recomendação por filtragem colaborativa e recomendação baseada em conteúdo. Essas técnicas serão associadas as características que representem ambientes de armazenamento em nuvem. 1. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Cloudadvisor: A recommendation-as-a-service platform for cloud configuration and pricing. In Services (SERVICES), 203 IEEE Ninth World Congress on, pages 456–463, 2013.<file_sep>/_posts/2015-03-19-assert-dgo-2015-ii.md --- layout: post title: "ASSERT @ dg.o 2015 II" categories: Artigos tag: conferencia --- Com prazer informamos que o artigo “_**Brazilian Smart Cities: Using a Maturity Model to Measure and Compare Inequality in Cities”**_, de autoria de <NAME>, <NAME>, <NAME>, <NAME> e <NAME> foi aceito como full paper para apresentação oral e publicação na [16th International Digital Government Research Conference (dg.o 2015)](http://dgo2015.dgsociety.org/){:target="_blank"}. O resumo do artigo diz que: > Currently there are several publications on smart cities and advances offered to the routine of its inhabitants and resource optimization, however, there is still no consensus on the definition of “Smart Cities”, nor of their domains and indicators. The lack of a clear and widely usable definition and delimitation of areas and indicators makes it difficult to compare or measure cities in this context. This paper compares some of the Brazilian capital indicators and presents a maturity model called br-SCMM (Brazilian Smart City Maturity Model) developed to allow extracted indicators of public databases may be used to assist city managers.<file_sep>/_posts/2015-09-11-results-of-the-research-entitled-developing.md --- layout: post title: "Results of the research entitled 'Developing programming skills on digital native children through the interaction with smart devices'" categories: Pesquisa tag: mestrado --- Since the production of the personal computer researchers have tried to lower the barriers of programming to children by inventing more intuitive programming languages and platforms where they can interact and develop programming skills. Many attempts have been made with LOGO language, Lego/LOGO, and in 2007 the MIT Lifelong Kindergarten developed Scratch, a platform where children are able to build multimedia presentations and games using a language inspired on the connections of Lego bricks where children uses programming blocks to build algorithms. Most of these approaches are focused on certain age ranges and normally demands that the child are able to read which limitates the starting age to six years old and following the same principle described by Papert in 1980 that since the LOGO creation, everyone involved in teaching programming to children should try to lower the barriers to knowledge, this research affirms that prescholar children are able to start developing programmings skills through the hypothesis that “_programming games enable children to develop and improve their programming skills_”. Based on popular programming games such as LightBot (<www.lightbot.com>) and emerging new approaches such as primo.io initiative (<http://primo.io>) a game was developed to be used on the data collection phase of an experiment that involved 10 children with a specific profile, they should be between 4 and 6 years old and have a high intimacy with technology. The first test was a pilot to identify major flaws in the game and the other were grouped by the ages of 4, 5 and 6 (3 children in each group). The game consists of a tablet application where the user can build an algorithm by selecting a set of ordered commands to be sent to a spherical robot, the commands are basically to move forward, turn right, and left. Three levels were built with EVA material to serve as challenges, and while the user faces each level the application collects the data to be analyzed, each attempt from each level corresponds to a score, and all theses attempts are recorded to the data analysis phase. The final version of the second level of the game is presented on the attached video. While analyzing the data an important fact was noticed, many children when started a new level had a significant decrease on their score, in order to better represent these situations the charts presented as result of the data analysis every attempt that starts a level was represented by a blue dot and every other attempts were represented by a green dot on the attempts axis. As an example of how the data was presented the following chart is the results of a five year old child. All of the involved children demonstrated interest on the game, and completed at least the first level, which suggests that preschoolers are able to start developing programming skills. ![]({{ BASE_PATH }}/images/2015-09-11-results-of-the-research-entitled-developing/figure1.png) <iframe width="560" height="315" src="https://www.youtube.com/embed/RFFH3-uLsso" frameborder="0" allowfullscreen></iframe><file_sep>/_posts/2014-01-14-reccloud-um-modelo-de-recomendacao-baseado-em.md --- layout: post title: "RecCloud: Um Modelo de Recomendação Baseado em Nuvem" categories: Pesquisa tag: mestrado --- Há mais informação no mundo do que a nossa capacidade, humana, de processá-la [2]. Vivemos numa era de efervescência informacional, a cada dia se produz mais&nbsp;informação e, geralmente, estas informações são armazenadas em meios digitais. O tamanho desse “_universo digital_" cresce de forma exponencial. Segundo relatório publicado pela EMC Corporation [1], em 2005, o volume de dados chegou a 130 exabytes; em 2010, superou 1 zettabyte e a previsão é que em 2015 chegue a quase 8 zettabytes, conforme mostrado na Figura abaixo. ![]({{ BASE_PATH }}/images/2014-01-14-reccloud-um-modelo-de-recomendacao-baseado-em/figura1.png) Este “_universo digital_” citado em Gantz e Reinsel [1] expande e se torna cada vez mais complexo a tarefa de filtragem de conteúdo e busca por conteúdo relevante que atenda as preferências do usuário. Parte deste “_universo digital_” está sendo armazenado em ambientes de armazenamento em nuvem, ocasionando a criação de grandes massas de dados nesses sistemas. As massas de dados geradas se tornaram humanisticamente impossíveis de serem processadas. Este cenário é contrário à demanda tecnológica do século XXI, que é encontrar e extrair informações em tempo hábil no meio dessa quantidade de informações, uma opção que atende a este questionamento são os sistemas de recomendação. Ao analisar a literatura e os sistemas de armazenamento em nuvem mais populares e utilizados atualmente, observamos que, no geral esses sistemas não fornecem ao usuário o serviço de recomendação de arquivos. Na maioria dos sistemas de armazenamento em nuvem, a filtragem de conteúdo é realizada por sistemas de busca, onde o usuário fornece termos chaves e o sistema retorna arquivos similares aos termos apresentados pelo usuário. Por outro lado, a enorme quantidade de sistemas de recomendação que rodam em nuvem, não utilizam características da nuvem na geração de suas recomendações. Esses sistemas normalmente têm como objetivo recomendar itens que atendam as preferências dos usuários, sem considerar requisitos do ambiente. Neste trabalho investigamos a utilização de características da nuvem que possam ser usadas no processo de recomendação de arquivos em ambiente de armazenamento em nuvem. Com o aumento substancial da utilização de ambientes de armazenamento em nuvem, o nosso objetivo é que esse novo modelo tire proveito das vantagens oferecidas pela utilização de ambientes de armazenamento em nuvem, auxiliando o usuário na filtragem de conteúdo que atenda suas preferências, e amenizar o tempo gasto nesta tarefa e no download de arquivos recomendados. O modelo de recomendação modelado neste trabalho é formado pela técnica de recomendação baseada em conteúdo, combinado a características da nuvem. O modelo de recomendação proposto é composto por cinco fatores, os fatores que serão utilizados no processo de recomendação, são oriundos da nuvem, e de metadados dos arquivos armazenados em nuvem. Os fatores propostos foram definidos a partir da observação de ambientes de armazenamento em nuvem e quais as prioridades de usuários nesses ambientes. Os fatores são: * Similaridade * Disponibilidade * Taxa de Download * Tamanho do arquivo * Relevância do arquivo Na Figura 2, apresentamos o processo de recomendação completo do modelo RecCloud. ![]({{ BASE_PATH }}/images/2014-01-14-reccloud-um-modelo-de-recomendacao-baseado-em/figura2.png) Na Figura 2, o usuário elicita suas preferências através do “_Arquivo Y_”, em seguida o SR calcula a recomendação. A partir do cálculo de cada fator, é gerada a recomendação ao usuário, o arquivo “_X_”, que estava disponível na nuvem é recomendado ao usuário. Esta pesquisa encontra-se em processo de avaliação. Para avaliação do modelo proposto serão utilizadas 5 (cinco) métricas, definidas a partir da análise da literatura. As métricas escolhidas são: **Precisão**: Proporção entre o número de arquivos relevantes recomendados e o número total de arquivos recomendados. **Recall**: Proporção entre o número de arquivos recomendados e o número de arquivos relevantes utilizados na avaliação. **F-Measure**: Média harmônica ponderada da precisão e recall. **Tempo gasto no download**: Tempo gasto para realizar o download de um arquivo recomendado. **Avaliação do conteúdo recomendado**: Avaliação do conteúdo recomendado em relação às preferências do solicitante. Referências 1. <NAME>. and <NAME>. (2011). Extracting value from chaos state of the universe: An executive summary. 1-12. 2. <NAME>. (2012). Sistemas de Recomendação Utilizando Similaridade Globais para Aliviar o Problema da Esparcidade. Dissertação de Mestrado, Universidade Federal de Pernambuco (UFPE). Texto escrito por _<NAME>_ (rbr at cin.ufpe.br)<file_sep>/_posts/2014-02-12-uma-abordagem-para-o-balanceamento-de-carga-de.md --- layout: post title: "Uma abordagem para o balanceamento de carga de servidores de busca em sistemas de armazenamento de dados P2P JXTA" categories: Pesquisa tag: mestrado --- Computação em nuvem se refere, essencialmente, à ideia de utilizarmos, em qualquer lugar e independente de plataforma, as mais variadas aplicações através da Internet com a mesma facilidade de tê-las instaladas em nossos próprios servidores. Um dos tipos de serviços que podem ser oferecidos sobre essa plataforma é o armazenamento de dados em nuvem. Zeng et. al introduz o armazenamento de dados em nuvem como um dos serviços que fornecem recursos para armazenamento e serviços em servidores remotos baseados na computação em nuvem. Um sistema para armazenamento em nuvem pode ser desenvolvido em cima da arquitetura peer-to-peer (P2P), para tirar proveito desse modelo, por exemplo, para evitar gargalos de forma eficiente e pontos únicos de falha. Além disso, esses sistemas podem usar o espaço disponível nos peerspara armazenar dados, devendo, para isso, levar em consideração atributos como replicação de dados, segurança, seleção de peers com alta disponibilidade, etc. [Machado, 2013]. Desse cenário, surge a necessidade da busca de conteúdo dos arquivos, de forma que permita que sejam realizadas buscas em sistemas de armazenamento em nuvem implementados sobre redes peer-to-peer. Para tal, determinados peers na rede podem atuar como servidores de busca, e fornecer aos outros peers serviços de indexação de conteúdo de arquivos e busca. Essa pesquisa tem como objetivo principal propor uma abordagem eficiente para o balanceamento de carga de servidores de busca, em sistemas de armazenamento de dados P2P com JXTA, implementada sobre a plataforma de nuvem. O balanceamento de carga será utilizado visando às ações de indexação de conteúdo de arquivos, busca de arquivos e replicação de índices. Tendo em vista a necessidade de realizar um balanceamento distribuído, o balanceador estará situado no super peer rendezvous, pois todos os peers na rede conectam-se a ele, possibilitando assim que o balanceador tenha sempre sua lista de peers servidores de busca atualizada. Essa lista com os peers conectados será fornecida por um componente responsável pela descoberta de peers servidores de busca. Quando um super peer se conecta a rede, o mesmo inicializa o Peer Discovery, que é o componente responsável pelo descobrimento dos servidores de busca na rede. Periodicamente, o Peer Discovery atualiza a lista de servidores de busca, adicionando novos e removendo os desconectados da rede, para ser utilizada pelo Load Balancer. Um peer, ao se conectar a rede JXTA, publica um advertisement informando qual é o seu tipo (cliente, servidor, servidor de busca, etc.). Se o peer recém conectado a rede for do tipo servidor de busca, o mesmo é descoberto e adicionado a lista de servidores de busca do Peer Discovery. A Figura 1 demonstra o fluxo da descoberta e atualização da lista de servidores de busca pelo Peer Discovery. ![]({{ BASE_PATH }}/images/2014-02-12-uma-abordagem-para-o-balanceamento-de-carga-de/figura1.png) As próximas etapas do projeto são: * De posse da lista de servidores de busca disponíveis na rede, definir a estratégia e componente para o balanceamento de carga. * Definir e utilizar métricas para saber se um determinado peer servidor de busca está balanceado. * Replicação e mesclagem de índices de conteúdo de arquivos. * Os testes para validação ainda serão implementados e executados dentro de um sistema real de armazenamento de dados em nuvem, e medirão, através de métricas que indiquem o nível de balanceamento, a distribuição da carga realizada pela abordagem proposta. A replicação dos índices de busca de arquivos e mesclagem dos mesmos também serão testadas nessa etapa. Qualquer informação sobre o projeto entre em contato com a equipe pelos endereços: * <NAME>: jlbfc (at) cin dot ufpe dot br * <NAME>: vcg (at) cin dot ufpe dot br<file_sep>/contact.md --- layout: page title: Contato tagline: Entre em contato --- Att. [Prof. <NAME>](http://viniciusgarcia.me){:target="_blank"} Departamento de Informação e Sistemas [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} – [Universidade Federal de Pernambuco](http://www.ufpe.br){:target="_blank"} Av. Jornalista Anibal Fernandes s/n – Cidade Universitária (Campus Recife), 50740-560 Recife-PE, Brazil. Tel: (+55 81) 2126-8430, x4092 Fax: (+55 81) 2126-8438 <form method="POST" action="http://formspree.io/<EMAIL>"> <input type="name" name="name" placeholder="Your name"> <br><br> <input type="email" name="email" placeholder="Your email"> <br><br> <textarea name="message" placeholder="Your message"></textarea> <br> <input type="hidden" name="utf8" value="✓"> <button type="submit">Enviar</button> </form> [Go to the Home Page]({{ site.url }}{{ site.baseurl }}) <file_sep>/_posts/2013-01-22-accounting-cloud-computing.md --- layout: post title: "Accounting & Cloud Computing" categories: Pesquisa tag: mestrado --- My name is <NAME>, I am a Masters graduate student and this post aims at giving an introductory view of my master degree research at Centro de Informática (UFPE, Brazil), titled “**JiTCA: An Accounting Framework for Federated Clouds**”. ![]({{ BASE_PATH }}/images/2013-01-22-accounting-cloud-computing/figura1.png) Cloud Computing has become an established paradigm for running services on external infrastructure, where virtually unlimited capacity can be dynamically allocated. This paradigm provides a new scenario for the deployment of applications and IT services. In such a model, as complete applications as infrastructure of machines are offered to users and charged only for the consumed resources. Thus, the Cloud resources are offered through service abstractions, which today are known three main categories: Software as a Service (SaaS), Platform as a Service (PaaS) and Infrastructure as a Service (IaaS). In the IaaS case, computing resources are offered as Virtual Machines for final customers. Aiming to achieve the unlimited resources aspect of cloud is necessary to distribute these Virtual Machines through multiple Data Centers. This distribution makes harnessing to fulfil a number of requirements such as Security, Reliability, Availability and Accounting for the consumed resources. The Accounting function refers to how resources are recorded and charged, or more formally described: _Accounting is “the art of recording, classifying, and summarizing in a significant manner and in terms of money, transactions and events which are, in part at least, of financial character, and interpreting the results thereof " (Wahla, 1941)_ It is important to highlight that regarding Cloud Computing the term broadly used to refer such area is Billing, however recent studies established that the entire process from recording usage to the payment of consumed resources is in fact Accounting (Ruiz-Agundez, 2010). So, even in the case of a single cloud provider this task of Accounting is hard and there is a context which it becomes even worse, known as the Federation of Cloud Computing or also called Federated Cloud. Federated Cloud happens when a cloud provider dynamically outsource resources to other providers in response to demand variation. ![]({{ BASE_PATH }}/images/2013-01-22-accounting-cloud-computing/figura2.png) To better clarify Federated Cloud, imagine joining IaaS resources from different providers such as Amazon, GoGrid or Rackspace and you as a final user pay less money due to the possible intelligent scheduling, or even more simple, imagine Data Centers installed under several universities partnering with each other and offering such pool of resources for the students. That’s right, this is Federated Cloud. Thus, there is a cluster of clouds, but their resources are heterogeneous, resulting in a greater effort to manage the distributed resources and consequently for the Accounting. In this context, it was identified some research addressing this area which developed platforms for Federated Clouds, however without addressing the Accounting requirement. My work presents the **JiTCA**, an accounting framework which objective is charge _Infrastructure as a Service_ with focus on Federated Cloud. In order to gather information and consequently generate guidelines to substantiate decisions in building the framework, we applied a _Systematic Mapping Study_. In summary a _Systematic Mapping Study_ provides an overview of a research area, and identifies results available within it. &nbsp; ![]({{ BASE_PATH }}/images/2013-01-22-accounting-cloud-computing/figura3.png) Among the main functionalities are: a _Domain Specific Language_ to specify charging policies (a kind of formula to calculate how much the customers are going to pay); _Service Level Agreement_ Support; and Pre/Post-Paid Models Support. Finally, the framework was evaluated through an experimental study, showing evidences that the requirements generated by the Mapping Study were fulfilled by the framework and presenting indicators of its viability in a real Federated Cloud Platform called JiTCloud. The JiTCloud is a result from the research which involved eighteen Brazilian universities, sponsored by the _Centro de Pesquisa e Desenvolvimento em Tecnologias Digitais para Informação e Comunicação _(CTIC). Its proposal addresses an alternative to build computational infrastructure to support cloud computing which is not based on traditional capacity planning. If you want to know more about this research access: http://cin.ufpe.br/~faps/jitca<file_sep>/_posts/2014-10-14-o-caminho-da-inovacao-da-universidade-para-a-sociedade-e-de-volta-para-ela-2014.md --- layout: post title: "O Caminho da Inovação: Da Universidade para a Sociedade e de Volta para Ela (2014)" categories: Pesquisa tag: seminario --- No início de Setembro eu fui convidado a ministrar uma palestra na Semana do Administrador promovida pela FACIPE mais especificamente nos dias 09 e 10 de Setembro de 2014. O papo foi muito legal, sobre Inovação e como ela sai da Universidade, vai para a Sociedade e pro Mercado, claro, e depois volta para a Universidade! Foi um ótimo papo! <iframe class="scribd_iframe_embed" src="https://www.scribd.com/embeds/239245308/content?start_page=1&view_mode=scroll&access_key=key-7SOaKTp2OUC6WQLkOsD5&show_recommendations=true" data-auto-height="false" data-aspect-ratio="1.3323485967503692" scrolling="no" id="doc_47228" width="400" height="600" frameborder="0"></iframe> _Artigo originalmente publicado por [<NAME>](http://viniciusgarcia.me/education/o-caminho-da-inovacao-da-universidade-para-a-sociedade-e-de-volta-para-ela-2014/)_<file_sep>/pessoal.md --- layout: page title: Pessoal tagline: Lista dos membros permalink: /pessoal.html --- # Faculty * [**<NAME>**](http://viniciusgarcia/me){:target="_blank"}, Ph.D. (Líder), Adjunct Professor, [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE), [Lattes](http://lattes.cnpq.br/6613487636748832){:target="_blank"} * **<NAME>**, Ph.D., CNO (*Chief Ned Officer*) of [USTORE](http://ustore.com.br/){:target="_blank"} & Adjunct Professor, Universidade Federal Rural de Pernambuco (UFRPE), [Lattes](http://lattes.cnpq.br/3791808485485116){:target="_blank"} * **<NAME>**, Ph.D. (Coordenador), Full Professor, [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE), [Lattes](http://lattes.cnpq.br/4973731190814126){:target="_blank"} * **<NAME>**, Ph.D., Adjunct Professor, Universidade Federal da Bahia (UFBA), [Lattes](http://lattes.cnpq.br/6271096128174325){:target="_blank"} * **<NAME>**, Ph.D., Assistant Professor, Universidade Federal Rural de Pernambuco (UFRPE), [Lattes](http://lattes.cnpq.br/9163931285515006){:target="_blank"} * **<NAME>**, Ph.D., Assistant Professor, Universidade Federal Rural de Pernambuco (UFRPE), [Lattes](http://lattes.cnpq.br/5980278074458900){:target="_blank"} * **<NAME>**, Ph.D., Assistant Professor, Universidade Federal Rural de Pernambuco (UFRPE), [Lattes](http://lattes.cnpq.br/3518416272921878){:target="_blank"} * **<NAME>**, Ph.D. at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE) & Assistant Professor (UFRPE), [Lattes](http://lattes.cnpq.br/6465144387155252){:target="_blank"} * **<NAME>**, Ph.D. at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE) & Assistant Professor (UFAL), [Lattes](http://lattes.cnpq.br/3117877031824338){:target="_blank"} * **<NAME>**, M.Sc., Ph.D. candidate at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE) & Assistant Professor (UFRPE), [Lattes](http://lattes.cnpq.br/8750956715158540){:target="_blank"} * **<NAME>**, M.Sc., Ph.D. candidate at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE) & Assistant Professor (UFRPE), [Lattes](http://lattes.cnpq.br/6060587704569605){:target="_blank"} * **<NAME>**, Ph.D. candidate at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE) & Assistant Professor (UPE), [Lattes](http://lattes.cnpq.br/5941653866734201){:target="_blank"} * **<NAME>**, M.Sc., Ph.D. at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE) & Assistant Professor (UPE), [Lattes](http://lattes.cnpq.br/0804375840636282){:target="_blank"} # Collaborators * **<NAME>**, Ph.D., Adjunct Professor, Universidade Federal de São Carlos (UFSCar) - Campus Sorocaba, [Lattes](http://lattes.cnpq.br/9929982894313130){:target="_blank"} * **<NAME>**, Ph.D., Adjunct Professor, Departamento de Computação (UFSCar), Campus São Carlos, [Lattes](http://lattes.cnpq.br/9090396559596221){:target="_blank"} * **<NAME>**, Ph.D., Adjunct Professor, Departamento de Computação (UFC), [Lattes](http://lattes.cnpq.br/8908026219336623){:target="_blank"} * **<NAME>**, Ph.D., Adjunct Professor, Departamento de Ciência da Informação (UFPE), [Lattes](http://lattes.cnpq.br/3656327420806840){:target="_blank"} * **<NAME>**, Ph.D. candidate at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE), Software Architect (Accenture), [Lattes](http://lattes.cnpq.br/3832479082925280){:target="_blank"} * **<NAME>**, M.Sc. at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE), Software Engineer ([USTORE](http://ustore.com.br/){:target="_blank"}), & Assistant Professor (IFPE) [Lattes](http://lattes.cnpq.br/9966676370707957){:target="_blank"} # Current members * **<NAME>**, M.Sc., Ph.D. candidate at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE), [Lattes](http://lattes.cnpq.br/1521869500050398){:target="_blank"} * **<NAME>**, M.Sc., Ph.D. candidate at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE), [Lattes](http://lattes.cnpq.br/4349146742631578){:target="_blank"} * **<NAME>**, M.Sc., Ph.D. candidate at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE), [Lattes](http://lattes.cnpq.br/9861261850443973){:target="_blank"} * **<NAME>**, M.Sc., Ph.D. candidate at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE), [Lattes](http://lattes.cnpq.br/9846282643551300){:target="_blank"} * **<NAME>**, M.Sc., Ph.D. candidate at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE), [Lattes](http://lattes.cnpq.br/7684467910401597){:target="_blank"} * **<NAME>**, M.Sc. candidate at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE), [Lattes](http://lattes.cnpq.br/1466400900503967) * **<NAME>**, M.Sc. candidate at [Centro de Informática](http://www.cin.ufpe.br){:target="_blank"} (UFPE), [Lattes](http://lattes.cnpq.br/6157477770606975) # Alumni * [<NAME>](http://lattes.cnpq.br/9832803117127707){:target="_blank"} * [<NAME>](http://lattes.cnpq.br/3989518164012856){:target="_blank"} * [<NAME>](http://lattes.cnpq.br/2815325942997286){:target="_blank"} * [<NAME>](http://lattes.cnpq.br/0049236912396224){:target="_blank"} * [<NAME>](http://lattes.cnpq.br/){:target="_blank"} * [<NAME>](http://lattes.cnpq.br/9264504615692760){:target="_blank"} * <NAME> * [<NAME>](http://lattes.cnpq.br/6574079041682690){:target="_blank"} * [<NAME>](http://lattes.cnpq.br/8424333590929645){:target="_blank"} * [<NAME>](http://lattes.cnpq.br/5478160292712974){:target="_blank"} * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME>, M.Sc., CIn (UFPE) & System Engineer (CESAR). * <NAME>, M.Sc., CIn (UFPE) & System Engineer (CESAR). * <NAME> * <NAME>, M.Sc., CIn (UFPE) & Analyst (ANATEL). * <NAME>, M.Sc., PhD. candidate at UFBA. * <NAME>, Professional M.Sc., CIn (UFPE). * <NAME>, PhD. candidate at (PUC-SP). * <NAME>, Professional M.Sc. CESAR.EDU. * <NAME>, M.Sc. at CIn (UFPE). * <NAME>, M.Sc. at CIn (UFPE) & Software Architect at Banco Central (BACEN). * <NAME>, B.Sc. * <NAME>, M.Sc., Project Manager (Ogilvy & Mather, OGILVY). * <NAME> * <NAME>, M.Sc., Ph.D. candidate at CIn (UFPE). * <NAME>, M.Sc., Software Engineer (USTORE), curriculum. * <NAME>, M.Sc., Software Engineer (USTORE), curriculum. * <NAME> * <NAME>, Information Systems B.Sc. student at UFPE. * <NAME> * <NAME>, B.Sc., UFRPE. * <NAME>, B.Sc., UFRPE. * <NAME> * <NAME>únior. * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> <file_sep>/_posts/2013-05-24-assert-at-13th-international-conference-on-web.md --- layout: post title: "ASSERT at 13th International Conference on Web Engineering (ICWE 2013) - Industry track" categories: Artigos tag: conferencia --- The paper “**USTO.RE: A Private Cloud Storage System**“ authored by <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME> has been accepted for publication at [13th International Conference on Web Engineering (ICWE 2013) - Industry track](http://icwe2013.webengineering.org/industryTrack). The conference will be held in July 8-12, 2013 in Aalborg, Denmark. A brief overview of the paper is given next. _Cloud computing is a computing model where hardware, platforms and software are seen as services; viz. Infrastructure as a Service, Platform as a Service, and Software as a Service, respectively. Data as a Service (DaaS) is based on the concept that the product, data in this case, can be provided on demand to the user, regardless of geographic or organizational separation between provider and consumer. DaaS applications are for the most part based on excessive data replication in order to guarantee data availability, which means excessive costs in hardware investments. This white paper presents the specification, implementation and evaluation of a system called USTO.RE which aims to be an effective and low-cost alternative for storing data, thereby mitigating the problem of excessive data replication and thus allows itself to be considered a reliable platform from the perspective of data availability. Evaluation scenarios and the results achieved in our experiments to evaluate the system as well as possible lines for future development will be presented._<file_sep>/_posts/2013-04-03-assert-lab-and-ines-at-the-13th-ieeeacm.md --- layout: post title: "Assert Lab and INES at the 13th IEEE/ACM International Symposium on Cluster, Cloud and Grid Computing (CCGrid 2013)" categories: Artigos tag: conferencia --- The paper "Accounting Federated Clouds based on the JiTCloud Platform" authored by <NAME>, <NAME>, <NAME>, <NAME> and <NAME>, has been accepted as a poster for publication at the [13th IEEE/ACM International Symposium on Cluster, Cloud and Grid Computing](http://www.pds.ewi.tudelft.nl/ccgrid2013) (CCGrid 2013). The symposium will be held in May 13-16, 2013 at Delft, Netherlands. This activity is part of the project "[JiTCloud - Highly scalable IaaS](http://jitclouds.lsd.ufcg.edu.br/site/)" and is one of the results of the MSc research developed by <NAME>ton. A brief overview of the paper is given next _Cloud accounting refers to how cloud usage is recorded and charged. We identified four federated cloud plat-forms which do not include an accounting system. This work presents an accounting mechanism implemented for one of these platforms focused on IaaS. Further, we analyse our proposal in a qualitative fashion._<file_sep>/_posts/2014-04-17-o-que-sao-web-apps-e-como-construi-las-parte-2.md --- layout: post title: "O que são Web Apps e como construí-las. (parte 2)" categories: Pesquisa tag: mestrado --- _By By <NAME> in [Hyper Reactive](http://hyperreactive.com/){:target="_blank"}_ No post anterior falamos a respeito de Web Apps e suas características básicas. Também falamos de algumas das vantagens em se adotar um modelo de Single-page application para desenvolver esse tipo de aplicação. Hoje falaremos sobre as dificuldades que podem aparecer ao se adotar esse paradigma e como contorná-las. Para isso criaremos uma aplicação que ficará hospedada nesse endereço: <http://case.hyperreactive.com>. O código fonte ficará aqui <https://github.com/misawsneto/hyperreactive>. Eu escolhi um framework para desenvolvimento de aplicações web chamado [Play!](https://www.playframework.com/){:target="_blank"}. É um framework Java/Scala bastante fácil de aprender, manipular, implantar (fazer deploy). Esse framework é mantido pelo pessoal do Typesafe, os mesmos caras por trás da linguagem de programação Scala e do middleware orientado a eventos chamado [Akka](https://akka.io/){:target="_blank"} (mais sobre programação orientada a eventos [aqui](http://hyperreactive.com/2013/12/o-que-e-event-driven-architecture-e-o-modelo-de-atores-de-hewitt/){:target="_blank"}). Bom, um dos problemas que emergem quando se constrói uma Single-page application utilizando a técnica citada no post anterior tem a ver com o endereçamento das páginas. A principal função dos browsers é apresentar o conteúdo retornado quando se faz uma requisição HTTP do tipo GET para a url definida na barra de endereços. Outra função fundamental do browser é manter um histórico de navegação e permitir que o usuário navegue entre as páginas deste histórico. Um browser não é um browser se não executar essas tarefas. Uma vez que uma Web App controla a navegação entre as páginas por meio de Ajax ela também deve controlar o histórico de navegação. Pense bem, o método descrito no post anterior injeta páginas dentro de uma div, mas até onde o browser consegue perceber, não há mudança de páginas (o endereço não muda). > <http://hyperreactive.com/2014/04/o-que-sao-web-apps-e-como-construi-las-parte-2/><file_sep>/_posts/2015-09-25-assert-wtd-webmedia-2015.md --- layout: post title: "ASSERT @WTD WebMedia 2015" categories: Artigos tag: conferencia --- Com prazer informamos que o artigo “_**Uma Metodologia de Recomendação Híbrida Para Sistemas de Armazenamento em Nuvem**_”, de autoria de <NAME> Rodrigues, <NAME> e <NAME> foi aceito para apresentação no XII Workshop de Teses e Dissertações do [21th Brazilian Symposium on Multimedia and The Web (WTD - WebMedia’2015)](http://webmedia.icomp.ufam.edu.br/){:target="_blank"}. O resumo do artigo diz que: > Um grande volume de dados armazenado em nuvem dificulta a filtragem de conteúdo relevante, demanda tempo e trabalho por parte do usuário na busca por arquivos com conteúdo similar as suas preferências. Este trabalho apresenta uma proposta de metodologia para recomendação de arquivos em sistemas de armazenamento em nuvem, utilizando as principais técnicas de recomendação e características da nuvem.<file_sep>/_posts/2013-06-04-assert-at-journal-of-knowledge-and-web.md --- layout: post title: "ASSERT at Journal of Knowledge and Web Intelligence (IJKWI)" categories: Artigos tag: periodico --- The journal paper “**Towards Effective Course-based Recommendations for Public Tenders**“ authored by <NAME>, <NAME>, <NAME> e <NAME> has been accepted for publication at International [Journal of Knowledge and Web Intelligence](http://www.inderscience.com/jhome.php?jcode=ijkwi). A brief overview of the paper is given next. _In this paper, we propose a recommendation model to assist users find relevant courses for public tenders. The recommendations are computed based on the user study activity at Atepassar.com, a web-based learning environment for public tender candidates. Unlike traditional academic-oriented recommender systems, our approach takes into account crucial information for public tender candidates such as salary offered by public tenders and location where the exams take place. Technically, our recommendations rely on content-based techniques and a location reasoning method in order to provide users with most feasible courses. Results from a real-world dataset indicate reasonable improvement in recommendation quality over compared baseline models --- we observed about 11% of precision improvement and 12.7% of recall gain over the best model compared --- demonstrating the potential of our approach in recommending personalized courses._<file_sep>/publicacoes.md --- layout: page title: Publicação tagline: Lista de Produção Tecnológica & Científica permalink: /publicacoes.html --- # Lista de publicações ## [2021](#2021) ### Artigos em Conferências / Conference papers 1. <NAME>, <NAME>.; <NAME>; <NAME>; <NAME>; FEITOSA, <NAME>.; **GARCIA, <NAME>**; <NAME>, <NAME>; ARCOVERDE, <NAME>. [**Uma avaliação de comportamentos homográficos em ataques de phishing direcionados que exploram a suscetibilidade pela fidedignidade e sazonalidade**](). In: [XXI Simpósio Brasileiro de Segurança da Informação e de Sistemas Computacionais (SBSeg 2021)](https://sbseg2021.ufpa.br/), 04 a 07 de Outubro de 2021, Belém, Pará, Brasil. 1. NEVES, Flávio; **GARCIA, <NAME>**; BONFIM, <NAME>. [**Um mecanismo para recomendação de algoritmos de anonimização de dados baseado no perfil dos dados para ambientes IoT**](). XI Workshop de Teses e Dissertações (WTDSoft) - evento permanente associado ao [Congresso Brasileiro de Software: Teoria e Prática (CBSoft)](http://cbsoft2021.joinville.udesc.br/index.php), 27 de Setembro a 1 de Outubro de 2021, Joinvile, Santa Catarina, Brasil. ## [2020](#2020) ### Periódicos / Journals 1. FREITAS, <NAME>; <NAME>, <NAME>; **GARCIA, <NAME>**; FALCÃO, <NAME>; MARQUES, <NAME>; <NAME>, <NAME>. [**Avaliação de um Modelo de Maturidade para Adoção de Learning Analytics em Instituições de Ensino Superior**](https://doi.org/10.17398/1695-288X.19.2.101), In [Revista Latinoamericana de Tecnología Educativa (RELATEC)](https://relatec.unex.es), vol. 19, no. 2, ISSN 1695-288X, 2020. DOI: 10.17398/1695-288X.19.2.101 1. <NAME>; <NAME>.; <NAME>.; <NAME>; **GARCIA, <NAME>**; and <NAME>. [**Evolution of the Web of Social Machines: A Systematic Review and Research Challenges**](https://doi.org/10.1109/TCSS.2019.2961269), in [IEEE Transactions on Computational Social Systems](https://ieeexplore.ieee.org/xpl/RecentIssue.jsp?punumber=6570650), vol. 7, no. 2, ISSN: 2329-924X, pp. 373-388, April 2020. DOI: 10.1109/TCSS.2019.2961269 1. <NAME>, <NAME>.; FEITOSA, <NAME>.; **GARCIA, <NAME>**. [**Heuristic-based Strategy for Phishing Prediction: A Survey of URL-based approach**](https://doi.org/10.1016/j.cose.2019.101613). In: [Computers & Security](https://www.journals.elsevier.com/computers-and-security), Volume 88, ISSN: 0167-4048, January 2020. DOI: <https://doi.org/10.1016/j.cose.2019.101613> ### Artigos em Conferências / Conference papers 1. <NAME>; <NAME>; **GARCIA, <NAME>**; <NAME>. [**Applying a Multi-plataform Architectural Conformance Solution in a Real-world Microservice-based System**](https://doi.org/10.1145/3425269.3425270), In [14th Brazilian Symposium on Software Components, Architectures, and Reuse (SBCARS 2020)](https://cbsoft2020.imd.ufrn.br/sbcars.php), October 19 - 23, Natal-RN, Brazil, *Virtual Conference*, Association for Computing Machinery, New York, NY, USA, 41–50. DOI: https://doi.org/10.1145/3425269.3425270 1. <NAME>; <NAME>, <NAME>; **GARCIA, <NAME>**; <NAME>; <NAME>. [**Towards a Maturity Model for Learning Analytics Adoption**: An Overview of its Levels and Areas](https://doi.org/10.1109/ICALT49669.2020.00059), in [IEEE 20th International Conference on Advanced Learning Technologies and Technology-enhanced Learning (ICALT'2020)](https://ieeexplore.ieee.org/xpl/conhome/9146898/proceeding), pages 180 -- 184, 6 - 9 July, Tartu, Estonia. DOI: 10.1109/ICALT49669.2020.00059. ### Teses e Dissertações / Thesis & Dissertations 1. <NAME>. **MMALA: Um Modelo de Maturidade para Adoção de Learning Analytics**. 2020. Tese (Doutorado em Ciências da Computação) - Universidade Federal de Pernambuco. (_Co-Supervision_). [[lattes](http://lattes.cnpq.br/0804375840636282){:target="\_blank"}] [[pdf](https://www.scribd.com/document/478179303/MMALA-Um-Modelo-de-Maturidade-para-Adocao-de-Learning-Analytics){:target="\_blank"}] [[ppt](https://www.scribd.com/document/478180292/MMALA-Um-Modelo-de-Maturidade-para-Adocao-de-Learning-Analytics-Apresentacao){:target="\_blank"}] 1. <NAME>. **Piracema.io: Um Sistema Especialista Baseado em Heurística Direcionada por Características Estáticas e Dinâmicas para a Detecção Gradual de Phishing Direcionados**. 2020. Tese (Doutorado em Ciências da Computação) - Universidade Federal de Pernambuco. (_Supervision_). [[lattes](http://lattes.cnpq.br/5941653866734201){:target="\_blank"}] [[pdf](https://www.scribd.com/document/478179988/Piracema-io-Um-Sistema-Especialista-Baseado-em-Heuristica-Direcionada-por-Caracteristicas-Estaticas-e-Dinamicas-para-a-Deteccao-Gradual-de-Phishing-D){:target="\_blank"}] [[ppt](https://www.scribd.com/presentation/468216499/Piracema-io-Um-Sistema-Especialista-Baseado-em-Heuristica-Direcionada-por-Caracteristicas-Estaticas-e-Dinamicas-para-a-Deteccao-Gradual-de-Phishing-D){:target="\_blank"}] ## [2019](#2019) ### Periódicos / Journals 1. SOARES, <NAME>; DURÃO, <NAME>; **GARCIA, <NAME>**; ASSAD, <NAME>; SILVA, <NAME>; E SILVA, <NAME>; MEIRA, <NAME>. [**Dedupeer: An Algorithm for File Deduplication Through Partitioned Processing**](http://www.globalcis.org/dl/citation.html?id=JCIT-4422). In: [Journal of Convergence Information Technology (JCIT)](http://www.globalcis.org/jcit/home/index.html), Volume 14 Issue 1, January, 2019, Pages 100-111, ISSN 1975-9320 (Print) 2233-9299 (Online). GlobalCIS (Convergence Information Society, Republic of Korea). ### Artigos em Conferências / Conference papers 1. FREITAS, Elyda; <NAME>, <NAME>; **GARCIA, <NAME>**. [**Learning Analytics em Ação: Uma Revisão Sistemática de Literatura**](https://br-ie.org/pub/index.php/sbie/article/view/8891). In: [Simpósio Brasileiro de Informática na Educação (SBIE 2019)](https://br-ie.org/pub/index.php/sbie) - Trilha 4: Sistemas Inteligentes para a Promoção do Ensino e da Aprendizagem, Brasília, DF, 11 a 14 de Novembro de 2019. DOI: 10.5753/cbie.sbie.2019.1581 1. CÂNDIDO, <NAME>; TRINTA, <NAME>; REGO, Paulo; MENDONÇA, <NAME>.; **GARCIA, <NAME>**; <NAME>. [**Um relato sobre a migração de uma plataforma de offloading para microsserviços**](https://sol.sbc.org.br/index.php/vem/article/view/7581/7456). In: [VII Workshop on Software Visualization, Evolution and Maintenance (VEM 2019)](https://sol.sbc.org.br/index.php/vem/issue/view/440), Salvador/BA, September 23rd and 27th, 2019. 1. CÂNDIDO, <NAME>; TRINTA, <NAME>; REGO, Paulo; MENDONÇA, <NAME>.; **GARCIA, <NAME>**. [**A Microservice Based Architecture to Support Offloading in Mobile Cloud Computing**](https://doi.org/10.1145/3357141.3357148). In: [XIII Brazilian Symposium on Software Components, Architectures, and Reuse (SBCARS 2019)](http://cbsoft2019.ufba.br/#/sbcars), 93--102, Salvador/BA, September 23rd and 27th, 2019. ACM, New York, NY, USA. DOI: https://doi.org/10.1145/3357141.3357148. 1. DA SILVA, <NAME>; TEXEIRA, <NAME>.; <NAME>, <NAME>.; FEITOSA, <NAME>.; **GARCIA, <NAME>**. [**Suscetibilidade através da forja de fidedignidade: uma abordagem sobre ataques de Phishing**](https://sbseg2019.ime.usp.br/anais/195693.pdf). In: [19th Brazilian Symposium on Information and Computer System Security (SBSeg 2019)](https://sbseg2019.ime.usp.br), São Paulo, SP, 2-5 September 2019. 1. DA SILVA, <NAME>; **GARCIA, <NAME>**. [**Uma Modelagem de Risco Centrada em Comportamentos para o Desenvolvimento Seguro de Serviços no Ecossistema Web**](https://sbseg2019.ime.usp.br/anais/196135.pdf). In: [19th Brazilian Symposium on Information and Computer System Security (SBSeg 2019)](https://sbseg2019.ime.usp.br), São Paulo, SP, 2-5 September 2019. ### Teses e Dissertações / Thesis & Dissertations 1. <NAME>. **SELF: Um framework de suporte para o ensino da Engenharia de Software**. 2019. Dissertação (Mestrado em Ciências da Computação) - Universidade Federal de Pernambuco. (_Supervision_). [[lattes](http://lattes.cnpq.br/3989518164012856){:target="\_blank"}] [[pdf](https://www.scribd.com/document/467634329/SELF-Um-framework-de-suporte-para-o-ensino-da-Engenharia-de-Software){:target="\_blank"}] [[ppt](){:target="\_blank"}] ## [2018](#2018) ### Livros / Books 1. <NAME>; **<NAME>**. [**Arquitetura Para Tratamento De Dados Não Estruturados**](https://www.morebooks.shop/bookprice_offer_574afe995dd180abf0ad09d30786aa1cc7f2f09b?auth_token=d<KEY>&locale=gb&currency=EUR). [Novas Edições Acadêmicas](https://www.morebooks.shop/books/gb/published_by/novas-edi%C3%A7%C3%B5es-acad%C3%AAmicas/332520/products), ISBN-13: 978-613-9-61515-5, Published on 24-05-2018. ### Teses e Dissertações / Thesis & Dissertations 1. <NAME> Silva. **Em Direção a um Método Baseado em Métricas para Avaliação Contínua e Tomada de Decisão em Projetos de Software**. 2018. Tese (Doutorado em Ciências da Computação) - Universidade Federal de Pernambuco. (_Supervision_). [[lattes](http://lattes.cnpq.br/3832479082925280){:target="\_blank"}] [[pdf](https://pt.scribd.com/document/395638096/Em-Direcao-a-um-Metodo-Baseado-em-Metricas-para-Avaliacao-Continua-e-Tomada-de-Decisao-em-Projetos-de-Software){:target="\_blank"}] [[ppt](https://pt.scribd.com/document/388458197/Em-Direcao-a-um-Metodo-Baseado-em-Metricas-para-Avaliacao-Continua-e-Tomada-de-Decisao-em-Projetos-de-Software-Apresentacao){:target="\_blank"}] 1. <NAME>. **Um Meta-modelo para Representação de Dados Biológicos Moleculares e Suporte ao Processo de Anotação de Variantes Genéticas**. 2018. Tese (Doutorado em Ciências da Computação) - Universidade Federal de Pernambuco. (_Supervision_). [[lattes](http://lattes.cnpq.br/6060587704569605){:target="\_blank"}] [[pdf](https://pt.scribd.com/document/395818978/Um-Meta-modelo-para-Representac-a-o-de-Dados-Biolo-gicos-Moleculares-e-Suporte-ao-Processo-de-Anotac-a-o-de-Variantes-Gene-ticas){:target="\_blank"}] [[ppt](https://pt.scribd.com/document/388458600/Um-Meta-modelo-para-Representac-a-o-de-Dados-Biolo-gicos-Moleculares-e-Suporte-ao-Processo-de-Anotac-a-o-de-Variantes-Gene-ticas-Apresentacao){:target="\_blank"}] ## [2017](#2017) ### Livros / Books 1. <NAME> ‎ **<NAME>**. [**UMA INVESTIGAÇÃO SOBRE AS DIFICULDADES DE PLANEJAMENTO DE TI EM INSTITUIÇÕES PÚBLICAS BRASILEIRAS: UMA ABORDAGEM COM TEORIA FUNDAMENTADA EM DADOS**](https://www.amazon.com.br/INVESTIGA%C3%87%C3%83O-DIFICULDADES-PLANEJAMENTO-INSTITUI%C3%87%C3%95ES-BRASILEIRAS-ebook/dp/B077GBLBQ3/ref=sr_1_1?ie=UTF8&qid=1510830571&sr=8-1&keywords=vinicius+cardoso+garcia){:target="_blank"}, Amazon Servicos de Varejo do Brasil Ltda, ASIN: B077GBLBQ3, 2017. ### Artigos em Conferências / Conference papers 1. <NAME>, <NAME>; FEITOSA, <NAME>.; **GARCIA, <NAME>**. [**Uma Avaliação das Prevenções de Phishing em Navegadores Web**](). In: [XVII Brazilian Symposium in Information Security and Computational Systems (SBSeg)](https://en.sbseg2017.redes.unb.br/), Brasília-DF, November 6th to 9th, 2017. 1. GUTIERREZ, <NAME>; **GARCIA, <NAME>**; <NAME>.; <NAME>, <NAME>; RO<NAME>; ASSAD, <NAME>; BARRETO, Marcos. [**uStorage - A storage architecture to provide Block-level Storage through Object-based Storage**](https://link.springer.com/chapter/10.1007/978-3-319-67262-5_16){:target="_blank"}. In: <NAME>., <NAME>., <NAME>. (eds) [6th European Conference on Service-Oriented and Cloud Computing](http://esocc2017.ifi.uio.no/){:target="_blank"}, ESOCC 2017. Lecture Notes in Computer Science, vol 10465. Springer, Cham, Oslo, Norway, September 27-29, 2017. ISBN: 978-3-319-67262-5, doi: [10.1007/978-3-319-67262-5_16](https://doi.org/10.1007/978-3-319-67262-5_16){:target="_blank"}. 1. <NAME>, <NAME>; <NAME>, <NAME>; ASSAD, <NAME>; **GARCIA, <NAME>**. [**A Experiência de Desenvolvimento de um Sistema de Armazenamento Multicamadas e Distribuído**](http://www.lia.ufc.br/~cbsoft2017/proceedings_files/AnaisTrilhaIndustria_CBSoft2017.pdf). In: [Industry Track of Congresso Brasileiro de Software: Teoria e Prática (CBSoft'2017)](http://cbsoft.org/cbsoft2017/){:target="_blank"}, Fortaleza, Brasil, September 18-22, 2017. 1. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, **<NAME>**, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. [**Towards automated deployment of self-adaptive applications on hybrid clouds**](https://link.springer.com/chapter/10.1007/978-3-319-66197-1_26). In: In: <NAME>., <NAME>. (eds) [Software Engineering and Formal Methods](https://link.springer.com/book/10.1007/978-3-319-66197-1){:target="_blank"}. SEFM 2017. Lecture Notes in Computer Science, vol 10469. Springer, Cham, Trento, Italy, September 4-8, 2017. doi: <https://doi.org/10.1007/978-3-319-66197-1_26>. Online ISBN: 978-3-319-66197-1 1. <NAME>, <NAME>; **GARCIA, <NAME>**; REVOREDO, <NAME>; AFONSO, <NAME>. **Problems of Software Development Documentation: A Survey**. In: [Euromicro Conference on Software Engineering and Advanced Applications (SEAA)](http://dsd-seaa2017.ocg.at/seaa2017){:target="_blank"}, Vienna, Austria, 30 August - 1 September, 2017 ### Teses e Dissertações / Thesis & Dissertations 1. <NAME>. [**Smartcluster: A Metamodel Indicators for Smart and Human Cities**](https://pt.scribd.com/document/349849699/Smartcluster-A-Metamodel-Indicators-for-Smart-and-Human-Cities). 2017. Tese (Doutorado em Ciências da Computação) - Universidade Federal de Pernambuco, Fundação de Amparo à Ciência e Tecnologia do Estado de Pernambuco. (Supervision: <NAME>). 1. <NAME>. [**Assessing Security in Software Product Lines: A Maintenance Analysis**](https://pt.scribd.com/document/359855895/Assessing-Security-in-Software-Product-Lines-A-Maintenance-Analysis). 2017. Tese (Doutorado em Ciências da Computação) - Universidade Federal de Pernambuco. (Supervision). 1. <NAME>. [**Buscando a proposição de uma forma de configuração e comercialização de computação em nuvem com alto nível de abstração com base no mapeamento sistemático da literatura sobre serviço medido**](https://pt.scribd.com/document/341850586/Buscando-a-proposic-a-o-de-uma-forma-de-configurac-a-o-e-comercializac-a-o-de-computac-a-o-em-nuvem-com-alto-ni-vel-de-abstrac-a-o-com-base-no-mapeame). 2017. Dissertação (Mestrado Profissional em Ciências da Computação) - Universidade Federal de Pernambuco. (Supervision: V<NAME>). 1. <NAME>. [**Proposta de arquitetura para tratamento de dados não estruturados no âmbito dos Institutos Federais de Educação**](https://pt.scribd.com/document/367171325/Proposta-de-arquitetura-para-tratamento-de-dados-nao-estruturados-no-ambito-dos-Institutos-Federais-de-Educacao). 2017. Dissertação (Mestrado Profissional em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: V<NAME>). 1. <NAME>. [**Uma Abordagem Orientada a Modelos para Geração de Aplicações Baseadas em Internet das Coisas para Smartphones**](https://pt.scribd.com/document/367170836/Uma-Abordagem-Orientada-a-Modelos-para-Geracao-De-aplicacoes-baseadas-em-internet-das-coisas-para-Smartphones). 2017. Dissertação (Mestrado Profissional em Ciências da Computação) - Universidade Federal de Pernambuco. (Supervision: V<NAME>ia). 1. <NAME>. [**Análise Qualitativa sobre Engajamento no Uso de uma Rede Social Educacional: Aprendizagem Colaborativa sobre Doenças Genéticas**](https://pt.scribd.com/document/360178177/Analise-Qualitativa-sobre-Engajamento-no-Uso-de-uma-Rede-Social-Educacional-Aprendizagem-Colaborativa-sobre-Doencas-Geneticas). 2017. Dissertação (Mestrado em Ciências da Computação) - Universidade Federal de Pernambuco. (Co-Supervision: V<NAME>ia). 1. <NAME>. [**Uma Arquitetura para Orquestração da Distribuição de Água no Semiárido Brasileiro Baseada em Internet das Coisas e Computação em Nuvem**](https://pt.scribd.com/document/360170925/Uma-Arquitetura-para-Orquestracao-da-Distribuicao-de-Agua-no-Semiarido-Brasileiro-Baseada-em-Internet-das-Coisas-e-Computacao-em-Nuvem). 2017. Dissertação (Mestrado em Ciências da Computação) - Universidade Federal de Pernambuco. (Supervision: <NAME>). ### Monografias / Monoraphies 1. <NAME>. [**Avaliação da suscetibilidade dos discentes de TI a ataques de phishing**](https://pt.scribd.com/document/367106132/Avaliac-a-o-da-suscetibilidade-dos-discentes-de-TI-a-ataques-de-phishing){:target="_blank"}. 2017\. Trabalho de Conclusão de Curso (Graduação em Ciência da Computação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME> Brasile<NAME>. [**Análise do Impacto da Estratégia de Uso de Branching em Devops**](https://pt.scribd.com/document/367105873/Ana-lise-do-Impacto-da-Estrate-gia-de-Uso-de-Branching-em-Devops){:target="_blank"}. 2017\. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME>. [**picel - HTTP Middleware for image processing**](https://pt.scribd.com/document/367105701/picel-HTTP-Middleware-for-image-processing){:target="_blank"}. 2017\. Trabalho de Conclusão de Curso (Graduação em Ciência da Computação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME>. **Automatização na escolha de ferramentas em projetos que aplicam DevOps**. 2017. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME> Brasile<NAME>. **Análise do Impacto da Estratégia de Uso de Branching em Devops**. 2017. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME>. **Análise comparativa de ferramentas de gerenciamento e monitoramento de erros para aplicações java**. 2017. Trabalho de Conclusão de Curso (Graduação em Ciência da Computação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME>. **GenCloud - Uma abordagem para disponibilização de sistemas web baseado em contêineres em um ambiente de nuvem híbrida**. 2017. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME>. **Um Chatbot para o Centro de Informática**. 2017. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME>. **Uma proposta para centralizar práticas DevOps com uso do gitlab**. 2017. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). ## [2016](#2016) ### Periódicos / Journals 1. <NAME>; MOREIRA, Ana; LUCRÉDIO, Daniel; **GARCIA, <NAME>** and <NAME>. [**Issues on developing interoperable cloud applications: definitions, concepts, approaches, requirements, characteristics and evaluation models**](http://jserd.springeropen.com/articles/10.1186/s40411-016-0033-6){:target="_blank"}. In: [Journal of Software Engineering Research and Development](https://jserd.springeropen.com/){:target="_blank"}, 2016, 4:7. DOI: [10.1186/s40411-016-0033-6](http://dx.doi.org/10.1186/s40411-016-0033-6){:target="_blank"}. 1. <NAME>, <NAME>; **GARCIA, <NAME>**; SOUZA, <NAME>; RABÊLO, <NAME>; SOARES, <NAME>; Lopes, <NAME>. [**Extração de Conhecimento em um Survey sobre o Uso de Computação em Nuvem no Brasil**](http://dx.doi.org/10.21528/LNLM-vol14-no1-art6){:target="_blank"}. In: [Learning and Nonlinear Models – Journal of the Brazilian Computational Intelligence Society, Vol. 14, Iss. 1](http://abricom.org.br/lnlm/publicacoes/vol14-no1/){:target="_blank"}, pp. 58-71, 2016. ISSN 1676-2789. ### Capítulos de Livro / Book Chapters 1. GARCIA, <NAME>; **GARCIA, <NAME>**. [Aplicando Grounded Theory para compreender as dificuldades de Planejamento de TI em Órgãos Federais](http://sbsi2016.ufsc.br/?page_id=5060){:target="_blank"}. In: [IX Workshop de Teses e Dissetações em Sistemas de Informação (WTDSI)](http://sbsi2016.ufsc.br/?page_id=4956){:target="_blank"}, Evento integrante do [XII Simpósio Brasileiro de Sistemas de Informação (SBSI’2016)](http://sbsi2016.ufsc.br/){:target="_blank"}, pp. 24–26, Florianópolis, SC, 17 a 20 de Maio de 2016. ### Artigos em Conferências / Conference papers 1. <NAME>, <NAME>; <NAME>; <NAME>; <NAME>; **GARCIA, <NAME>**. [**A centralized platform on human genome for supporting clinical decisions**](http://www.sbis.org.br/biblioteca_virtual/cbis/Anais_CBIS_2016_Artigos_Completos.pdf){:target="_blank"}. In: [XV Congresso Brasileiro de Informática em Saúde (CBIS’2016)](http://www.sbis.org.br/cbis2016){:target="_blank"}, Goiânia – Brazil, 27-30 Novembro, 2016, pp. 569-577. 1. AFONSO, <NAME>; <NAME>; <NAME>; **GARCIA, <NAME>**. [**Cidades Inteligentes: IDH como Indicador de Serviços**](http://docplayer.com.br/44358384-Anais-sociedade-brasileira-de-informatica-em-saude-sbis.html){:target="_blank"}. In: [XV Congresso Brasileiro de Informática em Saúde (CBIS’2016) – Pôsteres](http://www.sbis.org.br/cbis2016){:target="_blank"}, Goiânia – Brazil, 27-30 Novembro, 2016, pp. 310. 1. AFONSO, <NAME>; <NAME>; <NAME>; **GARCIA, <NAME>**. [**DendroIDH: Agrupando Cidades por Semelhança de Indicadores**](http://www.sbis.org.br/biblioteca_virtual/cbis/Anais_CBIS_2016_Artigos_Completos.pdf){:target="_blank"}. In: [XV Congresso Brasileiro de Informática em Saúde (CBIS’2016)](http://www.sbis.org.br/cbis2016){:target="_blank"}, Goiânia – Brazil, 27-30 Novembro, 2016, pp. 907-913. 1. <NAME>, <NAME>; <NAME>, <NAME>; **GARCIA, <NAME>**. [**Estudo de mapeamento sistemático sobre as tendências e desafios do cloud gaming**](http://www.revista.ufpe.br/gestaoorg/index.php/gestao/article/view/902){:target="_blank"}. In: [V Simpósio Brasileiro de Tecnologia da Informação (SBTI’2016)](http://www.ufpb.br/idep/sbti2016/){:target="_blank"}, João Pessoa-PB, 05-07 de Outubro, 2016. Publicado na [Revista Eletrônica de Gestão Organizacional, vol. 14 Edição Especial: Anais do IV Simposio Brasileiro de Tecnologia da Informação (2016)](http://www.revista.ufpe.br/gestaoorg/index.php/gestao/issue/current){:target="_blank"}, ISSN: 1679-1827. DOI: 10.21714/1679-18272016v14Esp.p224-233. 1. <NAME>, <NAME>; BURÉGIO, <NAME>; <NAME>; <NAME>; **GARCIA, <NAME>**. [**A centralized platform for access of heterogeneous data on human genome repositories for supporting clinical decisions**](http://sbbd2016.fpc.ufba.br/e-book/satellites.pdf){:target="_blank"}. In: [Database Systems Industry Day Workshop (DSIDW’2016)](http://sbbd2016.fpc.ufba.br/en/chamada-dsidw/){:target="_blank"} – [Simpósio Brasileiro de Banco de Dados (SBBD’2016)](http://sbbd2016.fpc.ufba.br/en/){:target="_blank"}, p. 106, Salvador – BA – Brazil, 04-07 October, 2016. 1. MEIRA, <NAME>; BURÉGIO, <NAME>; BORBA, <NAME>; GARCIA, <NAME>; ALBUQUERQUE, <NAME>; SOARES; <NAME>. [**Programming the Universe: The First Commandment of Software Engineering for all Varieties of Information Systems**](http://bit.ly/1stCMD){:target="_blank"}. In: [Brazilian Symposium on Software Engineering (SBES’2016) – Insightful Ideas Track](http://cbsoft.org/cbsoft2016/sbes2016?lang=en){:target="_blank"}, [VII Brazilian Conference on Software:Theory and Practice (CBSoft)](http://cbsoft.org/cbsoft2016/){:target="_blank"}, Maringá – Brazil, 19-23 September, 2016. 1. SILVEIRA, <NAME>; <NAME>, <NAME>; <NAME>, <NAME>; CAVALCANTI, <NAME>; **GARCIA, <NAME>**. [**RiSE Events – A Testbed for Software Product Lines Experimentation**](http://dx.doi.org/10.1145/2897045.2897047){:target="_blank"}. In: [First International Workshop on Variability and Complexity in Software Design (VACE)](http://vaquita-workshop.org/vace/){:target="_blank"}, in conjunction with [38th International Conference on Software Engineering (ICSE)](http://2016.icse.cs.txstate.edu/){:target="_blank"}, USA, 2016. p.40–49. DOI: 10.1145/2897045.2897047. 1. GARCIA, <NAME>; **GARCIA, <NAME>**. [Aplicando Grounded Theory para compreender as dificuldades de Planejamento de TI em Órgãos Federais](http://sbsi2016.ufsc.br/?page_id=5060){:target="_blank"}. In: [IX Workshop de Teses e Dissetações em Sistemas de Informação (WTDSI)](http://sbsi2016.ufsc.br/?page_id=4956){:target="_blank"}, Evento integrante do [XII Simpósio Brasileiro de Sistemas de Informação (SBSI’2016)](http://sbsi2016.ufsc.br/){:target="_blank"}, pp. 24–26, Florianópolis, SC, 17 a 20 de Maio de 2016. 1. SILVA, <NAME>; SILVA, <NAME>; RODRIGUES, <NAME>; GATTI, <NAME>; MIRANDA, <NAME>; BRITO, <NAME>; NASCIMENTO, <NAME>; ASSAD, <NAME>; QUEIROZ, <NAME>; **GARCIA, <NAME>**. [**A Meta-Analysis for Security Threats over the Web Ecosystem**](http://dx.doi.org/10.1109/NOMS.2016.7502911){:target="_blank"}. In: [IEEE/IFIP Network Operations and Management Symposium (NOMS 2016)][3], Istanbul – Turkey, 25-29 APRIL 2016. DOI: 10.1109/NOMS.2016.7502911. 1. SILVA, <NAME>; SILVA, <NAME>; RODRIGUES, <NAME>; GATTI, <NAME>; MIRANDA, <NAME>; BRITO, <NAME>; NASCIMENTO, <NAME>; ASSAD, <NAME>; QUEIROZ, <NAME>; **GARCIA, <NAME>**. [**Towards a Taxonomy for Security Threats on the Web Ecosystem**](http://dx.doi.org/10.1109/NOMS.2016.7502862){:target="_blank"}. In: [IEEE/IFIP Network Operations and Management Symposium (NOMS 2016)][3], Istanbul – Turkey, 25-29 APRIL 2016. DOI: 10.1109/NOMS.2016.7502862. ### Teses e Dissertações / Thesis & Dissertations 1. <NAME>. Developing programming skills on digital native children through the interaction with smart devices. 2016. Dissertação (Mestrado Profissional em Ciências da Computação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME>. Uma Investigação sobre o Processo Migratório para a Plataforma de Computação em Nuvem no Brasil. 2016. Dissertação (Mestrado Profissional em Ciências da Computação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME>. Uma Arquitetura de Referência Guiada à Conformidades de Segurança para Web Services Baseados em Nuvem Privada. 2016. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME>. Rastreabilidade entre Artefatos Heterogêneos de Software - Um Mapeamento Sistemático. 2016. Dissertação (Mestrado em Ciências da Computação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). ### Monografias / Monographies 1. <NAME>. **Em Direção a uma Proposta Prática para o Ensino da Engenharia de Software no Centro de Informática**. 2016. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME>. **Usain Bot: Uma proposta de construção de chatterbots como serviço**. 2016. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 1. <NAME>. **Desenvolvimento de uma Ferramenta de Estratégia do Serviço de Pós-Venda para Auxiliar Lojistas do Ecommerce**. 2016. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia) 1. <NAME>. **Uma Revisão do Estado da Arte Sobre os Desafios e Efeitos do Uso de Software Defined Data Center (SDDC)**. 2016. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia) 1. <NAME>. **Estudo de Mapeamento Sistemático sobre as Tendências e Desafios do Cloud Gaming**. 2016. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia) 1. <NAME>. **Uma biblioteca Multi-Tenant para o framework Django**. 2016. Trabalho de Conclusão de Curso (Graduação em Ciência da Computação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia) 1. <NAME>. **Um Estudo Sobre Blockchain e Serviços de Armazenamento Em Nuvem**. 2016. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia) 1. <NAME> Pessa. **Internet das Coisas na Indústria Civil Brasileira**. 2016. Trabalho de Conclusão de Curso (Graduação em Engenharia da Computação) – Universidade Federal de Pernambuco. (Supervision: <NAME>) ## [2015](#2015) ### Periódicos / Journals 1. BRITO, <NAME> ; COSTA, <NAME> ; **<NAME>**; MEIRA, <NAME>. [**Is Brazilian Open Government Data Actually Open Data?**](http://www.irma-international.org/article/is-brazilian-open-government-data-actually-open-data/128245/]){:target="_blank"}. [International Journal of E-Planning Research (IJEPR)](http://www.irma-international.org/journal/international-journal-planning-research-ijepr/44994/){:target="_blank"}, v. 4, p. 57-73, 2015. DOI: 10.4018/ijepr.2015040104. 1. AFONSO, <NAME> ; BRITO, <NAME> ; <NAME>, <NAME> ; COSTA, <NAME>. ; ÁLVARO, ALEXANDRE ; **<NAME>**. [**(Br-SCMM) Brazilian Smart City Maturity Model: A Perspective from the Health Domain**](http://ebooks.iospress.nl/publication/40443){:target="_blank"}. [Studies in Health Technology and Informatics](http://ebooks.iospress.nl/bookseries/studies-in-health-technology-and-informatics){:target="_blank"}, v. 216 ([MEDINFO 2015: eHealth-enabled Health](http://ebooks.iospress.nl/volume/medinfo-2015-ehealth-enabled-health-proceedings-of-the-15th-world-congress-on-health-and-biomedical-informatics){:target="_blank"}), p. 983, 2015, doi: 10.3233/978-1-61499-564-7-983 ### Revistas / Magazines 1. <NAME>; <NAME>; **<NAME>**. [**SCiAl: Usando Dados Públicos para Agrupar Cidades Inteligentes Alagoanas**](https://periodicos.ufpe.br/revistas/gestaoorg/article/view/22125/18490){:target="_blank"}. In: [IV Simpósio Brasileiro de Tecnologia da Informação (SBTI)](http://octeventos.com/site/sbti/){:target="_blank"}, 14 a 16 de Outubro, Aracaju – SE, publicado na [Revista Gestão.Org, v. 13, Edição Especial, 2015. p. 331-339](https://periodicos.ufpe.br/revistas/gestaoorg/article/view/22125){:target="_blank"}, ISSN 1679-1827. 1. <NAME>.; <NAME>.; <NAME>.; <NAME>.; **<NAME>** <NAME>. . **GUIDELINE PARA PRIORIZAÇÃO DE SOLICITAÇÕES CORRETIVAS URGENTES BASEADO EM METODOLOGIAS ÁGEIS PARA O CONTEXTO DE FÁBRICAS DE SOFTWARE ORIENTADAS A PRODUTO**. REVISTA ELETRÔNICA ENG TECH SCIENCE, v. 3, p. 22-32, 2015. ### Artigos em Conferências / Conference papers 1. <NAME>. ; <NAME>. ; <NAME>. . [**Collaborative Enterprise Applications based on Business and Social Artifacts**](https://doi.org/10.1109/WETICE.2015.12). In: WETICE 2015, 2015, Larnaca. In: [24th IEEE International Conference on Enabling Technologies: Infrastructure for Collaborative Enterprises](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=7194241), 2015, pp. 150-155, doi:10.1109/WETICE.2015.12 1. <NAME>. ; <NAME>. ; <NAME>. ; <NAME>. ; <NAME>. . [**“Controlling" Web 2.0 Applications in the Workplace**](https://doi.org/10.1109/EDOC.2015.35). In: IEEE EDOC 2015, 2015, Adelaide. [The 19th IEEE International EDOC Conference (EDOC2015)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=7312652), 2015, pp.191-200, 21-25 Sept. 2015, doi: 10.1109/EDOC.2015.35 1. RODRIGUES, <NAME>; **GARCIA, <NAME>**; and MEIRA, <NAME>. [**Uma Metodologia de Recomendação Híbrida Para Sistemas de Armazenamento em Nuvem**](https://www.researchgate.net/publication/289537170_Uma_Metodologia_de_Recomendacao_Hibrida_Para_Sistemas_de_Armazenamento_em_Nuvem_Alternative_title_An_Hybrid_Methodology_Recommendation_in_Cloud_Storage_Systems){:target="_blank"}. In: XII Workshop de Teses e Dissertações do [21th Brazilian Symposium on Multimedia and The Web (WebMedia'2015)](https://dl.acm.org/citation.cfm?id=2820426){:target="_blank"}, 27 – 30 de Outubro – Manaus, AM, 2015. 1. SILVA, <NAME>.; <NAME>; RODRIGUES, <NAME>; BRITO, <NAME>; <NAME>, <NAME>; <NAME>; ASSAD, <NAME>; <NAME>; **GARCIA, <NAME>**. [**Uma Avaliação da Proteção de Dados Sensíveis através do Navegador Web**](http://siaiap34.univali.br/sbseg2015/anais/SBSegCompletos/artigoCompleto07.pdf){:target="_blank"}. In: [XV Simpósio Brasileiro em Segurança da Informação e de Sistemas Computacionais (SBSeg 15)](http://siaiap34.univali.br/sbseg2015/en){:target="_blank"} – Trilha de Trabalhos Completos, 09 – 12 de Novembro – Florianópolis, SC, 2015, pp. 86-99. 1. BITENCOURT, <NAME>.; DURÃO, <NAME>; <NAME>. **[EmergencyFire: An Ontology for Fire Emergency Situations**](https://doi.org/10.1145/2820426.2820453). In: [XXI Brazilian Symposium on Multimedia and the Web (WebMedia 2015)](http://webmedia.icomp.ufam.edu.br/), Manaus - AM, 27 - 30 October, 2015, pp. 73-76, doi: 10.1145/2820426.2820453 1. GAMA, <NAME>; WANDERLEY, <NAME>; MARANHÃO, <NAME>; **GARCIA, <NAME>**. [**TagHunt: Uma plataforma Combinando a Internet das Coisas com Scavenger Hunt Games**](https://www.researchgate.net/publication/280156733_TagHunt_Uma_plataforma_Combinando_a_Internet_das_Coisas_com_Scavenger_Hunt_Games){:target="_blank"}. In: [7º Simpósio Brasileiro de Computação Ubíqua e Pervasiva (SBCUP)](http://csbc2015.cin.ufpe.br/eventos_descricao/13){:target="_blank"}, Evento do XXXV Congresso da Sociedade Brasileira de Computação, Recife, 20 a 23 de Julho de 2015. 1. DO NASCIMENTO, <NAME>; AFONSO, <NAME>; **GARCIA, <NAME>**; DA SILVA, <NAME>. [**Convertview:A Tool for Conversion and Visualization of Open Heterogenic Governmental Data to the Rdf Standard**](http://www.scitepress.org/DigitalLibrary/Link.aspx?doi=10.5220/0005456902530258){:target="_blank"}. In: The [11th International Conference on Web Information Systems and Technologies (WEBIST)](http://dblp.uni-trier.de/db/conf/webist/webist2015){:target="_blank"}, ISBN 978-989-758-106-9, pages 253-258, Lisbon – Portugal, 20 – 22 May, 2015. doi: [10.5220/0005456902530258](http://www.scitepress.org/DigitalLibrary/Link.aspx?doi=10.5220/0005456902530258){:target="_blank"}. 1. BURÉGIO, <NAME>; BRITO, <NAME>; <NAME>; <NAME>, <NAME>; **GARCIA, <NAME>** and MEIRA, <NAME>. [**Towards Government as a Social Machine**](https://doi.org/10.1145/2740908.2743976){:target="_blank"}. In Proceedings of the [24th International Conference on World Wide Web Companion (WWW '15 Companion)](http://www.www2015.it/){:target="_blank"}. International World Wide Web Conferences Steering Committee, Republic and Canton of Geneva, Switzerland, 1131-1136. doi: 10.1145/2740908.2743976 1. <NAME>; <NAME>; <NAME>; **GARCIA, <NAME>**. [**A Web-based platform for Scavenger Hunt Games using the Internet of Things**](https://doi.org/10.1109/CCNC.2015.7158085){:target="_blank"}. In: [IEEE Consumer Communications & Networking Conference (CCNC)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=7151874){:target="_blank"} Held in conjunction with the International Consumer Electronics Show, Las Vegas, January 09-12, 2015. doi: 10.1109/CCNC.2015.7158040 1. AFONSO, <NAME>; BRITO, <NAME>; <NAME>, <NAME>; **GARCIA, <NAME>**; and ÁLVARO, Alexandre. 2015. [**Brazilian smart cities: using a maturity model to measure and compare inequality in cities**](https://doi.org/10.1145/2757401.2757426){:target="_blank"}. In Proceedings of the [16th Annual International Conference on Digital Government Research (dg.o '15)](http://dgo2015.dgsociety.org/about-conference){:target="_blank"}. ACM, New York, NY, USA, 230-238. doi: 10.1145/2757401.2757426 1. BRITO, <NAME>; COSTA, <NAME>; **GARCIA, <NAME>**; and MEIRA, <NAME>. 2015. [**Assessing the benefits of open government data: the case of Meu Congresso Nacional in Brazilian elections 2014**](https://doi.org/10.1145/2757401.2757422){:target="_blank"}. In Proceedings of the [16th Annual International Conference on Digital Government Research (dg.o '15)](http://dgo2015.dgsociety.org/about-conference){:target="_blank"}. ACM, New York, NY, USA, 89-96. doi: 10.1145/2757401.2757422 1. RODRIGUES, <NAME>; SILVA, <NAME>; **GARCIA, <NAME>**; MEIRA, <NAME>. [**Criando Startups: Métodos, Processos, Técnicas e Ferramentas**](http://www.inf.ufg.br/sbsi2015/sites/portal.inf.ufg.br.sbsi2015/files/criando_startups.pdf){:target="_blank"}. In: [Anais do XI Simpósio Brasileiro de Sistemas de Informação, Sistemas de Informação: A Visão Sociotécnica da Computação](http://www.portal.inf.ufg.br/sbsi2015/){:target="_blank"}. Goiânia, GO, Brasil: Instituto de Informática, Universidade Federal de Goiás, 2015. p.699 – 702. 1. RODRIGUES, <NAME>; SILVA, <NAME>; DURÃO, <NAME>; ASSAD, <NAME>; **GARCIA, <NAME>**; MEIRA, <NAME>. [**Um Modelo de Recomendação de Arquivos para Sistemas de Armazenamento em Nuvem**](https://www.researchgate.net/publication/280161614_Um_Modelo_de_Recomendacao_de_Arquivos_para_Sistemas_de_Armazenamento_em_Nuvem){:target="_blank"}. In: [Anais do XI Simpósio Brasileiro de Sistemas de Informação](http://www.portal.inf.ufg.br/sbsi2015/){:target="_blank"}, Prediction Methods and Recommender Systems Track. Goiânia, GO, Brasil: Instituto de Informática, Universidade Federal de Goiás, 2015. p.111 – 118. 1. AFONSO, <NAME>; <NAME>, <NAME>; **GARCIA, <NAME>**; <NAME>. [**SmartCluster: Utilizando Dados Públicos para Agrupar Cidades Inteligentes por Domínios**](http://www.lbd.dcc.ufmg.br/colecoes/sbsi/2015/093.pdf){:target="_blank"}. In: [Anais do XI Simpósio Brasileiro de Sistemas de Informação](http://www.portal.inf.ufg.br/sbsi2015/){:target="_blank"}, Government Information Systems (SIG) Special Track. Goiânia, GO, Brasil: Instituto de Informática, Universidade Federal de Goiás, 2015. p.699 – 702. ### Teses e Dissertações / Thesis & Dissertations 1. <NAME>. UCLOUD: Uma Abordagem para Implantação de Nuvem Privada para Administração Pública Federal. 2015. Tese de Doutorado (Ciência da Computação) - Universidade Federal de Pernambuco. (Supervision: <NAME>). 2. <NAME>. Em Direção a um Ambiente de Desenvolvimento de Software Orientado por Comportamento. 2015. Dissertação (Mestrado Profissional em Ciências da Computação) - Universidade Federal de Pernambuco. (Supervision: Vinicius Card<NAME>arcia). 3. <NAME>. Análise da Completude dos Relatos de Experimentos em Elasticidade na Computação em Nuvem: Um Mapeamento Sistemático. 2015. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: V<NAME>, Co-Supervision: Sergio Soares). 4. <NAME>. Otimizando Sistemas Intensivos em ES Através de Programação Concorrente. 2015. Dissertação (Mestrado em Ciências da Computação) - Universidade Federal de Pernambuco. (Supervision: Silvio Romero de Lemos Meira). ### Monografias / Monographies 1. <NAME>. Uma investigação do cuidado dos usuários na disponibilização de informações pessoais em Mídias Sociais. 2015. Trabalho de Conclusão de Curso (Graduação em Sistemas de Informação) - Universidade Federal de Pernambuco (Supervision: Vinicius Cardoso Garcia). 2. <NAME>. Uma proposta de uso de Gamification para o ensino de software. 2015. Trabalho de Conclusão de Curso (Graduação em Ciência da Computação) – Universidade Federal de Pernambuco (Supervision: Vinicius Cardoso Garcia). ## [2014](#2014) ### Periódicos / Journals 1. DURÃO, <NAME>.; CARVALHO, <NAME>; SILVA, <NAME> e; **GARCIA, <NAME>**. [**A Systematic Review on Cloud Computing**](https://link.springer.com/article/10.1007/s11227-014-1089-x){:target="_blank"}. In: [The Journal of Supercomputing](https://link.springer.com/journal/11227){:target="_blank"}, v. 68, [Issue 3](https://link.springer.com/journal/11227/68/3/page/1){:target="_blank"}, June 2014. doi: 10.1007/s11227-014-1089-x. ### Revistas / Magazines 1. DURÃO, <NAME>; BELTRÃO, <NAME>; CABRAL, <NAME>; MANZATO, <NAME>ia. P**[ersonalized Ranking of Movies: Evaluating Different Metadata Types and Recommendation Strategies**](http://www.revistas.unifacs.br/index.php/rsc/article/download/3036/2377). In: Revista de Sistemas e Computação - RSC, ISSN 2237-2903. ### Artigos em Conferências / Conference papers 1. <NAME>, <NAME>; RODRIGUES, <NAME>; <NAME>, <NAME>; **GARCIA, <NAME>**. [**SafeMash: A Platform for Safety Mashup Composition**](https://www.researchgate.net/publication/280157747_SafeMash_A_Platform_for_Safety_Mashup_Composition){:target="_blank"}. In: [International Conference on Web Information Systems and Technologies (WEBIST)](http://dblp.uni-trier.de/db/conf/webist/webist2014-2.html){:target="_blank"}, 3 – 5 April, 2014, Barcelona, Spain. (DBLP) 1. <NAME>. ; <NAME>. ; <NAME>. ; <NAME> ; **<NAME>.** . **[Mapeamento Sistemático de Informática Médica para Cidades Inteligentes](https://www.researchgate.net/publication/271138645_Mapeamento_Sistematico_de_Informatica_Medica_para_Cidades_Inteligentes){:target="_blank"}**. In: CBIS (Congresso Brasileiro de Informática em Saúde, 2014, Santos / SP. CBIS 2014 – XIV Congresso Brasileiro de Informática em Saúde. Santos / SP: SBIS (Sociedade Brasileira de Informática em Saúde), 07 a 10 de Dezembro, 2014. 1. CARVALHO, <NAME>.; **GARCIA, <NAME>**; ASSAD, <NAME>; <NAME>. **[USTORE: Uma plataforma de computação em nuvem privada para apoio a e-Science](http://www.ic.ufal.br/evento/cbsoft2014/anais/industria_v1_p.pdf){:target="_blank"}**. In: [Trilha da Indústria do Congresso Brasileiro de Software: Teoria e prática (CBSoft)](http://www.ic.ufal.br/evento/cbsoft2014/menu/trilha-industria.html){:target="_blank"}, September 28 to October 03, 2014, Maceió – AL, Brazil. 1. NASCIMENTO, <NAME>; **GARCIA, <NAME>**; ASSAD, <NAME>; MEIRA, <NAME>; DAMASCENO, <NAME>; NEVES, <NAME>. **[Uma Ferramenta para Gerenciamento de Infraestruturas de Computação em Nuvem](http://www.ic.ufal.br/evento/cbsoft2014/anais/industria_v1_p.pdf){:target="_blank"}**. In: [Trilha da Indústria do Congresso Brasileiro de Software: Teoria e prática (CBSoft)](http://www.ic.ufal.br/evento/cbsoft2014/menu/trilha-industria.html){:target="_blank"}, September 28 to October 03, 2014, Maceió – AL, Brazil. 1. BRASIL, <NAME>; **GARCIA, <NAME>**; ASSAD, <NAME>; <NAME>. **[Uma Proposta de Solução para Distribuição de Conteúdos Educacionais](http://www.ic.ufal.br/evento/cbsoft2014/anais/industria_v1_p.pdf){:target="_blank"}**. In: [Trilha da Indústria do Congresso Brasileiro de Software: Teoria e prática (CBSoft)](http://www.ic.ufal.br/evento/cbsoft2014/menu/trilha-industria.html){:target="_blank"}, September 28 to October 03, 2014, Maceió – AL, Brazil. 1. MACHADO, <NAME>; DURÃO, <NAME>; ASSAD, <NAME>; **GARCIA, <NAME>**. **[Uma Abordagem para Indexação e Buscas Full-Text Baseadas em Conteúdo para Sistemas de Armazenamento em Nuvem](http://www.ic.ufal.br/evento/cbsoft2014/anais/industria_v1_p.pdf){:target="_blank"}**. In: [Trilha da Indústria do Congresso Brasileiro de Software: Teoria e prática (CBSoft)](http://www.ic.ufal.br/evento/cbsoft2014/menu/trilha-industria.html){:target="_blank"}, September 28 to October 03, 2014, Maceió – AL, Brazil. 1. CABRAL, <NAME>; DURÃO, <NAME>; BELTRÃO, Renato; <NAME>. **[Combining Multiple Metadata Types in Movies Recommendation Using Ensemble Algorithms**](https://doi.org/10.1145/2664551.2664569). In: [XX Brazilian Symposium on Multimedia and the Web (Webmedia)](http://webmedia2014.lavid.ufpb.br/), 18-21 November, João Pessoa - PB, Brazil. 1. LINS, <NAME>; SOARES, <NAME>; **GARCIA, <NAME>**. **[Análise da Qualidade de Experimentos da Computação em Nuvem](https://www.researchgate.net/publication/280157496_Analise_da_Qualidade_de_Experimentos_da_Computacao_em_Nuvem)**. In: [IV Workshop de Teses e Dissertações do CBSoft (WTDSoft 2014)](http://www.ic.ufal.br/evento/cbsoft2014/wtdsoft-chamada-br.html){:target="_blank"} – [Congresso Brasileiro de Software: Teoria e Prática (CBSoft)](http://www.ic.ufal.br/evento/cbsoft2014/){:target="_blank"}, September 28 to October 03, 2014, Maceió – AL, Brazil. 1. <NAME>VA, <NAME>; DA SILVA, <NAME>; MELO, <NAME>; RODRIGUES, <NAME>; LUCIEN, <NAME>; DE MELO, <NAME>; <NAME>; **GARCIA, <NAME>**. **[A Privacy Maturity Model for Cloud Storage Services](https://doi.org/10.1109/CLOUD.2014.135){:target="_blank"}**. In: [2014 IEEE International Conference on Cloud Computing (IEEE CLOUD)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6968679){:target="_blank"}, June 27 – July 2, 2014, Alaska, USA. 1. DA SILVA, <NAME>; DA SILVA, <NAME>; ASSAD, <NAME>; <NAME>, <NAME>; **GARCIA, <NAME>**. **[Aegis: A Lightweight Tool for Prevent Frauds in Web Browsers](https://doi.org/10.1109/JISIC.2014.11){:target="_blank"}**. In: [2014 IEEE Intelligence & Security Informatics Conference (IEEE ISI)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6968676){:target="_blank"}, September 24-26, 2014, the Hague, the Netherlands. doi: 10.1109/JISIC.2014.11. 1. <NAME>; <NAME>; <NAME>; <NAME>. **[Evaluating the Combination of Multiple Metadata Types in Movies Recommendation**](https://doi.org/10.1109/BRACIS.2014.21). In: 2014 [Brazilian Conference on Intelligent Systems (BRACIS 14)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6979382), Sao Paulo, Brazil 18-22 Oct. 2014 1. BRITO, <NAME>; COSTA, <NAME>; **GARCIA, <NAME>**; MEIRA, <NAME>. **[Experiences Integrating Heterogeneous Government Open Data Sources to Deliver Services and Promote Transparency in Brazil](https://doi.org/10.1109/COMPSAC.2014.87){:target="_blank"}**. In: [The 38th Annual International Computers, Software & Applications Conference Special Sessions 2014 Industry Papers (COMPSAC)](https://dl.acm.org/citation.cfm?id=2671850&picked=prox&cfid=820017304&cftoken=25493364){:target="_blank"}, Västerås, Sweden 21–25 July, 2014. 1. BRITO, <NAME>; <NAME>; COSTA, <NAME>; **GARCIA, <NAME>**; MEIRA, <NAME>. **[Using Parliament Brazilian Open Data to Improve Transparency and Public Participation in Brazil](https://doi.org/10.1145/2612733.2612769){:target="_blank"}**. In: [International Digital Government Research Conference (dg.o 2014)](https://dl.acm.org/citation.cfm?id=2612733&picked=prox&cfid=820017304&cftoken=25493364){:target="_blank"}, Aguascalientes City, Mexico June 18-21, 2014. ACM, New York, NY, USA, 171-177. 1. BRITO, <NAME>; COSTA, <NAME>; **GARCIA, <NAME>**; MEIRA, <NAME>. **[Brazilian Government Open Data: Implementation, Challenges, and Potential Opportunities](https://doi.org/10.1145/2612733.2612770){:target="_blank"}**. In: [International Digital Government Research Conference (dg.o 2014)](https://dl.acm.org/citation.cfm?id=2612733&picked=prox&cfid=820017304&cftoken=25493364){:target="_blank"}, Aguascalientes City, Mexico, June 18-21, 2014. ACM, New York, NY, USA, 11-16. 1. <NAME>, <NAME>; <NAME>; <NAME>; <NAME>. **Use of Gamification Techniques and Visual Management to Improve the Transparency and Engagement of Last Planner Teams**. In: International Group for Lean Construction Conference - IGLC 2014, 23-27 June 2014 in Oslo. 1. RODRIGUES, <NAME>; <NAME>.; **GARCIA, <NAME>.**; SILVA, <NAME>; <NAME>; ASSAD, <NAME>. **[A Cloud-based Recommendation Model](https://doi.org/10.1145/2590651.2590673){:target="_blank"}**. 7th [Euro American Association on Telematics and Information Systems (EATIS)](https://dl.acm.org/citation.cfm?id=2590651&picked=prox&cfid=820017304&cftoken=25493364){:target="_blank"}, Valparaíso (Chile) April 2nd – 4th, 2014. 1. <NAME>, <NAME>; <NAME>, <NAME>; **GARCIA, <NAME>**. **[Toward a QoS based Run Time Reconfiguration in Service-Oriented Dynamic Software Product Lines](https://doi.org/10.5220/0004973404600465){:target="_blank"}**. In: [16th International Conference on Enterprise Information Systems (ICEIS)](https://dl.acm.org/citation.cfm?id=2973483&picked=prox&cfid=820017304&cftoken=25493364){:target="_blank"}, pages 460 – 465, Lisbon (Portugal) 27 – 30 April, 2014. 1. <NAME>.; **Garcia, <NAME>**; DURÃO, <NAME>; <NAME>. **[Cloud Disk Drive: Uma Abordagem para a Criação de Discos Virtuais de Baixo Custo Utilizando Redes P2P](https://www.researchgate.net/publication/280157327_Cloud_Disk_Drive_Uma_Abordagem_para_a_Criacao_de_Discos_Virtuais_de_Baixo_Custo_Utilizando_Redes_p2p){:target="_blank"}**. In: IX Workshop de Redes P2P, Dinâmicas, Sociais e Orientadas a Conteúdo (Wp2p+ 2014), Florianópolis. Porto Alegre: Sociedade Brasileira de Computação (SBC), 2014. p. 83-88. 1. NASCIMENTO, <NAME>; <NAME>; **GARCIA, <NAME>**; MEIRA, <NAME>. **[A New Architecture Description Language for Social Machines](https://doi.org/10.1145/2567948.2578831){:target="_blank"}**. In: [Theory and Practice of Social Machines 2014 Workshop](https://dl.acm.org/citation.cfm?id=2567948&picked=prox&cfid=820017304&cftoken=25493364){:target="_blank"}, The 23rd International World Wide Web Conference (WWW 2014), p. 873, Seoul (Korea) April 7th – 11th, 2014. 1. <NAME>. ; <NAME>. ; **<NAME>. **; <NAME> . **[e-PID: Electronic Professional Identity Document](https://www.researchgate.net/publication/271138652_e-PID_Electronic_Professional_Identity_Document){:target="_blank"}**. In: VII Congresso Tecnológico InfoBrasil 2014, 2014, Fortaleza – Ceará. VII Congresso Tecnológico InfoBrasil 2014. Fortaleza – Ceará: Editora InfoBrasil, 2014. 1. <NAME>. ; <NAME>. ; <NAME>. . **E-OD (Electronic Opinion Description) : Sistema Eletrônico de Parecer Descritivo**. In: 20 CIAED (Congresso Internacional ABED de Ensino à Distancia), 2014, Curitiba - Paraná: ABED (Associação Brasileira de Ensino à Distância), 2014. 1. <NAME>. ; <NAME>. ; <NAME>. ; <NAME>. . **Conteúdos Complementares: Implantando Múltiplos Cenários no Processo de Ensino/Aprendizagem através de uma Proposta Inovadora e de Baixo Custo**. In: 20º CIAED (Congresso Internacional ABED de Ensino a Distância), 2014, Curitiba - Paraná: ABED (Associação Brasileira de Ensino a Distância), 2014. 1. <NAME>.; <NAME>. ; <NAME>. ; <NAME>. **[Afluentes Concurrent I/O Made Easy with Lazy Evaluation**](https://doi.org/10.1109/PDP.2014.75). In: [2014 22nd Euromicro International Conference on Parallel, Distributed and Network-Based Processing (PDP)](https://dl.acm.org/citation.cfm?id=2607054&picked=prox&cfid=820017304&cftoken=25493364), pp. 279 - 287, 12-14 Feb. 2014, Torino. ### Teses e Dissertações / Thesis & Dissertations 1. <NAME>. Uma Arquitetura de Cloud Storage para Backup de Arquivos. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Sil<NAME>ira, Co-Supervision: Rod<NAME>lia Assad). 2. <NAME>. Uma Proposta de Solução para Distribuição de Conteúdos Educacionais. 2014. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: V<NAME>, Co-supervision: <NAME> Assad) 3. <NAME>. Go!SIP: Um Framework de Privacidade para Cidades Inteligentes Baseado em Pessoas Como Sensores. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: <NAME>, Co-Supervision: <NAME>). 4. <NAME>. Dymos QoS: Uma Abordagem para Seleção de Serviços em Tempo de Execução em Linhas de Produto de Software Dinâmicas. 2014. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Card<NAME>ia). 5. <NAME>. PyMDAGenerator: Uma Ferramenta para geração automática de aplicações baseada em MDA. 2014. Dissertação (Mestrado Profissional em Engenharia de Software) – Centro de Estudos e Sistemas Avançados do Recife. (Supervision: Vinicius Card<NAME>arcia). 6. <NAME>. Aegis: Um Modelo de Proteção à Dados Sensíveis em Ambientes Client-Side. 2014. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 7. <NAME>. Uma arquitetura para Cidades Inteligentes Baseada na Internet das Coisas. 2014. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: V<NAME>, Co-Supervision: <NAME>). 8. <NAME>. RecCloud: Um Modelo de Recomendação para Sistemas de Armazenamento em Nuvem. 2014. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: V<NAME>, Co-Supervision: <NAME>). 9. <NAME>. Social Machines: A Unified Paradigm to Describe, Design and Implement Emerging Social Systems. 2014. Tese (Doutorado em Ciências da Computação) - Universidade Federal de Pernambuco. (Supervision: Silvio Romero de Lemos Meira). 10. <NAME>. SMADL - The Social Machines Architecture Description Language. 2014. Tese (Doutorado em Ciências da Computação) - Universidade Federal de Pernambuco. (Supervision: Silvio Romero de Lemos Meira). ### Monografias / Monographies 1. <NAME>. Em Direção a uma Abordagem para o Desenvolvimento de Aplicativos Móveis Multiplataforma. 2014. Trabalho de Graduação. (Graduação em Engenharia da Computação) - Universidade Federal de Pernambuco (Supervision: Vinicius Cardoso Garcia). 2. <NAME>. Uma análise do marketing digital direcionado em redes sociais lançados a partir de plataformas móveis. 2014. Trabalho de Graduação. (Graduação em Engenharia da Computação) - Universidade Federal de Pernambuco (Supervision: <NAME>). ## [2013](#2013) ### Prêmios / Awards 1. Br-SCMM: Modelo Brasileiro de Maturidade para Cidades Inteligentes. Melhor artigo da trilha Sistemas de Informação e os Desafios do Mundo Aberto do IX Simpósio Brasileiro de Sistemas de Informação (SBSI 2013), João Pessoa, PB, Brazil. Promovido pela Sociedade Brasileira de Computação. ### Periódicos / Journals 1. SILVA, <NAME>; SILVA, <NAME>; RODRIGUES, <NAME>; NASCIMENTO, <NAME>; **GARCIA, <NAME>**. [**Systematic Mapping Study On Security Threats In Cloud Computing**](https://arxiv.org/abs/1303.6782){:target="_blank"}. In: [(IJCSIS) International Journal of Computer Science and Information Security, Vol. 11, No. 3](https://sites.google.com/site/ijcsis/vol-11-no-3-mar-2013){:target="_blank"}, March 2013. ### Artigos em Conferências / Conference papers 1. <NAME>, J.R.F.; <NAME>, F.A.; <NAME>. and <NAME>. and **<NAME>**. **[The dynamic aspects of product derivation in DSPL: A systematic literature review](https://doi.org/10.1109/IRI.2013.6642507){:target="_blank"}**. In: [IEEE 14th International Conference on Information Reuse and Integration (IRI)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6621630){:target="_blank"}, 2013, pp. 466,473, 14-16 Aug. 2013. doi: 10.1109/IRI.2013.6642507. 1. RODRIGUES, <NAME>; <NAME>; <NAME>.; **<NAME>**. **[RecCloud: Um Sistema de Recomendação Baseado em Nuvem](https://www.researchgate.net/publication/280157756_RecCloud_Um_Sistema_de_Recomendacao_Baseado_em_Nuvem){:target="_blank"}**. [III Workshop de Teses e Dissertações do Congresso Brasileiro de Software (WTDSoft)](http://cbsoft2013.unb.br/en/cbsoft-en/wtdsoft){:target="_blank"} – [Congresso Brasileiro de Software: Teoria e Prática (CBSoft)](http://cbsoft2013.unb.br/en/){:target="_blank"}, 2013, Brasília/DF. 1. <NAME>., <NAME>, <NAME>., <NAME>., **<NAME>**, <NAME>. **[aCCountS: A Service-Oriented Architecture for Flexible Pricing in Cloud Infrastructure](https://doi.org/10.1109/SBCARS.2013.16){:target="_blank"}**. In: [VII Brazilian Symposium on Software Components, Architectures and Reuse](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6684447){:target="_blank"}, 2013, v.1. p.49 – 58, Brasília. 1. RODRIGUES, <NAME>; SILVA, <NAME>; <NAME>; <NAME>; <NAME>.; **GARCIA, <NAME>**. **[A Cloud-based Recommendation System](https://www.researchgate.net/publication/266656825_A_Cloud-based_Recommendation_Model){:target="_blank"}**. In: IADIS International Conference WWW/INTERNET 2013 (ICWI), 2013, Texas. Proceedings of the IADIS International Conference WWW/INTERNET 2013 (ICWI), 2013. 1. BURÉGIO, <NAME>; MEIRA, <NAME>; <NAME>.; **Garcia, <NAME>**. **[Moving Towards 'Relationship-aware' Applications and Services – A Social Machine-oriented approach](https://doi.org/10.1109/EDOCW.2013.12){:target="_blank"}**. In: [Enterprise Distributed Object Computing Conference Workshops (EDOCW)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6689801){:target="_blank"}, 2013 17th IEEE International , vol., no., pp.43,52, 9-13 Sept. 2013 doi: 10.1109/EDOCW.2013.12. 1. <NAME>. ; <NAME>. ; CAMPOS, <NAME>. ; <NAME>. ; <NAME>. ; **GARCIA, <NAME>**. **[An Approach for Secure Mashup Composition](https://www.researchgate.net/publication/280157605_AN_APPROACH_FOR_SECURE_MASHUP_COMPOSITION){:target="_blank"}.** In: IADIS International Conference WWW/INTERNET 2013 (ICWI), 2013, Texas. Proceedings of the IADIS International Conference WWW/INTERNET 2013 (ICWI), 2013. 1. BRITO, <NAME>; <NAME>; **GARCIA, <NAME>** and MEIRA, <NAME>. **[How People Care about Their Personal Data Released on Social Media](https://doi.org/10.1109/PST.2013.6596044){:target="_blank"}**. In: [International Conference on Privacy, Security and Trust (PST'2013)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6589044){:target="_blank"}, pp. 111-118. Los Alamitos: IEEE Computer Society Press, 2013. 1. SILVA, <NAME>; SILVA, <NAME>; RODRIGUES, <NAME>; NASCIMENTO, <NAME>; **GARCIA, <NAME>**. **[Security Threats in Cloud Computing Models: Domains and Proposals](https://doi.org/10.1109/CLOUD.2013.125){:target="_blank"}**. In: [IEEE 6th International Conference on Cloud Computing (IEEE CLOUD 2013)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6596015){:target="_blank"}, pp. 383-389. Los Alamitos: IEEE Computer Society Press, 2013. 1. SILVA, <NAME>., <NAME>, <NAME>., **<NAME>**, TRINTA, <NAME>, <NAME>. **[VeloZ: A Charging Policy Specification Language for Infrastructure Clouds](https://doi.org/10.1109/ICCCN.2013.6614208){:target="_blank"}**. In: [22nd International Conference on Computer Communications and Networks Technology – Track on Grid and Cloud Computing (ICCCN13-GCC)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6603810){:target="_blank"}, pp. 1-7. Los Alamitos: IEEE Computer Society Press, 2013. 1. DURÃO, <NAME>; <NAME>.; <NAME>.; <NAME>.; **<NAME>;** TRINTA, <NAME>. **[USTO.RE: A Private Cloud Storage Software System](https://link.springer.com/chapter/10.1007/978-3-642-39200-9_38){:target="_blank"}**. In: [13th International Conference on Web Engineering (ICWE 2013) – Web Engineering](https://link.springer.com/book/10.1007/978-3-642-39200-9){:target="_blank"}, 2013, Aalborg. 1. LI<NAME>, <NAME>., <NAME>., **<NAME>**, ALMEIDA, <NAME>. **[Analyzing the Effectiveness of a System Testing Tool for Software Product Line Engineering](https://www.semanticscholar.org/paper/Analyzing-the-Effectiveness-of-a-System-Testing-To-Neto-Machado/c91cd21e190e6f75eb1cc59dc8717e6fb9fc2f78){:target="_blank"}**. In: 2013 International Conference on Software Engineering and Knowledge Engineering (SEKE 2013), 2013, BOSTON. p.584 – 588. 1. BURÉGIO, <NAME>; MEIRA, <NAME>; <NAME>. **[Social Machines: A Unified Paradigm to Describe Social Web-Oriented Systems**](https://doi.org/10.1145/2487788.2488074). In: [The Theory and Practice of Social Machines (SOCM2013) at the 22nd International World Wide Web Conference (WWW2013)](http://www2013.org/), Proceedings of the WWW 2013 Companion volume, ACM 978-1-4503-2038-2/13/05, May 13–17, 2013, Rio de Janeiro, Brazil. 1. VIEIRA, <NAME>., <NAME>., **<NAME>**. **[Evaluating MapReduce for Profiling Application Traffic](https://doi.org/10.1145/2465839.2465846){:target="_blank"}**. In: [1st Workshop on High Performance and Programmable Networking (HPPN'13)](https://dl.acm.org/citation.cfm?id=2465839&picked=prox&cfid=820017304&cftoken=25493364){:target="_blank"}, co-located with ACM HPDC'2013, pp. 45-52. ACM Press, 2013, New York, US. 1. <NAME>.; **<NAME>**. **[Cloud testing framework](https://doi.org/10.1145/2460999.2461037){:target="_blank"}**. In: [17th International Conference on Evaluation and Assessment in Software Engineering](https://dl.acm.org/citation.cfm?id=2460999&picked=prox&cfid=820017304&cftoken=25493364){:target="_blank"}, pp. 252-25, 2013, Porto de Galinhas. New York, NY, USA: ACM Press. 1. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, **<NAME>**, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. **[Just-in-Time Clouds Uma abordagem para Federação de Clouds Privadas](http://sbrc2013.unb.br/files/anais/salao-ferramentas/artigos/artigo-79.pdf){:target="_blank"}**. In: [Salão de Ferramentas](http://sbrc2013.unb.br/index.html%3Fpage_id=316.html){:target="_blank"} do [31o Simpósio Brasileiro de Redes de Computadores e Sistemas Distribuídos (SBRC)](http://sbrc2013.unb.br/index.html%3Fpage_id=11.html){:target="_blank"}, 2013, Brasília. 1. <NAME>., <NAME>., <NAME>., **Garcia, <NAME>**. **[Uma Avaliação do MapReduce para Inspeção Distribuída de Tráfego de Aplicações](http://wcga13.lncc.br/posters/presentation.pdf){:target="_blank"}**. In: [XI Workshop de Computação em Clouds e Aplicações (WCGA)](http://wcga13.lncc.br/){:target="_blank"}, Sessão de Poster – 31o Simpósio Brasileiro de Redes de Computadores e Sistemas Distribuídos (SBRC), 2013, Brasília. 1. <NAME>., TRINTA, <NAME>, VIANA, <NAME>., <NAME>., **<NAME>**, <NAME>.. **[aCCounts – Um Serviço de Tarifação de Recursos para Computação em Nuvem](https://www.researchgate.net/publication/280158032_aCCounts_-_Um_Servico_de_Tarifacao_de_Recursos_para_Computacao_em_Nuvem){:target="_blank"}**. In: [XI Workshop de Computação em Clouds e Aplicações (WCGA)](http://wcga13.lncc.br/){:target="_blank"}, Sessão de Poster – 31o Simpósio Brasileiro de Redes de Computadores e Sistemas Distribuídos (SBRC), 2013, Brasília. 1. <NAME>., DURÃO, <NAME>, <NAME>., **<NAME>**. **[USTO.RE: A Private Cloud Storage System**](http://wcga13.lncc.br/posters/WCGA-PosterPresentations.pdf){:target="_blank"}. In: [XI Workshop de Computação em Clouds e Aplicações (WCGA)](http://wcga13.lncc.br/){:target="_blank"}, Sessão de Poster – 31o Simpósio Brasileiro de Redes de Computadores e Sistemas Distribuídos (SBRC), 2013, Brasília. 1. <NAME>., TOMAS, <NAME>., <NAME>., <NAME>, <NAME>., **<NAME>**. **[Smart Cities Software Architectures: A Survey](https://doi.org/10.1145/2480362.2480688){:target="_blank"}**. In: [The 28th Symposium On Applied Computing, Software Architecture: Theory, Technology, and Applications (SA-TTA 2013) Technical Track](https://dl.acm.org/citation.cfm?id=2480362&picked=prox&cfid=820017304&cftoken=25<PASSWORD>4){:target="_blank"}, 2013, Coimbra. New York, NY, USA: ACM Press, 2013. p.1722 – 1727 1. TOMAS, <NAME>., <NAME>., **<NAME>**, <NAME>. **[Smart Cities Architectures: A Systematic Review](http://www.scitepress.org/DigitalLibrary/PublicationsDetail.aspx?ID=BJG3YRZAew4=&t=1){:target="_blank"}**. In: [The 15th International Conference on Enterprise Information Systems (ICEIS)](http://www.scitepress.org/DigitalLibrary/ProceedingsDetails.aspx?ID=732GcTjwDjI=&t=1){:target="_blank"}, 2013, Angers. Berlim: Springer-Verlag, 2013. 1. <NAME>., TOMAS, <NAME>., **<NAME>**, <NAME>. **[Synaptic City: An architectural approach using an OSGI Infrastructure and GMaps API to build a City Simulator.](http://www.scitepress.org/DigitalLibrary/Link.aspx?doi=10.5220/0004421204270434){:target="_blank"}** In: [The 15th International Conference on Enterprise Information Systems (ICEIS)](http://www.scitepress.org/DigitalLibrary/ProceedingsDetails.aspx?ID=732GcTjwDjI=&t=1){:target="_blank"}, 2013, <NAME>: Springer-Verlag, 2013. 1. SILVA, <NAME>; **GARCIA, <NAME>**. **[SafeMash: Uma Plataforma como Serviço para a Composição Segura e Colaborativa de Mashups][89]**. [VI Workshop de Teses e Dissertações em Sistemas de Informação (WTDSI)](http://www.lbd.dcc.ufmg.br/bdbcomp/servlet/Evento?id=657){:target="_blank"} do [IX Simpósio Brasileiro de Sistemas de Informação (SBSI)](http://www.lbd.dcc.ufmg.br/bdbcomp/servlet/Evento?id=656){:target="_blank"}, 2013, <NAME>. 1. <NAME>.; MACHADO, <NAME>.; <NAME>.; **Garcia, <NAME>**; <NAME>.; VIEIRA, <NAME>. ; <NAME>.; DURÃO, <NAME>. **[Desenvolvendo aplicativos peer-to-peer (p2p) no contexto de data storage para ambientes de Cloud Computing](https://www.researchgate.net/publication/280158231_Desenvolvendo_aplicativos_peer-to-peer_p2p_no_contexto_de_data_storage_para_ambientes_de_Cloud_Computing){:target="_blank"}**. In:[IX Simpósio Brasileiro de Sistemas de Informação (SBSI)](http://www.lbd.dcc.ufmg.br/bdbcomp/servlet/Evento?id=656){:target="_blank"}, 2013, <NAME>. 1. SILVA, <NAME>. ; <NAME>, <NAME>. ; **<NAME>**; TRINTA, <NAME> ; <NAME>. **[Monext: An Accounting Framework for Infrastructure Clouds](https://doi.org/10.1109/ISPDC.2013.13){:target="_blank"}**. In: [The 12th International Symposium on Parallel and Distributed Computing (ISPDC-2013)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6598363){:target="_blank"}, 2013, Bucharest, pp. 26-33. New York, NY, USA: IEEE Computer Society Press, 2013. doi: 10.1109/ISPDC.2013.13 1. OLIVEIRA, <NAME>. ; <NAME>. ; **<NAME>**. **[PBL in Teaching Computing: An overview of the Last 15 Years](https://doi.org/10.1109/FIE.2013.6684830){:target="_blank"}**. In: [2013 IEEE Frontiers in Education Conference (FIE)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6679339){:target="_blank"}, Oklahoma City, OK, 2013, pp. 267-272. doi: 10.1109/FIE.2013.6684830 1. SILVA, <NAME>. ; <NAME>, <NAME>. ; **<NAME>**; TRINTA, <NAME> ; <NAME>. **[Accounting Federated Clouds based on the JiTCloud Platform](https://doi.org/10.1109/CCGrid.2013.37){:target="_blank"}**. In: [13th IEEE/ACM International Symposium On Cluster, Cloud And Grid Computing](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6545869){:target="_blank"}, 2013, Delft, pp. 186-187. New York, NY, USA: IEEE Computer Society Press, 2013. 1. <NAME>. ; <NAME>. ; TOMAS, <NAME>. ; <NAME> ; **<NAME>**. **[Br-SCMM: Modelo Brasileiro de Maturidade para Cidades Inteligentes](http://www.lbd.dcc.ufmg.br/bdbcomp/servlet/Trabalho?id=19240){:target="_blank"}**. In: [IX Simpósio Brasileiro de Sistemas de Informação (SBSI)](http://www.lbd.dcc.ufmg.br/bdbcomp/servlet/Evento?id=656){:target="_blank"}, pp. 511 - 516, 2013, Jo<NAME>. 1. <NAME>. ; <NAME>. ; <NAME>. ; <NAME>. . **SocialMood: A visualization tool to measure the mood of students in social networks**. In: XXIV Simpósio Brasileiro de Informática na Educação (SBIE), 2013, Campinas / SP. SBIE 2013 - Trilha4 / SBIE - Trilha 4: Inteligência em Ambientes e Sistemas Computacionais para Ensino/Aprendizagem. Campinas / SP: Sociedade Brasileira de Computação (SBC), 2013. 1. SANTOS, <NAME>. ; <NAME>. ; <NAME>. . U**tilização de Jogos de Computador no Ensino Superior a Distância**. In: 19º CIAED - Congresso Internacional ABED de Educação à Distância, 2013, Salvador - Bahia. “Bons Profissionais fazem bons Programas de EaD: Como Estamos ?”. Salvador - Bahia: ABED - Associacao Brasileira de Educacao a Distancia, 2013. 1. <NAME> ; <NAME>. ; <NAME>. ; <NAME> ; <NAME> ; <NAME> ; <NAME> ; <NAME> ; <NAME> ; <NAME> ; <NAME> ; <NAME> . **[SocialMood: an information visualization tool to measure the mood of the people in social networks**](https://www.spiedigitallibrary.org/conference-proceedings-of-spie/9017/1/SocialMood--an-information-visualization-tool-to-measure-the-mood/10.1117/12.2042629.short?SSO=1). In: IS&T/SPIE Electronic Imaging, 2013, San Francisco. v. 9017. p. 90170X. DOI: 10.1117/12.2042629 ### Teses e Dissertações / Thesis & Dissertations 1. <NAME>. Monext: An Accounting Framework for Federated Clouds. 2013. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Vinic<NAME>arcia). 2. <NAME>. An Approach for Profiling Distributed Applications Through Network Traffic Analysis. 2013. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 3. <NAME>. Mobile User Interface Encoder - Uma Ferramenta para Desenvolvimento de Interfaces do Usuário em Aplicações Móveis. 2013. Dissertação (Mestrado Profissional em Engenharia de Software) – Centro de Estudos e Sistemas Avançados do Recife. (Supervision: Vinicius Cardoso Garcia) 4. <NAME>. Dedupeer: Deduplicação de Arquivos Através de um Algoritmo de Processamento Particionado. 2013. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: <NAME>) 5. <NAME>. Uma Abordagem para Indexação e Buscas Full-Text Baseadas em Conteúdo em Sistemas de Armazenamento em Nuvem. 2013. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia) 6. <NAME>. DYMOS: Uma abordagem para suporte a variabilidades dinâmicas em Linhas de Produto de Software Orientado a Serviços e Sensível ao Contexto. 2013. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 7. <NAME>. Definição de um método que estabelece critérios para priorização de novos projetos e aplicação em um processo de desenvolvimento de software. 2013. Dissertação (Mestrado Profissional em Ciências da Computação) – Universidade Federal de Pernambuco (Supervision: <NAME>). 8. <NAME>. A Adoção de Computação em Nuvem Privada em uma Empresa de Processamento de Dados Estadual: Os Impactos de Implantação em seu Ambiente Corporativo. 2013. Dissertação (Mestrado Profissional em Ciências da Computação) – Universidade Federal de Pernambuco (Supervision: <NAME>) ## [2012](#2012) ### Capítulos de Livro / Book Chapters 1. <NAME>. ; **<NAME>** ; <NAME>. ; <NAME>. ; <NAME>. ; TRINTA, <NAME> . **[Software as a Service: Desenvolvendo Aplicações Multi-tenancy com Alto Grau de Reuso](https://www.researchgate.net/publication/236823220_Software_as_a_Service_Desenvolvendo_Aplicacoes_Multi-tenancy_com_Alto_Grau_de_Reuso){:target="_blank"}**. In: <NAME>; <NAME>; <NAME>; <NAME>. (Org.). Tópicos em multimídia, hipermídia e Web : minicursos. 1ed.São Paulo: Sociedade Brasileira de Computação, 2012, v. , p. 35-73. 1. <NAME>. ; <NAME>. ; <NAME>. ; <NAME>. ; <NAME>. ; **<NAME> **; TRINTA, <NAME> ; MEIRA, <NAME> . **[Desafios em Cloud computing: Armazenamento, Banco de Dados e BIG Data](https://www.researchgate.net/publication/236823615_Desafios_em_Cloud_computing_Armazenamento_Banco_de_Dados_e_BIG_Data){:target="_blank"}**. In: <NAME>; <NAME>; <NAME>; <NAME>. (Org.). Tópicos em multimídia, hipermídia e Web : minicursos. 1ed.São Paulo: Sociedade Brasileira de Computação, 2012, v. , p. 75-116. ### Artigos em Conferências / Conference papers 1. <NAME>. ; **<NAME>** . **[Uma ferramenta para rastreabilidade de core assets em linha de produtos de software](http://www.lbd.dcc.ufmg.br/bdbcomp/servlet/Trabalho?id=11355){:target="_blank"}**. In: Simpósio Brasileiro de Sistemas de Informação, 2012, São Paulo. [Anais do VIII Simpósio Brasileiro de Sistemas de Informação: Trilhas Técnicas](http://www.lbd.dcc.ufmg.br/bdbcomp/servlet/Evento?id=402){:target="_blank"}, p. 690-699. Porto Alegre: Sociedade Brasileira de Computação, 2012. v. 1. 1. <NAME>. ; <NAME>. ; <NAME>. ; **GARCIA, <NAME>** ; <NAME>. . **[Uma proposta arquitetural para serviços escaláveis de dados em nuvens](https://www.researchgate.net/publication/236821468_Uma_proposta_arquitetural_para_servicos_escalaveis_de_dados_em_nuvens){:target="_blank"}**. In: VIII Workshop de Redes Dinâmicas e Sistemas P2P (WP2P), 2012, Ouro Preto. VIII Workshop de Redes Dinâmicas e Sistemas P2P (WP2P) em conjunto com o XXX Simpósio Brasileiro de Redes de Computadores. Porto Alegre: Sociedade Brasileira de Computação, 2012. p. 118-129. 1. SILVA, <NAME>. ; <NAME>, <NAME>. ; <NAME>. ; **GARCIA, <NAME>** ; TRINTA, <NAME>. **[Accounting Models for Cloud Computing: A Mapping Study](https://www.semanticscholar.org/paper/Accounting-Models-for-Cloud-Computing-A-Systematic-Garcia-Assad/96279842535d4513bd1f7fe6ee9c6c1713e58005){:target="_blank"}**. In: International Conference on Grid Computing and Applications (GCA 2012), 2012, Las Vegas. Proceedings of the International Conference on Grid Computing and Applications (GCA 2012), 2012. 1. <NAME>. ; <NAME>. ; <NAME>. ; **GARCIA, <NAME>** ; MEIRA, <NAME>. [**Adoção de Metodologias Ágeis para Produção de Jogos Sociais com Times Distribuídos**](http://www.lbd.dcc.ufmg.br/colecoes/sbqs/2012/025.pdf){:target="_blank"}. In: XI Simpósio Brasileiro de Qualidade de Software (SBQS), 2012, Fortaleza. Anais do XI Simpósio Brasileiro de Qualidade de Software (SBQS). Porto Alegre: Sociedade Brasileira de Computação, 2012. 1. <NAME>, <NAME>. ; <NAME>. ; ALMEIDA, <NAME> ; CAVALCANTI, <NAME> ; **GARCIA, <NAME>**. **[An Experimental Study to Evaluate a SPL Architecture Regression Testing Approach](https://doi.org/10.1109/IRI.2012.6303065){:target="_blank"}**. In: [13th International Conference on Information Reuse and Integration (IRI)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6294629){:target="_blank"}, 2012, Las Vegas. Proceedings of the 13th International Conference on Information Reuse and Integration (IRI). Los Alamitos, CA, USA: IEEE Computer Society Press, 2012. 1. OLIVEIRA, <NAME>. ; WANDERLEY, <NAME>. ; <NAME>. ; **GARCIA, <NAME>**. **[Uma Abordagem para o Desenvolvimento de um Sistema Clínico baseado em Arquétipos e Mapas Mentais](https://www.researchgate.net/publication/236817938_Uma_Abordagem_para_o_Desenvolvimento_de_um_Sistema_Clinico_baseado_em_Arquetipos_e_Mapas_Mentais){:target="_blank"}**. In: XIII Congresso Brasileiro de Informática em Saúde, 2012, Curitiba. Anais do XIII Congresso Brasileiro de Informática em Saúde. Porto Alegre: Sociedade Brasileira de Computação, 2012. 1. NASCIMENTO, <NAME> ; <NAME>. ; <NAME>, <NAME>. ; <NAME>. ; **GARCIA, <NAME>** ; MEIRA, <NAME> . **[A Systematic Mapping Study on Domain-Specific Languages](https://www.researchgate.net/publication/236817656_A_Systematic_Mapping_Study_on_Domain-Specific_Languages){:target="_blank"}**. In: [The Seventh International Conference on Software Engineering Advances](http://www.iaria.org/conferences2012/ICSEA12.html){:target="_blank"}, 2012, Lisboa. Proceedings of the Seventh International Conference on Software Engineering Advances, 2012. p. 179-187. 1. VIEIRA, <NAME>. ; <NAME>. ; <NAME>. ; <NAME>. ; **Garcia, <NAME>** . **[Evaluating Performance of Distributed Systems With MapReduce and Network Traffic Analysis](https://www.researchgate.net/publication/236817386_Evaluating_Performance_of_Distributed_Systems_With_MapReduce_and_Network_Traffic_Analysis){:target="_blank"}**. In: [The Seventh International Conference on Software Engineering Advances](http://www.iaria.org/conferences2012/ICSEA12.html){:target="_blank"}, 2012, Lisboa. Proceedings of the Seventh International Conference on Software Engineering Advances, 2012. p. 705-711. 1. OLIVEIRA, <NAME>. ; <NAME>. ; **Garcia, <NAME>**. **[Um Mapeamento Sistemático para Problem Based Learning aplicado à Ciência da Computação](https://www.researchgate.net/publication/236817033_Um_Mapeamento_Sistematico_para_Problem_Based_Learning_aplicado_a_Ciencia_da_Computacao){:target="_blank"}**. In: Workshop de Informática na Escola – Simpósio Brasileiro de Informática na Educação, 2012, Rio de Janeiro. Anais do 18º Workshop de Informática na Escola – 23º Simpósio Brasileiro de Informática na Educação, 2012. 1. CARTAXO, <NAME>. ; <NAME>. ; <NAME>. ; SANTOS, <NAME> ; <NAME>. ; **GARCIA, <NAME>**. **[ESEML – Empirical Software Engineering Modeling Language](https://doi.org/10.1145/2420918.2420933){:target="_blank"}**. In: [The 12th Workshop on Domain Specific Modeling (DSM 12)](https://dl.acm.org/citation.cfm?id=2420918&picked=prox&cfid=820017304&cftoken=25<PASSWORD>64){:target="_blank"}, 2012, Tucson. Proceedings of the 12th Workshop on Domain Specific Modeling (DSM 12), 2012. 1. NASCIMENTO, <NAME> ; **GARCIA, <NAME>** ; MEIRA, <NAME> . **[SMADL: The Social Machines Architecture Description Language](http://ceur-ws.org/Vol-935/p_09.pdf){:target="_blank"}**. In: [Doctoral Symposium at the 5th International Conference on Software Language Engineering (SLE'2012)](http://ceur-ws.org/Vol-935/SLE2012DSproceedings.pdf){:target="_blank"}, 2012, Desden. Proceedings of the Doctoral Symposium at the 5th International Conference on Software Language Engineering (SLE'2012), 2012. p. 45-52. 1. BRITO, <NAME> ; <NAME>. ; <NAME>. ; NASCIMENTO, <NAME> ; BURÉGIO, <NAME> ; **GARCIA, <NAME>** ; MEIRA, <NAME> . **[Implementing Web Applications as Social Machines Composition: a Case Study](https://www.researchgate.net/publication/236813747_Implementing_Web_Applications_as_Social_Machines_Composition_a_Case_Study){:target="_blank"}**. In: [International Conference on Software Engineering and Knowledge Engineering (SEKE 2012)](http://www.ksi.edu/seke/seke12.html){:target="_blank"}, 2012, Redwood City. Proceedings of the 2012 International Conference on Software Engineering and Knowledge Engineering (SEKE 2012). Skokie: Knowledge Systems Institute Graduate School, 2012. 1. <NAME>. ; <NAME>. ; <NAME>. ; <NAME>, <NAME>. ; **<NAME>** ; MEIRA, <NAME> . **[An Approach to Developing Multi-Tenancy SaaS Using Metaprogramming](https://doi.org/10.1145/2382636.2382681){:target="_blank"}**. In: [Simpósio Brasileiro de Sistemas Multimídia e Web (WebMedia)](https://dl.acm.org/citation.cfm?id=2382636&picked=prox&cfid=820017304&cftoken=25493364){:target="_blank"}, 2012, São Paulo. Anais do Simpósio Brasileiro de Sistemas Multimídia e Web (WebMedia). New York, NY, USA: ACM, 2012. p. 207-210. 1. VIE<NAME>. ; <NAME>. ; <NAME>. ; <NAME>. ; **<NAME>**. **[Measuring Distributed Applications Through MapReduce and Traffic Analysis](https://doi.org/10.1109/ICPADS.2012.104){:target="_blank"}**. In: [18th IEEE International Conference on Parallel and Distributed Systems](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=6412851){:target="_blank"}, 2012, Singapore. Proceedings of the 18th IEEE International Conference on Parallel and Distributed Systems. Los Alamitos: IEEE Computer Society Press, 2012. 1. <NAME>. ; **<NAME>** ; <NAME>. ; <NAME>. ; <NAME>. ; <NAME>. ; MEIRA, <NAME> . **[USTO.RE Uma plataforma descentralizada para storage de conteúdo em nuvens privadas]**. In: [Trilha da Indústria do Congresso Brasileiro de Software: Teoria e Prática](http://www.cbsoft.dimap.ufrn.br/cbsoft_industria.php){:target="_blank"}, 2012, Natal. Anais do III Congresso Brasileiro de Software: Teoria e Prática. Porto Alegre: Sociedade Brasileira de Computação, 2012. p. 17-17. ### Teses e Dissertações / Thesis & Dissertations 1. <NAME>. Estudo da viabilidade de um serviço de Cloud Storage, utilizando recursos ociosos, por uma Operadora de Telecomunicações. 2012. Dissertação (Mestrado Profissional em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia) 2. <NAME>. Metodologia para Concepção de Máquinas Sociais no Contexto da Web 3.0. 2012. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Silvio Romero de Lemos Meira & Co-Supervision: Vinicius Cardoso Garcia) 3. <NAME>. Um framework PBL para apoiar o processo de aprendizagem em cursos de Engenharia de Software. 2012. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia) 4. <NAME>. Um Mapeamento Sistemático de Estudos em Cloud Computing. 2012. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Silvio Romero de Lemos Meira & Co-Supervision: Vinicius Cardoso Garcia) 5. <NAME>. Um Plugin Para Monitoramento e Gerenciamento de Web Services Baseados Em SOAP. 2012. Dissertação (Mestrado Profissional em Engenharia de Software) – Centro de Estudos e Sistemas Avançados do Recife. (Supervision: Vinicius Cardoso Garcia) 6. <NAME>. Uma abordagem orientada a modelos no desenvolvimento de sistemas clínicos baseado em arquétipos. 2012. Dissertação (Mestrado em Engenharia da Computação) – Universidade de Pernambuco. (Supervision: Vinicius Cardoso Garcia) 7. <NAME>. Desenvolvimento de aplicações multi-tenant: um estudo de mapeamento sistemático. 2012. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Sil<NAME> Meira & Co-Supervision: Vinicius Cardoso Garcia) 8. <NAME>. Fast Game Language – Uma DSL (linguagem de domínio específico) para criação rápida de jogos. 2012. Dissertação (Mestrado Profissional em Engenharia de Software) – Centro de Estudos e Sistemas Avançados do Recife. (Supervision: Vinicius Cardoso Garcia). ### Monografias / Monographies 1. <NAME>. Um Modelo de Gerenciamento de Identidade para Segurança de Aplicativos SaaS. 2012. Monografia (Curso de Especialização em Engenharia de Software com Ênfase em SEGURANÇA DA INFORMAÇÃO EM ENGENHARIA DE SOFTWARE – SIESTTA) – Centro de Estudos e Sistemas Avançados do Recife. (Supervision: Vinicius Cardoso Garcia) 2. <NAME>. O Lado Bom e Desconhecido da Camada mais Profunda da Web. 2012. Monografia (Curso de Especialização em Engenharia de Software com Ênfase em SEGURANÇA DA INFORMAÇÃO EM ENGENHARIA DE SOFTWARE – SIESTTA) – Centro de Estudos e Sistemas Avançados do Recife. (Supervision: Vinicius Cardoso Garcia) 3. <NAME>. Segurança em Web Services: Análise de WS-Security, WS-Policy e SAML. 2012. Monografia (Curso de Especialização em Engenharia de Software com Ênfase em SEGURANÇA DA INFORMAÇÃO EM ENGENHARIA DE SOFTWARE – SIESTTA) – Centro de Estudos e Sistemas Avançados do Recife. (Supervision: <NAME>) ## [2011](#2011) ### Prêmios / Awards 1. RiSE Reference Model for Software Reuse Adoption in Brazilian Companies. First place in the Contest of Thesis and Dissertations in Software Quality (Concurso de Teses e Dissertações em Qualidade de Software - CTDQS) - Type: Ph.D., X Brazilian Symposium on Software Quality (SBQS Conference), Sociedade Brasileira de Computação (SBC), Curitiba-PR, Brazil, 2011. 2. Honorable Mention as THE BEST TOOL of the X Workshop on Tools and Applications (X Workshop de Ferramentas e Aplicações), XVII Brazilian Symposium on Multimedia Systems and Web - WebMedia (XVII Simpósio Brasileiro de Sistemas Multimídia e Web), Sociedade Brasileira de Computação (SBC), Curitiba-PR, Brazil, 2011. ### Livros / Books 1. **GARCIA, <NAME>**. **[RiSE Reference Model for Software Reuse Adoption: An Approach for Brazilian Companies](https://www.amazon.com/Reference-Model-Software-Reuse-Adoption/dp/3844318488){:target="_blank"}**. 1. ed. Saarbrüken: LAP LAMBERT Academic Publishing, 2011. 212p . ### Capítulos de Livro / Book Chapters 1. SILVA, <NAME>. ; <NAME>, <NAME>. ; **GARCIA, <NAME>** ; <NAME>. . **[Linhas de produto de software: Uma tendência da indústria](https://www.researchgate.net/publication/236784308_Linhas_de_Produtos_de_Software_Uma_tendencia_da_industria){:target="_blank"}**. In: <NAME>; <NAME>; <NAME>. (Org.). Escola Regional de Informática Ceará, Maranhão, Piauí: Livro texto dos minicursos, 07 e 08 de novembro de 2011. Teresina: Sociedade Brasileira de Computação, 2011, v. , p. 7-31. 1. <NAME>. ; **GARCIA, <NAME>** ; <NAME>. **[Desenvolvendo aplicações multi-tenancy para computação em nuvem](https://www.researchgate.net/publication/236784279_Desenvolvendo_aplicacoes_multi-tenancy_para_computacao_em_nuvem){:target="_blank"}**. In: <NAME>; <NAME>; <NAME>. (Org.). Escola Regional de Informática Ceará, Maranhão, Piauí: Livro texto dos minicursos. Teresina: Sociedade Brasileira de Computação, 2011, v. , p. 124-141. ### Periódicos / Journals 1. LISBOA, <NAME>; **GARCIA, <NAME>**; ALMEIDA, <NAME>; MEIRA, <NAME>. **[ToolDAy: a tool for domain analysis](https://link.springer.com/article/10.1007/s10009-010-0174-6){:target="_blank"}**. [International Journal on Software Tools for Technology Transfer (Print), v. 13, p. 337-353, 2011](http://link.springer.com/journal/10009){:target="_blank"}. ### Revistas / Magazines 1. MORAES, <NAME>; **GARCIA, <NAME>**; MEIRA, <NAME>. **[ONTOPHC: UMA ABORDAGEM SEMÂNTICA PARA REPRESENTAÇÃO DO CONHECIMENTO APLICADO AO PROGRAMA BRASILEIRO DE SAÚDE NA FAMÍLIA](https://www.researchgate.net/publication/266223791_ONTOPHC_UMA_ABORDAGEM_SEMANTICA_PARA_REPRESENTACAO_DO_CONHECIMENTO_APLICADO_AO_PROGRAMA_BRASILEIRO_DE_SAUDE_NA_FAMILIA){:target="_blank"}**. [EDUCTE: Revista Científica do Instituto Federal de Alagoas](http://www.kentron.ifal.edu.br/index.php/educte/article/view/43){:target="_blank"}, 2011. 1. <NAME>.; <NAME>.; **GARCIA, <NAME>**. **[Utilizando Gestão de Portfólio de Projetos em uma Empresa Júnior de Tecnologia](http://www.fsma.edu.br/si/edicao7/FSMA_SI_2011_1_Estudantil_1.html){:target="_blank"}**. [Revista de Sistemas de Informação da FSMA, 7a Edição - Jan/2010-Jun/2011](http://www.fsma.edu.br/si/7edicao.html){:target="_blank"}, p. 32 – 38, 01 jul. 2011. ### Artigos em Conferências / Conference papers 1. **GARCIA, <NAME>.**; ALMEIDA, <NAME>; MEIRA, <NAME>. **[RiSE Reference Model for Software Reuse Adoption in Brazilian Companies](https://www.researchgate.net/publication/236784209_RiSE_Reference_Model_for_Software_Reuse_Adoption_in_Brazilian_Companies){:target="_blank"}**. In: Concurso de Teses e Dissertações em Qualidade de Software (CTDQS) do [X Simpósio Brasileiro de Qualidade de Software](https://www.researchgate.net/conference-event/SBQS_SBQS-Simposio-Brasileiro-de-Qualidade-de-Software_2011/7529){:target="_blank"}, 2011, Curitiba. Anais do Concurso de Teses e Dissertações em Qualidade de Software (CTDQS) do X Simpósio Brasileiro de Qualidade de Software, 2011. 1. <NAME>.; <NAME>.; <NAME>.; <NAME>.; BRITO, <NAME>; <NAME>.; <NAME>.; **GARCIA, <NAME>**; MEIRA, <NAME>. **[Methods and Processes Definitions for Multiplatform Social Network Games Development with Distributed Teams](https://doi.org/10.1109/SBGAMES.2011.11){:target="_blank"}**. In: [X Simpósio Brasileiro de Games e Entretenimento Digital](http://www.sbgames.org/sbgames2011/){:target="_blank"}, 2011, Salvador. Proceedings of SBGames, Computing Track – Full Papers, 2011. 1. <NAME>.; **GARCIA**, **<NAME>** . **[A Traceability Tool for Mapping Features and Core Assets in Software Product Lines](https://www.researchgate.net/publication/267917246_A_Traceability_Tool_for_Mapping_Features_and_Core_Assets_in_Software_Product_Lines){:target="_blank"}**. In: The 12th International Conference on Software Reuse, 2011, Pohang. Proceedings of The 12th International Conference on Software Reuse, 2011. 1. <NAME>.; MEIRA, <NAME>; **GARCIA, <NAME>**; TRINTA, <NAME>. **[U-STORE: Implementação de Data Cloud utilizando Ferramentas P2P](https://www.researchgate.net/publication/236784101_U-STORE_Implementacao_de_Data_Cloud_utilizando_Ferramentas_P2P){:target="_blank"}**. In: Workshop for Tools and Applications (WTA) – [XVII Simpósio Brasileiro de Sistemas Multimídia e Web (Webmedia)](http://www.sbbd-webmedia2011.inf.ufsc.br/webmedia/index.php/en/){:target="_blank"}, 2011, Florianópolis. Anais do XVII Simpósio Brasileiro de Sistemas Multimídia e Web (Webmedia), 2011. 1. DANTAS, <NAME>.; <NAME>.; **GARCIA, <NAME>**; <NAME>.; <NAME>.; FREITAS, <NAME>. **[PuzzlEdu: uma Ferramenta para Prover Educação como Serviço](https://www.researchgate.net/publication/236784080_PuzzlEdu_uma_Ferramenta_para_Prover_Educacao_como_Servico){:target="_blank"}**. In: Workshop for Tools and Applications (WTA) – [XVII Simpósio Brasileiro de Sistemas Multimídia e Web (Webmedia)](http://www.sbbd-webmedia2011.inf.ufsc.br/webmedia/index.php/en/){:target="_blank"}, 2011, Florianópolis. Anais do XVII Simpósio Brasileiro de Sistemas Multimídia e Web (Webmedia), 2011. 1. <NAME>.; <NAME>.; <NAME>.; <NAME>.; **<NAME>** ; MEIRA, <NAME>. **[Adoção de Metodologias Ágeis para Produção de Jogos Sociais com Times Distribuídos](https://www.researchgate.net/publication/236784175_Adocao_de_Metodologias_Ageis_para_Producao_de_Jogos_Sociais_com_Times_Distribuidos){:target="_blank"}**. In: [X Simpósio Brasileiro de Games e Entretenimento Digital](http://www.sbgames.org/sbgames2011/){:target="_blank"}, 2011, Salvador. Proceedings of the SBGames, Computing Track – Short Papers, 2011. 1. <NAME>.; <NAME>.; **<NAME>**; <NAME>.; RODRIGUES, <NAME>.; <NAME>. [**PuzzlEdu: uma Ferramenta para Apoiar o Ensino Aprendizagem de Orientação a Objetos**](https://www.researchgate.net/publication/236784140_PuzzlEdu_uma_Ferramenta_para_Apoiar_o_Ensino_Aprendizagem_de_Orientacao_a_Objetos){:target="_blank"}. In: 17o Workshop de Informática na Escola – [22o Simpósio Brasileiro de Informática na Educação](http://www.ufrgs.br/tri/sead/events/22o-simposio-brasileiro-de-informatica-na-educacao-e-17o-workshop-de-informatica-na-esc){:target="_blank"}, 2011, Aracaju. Anais do 17º Workshop de Informática na Escola – 22º Simpósio Brasileiro de Informática na Educação. Porto Alegre: Sociedade Brasileira de Computação, 2011. 1. <NAME>.; <NAME>.; <NAME>.; <NAME>.; **<NAME>**; <NAME>. **[A proposal for an educational system service to support teaching/learning process for logic programming](https://doi.org/10.1109/CSEET.2011.5876152){:target="_blank"}**. In: [24th IEEE-CS Conference on Software Engineering Education and Trainning](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=5783969){:target="_blank"}, 2011, Waikiki, Honolulu, Hawaii. Proceedings of the 24th IEEE-CS Conference on Software Engineering Education and Trainning, 2011. p. 556-556. 1. MEIRA, <NAME>; <NAME>; <NAME>; <NAME>.; <NAME>.; **<NAME>**. **[The Emerging Web of Social Machines](http://ieeexplore.ieee.org/document/6032321/){:target="_blank"}**. In: [IEEE 35th Annual Computer Software and Applications Conference](http://www.ieee.org/conferences_events/conferences/conferencedetails/index.html?Conf_ID=18045){:target="_blank"}, 2011, Munich. Proceedings of the IEEE 35th Annual Computer Software and Applications Conference. Los Alamitos: IEEE Computer Society Press, 2011. p. 26-27. ### Teses e Dissertações / Thesis & Dissertations 1. <NAME>. Integrando SOA e MDE em um Processo Sistemático de Desenvolvimento de Software. 2011. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Co-Supervision: Vinicius Cardoso Garcia). 2. <NAME>. Uma proposta de plataforma de comércio eletrônico para redes sociais. 2011. Dissertação (Mestrado em Ciências da Computação) – Universidade Federal de Pernambuco. (Supervsion: Silvio romero de Lemos Meira & Co-Supervision: Vinicius Cardoso Garcia). 3. <NAME>. PuzzlEdu: Uma Proposta de Software Educacional Modelado como Serviço para Apoiar o Ensino/Aprendizagem de Programação Orientada a Objetos. 2011. Dissertação (Ciências da Computação) – Universidade Federal de Pernambuco. (Supervision: Vinicius Cardoso Garcia). 4. <NAME> e Silva. Uma ferramenta para rastreabilidade de core assets em Linhas de Produtos de Software. 2011. Dissertação (Mestrado Profissional em Engenharia de Software) – Centro de Estudos e Sistemas Avançados do Recife. (Supervision: Vinicius Cardoso Garcia) ### Monografias / Monographies 1. <NAME>. Um Estudo sobre Ferramentas CASE para Gerenciamento do Processo de Engenharia de Domínio em Linha de Produtos de Software. 2011. Trabalho de Conclusão de Curso. (Graduação em Sistemas de Informação) – Universidade de Pernambuco. (Co-supervision: Vinicius Cardoso Garcia) 2. Diógenes <NAME>. UM ESTUDO SOBRE GERENCIAMENTO DE VARIABILIDADE EM LINHA DE PRODUTOS DE SOFTWARE. 2011. Trabalho de Conclusão de Curso. (Graduação em Sistemas de Informação) – Universidade de Pernambuco. (Co-supervision: Vinicius Cardoso Garcia) ## [2010](#2010) ### Periódicos / Journals 1. LISBOA, <NAME>; **GARCIA, <NAME>**; <NAME>; ALMEIDA, <NAME>; MEIRA, <NAME>; FORTES, <NAME>. **[A Systematic Review of Domain Analysis Tools](http://dx.doi.org/10.1016/j.infsof.2009.05.001){:target="_blank"}**. [Information and Software Technology, Volume 52, Issue 1, p. 1-13](http://www.sciencedirect.com/science/journal/09505849/52/1){:target="_blank"} (January 2010), ISSN 0950-5849. ### Artigos em Conferências / Conference papers 1. LISBOA, <NAME>; **GARCIA, <NAME>**; MEIRA, <NAME>; ALMEIDA, <NAME>. **[A Support Tool for Domain Analysis](https://www.researchgate.net/publication/221631781_A_Support_Tool_for_Domain_Analysis){:target="_blank"}**. In: [Fourth International Workshop on Variability Modelling of Software-intensive Systems](http://dblp.uni-trier.de/db/conf/vamos/vamos2010.html){:target="_blank"}, 2010, Linz. Proceedings of the Fourth International Workshop on Variability Modelling of Software-intensive Systems, 2010. 1. <NAME>, <NAME> ; <NAME>. ; CAVALCANTI, <NAME> ; **<NAME>** ; ALMEIDA, <NAME> ; MEIRA, <NAME>. **[A Regression Testing Approach for Software Product Lines Architectures](http://dx.doi.org/10.1109/SBCARS.2010.14){:target="_blank"}**. In:[4th Brazilian Symposium on Software Components, Architectures and Reuse (SBCARS)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=5628340){:target="_blank"}, 2010, Salvador. Proceedings of the 4th Brazilian Symposium on Software Components, Architectures and Reuse (SBCARS), 2010. 1. RIBEIRO, <NAME>.; **<NAME>**; <NAME>; <NAME>; ALMEIDA, <NAME>; MEIRA, <NAME>. **[An Assessment on Technologies for Implementing Core Assets in Service-Oriented Product Lines](http://dx.doi.org/10.1109/SBCARS.2010.19){:target="_blank"}**. In: [4th Brazilian Symposium on Software Components, Architectures and Reuse (SBCARS)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=5628340){:target="_blank"}, 2010, Salvador. Proceedings of the 4th Brazilian Symposium on Software Components, Architectures and Reuse (SBCARS), 2010. 1. <NAME>.; <NAME>.; **<NAME>**; <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>. **[Game Development Guidelines: Practices To Avoid Conflicts Between Software and Design](https://www.researchgate.net/publication/236661260_Game_Development_Guidelines_Practices_To_Avoid_Conflicts_Between_Software_and_Design){:target="_blank"}**. In: [IX Brazilian Symposium on Computer Games and Digital Entertainment](http://www.sbgames.org/sbgames2010/){:target="_blank"}, 2010, Florianópolis. Proceedings of the IX Brazilian Symposium on Computer Games and Digital Entertainment, Computing Track, 2010. 1. BRITO, <NAME>; **<NAME>**; MEIRA, <NAME>. **[LIFT Revisited: Enhancing the Understanding of NATURAL/ADABAS Legacy Systems](http://dx.doi.org/10.1109/CSMR.2010.41){:target="_blank"}**. In: [European Conference on Software Maintenance and Reengineering (CSMR)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=5714189){:target="_blank"}, 2010, Madrid. Proceedings of the European Conference on Software Maintenance and Reengineering (CSMR), 2010. 1. BRITO, <NAME>; **<NAME>**; MEIRA, <NAME>. **[Experiences from a Brazilian Bank Reengineering Project](http://dx.doi.org/10.1109/CSMR.2010.28){:target="_blank"}**. In: [European Conference on Software Maintenance and Reengineering (CSMR)](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=5714189){:target="_blank"}, 2010, Madrid. Proceedings of the European Conference on Software Maintenance and Reengineering (CSMR), 2010. ### Teses e Dissertações / Thesis & Dissertation 1. <NAME>. **Um Experimento de Engenharia de Requisitos para caracterização do Processo e sua Adequação às Práticas Específicas do CMMI**. 2010. Dissertação (Mestrado Profissional em Engenharia de Software) – Centro de Estudos e Sistemas Avançados do Recife. (Supervision: Vinicius Cardoso Garcia) 2. <NAME>. **UMA PROPOSTA PARA EXPANSÃO SEMÂNTICA DE CONSULTAS BASEADA EM ONTOLOGIA DE DOMÍNIO ESPECÍFICO**. 2010. Dissertação (Mestrado Profissional em Engenharia de Software) – Centro de Estudos e Sistemas Avançados do Recife. (Co-supervision: Vinicius Cardoso Garcia). ### Monografias / Monographies 1. <NAME>. **Usabilidade em Páginas Web sob a ótica das 10 Heurísticas de Nielsen: Um Estudo de Caso no SIGA da UPE Campus Caruaru**. 2010. Trabalho de Conclusão de Curso. (Graduação em Sistemas de Informação) – Universidade de Pernambuco. (Co-supervision: Vinicius Cardoso Garcia) <file_sep>/_posts/2013-05-24-assert-at-22nd-international-conference-on.md --- layout: post title: "ASSERT at 22nd International Conference on Computer Communications and Networks Technology - Track on Grid and Cloud Computing (ICCCN13-GCC)" categories: Artigos tag: conferencia --- The paper “**VeloZ: A Charging Policy Specification Language for Infrastructure Clouds**“ authored by <NAME>, <NAME>, <NAME>, <NAME>, <NAME> has been accepted for publication at&nbsp;[22nd International Conference on Computer Communications and Networks Technology - Track on Grid and Cloud Computing](http://www.icccn.org/icccn13/tracks/GCC.html) (ICCCN13-GCC). The conference will be held in July 30 - August 2, 2013 in Nassau, Bahamas. A brief overview of the paper is given next. _Cloud Accounting refers to how cloud usage is recorded and charged. It is present at all commercialized cloud services (SaaS, PaaS and IaaS), since they have to monitor the consumption aiming to charge the customers. In a previous research we performed a systematic mapping study regarding cloud accounting and identified a set of shortcomings in the existing accounting models for IaaS. One of these limitations was related to charging policy specification. Charging policies are mechanisms that establish rules to convert usage records into monetary information. This paper presents a Domain Specific Language (DSL) for charging policy specification: VeloZ. Such DSL enables cloud providers to write charging policies following the economic model RaaS. According to RaaS, the IaaS must be provisioned in a high granularity in terms of resource types and such granularity is profitable for both, provider and customer. We evaluated the DSL under a real cloud platform called JiTCloud. The experiment results evidences that VeloZ can be considered feasible in terms of flexibility and reliability._<file_sep>/_posts/2018-12-28-react-native-para-startups.md --- layout: post title: "React Native para Startups" categories: Empreendedorismo tag: - startup - innovation - react - framework - js - javascript --- Começar um novo negócio é sempre um ato de **coragem insana**. É como descer uma montanha russa de costas para a direção do carrinho. E isso aumenta em níveis catastróficos quando se trata de uma startup específica e intensiva em tecnologia. Ok, tudo bem, já não podemos dizer com tanta certeza e pompa uma vez que hoje, praticamente todas as empresas se parecem com uma empresa de tecnologia seguindo um modelo de negócio que não só é dependente como também é impulsionado pela tecnologia. *Every company is a technology company, no matter what product or service it provides. The companies that embrace this fact are the ones that shape our world (Forbes Technology Council).* Em se tratando de startups de tecnologia, a **IDEIA** é o primeiro fator-chave para o sucesso e podemos dizer que a **seleção das TECNOLOGIAS** a serem utilizadas, é a segunda. A abundância de tecnologias tornou extremamente complicado decidir qual a tecnologia adequada para o início do negócio. Na verdade, escolher o framework ou a tecnologia certa é um processo minucioso e por vezes tedioso. Todos os dias, entramos em contato com um novo framework, ferramenta ou tecnologia que tem algo diferente para oferecer do que outros. Neste contexto, o artigo "[React Native For Startups: How to Cut Costs Instead of Corners](http://bit.ly/2ESzQfz)" defende a escolha do framework React Native do Facebook para o desenvolvimento de aplicativos móveis como uma alternativa que corta os custos ao invés de aparar as características do seu negócio! Vale a pena conferir! Vocês que tiveram experiências com React Native, o que acham? É isso mesmo? Artigo originalmente publicado em [React Native para Startups](http://viniciusgarcia.me/entrepreneurship/react-native-para-startups/) :: [viniciusgarcia.me](http://viniciusgarcia.me/) <file_sep>/_posts/2016-09-01-assert-at-sbti2016.md --- layout: post title: "ASSERT @ SBTI'2016" categories: Artigos tag: conferencia --- É com prazer que informamos que os artigos “_**Uma biblioteca Multi-Tenant para o framework Django**_”, de autoria de <NAME>, <NAME> e <NAME> e “_**Estudo de mapeamento sistemático sobre as tendências e desafios do cloud gaming**_” de autoria de <NAME>, <NAME> e <NAME> foram aceitos para apresentação no [V Simpósio Brasileiro de Tecnologia da Informação (SBTI'2016)](http://www.ufpb.br/idep/sbti2016/){:target="_blank"} que vai ser realizado entre os dias 05 a 07 de Outubro em João Pessoa-PB. O resumo do primeiro artigo seguinte descreve o trabalho: > Nos últimos anos o modelo de entrega de software como serviço, ou Software as a Service (SaaS), surgiu trazendo software mais flexíveis e reutilizáveis. Este modelo provê suporte a diversos usuários sobre uma mesma infraestrutura configurável, oferecendo funcionalidades sob demanda. Multi-Tenancy, ou Multi-Inquilino, é uma abordagem organizacional do modelo SaaS. Características de uma arquitetura Multi-Tenant são: compartilhamento de recursos de hardware, alto grau de configurabilidade e bancos de dados compartilhados. Alguns benefícios da utilização desta arquitetura são: melhor utilização dos recursos de hardware, maior manutenibilidade e redução nos custos globais do sistema. Tomando como base as características desta arquitetura, esta pesquisa propõe facilitar o desenvolvimento de aplicações Web Multi-Tenant através de uma biblioteca open source para o framework Django. Assim, os desenvolvedores podem focar seus esforços na regra de negócio e não com a arquitetura, já implementada pela biblioteca. O resumo do segundo artigo seguinte descreve o trabalho: > A fim de apresentar um panorama sobre as dificuldades e os possíveis caminhos em direção ao aumento da adoção do Cloud Gaming, este trabalho analisou, através de um mapeamento sistemático, as tendências e desafios na utilização da computação em nuvem para jogos digitais. Após a definição do protocolo do mapeamento, diversos critérios de seleção e exclusão foram aplicados aos estudos encontrados. Em seguida, uma análise foi realizada e teve seus dados apresentados e interpretados através de gráficos, tabelas, além de descrição textual. Foram identificados como problemas e desafios a limitação de banda e compressão dos vídeos, alocação de recursos de rede para servidores com máquinas virtuais, entre outros. Como possíveis tendências do serviço, os estudos evidenciaram o foco no streaming baseado em gráficos, ao invés do streaming baseado em vídeo e virtualização de GPU.<file_sep>/_posts/2015-02-26-socm2015-notification.md --- layout: post title: "SOCM2015 notification" categories: Artigos tag: conferencia --- É com prazer que informo que o artigo entitulado "**Towards Government as a Social Machine**", de autoria de <NAME>, <NAME>, <NAME>, <NAME>, <NAME> e <NAME>, foi aprovado para publicação no [3rd International Workshop on the Theory and Practice of Social Machines](http://sociam.org/socm2015/), workshop que acontece em conjunto com o [24th International World Wide Web (WWW) Conference](http://www.www2015.it). O evento acontecerá entre os dias 18 e 22 de Maio deste ano. Parabéns a todos os envolvidos! Segue o abstract do artigo: _Government initiatives to open data to the public are becoming increasingly popular every day. The vast amount of data made available by government organizations yields interesting opportunities and challenges - both socially and technically. In this paper, we propose a social machine-oriented architecture as a way to extend the power of open data and create the basis to derive government as a social machine (Gov-SM). The proposed Gov-SM combines principles from existing architectural patterns and provides a platform of specialized APIs to enable the creation of several other social-technical systems on top of it. Based on some implementation experiences, we believe that deriving government as a social machine can, in more than one sense, collaborate to fully integrate users, developers and crowd in order to participate in and solve a multitude of governmental issues and policy._<file_sep>/_posts/2014-01-20-assert-at-the-7th-euro-american-association-on.md --- layout: post title: "ASSERT at the 7th Euro American Association on Telematics and Information Systems (EATIS 2014)" categories: Artigos tag: conferencia --- The paper “**A Cloud-Based Recommendation Model**" authored by <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME>, has been accepted for presentation at the [7th Euro American Association on Telematics and Information Systems (EATIS 2014)](http://eatis.org/eatis2014/) and for inclusion in the conference proceedings to be published by the ACM Digital Library within its International Conference Proceedings Series (ISBN 978-1-4503-2435-9). The conference is being held in Valparaíso, Chile, April 2-4, 2014. This research is sponsored by the Fundação de Amparo à Ciência e Tecnologia de Pernambuco (FACEPE) grants in the process IBPG-0483-1.03/11. It was also partially supported by the National Institute of Science and Technology for Software Engineering (INES), funded by National Counsel of Technological and Scientific Development (CNPq) and FACEPE, grants 573964/2008-4 and APQ-1037-1.03/08. A brief overview of the paper is given next. _The technological development we have experienced in recent years has provided exponential growth of the digital universe. This growth has generated a large data volume which is expected to reach almost 8 zettabytes in 2015. A good part of this data is in the cloud, and has surpassed the cognitive abilities of users to analyze such large data sets. Faced with this scenario, we investigate the use of cloud factors able to have a positive influence on generating recommendations. Thus, we present a new, simple model based on cloud features which is associated with the content-based technique of recommendation. The practical applicability of data storage environments in the cloud provides the best use of cloud resources and meets user’s preferences._<file_sep>/_posts/2013-05-27-assert-at-ieee-6th-international-conference-on.md --- layout: post title: "ASSERT at IEEE 6th International Conference on Cloud Computing (IEEE CLOUD 2013)" categories: Artigos tag: conferencia --- The paper “**Security Threats in Cloud Computing Models: Domains and Proposals**“ authored by <NAME>, <NAME>, <NAME>, <NAME> and <NAME> has been accepted for publication at the [IEEE 6th International Conference on Cloud Computing (IEEE CLOUD 2013)](http://www.thecloudcomputing.org/2013/). The conference will be held in June 27-July 2, 2013, Santa Clara Marriott, CA, USA (Center of Silicon Valley). A brief overview of the paper is given next. _This work displays metrics about publications available in the literature which deal with some of the seven Security threats in Cloud Computing based in the guide entitled "Top Threats to Cloud Computing" from the Cloud Security Alliance (CSA). Through this research, it is identified the most explored threats, distributed the results between fifteen Security Domains and identified between eight types of solutions proposed for the threats. In face of those results, it was observed that publications in the literature mostly show a certain trend as the proposals presented for the involved Threats. However, in some cases some variations occur, what motivated us to fulfill an analysis of standard deviation in the results obtained in our research. Based on these data, we present our conception regarding this behavior._<file_sep>/_posts/2013-08-30-defesa-de-dissertacao-de-mestrado-n-1309.md --- layout: post title: "Defesa de Dissertação de Mestrado Nº 1.309" categories: Defesa tag: mestrado --- ## Pós-Graduação em Ciência da Computação – UFPE ### Defesa de Dissertação de Mestrado Nº 1.309 * Aluno: <NAME> * Orientador: Prof. <NAME> * Co-orientador: Prof. <NAME> * Título: Dedupeer: Deduplicação de Arquivos Através de um Algoritmo de Processamento Particionado * Data: 27/08/2013 * Hora/Local: 15:00h à Auditório Banca Examinadora: * Prof. <NAME> ( CIn / UFPE) * Prof. <NAME> (Departamento de Ciência da Computação/ UFBA) * Prof. <NAME> (Departamento de Estatística e Informática / UFRPE) RESUMO: _A deduplicação é uma técnica de compressão de dados sem perda que elimina dados redundantes tanto intra-file como inter-file, diferente de ferramentas de compressão de dados como o gzip que só eliminam a redundância intra-file. A deduplicação reduz a necessidade de armazenamento através da eliminação de blocos de dados redundantes._ _Na deduplicação, todos os blocos de dados que estão duplicados em um sistema de armazenamento podem ser reduzidos à uma única cópia, esses blocos desalocados pela deduplicação são transformados em referência para o que foi mantido no sistema._ _Técnicas de deduplicação começaram a ser estudadas para sistemas de armazenamento comerciais em meados de 2004. Hoje, os principais sistemas de armazenamento de dados usam deduplicação, mas os algoritmos implementados e as técnicas utilizadas_ _não são detalhadas publicamente. Existem alguns trabalhos acadêmicos focados na implementação de algoritmos de deduplicação, mas eles são raros e não são voltados para a sua utilização em sistemas de armazenamento existentes. O principal objetivo deste trabalho é criar um algoritmo para deduplicação de arquivos no cliente de forma remota, através de processamento particionado e utilizando comparação por fingerprints. Este algoritmo foi incorporado em um componente de software com interface interoperável para facilitar a utilização em qualquer sistema de armazenamento de dados e beneficiá-los com economia de armazenamento, e na transferência de dados no caso dos sistemas de armazenamento distribuídos._ _Além do componente de software, foi desenvolvido também um sistema de armazenamento com gerenciamento de dados baseado no Apache Cassandra, o que o torna capaz de ser distribuído, com o objetivo de validar o algoritmo de deduplicação. A integração do componente de software com o sistema de armazenamento foi implementada e avaliada neste trabalho._ Palavras-chave: Deduplicação, compressão de dados, economia de armazenamento, sistemas de armazenamento de dados<file_sep>/_posts/2017-10-24-escrevendo-um-artigo-cientifico-um-livro-de-receitas.md --- layout: post title: "Escrevendo um artigo científico, um livro de receitas" categories: Educacao tag: pesquisa --- Escrever um artigo científico é uma das primeiras - senão a primeira - atividade **aterradora** para um aspirante a pesquisador(a) (seja um(a) estudante de iniciação científica, especialização, mestrado ou mesmo doutorado). Segundo o pesquisador [**<NAME>**](http://gmwgroup.harvard.edu/content.php?page=gwhitesides){:target="_blank"}, "_Um artigo é uma descrição organizada de hipóteses, dados e conclusões, destinados a instruir o leitor_". Adicionalmente, **Whitesides** ainda destaca que artigos - científicos, em especial - são parte **central de uma vida de uma pesquisa**, ou de um projeto de pesquisa, uma vez que eles visam **disseminar o conhecimento** junto a comunidade interessada na área e que, não necessariamente, é a comunidade acadêmica - mesmo porque temos cada vez mais grupos de pesquisa com ressultados extremamente interessantes dentro de empresas, principalmente em TI onde podemos citar Amazon, Google e Microsoft como exemplos - acrescentando que se sua pesquisa não gerar artigos, ou seja, disseminação de conhecimento, pode indicar que ela em si também não foi bem executada. Ou ainda, sendo um pouco mais radical, **<NAME>** afirma que "_Interessante e não publicado é equivalente a inexistente_". Um ponto importante a se destacar aqui é que o objetivo, ou **missão**, de um pesquisador **não é publicar artigos**. Mas publicar artigos é um **meio** pelo qual pesquisadores **alcançam** o seu objetivo inerente à sua escolha profissional que é investigar problemas, formular e testar hipóteses, estabelecer conclusões a partir destes testes e **compartilhar** suas ideias e conclusões com outras pessoas interessadas. **O objetivo de um pesquisador não pode ser apenas coletar dados** (nota mental: _morte as revisões sistemáticas como objetivo final!_ hahahahaha)! Um(a) aspirante a pesquisador(a) deve ter em mente que um artigo científico (ou um relatório técnico, que seja) não deve servir apenas como um armazenamento de dados, ou ideias, ou ainda um programa de pesquisa completo. Ele é também uma **"estrutura" para auxiliar no planejamento de um projeto de pesquisa em andamento** (_working in progress_). Se você entender claramente o propósito e a forma de um artigo científico (ou, de novo, um relatório técnico), ele pode ser **imensamente útil** para você na organização e realização da sua pesquisa. Neste contexto, um bom esboço para o trabalho também é um bom **plano para seu o projeto de pesquisa**, ainda mais considerando que a escrita de um plano de um projeto de pesquisa é uma atividade **iterativa e incremental**, executada ao longo do "_ciclo de vida_" da pesquisa em si. Uma boa prática que sempre me ajudou nesta tarefa foi partir de um esboço, ou _outline_, que fucionava como uma **receita de bolo**. Um _metamodelo_ para a estruturação das ideias necessárias para um projeto de pesquisa bem fundamentado, consistente, robusto e com qualidade no seu conteúdo. Você deve, de fato, pensar em um esboço de um artigo como um conjunto de dados cuidadosamente organizado e apresentado, com objetivos, hipóteses e conclusões, em vez de um esboço de texto livre. Na verdade, um esboço não precisa ser em formato de texto contínuo. Às vezes, a primeira versão do esboço pode ser desenvolvida como uma apresentação, utilizando tópicos ou imagens gerais para a organização primária das ideias a serem desenvolvidas. Mas como construir o esboço? Bem, a boa sugestão dada pelo **Professor Whitesides** é tentar responder algumas perguntas básicas, como: - (i) Por que eu fiz (ou devo fazer) esse trabalho? (ii) O que exatamente isso significa? - (iii) Que hipóteses eu utilizei (ou devo utilizar) para testar? (iv) O que eu realmente testei? (v) Quais foram os resultados? (vi) O trabalho produziu um novo método ou produto? (vii) Qual? - (viii) Quais as medições (métricas) que fiz (ou farei)? - (ix) Quais métodos ou resultados? (x) Como eles foram caracterizados? Ajuda muito preparar equações, gráficos, ou ainda figuras em alto nível de abstração para ajudar no entendimento de fluxos de trabalho ou informações, bem como de que forma as ideias estao conectadas, ou como a arquitetura da sua solução estará organizada de forma que irá atender às suas premissas. Escreva sempre suas ideias, hipóteses e resultados, e em seguida você pode escolher as melhores combinações de hipóteses, objetivos e dados. Muitas vezes, os objetivos de um artigo/projeto de pesquisa quando "_quasi-terminado_" (amadurecido, por melhor dizer) são diferentes dos usados para justificar o início do trabalho. Muitas das boas pesquisas científicas são **oportunistas** e **revisionistas**. Após organizar as ideias de acordo com as 10 perguntas citadas anteriormente, você está pronto para começar a estruturar suas informações de forma mais rica, semânticamente falando, orgnizando tudo em três grandes pontos: - **Introdução**: _Por que eu fiz o trabalho? Quais foram as motivações e hipóteses centrais?_ - **Resultados e Discussão**: _Quais foram os resultados? Como os produtos do trabalho (ou requisitos) foram feitos e caracterizados? O que foi medido?_ - **Conclusões**: _O que tudo isso significa? Quais as hipóteses provadas ou refutadas? O que eu aprendi? Por que faz a diferença?_ A partir destas três seções iniciais - digamos assim - você pode passar a explodir a granularidade delas à medida que sente a necessidade de explicar com mais detalhes questões específicas. Não se furte em utilizar recursos visuais (i.e. figuras ou gráficos) e estruturas de dados (i.e. tabelas ou equações). Em seu artigo, **<NAME>** dá ainda outras dicas e detalhes para serem abordados na construção do seu esboço. Vale a pena dar uma olhada nele (link a seguir). Existem outros trabalhos **BEM** interessantes neste mesmo contexto, os destaco a seguir: * Whitesides, <NAME>. (2004), **Whitesides' Group: Writing a Paper**. Adv. Mater., 16: 1375–1377, 2004. [doi:10.1002/adma.200400767](http://dx.doi.org/10.1002/adma.200400767){:target="_blank"}. * [**Directions for writing a paper and preparing a presentation**](http://www.physics.ohio-state.edu/~wilkins/onepage/){:target="_blank"} and [**Directions for writing an abstract**](http://www.ee.ucr.edu/~rlake/Abstracts.doc){:target="_blank"} by [Professor <NAME>](http://www.ee.ucr.edu/~rlake/){:target="_blank"} (University of California). * <NAME>. **Writing for Computer Science**. Springer-Verlag London, 3rd Edition, 2014. [doi:10.1007/978-1-4471-6639-9](https://www.springer.com/us/book/9781447166382){:target="_blank"}. eBook ISBN: 978-1-4471-6639-9. * <NAME>. [**Metodologia De Pesquisa Para Ciência Da Computação**](http://www.sciencedirect.com/science/book/9788535235227){:target="_blank"}. Elsevier Editora Ltda., 2009. ISBN: 978-85-352-3522-7. * <NAME>, [**A letter from the frustrated author of a journal paper**](http://www.sciencedirect.com/science/article/pii/S0164121200000200){:target="_blank"}, In Journal of Systems and Software, Volume 54, Issue 1, 2000, Page 1, ISSN 0164-1212, <https://doi.org/10.1016/S0164-1212(00)00020-0>. * Gil, <NAME> . **Como elaborar projetos de pesquisa**. Atlas, 6ª Edição, 2017. * <NAME>, <NAME>. **Getting Your PhD: A Practical Insider′s Guide (Survival Skills for Scholars)**. SAGE Publications Ltd; 1 Edition (August 25, 2007). * <NAME>, [**How To Choose a Good Scientific Problem**](http://www.sciencedirect.com/science/article/pii/S1097276509006418){:target="_blank"}, In Molecular Cell, Volume 35, Issue 6, 2009, Pages 726-728, ISSN 1097-2765, <https://doi.org/10.1016/j.molcel.2009.09.013>. * <NAME>, <NAME>. **How to get a PhD: a handbook for students and their supervisors**. Open University Press; 5 edition (October 1, 2010). * <NAME>. **How to read a paper**. SIGCOMM Comput. Commun. Rev. 37, 3 (July 2007), 83-84. DOI: <https://doi.org/10.1145/1273445.1273458>. * Tao Xie. **Mapping out a Research Agenda**. [Jan, 2014 (last update)](http://taoxie.cs.illinois.edu/publications/researchagenda.pdf){:target="_blank"} * <NAME> et al. **Thesis Projects: A Guide for Students in Computer Science and Information Systems**. Springer-Verlag London (Second Edition), 2008. DOI: [10.1007/978-1-84800-009-4](https://www.springer.com/la/book/9781848000087){:target="_blank"}. * <NAME>. 2003. [**Writing good software engineering research papers: minitutorial**](https://dl.acm.org/citation.cfm?id=776816.776925){:target="_blank"}. In Proceedings of the 25th International Conference on Software Engineering (ICSE '03). IEEE Computer Society, Washington, DC, USA, 726-736. Espero que ajude nessa jornada! _Artigo originalmente publicado por [<NAME>](http://viniciusgarcia.me/education/a-biblioteca-do-desenvolvedor-de-software-dos-dias-de-hoje/)_<file_sep>/_posts/2013-05-14-assert-at-the-theory-and-practice-of-social.md --- layout: post title: "ASSERT at The Theory and Practice of Social Machines (SOCM2013) co-located with 22nd International World Wide Web Conference (WWW2013)" categories: Artigos tag: conferencia --- The paper “**Social Machines: A Unified Paradigm to Describe Social Web-Oriented Systems**“ authored by <NAME>, <NAME> e <NAME> has been accepted for publication at [The Theory and Practice of Social Machines](http://sociam.org/www2013/) (SOCM2013) co-located with [22nd International World Wide Web Conference](http://www2013.org/) (WWW2013). The conference will be held in May 13th-17th, 2013 at Rio de Janeiro, Brazil. A brief overview of the [paper](http://sociam.org/www2013/papers/socm2013_submission_5.pdf) is given next. _Blending computational and social elements into software has&nbsp;gained significant attention in key conferences and journals. In&nbsp;this context, “Social Machines” appears as a promising model&nbsp;for unifying both computational and social processes. However,&nbsp;it is a fresh topic, with concepts and definitions coming from&nbsp;different research fields, making a unified understanding of the&nbsp;concept a somewhat challenging endeavor. This paper aims to&nbsp;investigate efforts related to this topic and build a preliminary&nbsp;classification scheme to structure the science of Social&nbsp;Machines. We provide a preliminary overview of this research&nbsp;area through the identification of the main visions, concepts, and&nbsp;approaches; we additionally examine the result of the&nbsp;convergence of existing contributions. With the field still in its&nbsp;early stage, we believe that this work can collaborate to the&nbsp;process of providing a more common and coherent conceptual&nbsp;basis for understanding Social Machines as a paradigm.&nbsp;Furthermore, this study helps detect important research issues&nbsp;and gaps in the area._<file_sep>/_posts/2017-03-10-defesa-de-dissertacao-de-mestrado-n-225.md --- layout: post title: "Defesa de Tese de Doutorado Nº 225" categories: Defesa tag: doutorado --- ## Pós-Graduação em Ciência da Computação – UFPE ### Defesa de Tese de Doutorado Nº 225 **Aluno**: <NAME> **Orientador**: <NAME> **Título da Dissertação**: Buscando a proposição de uma forma de configuração e comercialização de computação em nuvem com alto nível de abstração com base no mapeamento sistemático da literatura sobre serviço medido. **Data**: 10/03/2017 **Hora/Local**: 09h, Sala A-14 Membros da Banca: * 1º Examinador: <NAME> (UFPE) * 2º Examinador: <NAME> (UFRPE) * 3º Examinador: <NAME> (UFPE) Resumo: > A computação em nuvem é um dos temas da tecnologia da informação mais discutidos atualmente. Pesquisas relacionadas à segurança e elasticidade têm contribuído substancialmente na evolução do modelo. Nesse estudo, é realizado um mapeamento sistemático da literatura em busca de experimentos que explicitem as linhas de pesquisas que estão sendo trabalhadas atualmente sobre outra característica básica do modelo de computação em nuvem, trata-se do serviço medido. A pesquisa apontou que o serviço medido ainda é um campo pouco explorado cientificamente mesmo já possuindo um modelo de configuração e comercialização consolidado no mercado atual. A configuração e comercialização do modelo de computação em nuvem por meio de instâncias proporciona aos usuários do serviço uma experiência próxima à aquisição de uma máquina física com a possibilidade de escolha de máquinas virtuais (VMs) pré-configuradas e customizadas mas apesar de existirem estudos e experimentos que buscam evoluir esse modelo de comercialização e configuração não foi encontrado nenhum estudo que busque comprovar o poder de processamento real do conjunto provido pela instância de máquina virtual, frente às garantias de SLA atuais, que buscam comprovar apenas as grandezas unitárias de cada item que compõem a VM como processador, memória ram, discos de armazenamento e largura de banda, e, também, não foi encontrado nenhum experimento que buscasse calcular de forma precisa a demanda computacional de cada projeto de migração para o modelo de computação em nuvem com o objetivo de oportunizar o cálculo do investimento financeiro necessário com um projeto de migração e ou adoção ao modelo de computação em nuvem. Frente a esse cenário esse estudo encaminha a construção de um modelo de processamento por porta que busca abstrair ao máximo o conceito de instância de máquina virtual, extraindo desse conceito apenas o coeficiente de processamento dos itens que compõem o conjunto da VM os comercializando por meio de uma porta com largura de processamento possível de ser facilmente gerida, medida e regulamentada via SLA. O modelo proposto confronta algumas características do modelo de instâncias e projeta ganhos ao modelo de computação em nuvem com a sua adoção tomando como base outros modelos de prestação de serviço de alto nível de abstração e configuração aos usuários finais. Palavras-Chave: Computação em Nuvem, Serviço Medido, PaaS, IaaS, Modelo de Configuração, Modelo de Comercialização, Instâncias, Porta de Processamento<file_sep>/_posts/2019-01-02-quer-ser-um-ceo-de-sucesso.md --- layout: post title: "Quer ser um CEO de sucesso? Adote um cachorro!" categories: Empreendedorismo tag: - startup - innovation - ceo - dog --- Por trás da maioria dos executivos **C\*** tem um menino bomzinho que definitivamente merece um biscoito, de acordo com uma nova pesquisa envolvendo 857 pessoas conduzidas pelo Kelton Research para o Banfield Pet Hospital. Acontece que o caminho para o sucesso na carreira não passa apenas por uma boa formação, educação, empenho e tudo isso que a gente já sabe, mas começa com uma infância cheia de filhotes, gatinhos, coelhos e hamsters! De acordo com a pesquisa, um surpreendente número de 93% dos executivos C* entrevistados cresceram com um animal de estimação, e 78% atribuem parcialmente o sucesso de sua carreira em parte à posse de um animal de estimação quando criança. Mais informações "[Want to be a successful CEO? Get a dog](http://bit.ly/2R3xqBm)" Já adotou o seu filhote? Recomendo visitar o [@abrigodeseualberto](https://www.instagram.com/abrigodeseualberto)! Artigo originalmente publicado em [Quer ser um CEO de sucesso? Adote um cachorro!](http://viniciusgarcia.me/entrepreneurship/quer-ser-um-ceo-de-sucesso/) :: [viniciusgarcia.me](http://viniciusgarcia.me/) <file_sep>/_posts/2013-04-07-assert-lab-and-ines-at-the-22nd-world-wide-web.md --- layout: post title: "Assert Lab and INES at the 22nd World Wide Web Conference (WWW 2013)" categories: Artigos tag: conferencia --- The paper “**Social Machines: A Unified Paradigm to Describe Social Web-Oriented Systems**” authored by <NAME>, <NAME> and <NAME>, has been accepted for publication in "The Theory and Practice of Social Machines" (SOCM2013), the First International Workshop focused on Social Machines at the [22nd International World Wide Web Conference (WWW2013)](http://www2013.org/). This is one of the results of the research work by <NAME> and part of our position about Social Machines. WWW 2013 will feature <NAME> (organizer of the SOCM2013 and director of the Web Science Trust, and the Web Foundation - organisations that have a common commitment to advance our understanding of the Web), <NAME> (of CAPTCHA) and <NAME>, the inventor of the Web. A brief overview of the paper is given next _Blending computational and social elements into software has gained significant attention in key conferences and journals. In this context, “Social Machines” appears as a promising model for unifying both computational and social processes. However, it is a fresh topic, with concepts and definitions coming from different research fields, making a unified understanding of the concept a somewhat challenging endeavor. This paper aims to investigate efforts related to this topic and build a preliminary classification scheme to structure the science of Social Machines. We provide a preliminary overview of this research area through the identification of the main visions, concepts, and approaches; we additionally examine the result of the convergence of existing contributions. With the field still in its early stage, we believe that this work can collaborate to the process of providing a more common and coherent conceptual basis for understanding Social Machines as a paradigm. Furthermore, this study helps detect important research issues and gaps in the area._ For more details:&nbsp;[bit.ly/16TUfEG&nbsp;](bit.ly/16TUfEG)<file_sep>/_posts/2015-08-28-analise-da-completude-dos-relatorios-de.md --- layout: post title: "Análise da Completude dos Relatórios de Experimentos em Elasticidade na Computaçao em Nuvem" categories: Pesquisa tag: mestrado --- Nesta segunda-feira, dia 31 de Agosto de 2015 vai ocorrer a defesa de dissertação de mestrado de <NAME>, orientada pelo prof. <NAME> e com co-orientação do prof. <NAME>. O trabalho foi desenvolvido com o objetivo de investigar como estão sendo conduzidos e documentados os experimentos e avaliações realizados no contexto da arquitetura de software da computação em nuvem, mais especificamente falando, tratando do principal atributo de qualidade deste paradigma: a elasticidade. Helaine realizou uma intensa pesquisa acerca dos relatórios e demais documentos publicados acerca destes experimentos, analisou seus pontos positivos, negativos, encontrou as similaridades e discrepâncias e ainda contou com a colaboração de profissionais da indústria para identificar o que seria mais relevante ou ainda o que não estava sendo avaliado ou documentado. Seguem as informações acerca da defesa da dissertação. Pós-Graduação em Ciência da Computação - UFPE Defesa de Dissertação de Mestrado Nº 1.559 * Aluno: <NAME> * Orientador: Prof. <NAME> * Co-orientador: Prof. <NAME> * Título: Análise da Completude dos Relatórios de Experimentos em Elasticidade na Computaçao em Nuvem * Data: 31/08/2015 * Hora/Local: 13h – Centro de Informática – Sala D224 * Banca Examinadora: - Prof. <NAME> (Cin/UFPE) - Prof. <NAME> (UFC / Departamento de Computação) - Prof. <NAME> (UFRPE/DEINFO - Prof. <NAME> (Cin/UFPE) RESUMO: > Contexto: A elasticidade é sem dúvida uma das características mais marcantes da computação em nuvem (CN). À medida que esta vem se tornando cada vez mais aceita como um paradigma de computação promissor na indústria, a avaliação/comparação de ofertas de serviços se torna naturalmente necessária. Estudos de avaliação possuem relação bem próxima com o método empírico de experimentação. O relato de um experimento comunica suas conclusões e achados, sendo a principal fonte de informação para se avaliar a qualidade e validade de seus resultados. Porém, estudos indicam que no contexto da CN tais relatos são incompletos, o que dificulta a avaliação da qualidade, interpretação, validade e generalização de resultados, bem como a possibilidade de replicação dos mesmos. > Objetivo: Apesar de vários autores apontarem problemas relacionados à completudedos relatos de estudos empíricos na CN, até o momento nenhum estudo apresentou uma visãoholística dos problemas existentes. Como um primeiro esforço neste sentido, o objetivo desteestudo é identificar os relatos de experimentos em elasticidade na computação em nuvem,caracterizá-los e analisar suas completudes. > Método: Através de um Mapeamento Sistemático da Literatura os relatos de experimentosforam identificados e caracterizados. Por meio de instrumento de avaliação, criado com baseem orientações existentes para se reportar experimentos na engenharia de software experimental,a completude destes experimentos foi avaliada. Resultado: Nenhum dos estudos mencionaram a utilização de guias ou mecanismos desuporte para conduzir, planejar ou reportar experimentos. Em um índice de completude que vaide 0 a 51 pontos o maior valor alcançado foi 34, representando a nota 6.67 em uma escala de 0 a10, sendo tal completude considerada baixa em valores quantitativos. Também foi realizada umaanálise qualitativa que revela que, ainda que reportadas, muitas das informações apresentadas pelos relatos são superficiais e dificultam a interpretação, validação, generalização e replicaçãodos resultados dos estudos. Palavras-chave: Engenharia de Software, Computação em Nuvem, Elasticidade, Engenharia de Software Experimental, Experimentos.<file_sep>/_posts/2014-01-02-uma-arquitetura-para-smart-cities-baseada-na.md --- layout: post title: "Uma arquitetura para Smart Cities baseada na Internet of things" categories: Pesquisa tag: mestrado --- De acordo com relatório divulgado pela UNESCO [Nations, U. (2007)], por volta de 1950, 30% da população mundial vivia em áreas urbanas e em 2010 esta porcentagem subiu para 50%. Estima-se que em 2050 a porcentagem de pessoas vivendo nos grandes centros urbanos será de 70%. Além disso, 10% da população mundial vive nas 30 principais metrópoles [Dobbs, R. and Institute, M. G. (2011)]. No cenário nacional, segundo a pesquisa realizada pelo Instituto Brasileiro de Geografia e Estatística (IBGE), publicada no [Diário Oficial da União](http://saladeimprensa.ibge.gov.br/noticias?view=noticia%5C&amp;idnoticia=2204), em julho de 2012 o Brasil chegou a 193.946.886 habitantes, que representa um aumento de aproximadamente 1,65% em relação ao ano de 2010. Este crescimento populacional é natural, pois é justamente nas cidades onde há mais oportunidades econômicas.&nbsp; Este fato tem originado grandes desafios para os gestores das cidades. Problemas relacionados ao tráfego, segurança, consumo de água e energia, dentre outros, têm sido cada vez mais difíceis de serem administrados. Dessa forma, o conceito de Cidades Inteligentes (CI) surge a partir da necessidade de combinar Tecnologia da Informação e Comunicação (TIC) com esses aspectos operacionais das cidades [<NAME>., <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. (2011)] visando otimizar a qualidade de vida dos cidadãos. Apesar dessa necessidade, não há um consenso a respeito da definição deste conceito, nem quanto ao ambiente mais adequado para empregá-lo. Existem algumas iniciativas isoladas que visam tratar alguma defâsagem urbana. As iniciativas vão de aplicativos como [Waze](https://www.waze.com/), um serviço que mistura geolocalização no celular com indicações do fluxo e problemas de trânsito via smartphones, até governamentais, como [Centro de Operações da prefeitura do Rio de Janeiro](http://www.rio.rj.gov.br/web/corio), que integra órgãos que produzem informações úteis sobre a cidade. Porém, estas iniciativas podem ser consideradas apenas o começo da implementação de uma CI. Além disso, para de fato estabelecer uma SC é necessário que estas iniciativas estejam integradas em um mesmo ambiente, seja compartilhando informações ou até mesmo para facilitar a definição da estratégia de atuação. Neste contexto, surge a necessidade de uma arquitetura capaz de integrar os recursos de uma cidade. Nesse sentido, um recurso pode ser qualquer objeto distribuído em uma rede, constituindo a Internet das Coisas (IoT). Um exemplo destes recursos são os fornecedores de dados, como um ônibus, perfil de uma rede social, smartphone ou até mesmo outro sistema. Esta arquitetura deve permitir que os dados desses recursos fossem combinados de forma a obter uma informação mais completa sobre determinado evento na cidade. Para a concepção da proposta deste trabalho, foram realizadas duas revisões da literatura: Revisão Sistemática e Revisão Exploratória. Esta duas revisões foram necessárias devido ao contexto de mercado que envolve as duas grandes áreas de pesquisa: Cidades Inteligentes e Internet das Coisas. A partir destas revisões, um conjunto de requisitos que uma arquitetura para Cidades Inteligentes deve atender. A Tabela 1 apresenta estes requisitos. ![image]({{ BASE_PATH }}/images/2014-01-02-uma-arquitetura-para-smart-cities-baseada-na/tabela1.png) Ao analisar esta tabela, percebe-se que a Revisão Exploratória foi mais eficaz. Porém, devido à falta de um processo formal que possa ser repetido, este fato não deve ser considerado que as Revisões Exploratórias são mais eficientes que as Revisões Sistemáticas. A partir destes requisitos, a proposta deste trabalho foi definida, exemplificada na Figura 1. ![image]({{ BASE_PATH }}/images/2014-01-02-uma-arquitetura-para-smart-cities-baseada-na/figura1.png) Após o estabelecimento da proposta, foi necessário avaliá-la. Para tal, vários métodos de avaliação disponíveis na arquitetura foram estudados, porém nenhum deles atendia o contexto deste trabalho. Logo, foi realizada a adaptação de dois métodos amplamente utilizados na liteturatura (SAAM e ATAM) para ser executado remotamente. Inicialmente uma equipe totalmente multidisciplinar de 16 pessoas foi construída. Em seguida, esta equipe realizou três reuniões remotas na qual cada etapa do método de avaliação foi executada, que incluiu a proposta de cenários de utilização da arquitetura e avaliação da adequação destes cenários. A Figura 2&nbsp;apresenta o resultado da adequação de cada cenário, de acordo com a visão da equpe de avaliação. Nesta figura, os cenários mais prioritários estão organizados da esquerda para direita (C1 até C14). ![image]({{ BASE_PATH }}/images/2014-01-02-uma-arquitetura-para-smart-cities-baseada-na/figura2.png) Conforme se pode notar, na opinião dos participantes, a arquitetura atendente de forma EXCELENTE três cenários. O primeiro cenário (C2) é relacionado aos mecanismos de distribuição de dados implementados no MGDD , principalmente a utilização da _DHT_ de dados. Já o segundo cenário (C4) foi obtido a partir da implementação do padrão _publisher-subscriber_ também no MGDD. Por fim, o último cenário avaliado positivamente é oriundo do modelo de abstração e da flexibilidade implementada no MAC. Já a maioria dos cenários foi considerada SATISFATÓRIO, pelos participantes da avaliação. Este resultado indica que a arquitetura, em uma primeira instância, atende a um conjunto de contextos de utilização. Por outro lado, este resultado também indica que a arquitetura deve ser aprimorada para atender de forma segura e eficiente os demais contextos. Além disso, dois cenários foram classificados como PÉSSIMO. O primeiro (C9) está relacionado à inserção de algum mecanismo de tolerância a falhas. O outro cenário (C14) corresponde às políticas de privacidade de dados utilizadas pela arquitetura. De fato, estes dois cenários não foram previstos inicialmente. No caso do cenário C9, não foi encontrado nenhum mecanismo semelhante nas abordagens encontradas na literatura. Por fim, como a arquitetura proposta mostrou-se modular, para trabalhos futuros serão incluídos dois componentes para mitigar essas deficiências. De uma forma geral, estes resultados mostram que a arquitetura pode e deve ser utilizada em um contexto real, para, de fato, verificar a adequação da arquitetura ao contexto de Cidades Inteligentes e Internet das Coisas. A Tabela 2 resume os próximos passos deste trabalho. ![image]({{ BASE_PATH }}/images/2014-01-02-uma-arquitetura-para-smart-cities-baseada-na/tabela2.png) **Referências**: Nations, U. (2007). World population prospects: The 2006 revision and world urbanization prospects. Technical report, United Nations, New York. Dobbs, R. and Institute, M. G. (2011). Urban World: Mapping the Economic Power of Cities. McKinsey Global Institute. <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. (2011). Smart community: an internet of things application. IEEE Communications Magazine, 49(11), 68–75. Post originalmente publicado por [<NAME>](http://www.gustahrodrigues.com/)<file_sep>/_posts/2014-05-08-assert-meeting-10-may-2014.md --- layout: post title: "ASSERT Meeting (10-May-2014)" categories: Pesquisa tag: seminario --- No próximo **Sábado**, **10/05/2014**, de **10hrs às 12hs**, na sala B020 do [**Centro de Informática**](http://www.cin.ufpe.br){:target="_blank"} da UFPE, iniciaremos a série de seminários sobre os projetos que estão sendo desenvolvidos pelos membros do grupo ASSERT Lab. A série serve para a apresentação do andamento de todas as pesquisas realizadas pelos membros do grupo, assim como, resultados e trabalhos futuros. O objetivo principal é gerar um momento de debate e colaboração, onde todos possam contribuir com o desenvolvimento e amadurecimento das pesquisas realizadas pelo grupo. Neste Sábado teremos as seguintes apresentações: **<NAME> (Doutorado)**: * Experiences Integrating Heterogeneous Government Open Data Sources to Deliver Services and Promote Transparency in Brazil. Artigo aceito para publicação na 38ª Annual International Computers, software & Applications Conference Special Sessions 2014 (COMPSAC), em Västerås, Sweden 21–25 Jul, 2014; * Using Parliament Brazilian Open Data to Improve Transparency and Public Participation in Brazil. Artigo aceito para publicação na International Digital Government Research Conference (2014), em Aguascalientes City - Mexico, 18–21 Jun, 2014; **<NAME> (Mestrado)**: “_Afluentes Concurrent I/O Made Easy with Lazy Evaluation_”. * I/O intensive systems can significantly reduce their total execution time by performing these operations concurrently. Despite this enormous potential, most systems perform I/O operations sequentially. One of the reasons behind this is that the most widespread mechanisms for concurrent I/O are callback-based, resulting in code hard to write and maintain. In this context, we propose Afluentes, a Java framework that allows asynchronous functions to be composed just as easily as synchronous ones, facilitating the development of concurrent I/O intensive systems. We performed an experimental evaluation whose results showed that Afluentes leads to significant performance gains over sequential I/O. Compared to callback-based approaches, Afluentes provides similar increases in performance, but with less programming effort. Trata-se de evento aberto à participação de todos os interessados. Todos são bem-vindos!<file_sep>/_posts/2012-10-24-assert-no-icsea2012-e-no-icpads2012.md --- layout: post title: "ASSERT no ICSEA'2012 e no ICPADS’20122" categories: Artigos tag: conferencia --- Pesquisadores do ASSERT tiveram dois artigos publicados no ICSEA'2012 e um artigo publicado no ICPADS'2012. Os artigos publicados no&nbsp;[7th International Conference on Software Engineering Advances (ICSEA) 2012](http://www.iaria.org/conferences2012/ICSEA12.html), que ocorrerá nos dias 18-23 de Novembro de 2012 em Lisboa (Portugal),&nbsp;foram os seguintes: “**Evaluating performance of distributed systems with MapReduce and application traffic analysis**” de autoria de <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. > Abstract. _Test, monitoring and evaluation of distributed systems at runtime is a difficult effort, due the dynamicity of the environment, the large amount of data exchanged between the nodes and the difficulty of reproduce an error for debugging. Application traffic analysis is a method to evaluate distributed systems, but the capacity of analyze large amount of data is a challenge. This paper proposes and evaluates the use of MapReduce programming model to deep packet inspection the application traffic of distributed systems, evaluating the effectiveness and the processing capacity of the MapReduce programming model for deep packet inspection of a JXTA distributed storage application, in order to measure performance indicators._ “**A Systematic Mapping Study on Domain-Specific Languages**” de autoria de <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. > Abstract. _Domain-Specific Languages (DSLs) offer substantial gains in expressiveness and ease of use compared with general purpose languages. This way, DSLs have gained significant attention in industry and academy, as can be seen by the increased number of related publications in key conferences and journals. This paper aims to provide a broad view of the DSL research field by performing a Systematic Mapping Study. Adopting a detailed search strategy, 4450 studies were initially identified, and, after filtering, 1440 primary studies were selected and categorized using a particular classification scheme. So, this work presents the most popular application domains where DSLs have been applied, identifies different tools for handling DSLs, including language workbenches, and enumerates several techniques, methods and/or processes for dealing with DSLs_. Já no&nbsp;[18th IEEE International Conference on Parallel and Distributed Systems (ICPADS) 2012](http://pdcc.ntu.edu.sg/icpads2012/), que ocorrerá em&nbsp;Singapura&nbsp;nos dias&nbsp;17-19 de Dezembro de 2012 no&nbsp;Nanyang Executive Centre, Nanyang Technological University, teve o seguinte artigo aprovado “**Measuring performance of distributed applications through MapReduce and network traffic analysis**” de autoria de <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. > Abstract. _This paper proposes the use of MapReduce programming model to deep packet inspection of distributed systems network traffic, performing a initial evaluation of effectiveness and processing capacity of MapReduce for deep packet inspection, and also evaluating the performance indicators that can be extracted to evaluate a distributed application._ Os três artigos fazem parte das atividades de pesquisa relacionadas ao projeto&nbsp;[Social Machines and Research Team - SMaRT](http://www.ines.org.br/?p=502)&nbsp;apoiado pelo&nbsp;[INES (Instituto Nacional de Ciência e Tecnologia para Engenharia de Software)](http://www.ines.org.br/).&nbsp;<file_sep>/_posts/2015-12-10-introducao-ao-desenvolvimento-de-maquinas-sociais.md --- layout: post title: "Introdução ao desenvolvimento de Máquinas Sociais hiper-escaláveis" categories: Pesquisa tag: mestrado --- A evolução atual da máquina de turing e sua complexidade são incentivadas por desafios que confrontam os ambientes computacionais. Dentre os inúmeros fatores, temos mudança de requisitos dos usuários (pessoas que usavam PCs preferem a mobilidade de smartphones), as leis de Moore [1] e Amdahl [2] que desafiam o desenvolvimento de algorítmos, a falta de viabilidade financeira, falta de maturidade de modelos e processos, ou o crescimento instantâneo e exponencial de serviços (spikes). Big Players como Google, Netflix, Amazon.com ou Twitter têm se encontrado em um mundo único de inovações devido a singularidade de seus cenários alavancados por um dos maiores desafios da computação: o crescimento. Seja devido ao sucesso de um serviço homogêneo disponibilizado através de plataformas como Twitter e Netflix, a expansão global de lojas virtuais como a Amazon.com ou o crescimento rápido de empresas de apostas como a Paddy Power com turnover de 6 Billhões de euros por volta de 2015, a resposta para o fator crescimento o é desenvolver sistemas distribuídos escaláveis [3]. Escalabilidade é a capacidade que um sistema tem de adicionar mais recursos a fim de atender a necessidade de uma carga de trabalho maior [4]. Além disso, é preciso que tais sistemas apresentem respostas adequadas à solicitações on-demand. Portanto, que também sejam elásticos. Nossa pesquisa visa diretamente lidar com sistemas distribuídos que adotam alta escalabilidade e elasticidade como propriedades fundamentais em sua composição. Inicialmente, entendemos que para construir tais sistemas é necessária a definição de um elemento básico de software que possa ser adicionado ou removido do ambiente a fim de possibilitar alta escalabilidade e eslasticidade ao sistema. Para representar tal elemento utilizamos o conceito de máquinas sociais devido a seu foco no inter-relacionamento entre os elementos que compõem uma arquitetura [5]. Também, entendemos que o elemento básico dessa arquitetura (a máquina social) deve ser delimitado pelo dominio real do problema. Exemplificando, teríamos uma máquina social A responsável pelo departamento de CDs e outra máquinas social B responsável pelo departamento de livros. Partindo da premissa que ha apenas essas 2 instâncias heterogêneas ativas no ambiente, caso a quantidade de trabalho aumentasse além da capacidade da máquinas social A (CDs), bastaria inserir uma nova instância no sistema [7]. Acerca de sistemas distribuídos monolíticos já existentes, estamos trabalhando no desenvolvimento de uma melhor estratégia para o desmembramento dos “domínios reais” existentes e transformando-os em máquinas sociais. Atualmente estamos usando uma solução opensource a fim de validar o conceito através de um problema real. Até o momento esse estudo visa contribuir com o desenvolvimento de novas tecnologias e simplificar o desenvolvimento de aplicações distribuídas escaláveis através da definição de conceitos, estratégias, e uma arquitetura hiper-escalável. 1. Green, C.; The end of Moore’s Law? Why the theory that computer processors will double in power every two years may be becoming obsolete. URL: <http://www.independent.co.uk/life-style/gadgets-and-tech/news/the-end-of-moores-law-why-the-theory-that-computer-processors-will-double-in-power-every-two-years-10394659.html> 2. <NAME> <NAME>; The art of multiprocessor programming. Elsiever 2008 3. <NAME>. A Conversation with <NAME>. ACM QEUE 2006. 4. Lins, <NAME>. Análise da Completude dos Relatos de Experimentos em Elasticidade na Computação em Nuvem: Um Mapeamento Sistemático. Dissertação de mestrado, UFPE 2015. 5. <NAME>. The Emerging Web of Social Machines. <http://vanilson.com/2013/03/10/142/>. 6. Wikipedia. Monolithic system. <https://en.wikipedia.org/wiki/Monolithic_system> 7. ABBOTT, ML; <NAME>. THE ART OF SCALABILITY: Scalable Web Architecture, Processes, and Organizations for the Modern Enterprise<file_sep>/_posts/2019-01-03-Instalando-e-configurando-kubernetes-localmente-com-o-minikube-no-Mac-OSX.md --- layout: post title: "Instalando e configurando kubernetes localmente com o minikube no Mac OSX" categories: DevOps tag: - Container - Kubernetes - Minikube - Site Reliability Engineering - Docker - Helm - Container Registry --- O [Minikube](https://kubernetes.io/docs/setup/minikube/) é a ferramenta ideal para configurar uma instância/cluster [kubernetes](https://kubernetes.io/) (chamaremos de k8s a partir de agora) localmente para testar e experimentar suas implantações. Neste artigo vamos tentar ajudá-los a colocá-lo em funcionamento na sua máquina local (Mac OSX), registrar algumas dicas sobre onde e como as coisas deves ser feitas e também tentar torná-lo capaz de usar o Helm (eu suponho que quando você usa o k8s quer aprender e usar o Helm, etcd, istio etc). > Este artigo tem o objetivo de ser um guia de referência para um ambiente k8s local. # Instalação do Minikube O Minikube trabalha com máquinas virtuais e, para isso, pode usar várias opções dependendo de sua preferência e sistema operacional. Minha preferência neste caso é o [VirtualBox](https://www.virtualbox.org/wiki/Downloads) da Oracle. Você pode usar o **brew** para instalar tudo: ```bash $ brew cask install virtualbox minikube ``` Nesse caso, você pode obter algum tipo de erro de instalação inconclusivo relacionado à instalação do VirtualBox, especialmente no Mojave e provavelmente depois (hehehe). O que quer que seja dito, provavelmente é um novo recurso de segurança do MacOS X que está no seu caminho. Vá para **Preferências do Sistema> Segurança e Privacidade** e na tela **Geral**, você verá uma (ou algumas) mensagens sobre algum software que precisa de aprovação para instalar. Você deve revisar cuidadosamente a lista se houver mais de uma e permitir a instalação do software necessário - neste caso, o **software da Oracle**. Depois disso, você pode executar novamente o comando acima e, quando estiver pronto, você deve estar pronto para as próximas etapas. # Executando e acessando o cluster Começar não poderia ser tão fácil quanto ```bash $ minikube start ``` Para otimizar os recursos da sua máquina local, sugiro que sempre interrompa o minikube quando não precisar mais dele ... Com o VirtualBox sempre em execução, ele pode drenar a bateria do laptop (se for o caso) rapidamente: ```bash $ minikube stop ``` O dashboard do Kubernetes também está disponível (enquanto o minikube está em execução): ```bash $ minikube dashboard ``` Eu suponho que você já tenha o [**kubectl**](https://kubernetes.io/docs/tasks/tools/install-kubectl/) instalado localmente e que já o esteja usando para alguns clusters remotos, de modo que você tenha vários contextos. Neste caso, você precisa listar os contextos e mudar para o minikube (nos seguintes comandos, assumindo o nome padrão que é, “minikube”): ```bash $ kubectl config get-contexts $ kubectl config use-context minikube ``` Agora que você está no contexto do seu cluster k8s local que roda no minikube, podemos fazer todas as operações do k8s nele. # Ingress controller Para executar suas implantações que têm Ingress (e eu suponho que a maioria delas terá), você precisará do add-on: ```bash $ minikube addons enable ingress ``` Certifique-se de configurar a entrada com base em seus hosts locais. Basicamente, significa que o que você definir como host em suas regras do Ingress precisa ser configurado em seu arquivo `/etc/hosts` ``` [minikube ip] your.host ``` Onde você lê "[minikube ip]" deve substituir pelo ip atual do minikube. Ele também funciona com vários hosts locais separados por espaço após o ip do minikube. Aqui está o atalho para fazer isso no bash: ```bash $ echo "$(minikube ip) local.host" | sudo tee -a /etc/hosts ``` # Container registry — i.e. Docker registry > A realidade do uso real de um *container registry* no ambiente local é difícil, por isso vamos adotar uma opção fácil, rápida e corriqueira que torna bastante simples implantar seu trabalho local em seu k8s local, mas priva você da experiência realmente importante de usar um *container registry*. ## Container registry local Obtenha o contexto do docker local para apontar para o contexto do minikube: ```bash $ eval $(minikube docker-env) ``` > Para reverter: ```$ eval $(docker-machine env -u)``` **No contexto do minikube, para iniciar o registro do docker local:** ```bash $ docker run -d -p 5000:5000 --restart=always --name registry registry:2 ``` Então, agora você tem o registro local para enviar itens (contanto que sua janela de encaixe esteja no contexto do minikube). **Agora você pode fazer:** ```bash $ docker build . -t <your_tag> $ docker tag <your_tag> localhost:5000/<your_tag>:<version> ``` Nesse ponto, você pode usar **localhost:5000/<your_tag>:** como imagem em sua implantação e é isso. ##Usando o repositório de contêiner remoto Para usar o repositório de contêiner remoto localmente, você precisa fornecer uma maneira de autenticar, que é através dos [secrets](https://kubernetes.io/docs/concepts/configuration/secret/) do k8s. Para o gerenciamento de segredos locais para registros ECR, GCR e Docker, eu recomendo usar o addon minikube chamado de [registry-creds](https://github.com/upmc-enterprises/registry-creds)(credenciais de registro). Eu não o considero seguro o suficiente para ser usado em qualquer lugar, mas em ambiente local tudo bem. ```bash $ minikube addons configure registry-creds $ minikube addons enable registry-creds ``` > **Nota sobre a configuração do ECR**: Certifique-se de que, se você estiver configurando-o para o AWS ECR e não tiver o papel que deseja usar (normalmente não tem e é opcional), defina-o com algo aleatório como "changeme" ou smt... Ele requer valor, se você simplesmente pressionar enter (já que é opcional) a implantação do pod de creds falhará e tornará sua vida miserável (hahahaha). In case of AWS ECR, that will let you pull from your repo directly setting url as container image and adding pull secret named awsecr-cred: No caso do AWS ECR, isso permitirá que você faça o pull do repo definindo diretamente a URL como imagem do contêiner e adicionando o pull secret chamado awsecr-cred: ``` imagePullSecrets: - name: awsecr-cred ``` > Eu tenho que observar aqui que executar isso localmente funcionou de forma bastante caótica para mim e cada sessão foi uma nova experiência e um novo truque para fazer com que funcionasse... **Não é um caminho feliz**. # Helm Helm é o gerenciador de pacotes para o k8s e é frequentemente usado para gerenciamento de configurações entre implantações. Com alta da popularidade da ferramenta e o constante aumento da sua adoção, é interessante terminar este guia com a nota sobre a adição do Helm ao seu ambiente k8s local. É bem fácil neste momento, basta usar o minikube: ```bash $ brew install kubernetes-helm $ helm init ``` > Essa deve ser uma informação obsoleta muito em breve, mas atualmente o Helm usa um backend chamado Tiller e isso é o que é instalado/implantado durante a execução do helm init. > > Você deve verificar a implantação do Helm com: ```$ kubectl describe deploy tiller-deploy — namespace=kube-system``` Leitura muito importante: <https://docs.helm.sh/using_helm/> Agora você tem um ambiente local k8s completo capaz de aceitar todas as suas implantações de teste antes de decidir colocá-las na nuvem (ou em um servidor "*raw iron*" em algum lugar). Artigo originalmente publicado em [Instalando e configurando kubernetes localmente com o minikube no Mac OSX](http://viniciusgarcia.me/devops/Instalando-e-configurando-kubernetes-localmente-com-o-minikube-no-Mac-OSX/) :: [viniciusgarcia.me](http://viniciusgarcia.me/) <file_sep>/_posts/2013-03-20-uma-abordagem-para-indexacao-e-buscas-full-text-em.md --- layout: post title: "Uma Abordagem para Indexação e Buscas Full-Text em Sistemas de Armazenamento em Nuvem baseados em Peer-to-Peer" categories: Pesquisa tag: mestrado --- A cada dia se produz mais informação e, em muitos casos, essas informações são armazenadas em meios digitais. O tamanho desse “universo digital” cresce de forma exponencial: em 2005, o volume de dados chegou a 130 exabytes; em 2010, superou 1 zettabyte e a previsão é que em 2015 chegue a quase 8 zettabytes. Este “universo digital” citado por Gantz e Reinsel em expande e se torna cada vez mais complexo para processar, armazenar, gerenciar, garantir a segurança e disponibilizar essas informações. Para lidar com esses problemas, segundo o autor supracitado, serão necessárias habilidades, experiência e recursos que rapidamente se tornarão escassos, além de uma nova infraestrutura de Tecnologia da Informação escalável e flexível. Uma opção adequada para este cenário é a computação em nuvem. Essa grande quantidade de dados gerados pode ser armazenada em nuvem utilizando o conceito de armazenamento em nuvem. Zeng et. al introduz o armazenamento em nuvem como um dos serviços que fornecem recursos para armazenamento e serviços baseados em servidores remotos baseados na computação em nuvem. Segundo o autor, o armazenamento em nuvem está apto para prover serviços de armazenamento a um baixo custo com maior confiabilidade e segurança. Um sistema para armazenamento em nuvem pode ser desenvolvido em cima da arquitetura peer-to-peer (p2p), como mostrado na Figura 1, para tirar proveito desse modelo, por exemplo, para evitar gargalos de forma eficiente e pontos únicos de falha. Além disso, esses sistemas podem usar o espaço disponível nos _peers _para armazenar dados, devendo, para isso, levar em consideração atributos como replicação de dados, segurança, seleção de _peers_ com alta disponibilidade, etc. ![image]({{ BASE_PATH }}/images/2013-03-20-uma-abordagem-para-indexacao-e-buscas-full-text-em/figura1.png) Figura 1: Sistema rodando em nuvem sobre uma arquitetura P2P Com os dados armazenados em nuvem, também é importante que o usuário possa encontrá-los com facilidade. Com isso essa pesquisa tem como objetivo propor uma abordagem para extração e indexação de conteúdo dos arquivos, de forma que permita que sejam realizadas buscas full-text em um sistemas de armazenamento em nuvem baseado em peer-to-peer. Além disso, essa pesquisa também tem como objetivo investigar uma maneira eficiente para armazenar o índice de busca dentro da arquitetura P2P, de forma que seja possível replicar as informações com facilidade, permita elasticidade, garanta disponibilidadade e, com isso, permitir que as buscas tragar a maior quantidade de resultados relevantes possível. Para a indexação de arquivos foi utilizado o Apache Lucene, por ser um motor de buscas de alto desempenho escrito em Java. O Lucene contém apenas o núcleo do "motor" de busca. Por isso, ele não inclui um Web crawler ou um parser para diferentes formatos de documentos. Para resolver o problema do parser foi utilizado o Apache Tika, que é um detector e extrator de conteúdo de metadados e texto estruturado, podendo ser utilizado com arquivos de diversos formatos como: HTML, XML, OLE2 e OOXML do Microsoft Office, OpenDocument Format, PDF, ePub, RTF, arquivos compactados e empacotados. Em um sistema dessa natureza, os arquivos armazenados são quebrados em pedaços menores chamados chunks e armazenados separadamente, ou seja, não existe uma réplica do arquivo que o represente completamente. Devido a essa particularidade, a extração de dados e indexação iniciará paralelamente ao processo de backup e o índice gerado pelo Lucene poderá ser armazenado no próprio peer e/ou em um servidor específico, chamado de SearchServer. A busca por informações será do tipo full-text, onde o índice possui todas as palavras de seus dados textuais indexadas, portanto consultas procurando por partes de seqüências de caracteres poderão ser processadas de forma muito rápidas. Com o índice armazenado no próprio peer e no SearchServer, teremos 3 possibilidade de fazer uma consulta ao índice: * Busca local no próprio índice; * Busca no índice de outro peer da rede; * Busca no SearchServer; Os testes para validação da proposta ainda&nbsp; essa abordagem serão implementados e executados dentro de um sistema real de armazenamento em nuvem e medirão o _precision/recall _do sistema, bem como dados referentes a replicação e elasticidade da solução.. Qualquer informaçao sobre o projeto, entre em contato com a equipe pelos endereços: * **<NAME>: masm (at) cin dot ufpe dot br** * **<NAME>:&nbsp;freddurao&nbsp;(at) gmail (dot) com** * **<NAME>:&nbsp;****vcg (at) cin dot ufpe dot br**<file_sep>/_posts/2018-03-14-19-regras-de-codificacao-que-todo-programador-deveria-saber.md --- layout: post title: "Regras de codificação que todo programador deveria saber" categories: Desenvolvimento tag: - programação - Engenharia de Software - desenvolvimento - boas práticas - regras - prática - codificação --- Este é um post baseado em citaçes do livro "_Mastering Machine Learning with Python in Six Steps_" do cientista de dados <NAME>. 1. **Bonito** é melhor do que **feio** - seja consistente. 2. **Complexo** é melhor do que **complicado** - use bibliotecas existentes. 3. **Simples** é melhor do que **complexo** - mantenha-o simples e estúpido (_keep it simple and stupid_, KISS). 4. **Flat** é melhor do que **aninhado** - evite ```if's``` aninhados. 5. **Explícito** é melhor do que **implícito** - seja claro. 6. **Disperso** é melhor do que **denso** - separe o código em módulos. 7. A **legibilidade** é valiosa - use identação para facilitar a leitura e o entendimento. 8. Os **casos especiais** não são especiais o suficiente para **quebrar as regras** - tudo é um objeto. 9. Os **erros** nunca devem ser transmitidos **silenciosamente** - tenha um bom manipulador de exceções. 10. Contudo, a **praticidade** supera a **pureza** - se necessário, quebre as regras. 11. Silenciamento explícito - registro de erros e rastreabilidade. 12. Em situações de **ambiguidade**, evite a tentação de **adivinhar** - a sintaxe de Ruby é mais simples; no entanto, muitas vezes podemos demorar mais tempo para compreendê-la. 13. Embora dessa maneira não seja **óbvio** no começo, a menos que você seja holandês - não há apenas uma maneira de conseguir algo. 14. Deve haver **preferencialmente** apenas uma maneira óbvia de fazê-lo - use bibliotecas existentes. 15. Se a implementação é **difícil de explicar**, é uma **má ideia** - se você não pode explicar em termos simples, então você não entende bem o suficiente. 16. **Agora** é melhor do que **nunca** - há maneiras rápidas/sujas de fazer o trabalho em vez de tentar demais para otimizar. 17. Embora **nunca** seja geralmente melhor do que **agora** - embora exista uma maneira rápida/suja, não siga o caminho que não permitirá uma maneira graciosa de melhorar o que foi feito. 18. **Namespaces** são uma ótima ideia, então vamos fazer mais deles! - seja específico. 19. Se a **implementação** é **fácil** de explicar, pode ser uma **boa ideia** - simplicidade. ## Referência — <https://www.amazon.com/Mastering-Machine-Learning-Python-Steps/dp/1484228650> <file_sep>/_posts/2012-10-31-whassup-dude-episodio-02.md --- layout: post title: "WHASSUP DUDE, Episódio 02" categories: Pesquisa tag: seminario --- Continuando as reuniões de acompanhamento (veja detalhes da anterior [aqui](https://assertlab.github.io/pesquisa/2012/10/31/whassup-dude-episodio-02.html)), nessa sexta dia **09 de Novembro de 2012** teremos mais duas apresentações. A intenção é&nbsp;mostrar os avanços obtidos ao longo do semestre, os impedimentos e problemas, riscos e a maneira de mitigá-los e, claro, os próximos passos. Eventuais resultados alcançados também são bem vindos! Ressalto que este tipo de encontro é uma ótima oportunidade para ver pontos em comum, ou melhor, de convergência de interesses e mais ainda, oportunidades de trabalhos em parceria! Por isso este é um seminário aberto ao público. _**Lembrando, o que esperamos ver?**_ 1. Introdução ao projeto (Contextualização, Problema-Motivação, Proposta*) 2. Proposta em si** 3. Resultados esperados / Contribuição científica ou industrial 4. O que foi feito até aqui*** (100% concluído) com os indicadores de resultado (o que gerou cada atividade dessa?) 5. O que está em andamento, quantos % concluído, indicadores de resultado esperado (para cada atividade , previsão de conclusão, eventuais impedimentos e problemas e como estão sendo tratados, riscos e como eles serão mitigados 6. Próximos passos para os próximos 3 meses de trabalho, atividades em detalhes, com data de início, término e indicador de resultado. 7. Mapa comparativo do que foi proposto em [3] e o que já foi atingido. > _* proposta é o que você se propôs a fazer no mestrado/doutorado_ > _** notem que não coloquei aqui a parte referente a revisão bibliográfica, isso vai estar na sua defesa. para este acompanhamento não precisa._ > _*** considerando adicionalmente as 136 horas recém trabalhadas (referente aos últimos 34 dias trabalhados, contados a partir de 25/08/2012, data do nosso último checkpoint e que vocês têm dedicado pelo menos 28 horas por semana no projeto de vocês)._ Desta forma, convidamos a todos os interessados para aparecerem na sala A014 do Centro de Informática (UFPE) para assistir às seguintes apresentações: **15:00 - <NAME>**, "[SMADL: The Social Machines Architecture Description Language](https://docs.google.com/open?id=0Bxt1VZoj3lGuRndNazJIY1lId3c)" > Abstract. We are experiencing a high growth in the number of web applications being developed. This is happening mainly because the web is going into a new phase, called programmable web, where several web-based systems make their APIs publicly available. In order to deal with the complexity of this emerging web, we define a notion of social machine and envisage a language that can describe networks of such. To start with, social machines are defined as tuples of input, output, processes, constraints, states, requests and responses; apart from defining the machines themselves, the language defines a set of connectors and conditionals that can be used to describe the interactions between any number of machines in a multitude of ways, as a means to represent real machines interacting in the real web. This work presents the Social Machine Architecture Description Language (SMADL). In the context of Web 3.0, SMADL is going to easy the development of web apps, increasing the level of abstraction for creating those types of apps, and bringing the power of connecting existing publicly available apps closer to end user. This is a work in progress and the main goal of this presentation is to show the current status of it, bringing up discussions of weaknesses, strengths and future work. **16:00 - <NAME>**, "[Uma abordagem para gerenciamento de variabilidades dinâmicas em SOPL](https://docs.google.com/open?id=0Bxt1VZoj3lGuck41OUw0MEpqNjQ)" > Dynamic variations in user requirements and system environments become more frequent, there is a growing need for systems to be able &nbsp;to self-adapt to such conditions. Software Product Lines (SPLs) engineering aims to develop similar software systems by sharing a common set of software assets. Service-Oriented Architecture (SOA) has appeared as an emergent approach for developing distributed applications as a set of self-contained &nbsp;and business-aligned services, providing dynamic capabilities that are needed in many product-lines. SPLs provide useful mechanisms for modeling dynamic applications implemented through services. This main goal is to investigate how to modularize 'variability as a service' in order to enable the reconfiguration and management of such services at runtime. As apresentações serão de&nbsp;**25 minutos**. **O que**: WHASSUP DUDE, reunião de acompanhamento e avaliação do grupo ASSERT **Quem**: 15:00 - <NAME>, "SMADL: The Social Machines Architecture Description Language" **Quem**: 16:00 - <NAME>, "Uma abordagem para gerenciamento de variabilidades dinâmicas em SOPL" **Quando**: 09 de Novembro de 2012, 15 horas **Onde**: Centro de Informática (UFPE), Sala A014&nbsp;<file_sep>/_posts/2015-10-21-assert-sbseg-2015-trilha-principal.md --- layout: post title: "Assert @SBSeg 2015 – Trilha Principal" categories: Artigos tag: conferencia --- Com prazer informamos que o artigo “_**Uma Avaliação da Proteção de Dados Sensíveis através do Navegador Web**_” de autoria de <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> e <NAME> foi aceito para apresentação como artigo completo na trilha principal do [XV Simpósio Brasileiro em Segurança da Informação e de Sistemas Computacionais](http://siaiap34.univali.br/sbseg2015/){:target="_blank"}. Segue um resumo do artigo: > Navegadores Web são ferramentas de extrema importância no que diz respeito ao consumo de dados na internet, pois possibilitam a interação e consumo de informações providas por diversos serviços disponíveis na Web. Em contrapartida, é nítida a dificuldade destas ferramentas em evitar que seus usuários sejam vítimas de vulnerabilidades, sejam localizadas em seus próprios mecanismos internos, oriundas de aplicações Web disponíveis ou resultadas pela ingenuidade do próprio usuário. Tais vulnerabilidades quando exploradas resultam em violações aos dados trafegados, produzindo consequências devastadoras, e muitas vezes irreversíveis aos negócios. Através deste artigo, apresentamos um estudo que evidencia a carência de soluções eficazes em analisar e minimizar tal problemática nestes cenários. Nosso estudo tem como objetivo duas contribuições: (i) o desenvolvimento de um ambiente controlado, que se define como uma aplicação Web que simula vulnerabilidades reais suscetíveis a 13 ataques distintos, considerados mais explorados da atualidade. (ii) E uma avaliação da eficácia de 25 ferramentas que visam proteger os usuários de navegadores web contra estes ataques.<file_sep>/_posts/2014-02-25-defesa-de-dissertacao-de-mestrado-n-1359.md --- layout: post title: "Defesa de Dissertação de Mestrado Nº 1.359" categories: Defesa tag: mestrado --- ## Pós-Graduação em Ciência da Computação – UFPE ### Defesa de Dissertação de Mestrado Nº 1.359 **Aluno**: <NAME> **Orientador**: Prof. <NAME> **Co-Orientador**: Prof. <NAME> (DC / UFSCar/Sorocaba) **Título**: _**Uma arquitetura para Cidades Inteligentes Baseada na Internet das Coisas**_ **Data**: 26/02/2014 **Hora/Local**: 10h – Centro de Informática – Sala D222 Banca Examinadora: * Prof. <NAME> (UFPE / CIn) * Prof. <NAME> (UFRN / DIMAp) * Prof. <NAME>(UFPE / CIn) **RESUMO**: > De acordo com relatório divulgado pela UNESCO, por volta de 1950, 30% da população mundial vivia em áreas urbanas e em 2010 esta porcentagem subiu para 50%. Estima-se que em 2050 a porcentagem de pessoas vivendo nos grandes centros urbanos será de 70%. No cenário nacional, segundo dados do Instituto Brasileiro de Geografia e Estatística (IBGE) em julho de 2012 o Brasil chegou a 193.946.886 habitantes, que representa um aumento de aproximadamente 1,65% em relação ao ano de 2010. > Este desenfreado crescimento populacional, além de demais fatores como má governança, ocasiona e/ou intensifica diversos problemas urbanos. Para exemplificar este fato, podem-se citar os grandes problemas que as cidades brasileiras enfrentam nas áreas de transporte, saúde e educação, evidenciados, rotineiramente, pela mídia em geral. > Neste contexto, o conceito de Cidade Inteligente (CS) visa mitigar estes problemas a fim de aumentar a qualidade de vida dos cidadãos. Para tal, uma importante ferramenta para a implementação de uma CS é a Internet das Coisas (IoT), na qual diversos objetos são combinados para atingir um objetivo em comum, como, fornecer informações do fluxo de veículos de uma cidade. > Porém, para que este cenário seja de fato consolidado, necessita-se de uma arquitetura de software capaz de integrar e combinar as diferentes tecnologias e dados que compõem os serviços urbanos. Na literatura podem-se encontrar várias arquiteturas para CS, inclusive com apoio de grandes empresas. Porém, estas arquiteturas visam atender apenas um determinado serviço urbano com uma aplicação específica, o que não caracteriza de fato uma implementação de CS. > Motivado por estes desafios, esta dissertação apresenta a especificação, o projeto e a avaliação de uma arquitetura para CS que permite a integração com IoT, baseado no conjunto de requisitos extraídos das soluções existentes. Adicionalmente, são discutidos os resultados obtidos, os problemas encontrados, e as direções futuras para pesquisa e o desenvolvimento. **Palavras-chave**: Cidades Inteligentes, Internet das Coisas, Arquitetura de Software.<file_sep>/_posts/2014-02-18-servico-de-monitoramento-de-backup-para-cloud.md --- layout: post title: "Serviço de monitoramento de backup para Cloud Storage em uma arquitetura P2P" categories: Pesquisa tag: mestrado --- O aumento da quantidade de dados produzida pelos usuários domésticos através da popularização de dispositivos de produção de conteúdo desafia as empresas de TI a disponibilizarem e gerirem esses dados de forma ubíqua. Nesse contexto, surgi os sistemas de armazenamento de dados em nuvem (cloud storage). Dentre o sistemas mais conhecidos neste modelo podemos citar Amazon S3[1], AllMyData[2] e Rackspace[3]. Visando garantir transparência e qualidade do serviço fornecido ao usuário é necessário à definição de uma SLA (Service Level Agreements). SLA é um acordo entre o serviço web fornecedor e serviço web usuário que especifica o nível garantido de qualidade de serviço e as propriedades funcionais de um serviço web. Devido a natureza dinâmica da cloud, o monitoramento continuo dos atributos de Qualidade de Serviço (QoS) é necessário para a implementação de SLAs. Portanto para acompanhamento e cumprimento do acordo, são definidos estratégias de monitoramento dos recursos utilizados. Este trabalho trata exatamente de monitorar alguns atributos responsáveis por definir um mínimo de qualidade no serviço de backup, estes são: o tempo do backup, tamanho do arquivo e quantidade de peers que este arquivo esta sendo replicado. Além disso, o agente de monitoramento desenvolvido deverá seguir algumas premissas básicas: pouco invasivo, para que não dependa de código interno da aplicação cliente; rápida, para que o usuário não sofra com longas esperas de processamento; poucas mensagens enviadas, as mensagens devem ser as mais compactas possíveis, para que não sobrecarregue o trafego de rede; o mais genérico possível, para que possa ser utilizado em outras cloud storage; e canal de envio de mensagens assíncrono, para não precisar aguardar de respostas sobre envio de mensagem. Como pode ser visto na arquitetura da Figura 1 o agente é outro componente externo a aplicação cliente, esta o notificando sempre quando a aplicação estiver inativa, para que, desta forma, o agente possa fazer a leitura dos dados que constam no log, mapeá-los e enviar para a fila de mensagem. Enquanto isso, o Administrator fica aguardando a chegada das novas mensagens para consumi-las, tratar os dados e salva-los no banco de dados e, posteriormente, os gráficos serem gerados. ![]({{ BASE_PATH }}/images/2014-02-18-servico-de-monitoramento-de-backup-para-cloud/figura1.png) O usuário ao utilizar a aplicação cliente e realizar backup, todos os dados de cada backup estarão sendo inseridos no arquivo de log, sendo todos capturados a partir de algumas variáveis definidas no inicio do método run e capturados mais tarde os valores no final do método depois de ter decorrido o backup, por exemplo, o tempo de inicio e fim que são capturados de acordo o horário do sistema. Depois disso, e de todos os dados capturados, foi utilizado o padrão de projeto observer para quando o usuário finalizar a aplicação cliente, o modulo do agente ser notificado e disparar, em seguida, um chamada ao método run, que lerá o log, mapeando-o para um objeto BackupData que será enviado via mensagem para a fila do ActiveMQ. A aplicação de administração utilizando a classe ListenerBackupData, na qual foi sobrescrito o método onMessage, “escuta” a fila de mensagem, para que quando chegue uma nova, ele possa recebê-la automaticamente. Este método pega os dados da mensagem e insere no banco de dados, para mais tarde ser útil como um histórico para um administrador do sistema e gerar os gráficos demonstrando o comportamento do backup de acordo com a velocidade para cada quantidade de peers utilizados. Como pode ser visto na Figura 2. ![]({{ BASE_PATH }}/images/2014-02-18-servico-de-monitoramento-de-backup-para-cloud/figura2.png) Desta forma, o agente de monitoramento demonstrou ser capaz de medir e analisar os atributos de desempenho da funcionalidade do backup. Entretanto, garantir somente o backup na aplicação de cloud storage não é o suficiente para assegurar a qualidade do sistema. Além desta, é necessário outros parâmetros como melhor localização dos dados, recuperação dos dados, escalabilidade, segurança e rendimento do sistema [4]. Referências 1. <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>.; Dynamo: Amazon’s Highly Available Key-value Store, Amazon.com 2011 2. rackspace. URL: <http://www.rackspacecloud.com/tools/category/applications/cloud-filespartners/filesystems/>. Último acesso em 18/12/2012 3. Nimbus is cloud computing for science. URL: http://www.nimbusproject.org/. Último acesso em 20/12/2010. 4. <NAME>, <NAME>, <NAME>.Conceptual SLA framework for Cloud Computing.4th IEEE International Conference on Digital Ecosystems and Technologies. 2010, pp: 606-610. Texto escrito por: <NAME> (stos “at” cin “dot” ufpe “dot” br)<file_sep>/_posts/2012-09-19-in1163-inicio-das-atividades-do-assert-framework.md --- layout: post title: "[in1163] Início das atividades do ASSERT Framework" categories: Educacao tag: in1163 --- Também no início do mês foram apresentadas as propostas de trabalho dos novos membros do grupo. Após orientações dadas pelo líder do grupo, <NAME>, e pelos membros Seniores (<NAME>, <NAME> e <NAME>), os novos membros apresentaram um briefing das suas propostas de trabalho e um plano de trabalho inicial. A seguir, a lista das propostas: 1. **<NAME>:** _Pandora: Um ambiente virtual de pesquisa_ ::[ Briefing](https://docs.google.com/open?id=0B7obMPxfFDyIMUdaelNjc3lBNjA) - [Plano de Trabalho](https://docs.google.com/open?id=0B7obMPxfFDyIN3NaRE5tVFpFY2M) 2. **<NAME>**: _SafeMash: Um Framework para Detecção de Falhas de Segurança em Cloud-based Mashups_ :: [Briefing](https://docs.google.com/open?id=0Bxt1VZoj3lGuT0F4R2Q1TE13SXc) - [Cronograma](https://docs.google.com/open?id=0Bxt1VZoj3lGueVB5TnR4ZDY4RW8) - [Plano de Trabalho](https://docs.google.com/open?id=0Bxt1VZoj3lGuaW5memV2MXJxdGs) 3. **<NAME>**: _Um middleware para Smart Cities orientado a Citizens as Sensors_ ::[ Briefing](https://docs.google.com/open?id=0B7obMPxfFDyIMDJhYVZjMFFGME0) - [Plano de Trabalho](https://docs.google.com/open?id=0Bxt1VZoj3lGuaVpxTGtrY1huZ0U) 4. **<NAME>**: _Avaliação de abordagens de derivação de produtos para SPLs sensíveis a contexto e com arquitetura orientada a serviços_ :: [Briefing](https://docs.google.com/open?id=0B7obMPxfFDyIbDhVcEtiekdzQ2s) - Plano de Trabalho 5. **<NAME>**: _Smart City Maturity Model_ :: [Briefing](https://docs.google.com/open?id=0B7obMPxfFDyITEdMT1R1TnpRZmc) - Plano de Trabalho 6. **<NAME>**: _Um Agente Inteligente para Tomada de Decisão de Segurança em Cloud Storage_ :: [Briefing](https://docs.google.com/open?id=0B7obMPxfFDyIcEpLeUdzM3haeFE) - Plano de Trabalho 7. **<NAME>**: _Abordagem de monitoramento e definição de SLA para Cloud Storage em uma arquitetura P2P_ :: [Briefing ](https://docs.google.com/open?id=0B7obMPxfFDyId0VVdWlDR0RuRW8)– [Plano de Trabalho](https://docs.google.com/open?id=0B7obMPxfFDyIN0twN3hIdEk4UDg) 8. **<NAME>**: _A Cognitive Privacy Framework to a Smart City Architecture Based on People as Sensors_ :: [Briefing ](https://docs.google.com/open?id=0B7obMPxfFDyIX1d0LTFBN2dtSnM)– [Plano de Trabalho](https://docs.google.com/open?id=0B7obMPxfFDyISnBPNXVpcnlCOWs) 9. **<NAME>**: _Uma DSL para Composição Segura de Software em SPL Sensíveis ao Contexto_ :: Briefing - [Plano de Trabalho](https://docs.google.com/open?id=0Bxt1VZoj3lGudkRFVDM1MkhnNDQ) 10. **<NAME>**: _Uma Abordagem Restful para Prover as Funcionalidades Ideais para Sistemas de Cloud Storage_ :: Briefing - Plano de Trabalho - [Cronograma](https://docs.google.com/spreadsheet/ccc?key=<KEY>) 11. **<NAME>**: _Emeio.us_ :: Briefing - Plano de Trabalho 12. **<NAME>**: _Melhoria de Performance para cloud storage P2P_ :: [Briefing](https://docs.google.com/open?id=0Bxt1VZoj3lGuY19DWjI0bDRBalk) - Plano de Trabalho<file_sep>/_posts/2012-10-02-in1163-final-da-1a-sprint-e-apresentacao-dos.md --- layout: post title: "[in1163] Final da 1ª sprint e apresentação dos resultados" categories: Educacao tag: in1163 --- De acordo com [nosso cronograma](https://docs.google.com/spreadsheet/pub?key=<KEY>&amp;output=html), nesta quarta, dia 03 de Outubro de 2012, é o dealine para entrega do release da 1ª Sprint dos projetos do ASSERT Framework que estão sendo desenvolvidos na disciplina da pós-graduação do Centro de Informática da UFPE [in1163] Tópicos Avançados em Desenvolvimento de Software de Código Aberto. Esta entrega será feita por email para o professor da disciplina, <NAME> (vcg), e na plataforma de acompanhamento de projeto Trello, dentro dos respectivos boards, na forma de um card para o release. Este release é formado por todos os artefatos desenvolvidos na 1ª Sprint (código, documento, imagens, organogramas, modelos, entre outros), que ocorreu entre os dias 05 e 28 de Setmbro de 2012. * **O que**: Apresentação dos resultados da 1ª Sprint * **Data/Hora**: 05 de Outubro de 2012, 15:00 * **Formato**: 5 + 5 minutos * **Local**: Sala A014, Centro de Informática, UFPE A ordem de apresentação será a seguinte: 1. <NAME>: **Uma Arquitetura de Referência para Data Cloud Storage** 2. <NAME>: **SafeMash: um framework para detecção de falhas de segurança em Cloud-based mashups** 3. <NAME>: **Emeio.us** 4. <NAME>: **Um middleware para Smart Cities orientado a Citizens as Sensors** 5. <NAME>: **Uma DSL para Composição Segura de Software em SPL Sensíveis ao Contexto** 6. <NAME>: **Uma Abordagem Restful para Prover as Funcionalidades Ideais para Sistemas de Cloud Storage** 7. <NAME>: **Avaliação de abordagens de derivação de produtos para SPLs sensíveis a contexto e com arquitetura orientada a serviços** 8. <NAME>: **SCMM (Smart City Maturity Model)** 9. <NAME>: **Um Agente Inteligente Para Recomendação em Cloud Storage** 10. <NAME>: **Abordagem de monitoramento e definição de SLA para Cloud Storage em uma arquitetura P2P** 11. <NAME>: **Melhoria de Performance para cloud storage P2P** 12. <NAME>: **A Cognitive Privacy Framework to a Smart City Architecture based on People as Sensors**<file_sep>/_posts/2019-01-05-desenvolvedores-e-programadores-de-sistemas-poderao-ser-enquadrados-como-mei.md --- layout: post title: "Desenvolvedores e programadores de sistemas poderão ser enquadrados como MEI" categories: Empreendedorismo tag: - mei - legislação - software - mercado - empreendedorismo - yabit - desenvolvedor - mercadodeti - ti --- Profissionais desenvolvedores de sistemas que atuam na informalidade poderão passar a ser enquadrados no regime de **Microempreendedor Individual (MEI)** e optar pela tributação do **Simples Nacional**. Mais informações: <http://bit.ly/2COpwCU> Considera-se MEI o empresário individual que atenda às seguintes condições: tenha faturamento limitado a R$ 81 mil por ano; não participe como sócio, administrador ou titular de outra empresa; contrate no máximo um empregado; e exerça atividades econômicas permitidas ao MEI. A categoria é regida pela Lei Complementar 128/2008. O MEI pode ou não optar pelo regime de tributação Simples Nacional. Artigo originalmente publicado em [Desenvolvedores e programadores de sistemas poderão ser enquadrados como MEI](http://viniciusgarcia.me/entrepreneurship/desenvolvedores-e-programadores-de-sistemas-poderao-ser-enquadrados-como-mei/) :: [viniciusgarcia.me](http://viniciusgarcia.me/) <file_sep>/_posts/2013-06-04-assertlab-abre-o-1o-workshop-internacional-sobre.md --- layout: post title: "AssertLab abre o 1º Workshop Internacional sobre Social Machines" categories: Artigos tag: conferencia --- O assertLab marcou presença no [1º workshop Internacional sobre Social Machines (SOCM2013)](http://sociam.org/www2013/), realizado no dia 13/05 no Rio de Janeiro, durante a conferência [WWW 2013](http://www2013.org/). O SOCM2013 teve como principal objetivo caracterizar sistemas na Web como “Máquinas Sociais”, entidades que unem processos computacionais e sociais em software. ![]({{ BASE_PATH }}/images/2013-06-04-assertlab-abre-o-1o-workshop-internacional-sobre/foto1.jpg?raw=true) _Na foto: <NAME>, <NAME>, <NAME> e <NAME>_ O formato adotado na sessão foi um ponto do Workshop que merece destaque. Além de ter sido transmitido ao vivo (video streaming), foi possível interagir com as apresentações e colaborar _on the fly_ com um _live note_ que resumia as anotações dos participantes a respeito do que acontecia durante o evento. O artigo intitulado&nbsp;[Social Machines: A Unified Paradigm to Describe Social Web-Oriented Systems](http://vanilson.com/2013/04/07/social-machines-one-paradigm-different-visions/), de autoria de <NAME>, <NAME> e <NAME>, abriu o fórum de discussões, logo após <NAME> setar o contexto do Workshop. Uma das “novidades”, mostrada durante a apresentação de Vanilson Buregio, foi o conceito de “Social PPT”, em que os participantes da sessão podiam interagir com os slides respondendo perguntas relacionadas aos objetivos do Workshop. * Resumo das apresentações do SOCM2013:&nbsp;[http://bit.ly/socm2013-live-notes](http://bit.ly/socm2013-live-notes) * Mais informações sobre o evento e download dos papers:&nbsp;[http://sociam.org/www2013/](http://sociam.org/www2013/) Nossa apresentação: <iframe src="//www.slideshare.net/slideshow/embed_code/key/z4C113esL8Eonm" width="595" height="485" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="border:1px solid #CCC; border-width:1px; margin-bottom:5px; max-width: 100%;" allowfullscreen> </iframe> <div style="margin-bottom:5px"> <strong> <a href="//www.slideshare.net/vaab/socm-www2013-vanilsonburegio" title="Socm_www2013: Social Machines: A Unified Paradigm to describe Web-Oriented Systems" target="_blank">Socm_www2013: Social Machines: A Unified Paradigm to describe Web-Oriented Systems</a> </strong> from <strong><a href="https://www.slideshare.net/vaab" target="_blank"><NAME></a></strong> </div> **[Socm_www2013: Social Machines: A Unified Paradigm to describe Web-Oriented Systems](http://www.slideshare.net/vaab/socm-www2013-vanilsonburegio "Socm_www2013: Social Machines: A Unified Paradigm to describe Web-Oriented Systems")** from **[vaab](http://www.slideshare.net/vaab)**<file_sep>/_posts/2013-06-26-assert-at-14th-ieee-international-conference-on.md --- layout: post title: "ASSERT at 14th IEEE International Conference on Information Reuse and Integration (IEEE IRI 2013)" categories: Artigos tag: conferencia --- The paper "**The dynamic aspects of product derivation in DSPL: a systematic literature review**" authored by <NAME>, <NAME>, <NAME>, <NAME> and <NAME> has been accepted for publication at [14th IEEE International Conference on Information Reuse and Integration](http://www.sis.pitt.edu/~iri2013/). The conference is being held in San Francisco, USA, August 14-16, 2013. This research is sponsored by the Brazilian National Council for Scientific and Technological Development (CNPq) grants in the process 381305/2011-2, by FACEPE grant APQ-1044-1.03/10. It was also partially supported by the National Institute of Science and Technology for Software Engineering (INES), funded by CNPq and FACEPE, grants 573964/2008-4 and APQ-1037-1.03/08. It is also part of UbiStructure - An infrastructure for developing and executing ubiquitous applications - CNPq 14/2011, process number 481417/2011-7. A brief overview of the paper is given next. _Dynamic Software Product Lines (DSPL) have gained significant attention in academic community by involving aspects of product lines and runtime adaptable systems development. Managing dynamic variations demands is a challenge addressed by DSPL paradigm. In this context, this paper introduces the results of a systematic literature review that involved 2,084 studies, with the objective of understanding how the dynamic derivation in DSPL is made. The contributions of this study are: a) an embracing analysis and classification of scientific literature in DSPL area, b) the definition of inputs that are needed to perform the dynamic derivation, c) the description of what composes these inputs, and d) the understanding of the process to perform the dynamic derivation. We conclude that due to the lack of maturity in the dynamic derivation field, there are many open research opportunities still available._<file_sep>/_posts/2015-03-23-assert-sbsi-2015.md --- layout: post title: "ASSERT @SBSI 2015" categories: Artigos tag: conferencia --- Com prazer informamos que o artigo “_**Criando Startups: Métodos, Processos, Técnicas e Ferramentas**_”, de autoria de <NAME> Rodrigues, <NAME> e <NAME> foi aceito para apresentação como minicurso e para publicação como short paper no [XI Simpósio Brasileiro de Sistemas de Informação (SBSI'2015)](http://www.portal.inf.ufg.br/sbsi2015/index){:target="_blank"}. O resumo do artigo diz que: > O que é um Startup? Que métodos, processos, técnicas ou ferramentas podem maximizar as chances de sucesso de um Startup de Software em um cenário, onde o acesso a computadores, smartphones, tablets e a produtos e serviços pela internet parecem não parar de crescer? Este minicurso reúne uma série de conceitos, tais como: Lean Startup, Business Model Canvas e Customer Development, além de uma série de estratégias que podem ajudar o empreendedor a criar um Produto Mínimo Viável (MVP) de modo a maximizar as chances de sucesso em um negócio inovador. Os participantes conhecerão ainda como e onde incubar e acelerar seu negócio, descobrir o que são e onde estão os investidores anjo, além de casos reais de sucessos e fracassos em alguns empreendimentos.<file_sep>/_posts/2012-09-12-i-assert-workshop.md --- layout: post title: "I ASSERT Workshop" categories: Pesquisa tag: seminario --- ![]({{ BASE_PATH }}/images/2012-09-12-i-assert-workshop/tumblr_ma8itwq6ez1rw0uxu.jpg) No primeiro sábado de Setembro ocorreu o primeiro Assert Workshop , com apresentações do status de trabalho de vários membros do grupo. O Workshop foi enriquecedor para todos os participantes, pois permitiu o compartilhamento da experiência dos apresentadores com o grupo, compartilhando seu conhecimento e o progresso de sua pesquisa com todos, além do feedback do grupo para com o trabalho dos apresentadores, que receberam importantes críticas e observações &nbsp;sobre o seus trabalhos. O Workshop foi realizado no auditório do Centro de Informática da UFPE, e teve a seguinte agenda: **PhD Session** 09:00 – 09:15 – <NAME>: SMADL: [The Social Machines Architecture Description Language](https://docs.google.com/open?id=0B7obMPxfFDyIa1hVSU1pRlBTNnc "AW1-Leandro"). 09:20 – 09:35 – <NAME>: [A framework to redefine the meaning of “Social”, online, once and for all.](https://docs.google.com/open?id=0B7obMPxfFDyIWHdvTWU4QjRNa3c "AW1-Kellyton") 09:40 – 09:55 – Sabrina Souto: Checagem de Modelos e Testes de Linhas de Produtos apoiados por Análise Dinâmica de Código. 10:00 – 10:15 – <NAME>: Evaluating Feature Models Through Metrics. **MSc Session** 10:40 – 10:55 – <NAME>: [Agentes cognitivos para otimização de deduplicação através de pós-processamento de dados em sistemas de armazenamento distribuído](https://docs.google.com/open?id=0B7obMPxfFDyIV0pVb2hqTmFmWkU "AW1-PauloFernando"). 11:00 – 11:10 – <NAME>: [Avaliação de desempenho de aplicações distribuídas através da análise de tráfego de rede utilizando MapReduce.](https://docs.google.com/open?id=0B7obMPxfFDyIRDdIUXpGRkx0ODA "AW1-ThiagoVieira") 11:15 – 11:25 – <NAME>: [Uma estratégia para representação e gerenciamento de metadados em Cloud Computing.](https://docs.google.com/open?id=0B7obMPxfFDyIYV9hMWJ2eTlMTXc "AW1-Marco") 11:30 – 11:40 – <NAME>: [Uma abordagem para gerenciamento de variabilidades dinâmicas em SOPL.](https://docs.google.com/open?id=0B7obMPxfFDyINHkxOUJQRXliamM "AW1-Dhiego") 11:45 – 11:55 – <NAME>: [Uma Arquitetura para a Auto-Implantação de Máquinas Sociais.](https://docs.google.com/open?id=0B7obMPxfFDyIT01NR1BsVVVweVU "AW1-Lenin") 12:00 – 12:10 – <NAME>: [Um framework para contabilidade de consumo de recursos em Cloud Computing.](https://docs.google.com/open?id=0B7obMPxfFDyINjloYU9na0czLUk "AW1-Airton") 12:15 – 12:25 – <NAME>: [Melhoria de performance para sistemas de cloud storage baseados em redes peer-to-peer](https://docs.google.com/open?id=0B7obMPxfFDyIWkRQeS1YbXpweHM "AW1-TJamir") Parabéns a todos os participantes, e até o próximo.<file_sep>/_posts/2014-06-16-assert-meeting-07-jun-2014-post-mortem.md --- layout: post title: "ASSERT Meeting (07-Jun-2014) Post Mortem" categories: Pesquisa tag: seminario --- No dia 07/06/2014, ocorreu no [**Centro de Informática**](http://www.cin.ufpe.br){:target="_blank"} da UFPE o terceiro de uma série de seminários sobre os projetos que estão sendo desenvolvidos pelos membros do ASSERT Lab. No terceiro encontro, o Mestrando **<NAME>**, sob orientação do professor <NAME> e co-orientação de <NAME>, presentou o status do seu trabalho intitulado "_Desenvolvimento de uma arquitetura para um sistema de Cloud Storage_". O trabalho apresentado, pode ser dividido em duas partes, onde na primeira é apresentado os business drivers que analisam os requisitos de negócio para cloud storage aplicada em armazenamento de arquivos, e na segunda é apresentada uma proposta de arquitetura para suprir as necessidades de negócio apresentadas. Por fim, foi mostrada a metodologia que será usada para avaliar a arquitetura proposta, validando assim o trabalho apresentado. Após a apresentação, houve uma rica discussão envolvendo os presentes, aos quais o autor agradece a presença e as contribuições. Em seguida, a mestranda **<NAME>** apresentou a primeira versão da sua proposta de mestrado sobre o título: _Análise da Qualidade de Experimentos na Computação em Nuvem_. O trabalho está sendo desenvolvido sobre a orientação do prof. <NAME> e co-orientação do prof. <NAME>. O objetivo do trabalho se desdobra em três: (i) Realizar um Mapeamento Sistemático dos experimentos da Computação em Nuvem (CN); (ii) Construir um instrumento para Análise de Qualidade Metodológica destes experimentos e (iii) Avaliar e analisar a evolução da qualidade dos estudos de experimentação da CN. Espera-se como contribuição do Mapeamento Sistemático da Literatura identificar e caracterizar os estudos de avaliação da CN, além de traçar um contexto histórico e sensibilizar a necessidade da melhoria da qualidade metodológica destes estudos. Quanto ao instrumento de avaliação da qualidade, espera-se que através deste seja possível aferir a qualidade dos estudos de avaliação tomando-se como base o empacotamento de seus resultados e recomendações feitas por guias para report deste tipo de estudo. Quanto à análise de qualidade, espera-se detalhar e analisar criticamente os elementos metodológicos destes estudos apontando os pontos fortes e fracos no empacotamento dos resultados. Além disto será realizado um paralelo da análise da qualidade dos estudos de experimentação da CN e os realizados no contexto da Engenharia de Software Empírica, que é a disciplina da Engenharia de Software que tem como objetivo suportar estudos empíricos como a experimentação controlada. A pretensão de defesa do projeto é em fevereiro de 2015. Atualmente o trabalho encontra-se no desenvolvimento do protocolo do estudo de Mapeamento Sistemático e em seguida será realizado treinamento dos membros que participarão da realização do estudo. A proposta de trabalho também foi enviada ao IV Workshop de Teses e Dissertações do CBSoft (WTDSoft 2014) aguardando a divulgação dos resultados no dia 14 de julho de 2014. Após a apresentação foram realizadas as arguições pelos participantes do workshop, onde algumas sugestões foram apresentadas, discutidas e as alterações necessárias já estão sendo incorporadas ao projeto.<file_sep>/_posts/2013-05-14-assert-no-31o-simposio-brasileiro-de-redes-de.md --- layout: post title: "ASSERT no 31º Simpósio Brasileiro de Redes de Computadores e Sistemas Distribuídos (SBRC'2013)" categories: Artigos tag: conferencia --- O ASSERT teve 4 trabalhos publicados e apresentados no 31º Simpósio Brasileiro de Redes de Computadores e Sistemas Distribuídos (SBRC'2013)! O primeiro trabalho, entitulado "**USTO.RE: A Private Cloud Storage System**", de autoria de <NAME>, <NAME>, <NAME> e <NAME> e foi publicado no&nbsp;[XI Workshop de Computação em Clouds e Aplicações](http://sbrc2013.unb.br/?page_id=1657) (WCGA). Resumo do artigo:&nbsp;_Cloud computing is a computing model where hardware, platforms and software are seen as services; viz. Infrastructure as a Service, Platform as a Service, and Software as a Service, respectively. Data as a Service (DaaS) is based on the concept that the product, data in this case, can be provided on demand to the user, regardless of geographic or organizational separation between provider and consumer. DaaS applications are for the most part based on excessive data replication in order to guarantee data availability, which means excessive costs in hardware investments. This white paper presents the specifi- cation, implementation and evaluation of a system called USTO.RE which aims to be an effective and low-cost alternative for storing data, thereby mitigating the problem of excessive data replication and thus allows itself to be considered a reliable platform from the perspective of data availability. Evaluation scenarios and the results achieved in our experiments to evaluate the system as well as possible lines for future development will be presented._ O segundo artigo, entitulado "**aCCounts - Um Serviço de Tarifação de Recursos para Computação em Nuvem**", de autoria de&nbsp;<NAME>, <NAME>, <NAME>, <NAME>ade <NAME>, <NAME>&nbsp;e foi publicado no&nbsp;[XI Workshop de Computação em Clouds e Aplicações](http://sbrc2013.unb.br/?page_id=1657)&nbsp;(WCGA). Resumo do artigo:&nbsp;_A computação em nuvem apresenta com uma das suas características-chave um modelo de tarifação onde o cliente paga apenas pelo que foi efetivamente consumido. Há muitas questões em relação à tarifação de serviços em nuvem que ainda não estão bem definidas, como as políticas de definição de recursos tarifados e sua respectiva tarifação. Esse trabalho foca em desenvolver um serviço de tarifação para Infraestruturas em nuvem, o aCCounts (a Cloud aCCOUNTing Service) e uma DSL (do inglês Domain Specifc Language) chamada aCCounts-DSL, para definir políticas flexíveis de tarifação em nuvem. O aCCounts utiliza essa DSL para realizar a tarifação dos serviços de nuvem, através da medição da utilização dos recursos nas máquinas virtuais das nuvens. Como experimentação preliminar da proposta, um protótipo de sua arquitetura é apresentado._ _ _O terceiro artigo, entitulado "**Uma Avaliação do MapReduce para Inspeção Distribuída de Tráfego de Aplicações**", de autoria de&nbsp;<NAME>, <NAME>, <NAME>, <NAME> e foi publicado no&nbsp;[XI Workshop de Computação em Clouds e Aplicações](http://sbrc2013.unb.br/?page_id=1657)&nbsp;(WCGA). Resumo do artigo:&nbsp;_Diagnosticar sistemas distribuídos é uma tarefa complexa, a análise de tráfego de rede pode ser utilizada para avaliar estes sistemas, mas são necessários mecanismos capazes de avaliar uma crescente quantidade de tráfego de rede. MapReduce pode ser usado neste sentido, embora os traces de rede apresentem características diferentes do tipos de dados geralmente processados por MapReduce. Devido às lacunas existentes quanto a avaliação do MapReduce para análise de tráfego de rede, este artigo avalia o desempenho do MapReduce para análise em nível de pacotes e inspeção profunda de pacotes (DPI), caracterizando sua escalabilidade, ganhos em tempo de execução e o comportamento de suas fases. Os experimentos executados evidenciam as fases predomimantes neste tipo de processamento e mostram o impacto causado pelo tamanho do cluster, do bloco e da entrada de dado no tempo de conclusão e escalabilidade._ Estes trabalhos estão relacionados às pesquisas desenvolvidas pelos membros do grupo em seus mestrados, doutorados e nos projetos de P&amp;D&amp;I desenvolvidos pelo grupo com suas parcerias. E finalmente, o quarto artigo entitulado "**Just-in-Time Clouds Uma abordagem para Federação de Clouds Privadas**", de autoria de&nbsp;<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> e foi publicado no&nbsp;[Salão de Ferramentas](http://sbrc2013.unb.br/?page_id=1289) do SBRC. Resumo do artigo:&nbsp;_Este artigo descreve a solução Just-in-Time (JiT) Cloud para a federação de clouds privadas. Uma JiT Cloud consiste na agregação de diversos JiT Data Centres (JiT DCs) geograficamente dispersos e provê infraestrutura computacional como serviço (IaaS) por meio da alocação sob demanda de máquinas virtuais. A solução é composta por três módulos de software que permitem a gerência da infraestrutura por parte de um administrador e de máquinas virtuais por parte de usuários clientes. Atualmente existe uma JiT Cloud em produção composta por seis JiT DCs distribuídos em três estados brasileiros (Paraíba, São Paulo e Rio G. do Sul)._ O&nbsp;31º Simpósio Brasileiro de Redes de Computadores e Sistemas Distribuídos (SBRC'2013) aconteceu no período de 6 a 10 de Maio em Brasília, DF, Brasil.<file_sep>/_posts/2014-04-10-o-que-sao-web-apps-e-como-construi-las-parte-1.md --- layout: post title: "O que são Web Apps e como construí-las. (parte 1)" categories: Pesquisa tag: mestrado --- _By By <NAME> in [Hyper Reactive](http://hyperreactive.com/){:target="_blank"}_ Eu tenho visto cada vez mais Aplicações Web com características de softwares Desktop. A internet das páginas estáticas já se foi há muito tempo. Recentemente esbarrei em um “novo” padrão de desenvolvimento web chamado Web Components. Eu não fazia ideia do que se tratava e resolvi pesquisar…. vejam [aqui](https://www.youtube.com/watch?v=fqULJBBEVQE){:target="_blank"} e [aqui também](https://css-tricks.com/modular-future-web-components/){:target="_blank"}. Padrões como Web Componentes e bibliotecas javascript como [embem.js](https://emberjs.com/){:target="_blank"}, [angular.js](https://angularjs.org/){:target="_blank"}, [react](https://reactjs.org/){:target="_blank"} tem se tornado bastante populares e fazem parte de um conjunto de ferramentas de vanguarda que facilitam o processo de criação de Web Apps. Mas o que são Web Apps (ou o que não são)? Web App é um termo genérico que representa uma grande variedade de sistemas. _Tweetdeck_, [Gmail Web](https://mail.google.com/){:target="_blank"}, [Trello](https://trello.com/){:target="_blank"} e outros podem ser considerados Web Apps. Neste post vamos definir Web Apps como sendo softwares que são executados e apresentados em browsers e restringir o escopo de estudo sobre Web Apps a partir de uma característica fundamental: [Single-page application](https://en.wikipedia.org/wiki/Single-page_application){:target="_blank"}. Estudo? Sim! Fui aceito no mestrado em Engenharia de Software pela Universidade Federal de Pernambuco. Nos próximos meses (6 ~ 8) a maioria dos posts (não todos) deste blog serão relacionados a construção de sistemas web, arquitetura de software orientada a eventos, sistemas tempo real... Mas voltando ao que importa; Single-page applications são sites, sistemas, aplicações que possuem apenas uma página. Esse tipo de aplicação utiliza AJAX (_asynchronous javascript and xml_) para alterar , dinamicamente, o conteúdode uma página. _That’s old news_... A dificuldade está em construir TODA uma aplicação utilizando essa mecânica de modo que, uma vez carregada a página inicial, toda a navegação subsequente (mudança de páginas, carregamento de conteúdo, absolutamente) utilize um processo de carregamento assíncrono das páginas. Difícil de entender? Vou explicar melhor… imagine que um sistema de cadastro de estoque qualquer possua 5 páginas: página principal, edição de perfil de usuário, cadastro de produtos, listagem de todos os produtos e detalhamento do produto. Não é difícil imaginar que cada uma dessas páginas é bem distinta das outras. Uma vez que as páginas são diferentes umas das outras, qual é a melhor forma de arquitetar esse sistema de estoque utilizando o paradigma de Single-page layout? Uma maneira é fazer com que cada página seja injetada (via ajax) dentro de um elemento DIV. Por exemplo: ![]({{ BASE_PATH }}/images/2014-04-10-o-que-sao-web-apps-e-como-construi-las-parte-1/codigo1.png) O código acima contém uma div com id=”content-wrapper”. Nosso objetivo é fazer com que todas as páginas sejam carregadas, de maneira dinâmica (via ajax), dentro dessa div. Para isso, precisamos modificar o comportamento dos links que levam a outras páginas. Por exemplo: ![]({{ BASE_PATH }}/images/2014-04-10-o-que-sao-web-apps-e-como-construi-las-parte-1/codigo2.png) O que o código acima faz é modificar o comportamento dos links cuja classe é ajaxlink. Estou utilizando a biblioteca JQuery para associar uma função anônima ao evento de clique de botão: `$(‘body’).on(‘click’, ‘a.ajaxlink’, function(e)`. Quando um link como este... ![]({{ BASE_PATH }}/images/2014-04-10-o-que-sao-web-apps-e-como-construi-las-parte-1/codigo3.png) ...for clicado, o função anônima acima será executado. A primeira instrução é armazenar a url contida no link em uma variável chamada url. Em seguida, faz-se uma requisição ajax para resgatar a página em questão usando o método `$.ajax()`. Um dos parâmetros passados para o método $.ajax() é justamente a url do link clicado. Os outros parâmetros são o tipo da requisição, neste caso GET e também a função a ser executada caso a requisição ao servidor seja bem sucedida. Quando o servidor responder a requisição, o método success será executado e a página será injetada dentro da div. Por fim a função anônima retorna o valor false indicando que o comportamento padrão de clique no link não seja disparado (o browser não fará o processo natural de navegação, isso fica a cargo de nossa função anônima). Existem alguns benefícios em adotar essa abordagem: 1. Os arquivos `javascript` e `css` só precisam ser carregados uma úinica vez. Tudo bem, tudo bem, é possível utilizar mecanismos de cache para evitar que o browser faça diversas transferências com o servidor. Porém, como cada página geralmente possui arquivos `.js` e .`css` próprios, o usuário ainda terá que esperar um primeiro carregamento das páginas. Esse fato combinado ao tempo de recarregamento de página transmite uma experiência de navegação ruim para o usuário. 2. O browser só precisa carregar a página uma única vez. Na verdade, não é bem assim. Mas o usuário tem a percepção de que é. Isso porque, uma vez que a página principal e todos os arquivos javascript e css são carregados, não há necessidade de recarregamento da página como um todo. Isso permite que o programador controle a experiência de transição de páginas, por exemplo, esmaecendo a página durante o processo de transição para a página seguinte ( `.fadeIn() & .fadeOut()` do JQuery) ao invés da transição nada agradável que browsers fornecem. É possível realizar tarefas ainda mais complexas. Vejam este [post](https://signalvnoise.com/posts/3697-server-generated-javascript-responses){:target="_blank"} do pessoal do **37signals**. Não entrarei em detalhes, mas recomendo a leitura. Ao utilizar uma navegação do tipo _Single-page_ deve-se carregar apenas os recursos apropriados para a injeção dos elementos em questão. Logo, para cada requisição assíncrona (ajax) o servidor deve retornar apenas o bloco de código HTML necessário para exibição do conteúdo em questão. Os _“imports”_ `javascript`, css já foram carregados assim como os elementos `html`, `head`, `body`... O próximo post falará mais a respeito de _Single-page Applications_ e as dificuldades que emergem quando se tenta implementar esse paradigma. Mais informações: <http://hyperreactive.com/><file_sep>/_posts/2013-06-17-assert-participa-e-ganha-premio-no-sbsi-2013.md --- layout: post title: "ASSERT participa e ganha prêmio no SBSI 2013" categories: Artigos tag: premio --- ![image]({{ BASE_PATH }}/images/2013-06-17-assert-participa-e-ganha-premio-no-sbsi-2013/figura1.png) Entre os dias 22 a 24 de Maio, o membro do grupo ASSERT e estudante de doutorado <NAME> acompanhado pelo professor, e também membro do ASSERT, <NAME> (UFSCar) participaram do [IX Simpósio Brasileiro de Sistemas de Informação (SBSI 2013)](http://sbsi2013.dce.ufpb.br/) na cidade de João Pessoa, na Paraíba. O evento foi organizado pela UFPB e promovido pela SBC. Na ocasião, foi apresentado o trabalho “**Br-SCMM: Modelo Brasileiro de Maturidade para Cidades Inteligentes**”, que representa os primeiros resultados dos trabalhos de seu doutorado. Este trabalho foi premiado como “**Melhor Artigo da Trilha Sistemas de Informação e os Desafios do Mundo Aberto**”. Este é o resumo do artigo:&nbsp;_As Cidades Inteligentes estão emergindo frente às necessidades da nova sociedade da tecnologia e informação que surgiu neste século. Atualmente não existe um modelo de maturidade que possa medir o quão inteligente uma sociedade pode ser com base em indicadores sociais ou tecnológicos. Criar um &nbsp;modelo de maturidade pressupõe levantar requisitos, analisá-los e definir quais serão transformados em indicadores. Este trabalho visa apresentar o nível inicial de um Modelo de maturidade aplicado às cidades inteligentes._ Ao final das apresentações dos trabalhos, foi promovida uma mesa redonda, conduzida pela Professora <NAME> (UNIRIO) que contou com a presença de Astério Tanaka (UNIRIO), <NAME> (UFMG), <NAME> (Université de Bretage Sud, França), <NAME> (DATAPREV), <NAME> (SERPRO), <NAME> (UFAL/UFPE), <NAME> (DATAPREV) e <NAME> (UFPB/UFPE), onde foram apresentadas as visões de pesquisadores e profissionais de empresas sobre os princípios para viver e sobreviver no/ao mundo aberto - transparência, colaboração, compartilhamento e deslocamento de poder -tanto por empresas como por todo e qualquer cidadão comum.&nbsp; Agora, os próximos passos incluem a divulgação do modelo de maturidade em outros eventos e congressos, bem como o incentivo ao corpo acadêmico para propor novas soluções em cidades inteligentes que sejam direcionados a resolver problemas locais, ampliando assim as possibilidade de uso deste modelo de maturidade.<file_sep>/_posts/2014-02-26-defesa-de-dissertacao-de-mestrado-n-1370.md --- layout: post title: "Defesa de Dissertação de Mestrado Nº 1.370" categories: Defesa tag: mestrado --- ## Pós-Graduação em Ciência da Computação – UFPE ### Defesa de Dissertação de Mestrado Nº 1.370 **Aluno**: <NAME> **Orientador**: Prof. <NAME> **Título**: _**Aegis: Um Modelo de Proteção à Dados Sensíveis em Ambientes Client-side**_ **Data**: 28/02/2014 **Hora/Local**: 10h – Centro de Informática – Sala D226 Banca Examinadora: * Prof. <NAME>(UFPE / CIn) * Prof. <NAME> (UFRPE / Estattistica e Informática) * Prof. <NAME>(UFPE / CIn) **RESUMO**: > Os Navegadores Web, do inglês, Web Browsers, são ferramentas de extrema importância no que diz respeito ao consumo de informações na internet, consequentemente são os softwares dos quais os usuários utilizam a maior parte do tempo, sejam domésticos ou corporativos. Com o passar dos anos, a forma do que estava sendo publicado naweb foi evoluindo, o que antes era estático e apenas leitura, agora se apresenta como um cenário onde os internautas e serviços interagem, compartilhando informações em uma grande variedade de cenários, como e-mail, redes sociais e comércio eletrônico, tornando-se então em um ambiente dinâmico e colaborativo. Em meio ao advento da web, foram surgindo possibilidades para prestadores de serviços especializados, como bancos ou fontes pagadoras de transações comerciais, dos quais através da internet encontraram oportunidades para disponibilizarem seus serviços com alta disponibilidade, possibilitando que seus clientes consigam utilizar seus serviços através de um browser. O resultado disso é uma série de benefícios, como redução de filas, agilidade, interatividade, foco no domínio, que podemos traduzir em uma palavra: comodidade. Não obstante, em consequência ao seu advento, a web se apresenta como um ambiente cada vez mais hostil, onde pessoas mal-intencionadas executam crimes cibernéticos, dos quais visam roubar ou adulterar informações sigilosas dos usuários da web, violando os dados do usuários. Essas atividade ilícitas muitas vezes são executadas através de ataques que exploram fatores como Engenharia Social, Falhas nas Aplicações Web ou Vulnerabilidades no Browser do usuário. Estes vetores de ataques apresentam-se em diversas formas: capturando entradas dos usuários, forjando sites oficiais, injeção descripts maliciosos, propagação de Malwares, entre outros. Com o dinamismo da web, o processo de controle destes vetores de ataque torna-se cada vez mais difícil, e como a tendência da web é manter-se em constante evolução, estas ameaças tornam-se uma preocupação contínua. Nesta pesquisa é proposta uma ferramenta, intitulada Aegis, como modelo de proteção para interagir diretamente no browser do usuário, buscando minimizar os ataques mencionados através de uma solução puramente cliente-side. Para isso, foram realizados estudos e revisão na literatura sobre o tema, buscando uma justificativa bem fundamenta para as decisões e técnicas aplicadas. Adicionalmente, são apresentados os resultados obtidos na avaliação da Aegis em conjunto com demais ferramentas relacionadas. **Palavras-chave**: Segurança da Informação, Vulnerabilidades em Aplicações Web, Vulnerabilidades em Navegadores Web, Proteção à Fraudes.<file_sep>/_posts/2012-10-11-in1163-inicio-da-2a-sprint.md --- layout: post title: "[in1163] Início da 2ª sprint" categories: Educacao tag: in1163 --- Semana passada tivemos as apresentações dos resultados da nossa primeira sprint, conduzida dentro das disciplinas [in1163] Tópicos Avançados em Desenvolvimento de Software de Código Aberto e [in1184] Trabalho Individual em Engenharia de Software de forma casada. A turma está de parabéns pelo empenho e dedicação! E uma coisa ficou clara, os desafios são muitos assim como as oportunidades! O plano agora é seguir com força total porque a 2ª Sprint já começou! As apresentações foram as seguintes <NAME>, [Uma Arquitetura de Referência para Data Cloud Storage](https://docs.google.com/open?id=0Bxt1VZoj3lGuN0k3OTMtM01aT1E) <NAME>, [SafeMash: um framework para detecção de falhas de segurança em Cloud-based mashups](https://docs.google.com/open?id=0Bxt1VZoj3lGuQkdBLVR6V3J6b00) <NAME>, [eme.io](https://docs.google.com/open?id=0Bxt1VZoj3lGubTFjTGJDQ3pXMzg) <NAME>, [Um middleware para Smart Cities orientado a Citizens as Sensors](https://docs.google.com/open?id=0Bxt1VZoj3lGuV2loUm53NFNSUkU) <NAME>, [Uma DSL para Composição Segura de Software em SPL Sensíveis ao Contexto](https://docs.google.com/open?id=0Bxt1VZoj3lGuY19TSVA2aDBIRHc) <NAME>, [Uma Abordagem Restful para Prover as Funcionalidades Ideais para Sistemas de Cloud Storage](https://docs.google.com/open?id=0Bxt1VZoj3lGuMXM0OHNtX2pqYkU) <NAME>, [Avaliação de abordagens de derivação de produtos para SPLs sensíveis a contexto e com arquitetura orientada a serviços](https://docs.google.com/open?id=0Bxt1VZoj3lGuNW41aWw5X051Ync) <NAME>, [SCMM (Smart City Maturity Model)](https://docs.google.com/open?id=0Bxt1VZoj3lGuX2Y0ZklsUmh4X2c) <NAME>, [Um Agente Inteligente Para Recomendação em Cloud Storage](https://docs.google.com/open?id=0Bxt1VZoj3lGuT3c4QnZ4eEdvSEE) <NAME>, [Abordagem de monitoramento e definição de SLA para Cloud Storage em uma arquitetura P2P](https://docs.google.com/open?id=0Bxt1VZoj3lGuak44dVMzQkp3NEk) <NAME>, [Melhoria de Performance para cloud storage P2P](https://docs.google.com/open?id=0Bxt1VZoj3lGuMlJ6LXlLNE8yV1E) <NAME>, [A Cognitive Privacy Framework to a Smart City Architecture based on People as Sensors](https://docs.google.com/open?id=0Bxt1VZoj3lGuUk85b0FacDRhVWs)<file_sep>/_posts/2016-08-03-assert-at-cbis2016.md --- layout: post title: "ASSERT @ CBIS'2016" categories: Artigos tag: conferencia --- [_post atualizado novamente em 16/08/2016_] [_post atualizado em 12/08/2016_] É com prazer que informamos que os artigos “_**Cidades Inteligentes: IDH como Indicador de Serviços**_” e “_**DendroIDH: Agrupando Cidades por Semelhança de Indicadores**_”, ambos de autoria de <NAME>, <NAME>, <NAME> e <NAME> e o artigo “_**A centralized platform on human genome for supporting clinical decisions**_” de autoria de <NAME>, <NAME>, <NAME>, <NAME> e <NAME> foram aceitos para apresentação no [XV Congresso Brasileiro de Informática em Saúde (CBIS'2016)](http://www.sbis.org.br/cbis2016){:target="_blank"} que vai ser realizado entre os dias 27 a 30 de Novembro em Goiânia. O resumo do primeiro artigo detalha o trabalho da seguinte forma: > Objetivo: as cidades inteligentes estão surgindo mediante a necessidade de otimização de recursos e ampliação do bem-estar dos seus habitantes. Atualmente não existem dados claros sobre como comparar cidades inteligentes com base em indicadores que utilizem dados públicos, principalmente na área de Saúde. Método: este trabalho propõe a utilização de indicadores de IDH para comparar estatisticamente e agrupar cidades com semelhança de indicadores, e assim, oferecer aos seus gestores, a possibilidade de adotar estratégias de gestão baseadas em visualização de dados dispostos em dendrogramas. Resultado: foram realizados cálculos com a utilização de uma ferramenta estatística em bases de dados públicas para obter dendrogramas de dados. Conclusão: o agrupamento de cidades por semelhança de indicadores se mostrou promissor para comparar e medir cidades com semelhantes características. Já em relação ao segundo e terceiro, vale destacar que a apresentação dos mesmos no evento permitirá que eles sejam publicados no [(JHI) Journal of Health Informatics](http://www.jhi-sbis.saude.ws/ojs-jhi/index.php/jhi-sbis){:target="_blank"}. O Journal of Health Informatics (J. Health Inform.) é uma publicação oficial da Sociedade Brasileira de Informática em Saúde. É um periódico de revisão pareada, de acesso livre e aberto o qual é publicado trimestralmente. O J. Health Inform. oferece um meio internacional de disseminação de resultados originais de pesquisa e revisões interpretativas concernentes ao campo da Informática em Saúde. O resumo do segundo artigo detalha o trabalho da seguinte forma: > Objetivo: A área de saúde pública no Brasil é detentora de grandes bases de dados sobre atendimento à população, e ainda assim, estes dados muitas vezes não são explorados suficientemente para identificar possibilidades de melhoria nos atendimentos. Método: este trabalho propõe a utilização dessas bases de dados combinadas com a utilização de técnicas estatísticas para visualizar dados que identifiquem a qualidade de vida das cidades.Resultado: foram analisados os dados de todas as cidades dos nove estados nordestinos e comparados os gráficos de agrupamento. Conclusão: a utilização de grandes repositórios de dados combinados com ferramentas estatísticas permitiram obter diversas visualizações de dados sob a perspectiva de agrupamento de cidades. Finalmente, o resumo do terceiro artigo detalha o trabalho da seguinte forma: > The Data integration is a key challenge in clinical genetics area where analysts need to handle multiple heterogeneous data sources on biological and clinical domains. The research reported in this paper aims to provide unified access to these diverse data sources to support various clinical decisions. In this context, this article describes the work in progress for the construction and implementation of a platform that allows integration and unified access to sources of heterogeneous data. We detail the architecture defined for the platform and an online usage scenario for processing and annotation of clinical variants, which uses the main public data repositories genome as OMIM, Clinvar, Lovd, ExAC6500, and others. Thus, this platform helps in decision making of analysts and geneticists to release results of genetic tests.<file_sep>/_posts/2013-03-26-um-componente-de-software-para-deduplicacao-de.md --- layout: post title: "Um componente de software para deduplicação de arquivos em sistemas de armazenamento distribuído" categories: Pesquisa tag: mestrado --- Com o aumento da capacidade das unidades de armazenamento, aumentou também a demanda por utilização. Em 2000, a estimativa da indústria era de um aumento anual entre 50% a 100% dessa demanda, estimativa essa que se consolidou. Nos últimos anos esse aumento atingiu um valor anual de mais de 50% (KAPLAN, 2008). A Figura 1 mostra dois gráficos sobre a demanada por armazenamento entre 2006 e 2011. Um deles demonstra o forte crescimento da demanda por armazenamento nas empresas, e o segundo, exibe a queda de 20% ao ano no preço por Gigabytes. ![image]({{ BASE_PATH }}/images/2013-03-26-um-componente-de-software-para-deduplicacao-de/figura1.png) Figura 1 - Aumento da demanda e redução do custo de hardware de armazenamento (KAPLAN, 2008) A indústria de TI passou a apostar em sistemas de armazenamento de dados distribuído nos últimos anos. Empresas como Amazon, Google, Microsoft e Salesforce começaram a investir em centros de armazenamentos de dados na nuvem (Cloud Storages), espalhados pelo mundo, com garantia de redundânica e tolerância à falhas. Com esse aumento da demanda por armazenamento, a utilização de técnicas de compressão de dados se torna um fator chave para redução dos custos. A deduplicação de dados é um técnica de compressão de dados que armazena uma única cópia de dados redundantes, eliminando as outras do sistema de armazenamento. A deduplicação pode ser feita à nível de arquivo completo ou de bloco. A utilização de deduplicação de dados em sistemas de armazenamento em nuvem dá uma grande vantagem à empresa que fornece o serviço. Com a utilização da deduplicação, a empresa poderá vender para os cliente mais espaço de armazenamento do que ela tem fisicamente. Os principais sistemas distribuídos de deduplicação de dados são feitos para serem executados em clusters ou em nós simples, alguns deles usam framework para processamento distribuído de dados, como Hadoop, por exemplo, mas há uma falta de pesquisa envolvendo sistemas de deduplicação para ambientes de armazenamento de dados construídos com arquitetura peer-to-peer e utilizando computadores pessoais para armazenar esses dados. Apesar de grandes empresas como a EMC, Symantec, NetApp, entre outras, investiverem em sistemas para deduplicação de dados, detalhes importantes não são divulgados por questões comerciais. Um dos objetivos do [projeto](http://dedupeer.com/) foi a criação de algoritmos encapsulados dentro de componentes de software com interface de integração para os sistemas distribuído de armazenamento de dados. Foram desenvolvidos dois algoritmos, um mais simples, em que o arquivo a ser analisado para deduplicação é todo carregado para a memória principal, e um outro, que foi desenvolvido para dar suporte à arquivos sem limite de tamanho. Esse segundo algoritmo divide o arquivo em partes de tamanho definido no parâmetro da interface de comunicação, e processa o arquivo em partes, permitindo assim que arquivos maiores do que a memória sejam processados. Os [dois algoritmos](http://dedupeer.com/) foram inspirados no rsync, que é o algoritmo para otimização de transferência de arquivos entre computadores utilizado pela ferramenta rsync, desenvolvido por <NAME> and <NAME>. O rsync usa um um tipo de&nbsp;checksum&nbsp;(hash de 32 bits), chamado de&nbsp;rolling checksum,&nbsp;que tem a propriedade de ser calculado de forma pouco custosa quando o cálculo do&nbsp;checksum&nbsp;da janela anterior já tiver sido feito, por exemplo, se o&nbsp;checksum&nbsp;do bloco de bytes X<sub>k</sub>&nbsp;…&nbsp;X<sub>l</sub>&nbsp;já for conhecido, obter o do bloco X<sub>k+1</sub>... X<sub>l+1</sub>&nbsp;é mais rápido. A utilização dorolling checksum&nbsp;torna viável, por tornar a operação menos custosa, o cálculo de hashes para todos os possíveis&nbsp;chunks,&nbsp;de um determinado tamanho especificado, formados a partir de um arquivo. O [algoritmo para processamento do arquivo em partes](http://dedupeer.com/), tem uma abordagem diferente da forma como o rsync e o algoritmo mais simples fazem. O rsync e o primeiro algoritmo, percorrem o conteúdo binário do arquivo à procura de um conjunto sequencial de bytes que seja igual à um&nbsp;chunk&nbsp;conhecido. Com o segundo algoritmo, essa comparação é feita de uma forma reversa, primeiro é calculado o valor da função de hash em um conjunto sequencial de dados do arquivo em que se quer achar conteúdo duplicado, em seguida esse valor é comparado à uma estrutura de dados organizada como um map&lt;hash32, map&lt;md5, id&gt; &gt;, que tem as informações de todos os&nbsp;chunks&nbsp;para comparação. Caso encontre algum&nbsp;chunk&nbsp;que tenha o mesmo hash, é feita uma busca do md5 da sequência de dados no Map que é o valor da função hash32 encontrada. Isso possibilita a comparação sem que seja preciso ter todo o conteúdo do arquivo na memória principal. Também foi desenvolvido um [sistema para gerenciamento de arquivos](http://dedupeer.com/) com base fundamental no Cassandra, para funcionar como um sistema de armazenamento, e assim facilitar o teste da ferramenta e validação do trabalho, como para os pesquisadores que se interessarem opr analisar a trabalho desenvolvido. Os testes em um ambiente distribuído real estão planejados para início de abril. Todo o conteúdo produzido neste projeto estará disponível em breve no endereço: <https://github.com/paulofernando/dedupeer> Para mais informações sobre o projeto, acesse o site oficial [http://dedupeer.com](http://dedupeer.com/), ou entre em contato com <NAME>, <NAME> ou <NAME>, pelos respectivos endereços: (pfas || vcg || slrm) (at) ([cin.ufpe.br](http://cin.ufpe.br/)). <NAME>., <NAME>., AND <NAME>. [Meeting the demand for data storage](https://www.mckinseyquarterly.com/Meeting_the_demand_%20for_data_storage_2153#). Tech. rep., 2008. Acessado em: Fevereivo de 2012.<file_sep>/_posts/2013-04-01-assert-apresenta-artigos-no-sac2013.md --- layout: post title: "ASSERT apresenta artigos no SAC'2013" categories: Artigos tag: conferencia --- Entre os dias 18 a 22 estive em Coimbra, Portugal, participando do [28th Symposium on Applied Computing](http://www.acm.org/conferences/sac/sac2013/) (SAC 2013), evento classificado como qualis A1 de acordo com a CAPES, representando os autores (<NAME>, <NAME>, <NAME>, <NAME>, <NAME> e <NAME>) apresentando o paper [Smart Cities Software Architectures: A Survey](http://dinamico2.unibg.it/sa-tta/SAC2013_SA-TTA_accepted_papers.pdf). ![]({{ BASE_PATH }}/images/2013-04-01-assert-apresenta-artigos-no-sac2013/figura1.jpg) A track na qual participamos - [Software Architecture: Theory, Technology, and Applications](http://dinamico2.unibg.it/sa-tta/) - foi realizada na quinta feira (21/03). Os trabalhos foram subdividos em [duas sessões](http://dinamico2.unibg.it/sa-tta/SAC2013_SA-TTA_FinalProgram.pdf), sendo que o nosso survey encaixou-se na sessão Arquiteturas de Software para Sistemas Complexos. Os trabalhos foram permutados entre os [co]autores que fariam as apresentações, para que cada um liderasse as discussões de um trabalho. A primeira apresentação tratava-se de boas práticas de desenvolvimento de software aplicadas à robotica, &nbsp;na qual o autor explicava que é comum a construção de código priorizado prazo em detrimento à reuso, manutenção, etc. O trabalho propunha a utilização de um conjunto de práticas, associadas ao desenvolvimento orientado a modelo. A apresentação seguinte foi do nosso trabalho. Apesar de ser um assunto pop hoje em dia, o conceito de cidades inteligentes e sua aplicabilidade à diferentes realidade foram as grandes dúvidas dos pesquisadores presentes.&nbsp; A seguir foi apresentado um framework para derivação de métodos de modelagem de arquiteturas para software de grande porte, outro trabalho que tratava da representação de metadados de conformidade com regras governamentais e de segurança. Na segunda parte da track, foi apresentado um framework de gerenciamente de ciclo de vida de múltiplas linhas de produto e uma case de aplicação de SPL na construção de postais para serviços em supercomputing. Um fato bastante notável nesta track, que pode ser considerado um diferencial, foi a associação academia-indústria. A grande maioria dos trabalhos foram validados em empresas, em cases reais. Na sessão de posters, alguns dos trabalhos apresentados no [Mobile Computing and Applications Track](http://www4.comp.polyu.edu.hk/~sac13mca/), possuiam um foco implícito em cidades inteligente, principalmente voltados para atuação de pessoas como sensores. Pude discutir alguns aspectos de privacidade envolvidas no trabalho Towards a Total Recall: An Activity Tracking and Recall Mechanisms for Mobile Devices, apresentado por Sangho Yi. Conversamos sobre pontos em comum entre os assuntos abordados em nossas pesquisas. Esta foi minha primeira experiência em congresso internacional e acredito que o contato com pesquisadores de outros lugares, áreas, pontos de vista foi bastante enriquecedor para ampliar minha visão sobre o mundo acadêmico e, principalmente, sobre sua efetiva contribuição no desenvolvimento tecnológico a nível de indústria. _* Contribuição de&nbsp;<NAME> -&nbsp;__wms4 (at) cin&nbsp;__(dot)&nbsp;__ufpe (dot) br_<file_sep>/_posts/2013-08-30-assert-researcher-at-ieee-iri-2013.md --- layout: post title: "ASSERT researcher at IEEE IRI 2013" categories: Artigos tag: conferencia --- The master degree student, <NAME>, was participate of the 14th edition of the [International Conference on Information Reuse and Integration](http://www.sis.pitt.edu/~iri2013/), held 14-16 August in San Francisco, California. Sponsored annually by the Institute of Electrical and Electronics Engineers (IEEE), the conference serves as a forum for debate on the reuse of information and reusable integration of information systems. On the occasion, <NAME> presented the paper "The Dynamic Aspects of Product Derivation in DSPL: a Systematic Literature Review", work that is part of the research developed by the group ASSERT Lab during his Masters in Computer Science held at the Center for Informatics (CIn) UFPE. "This is a systematic review of the literature with the aim of identifying how is the derivation of products from dynamic software product lines," says Jackson. Jackson explains that these product lines involve dynamic programs that adapt to contexts according to stimuli picked up by sensors in the environment around them. Common Applications of these programs can be viewed on mobile devices in systems that need to be available 24 hours a day, in smart homes and telemonitoring of patients at risk. Among other contributions, the research helps in mapping the state of the art and identification of issues not yet addressed by the scientific community. According to Jackson, the participation in the event and the discussion generated on the subject were very satisfactory. "The discussion was very positive and confirmed the importance of what was discussed," he says. During the event, Jackson was also invited to mediate a session on reuse in software engineering. This research is sponsored by the Brazilian National Council for Scientific and Technological Development (CNPq) grants in the process 381305/2011-2, by FACEPE grant APQ-1044- 1.03/10. It was also partially supported by the National Institute of Science and Technology for Software Engineering ([INES](http://www.ines.org.br)) , funded by CNPq and FACEPE, grants 573964/2008-4 and APQ-1037-1.03/08. It is also part of UbiStructure - An infrastructure for developing and executing ubiquitous applications - CNPq 14/2011, process number 481417/2011-7.<file_sep>/_posts/2014-01-08-um-framework-cognitivo-para-protecao-de-dados.md --- layout: post title: "Um framework cognitivo para proteção de dados pessoais para arquiteturas de cidades inteligentes baseadas em People as Sensors" categories: Pesquisa tag: mestrado --- **Motivação**: Com os últimos acontecimentos divulgados ao público sobre o caso Snowden [[http://www.theguardian.com/world/2013/jun/09/edward-snowden-nsa-whistleblower-surveillance](http://www.theguardian.com/world/2013/jun/09/edward-snowden-nsa-whistleblower-surveillance)], o tema privacidade vem assumindo seu lugar nas discussões em diversas áreas do nosso cotidiano. Sabemos que, desde transações online que realizamos até nossos dispositivos móveis, a forma [nada sutil] como nos expomos na famigerada Web 2.0 - onde nós mesmos criamos o conteúdo (que eventualmente acaba revelando mais de nós mesmos do que gostaríamos) - os próprios serviços que utilizamos “gratuitamente”, nos quais a moeda de troca acaba sendo nossos dados, nós acabamos abrindo mão de um recurso que, até pouco, alguns de nós sequer davam alguma importância. O fato é que ‘eles’ [quem quer que sejam] sabem de nós. E pior que isso: tamanha nossa dependência da existência online, que somos vítimas - quase que voluntárias - de um monitoramento contínuo, que é um prato cheio para as corporações que sabem o que fazer com isso. Tudo que é monitorado sobre cada indivíduo vai parar na _cloud_ (formando um _big data_ sobre cada um de nós). Fotos, dados pessoais, histórico de compra, histórico de localização, quem são os familiares, assuntos de interesse e assim por diante. E uma vez na _cloud_, não há como recuperar esses dados de volta. Ninguém pode te garantir que isso pode ser ou será feito. Além disso, com técnicas modernas de mineração e análise de dados, as empresas interessadas podem saber mais sobre uma pessoa do que ela mesma. Recentemente foi publicado no New York Times [1] que, baseado em hábitos de compra, a Target - uma grande varejista americana - atribuía um índice de predição de gravidez a cada cliente, baseado na análise de dados históricos de mulheres que haviam manifestado seu interesse por produtos para recém-nascidos. Os estatísticos da Target descobriram alguns padrões de consumo para esse perfil específico de cliente que permitia prever a chance da mulher estar grávida e para quando seria o bebê. Certo dia, o pai de uma adolescente foi até uma loja da Target para questionar o gerente do porque sua filha tinha recebido cupons e propagandas de produtos para bebê. Um tanto surpreso, o gerente se desculpa pelo ocorrido. Dias mais tarde, o novo vovô liga para a loja para se desculpar com o gerente, dizendo que algumas coisas tinham ocorrido em sua casa sem que ele tivesse conhecimento. Sem sequer usar nada mais complexo que isso, dá pra sutilmente “manipular” suas ações futuras, baseado em suas ações passadas e de outras pessoas com perfis similares ao seu. Esse é o que eu considero o efeito mais nocivo da perda de privacidade: o desequilíbrio entre o que você sabe sobre você e o que as empresas sabem sobre você. Transpondo tudo isso, para o contexto de uma cidade inteligente, onde o objetivo principal é melhorar a qualidade das pessoas, não tem como fazer isso sem saber delas. Logo, as pessoas precisam ser monitoradas de alguma forma, direta ou indireta. Além do mais, a provisão de serviços inteligentes no contexto urbano vai depender de diversos provedores de serviços, para diferentes finalidades. Ou seja, assim como acontece na internet hoje, nossos dados estarão novamente em mãos alheias, portanto, antes que isso se torne real para a grande maioria da população, precisamos de alguma solução que nos permita tirar proveito da massa de dados que existe sobre nós, além de assegurar um dos substratos necessários para o processo de _smartening_ das nossas cidades. Quanto à privacidade, no estágio atual, a literatura científica aponta para um cenário onde a manutenção de dados vai girar em torno do usuário, do indivíduo (ao contrário do modelo atual, que gira em torno do próprio dado)**, **assim, haveria controle sobre o ciclo de vida de seus dados pessoais (coleta, gerenciamento e uso até sua eventual exclusão), mesmo que estes estejam sob controle de grandes corporações, além de fornecer o mínimo de dados possível quando for utilizar algum serviço (minimização de dados) e, quando for fazê-lo, explicitar seu consentimento de exposição baseado em informações relevantes sobre provedor de serviço, as características do serviço a ser consumido (dados necessários e a informação esperada como saída), bem como do risco assumido ao expor os dados em questão. Essas informações permitiriam uma tomada de decisão de exposição de dados baseada em parâmetros concretos sobre o referido contexto. Este é o objetivo da minha pesquisa, aplicar os conceitos explicitados no parágrafo anterior, na forma de um framework de gestão de privacidade para dados pessoais, ao contexto de cidades inteligentes, integrado a uma arquitetura subjacente, contemplando a provisão/utilização de serviços num ambiente urbano plenamente ubíquo e pervasivo. [1] <NAME>. (2012). How target figured out a teen girl was pregnant before her father did. <http://onforb.es/180SlGT>. "[Online] Available: November 12, 2013" **A proposta**: Inicialmente realizamos um levantamento sobre mecanismos de privacidade propostos para diferentes contextos inteligentes. Anteriormente, havíamos feito uma revisão sistemática especifica para arquiteturas de cidades inteligentes [[http://dl.acm.org/citation.cfm?id=2480688](http://dl.acm.org/citation.cfm?id=2480688)] e vimos que o assunto não era devidamente focado nos trabalhos encontrados. Assim, ponderamos que seria melhor abranger o escopo do levantamento para ambientes inteligentes (_smart homes, smart grid, smart health_, etc.), já que cidades inteligentes essencialmente compreenderiam todos eles. Foram estudados 28 trabalhos, dos quais foi extraído um conjunto de requisitos. Desse conjunto de requisitos, o subconjunto que melhor representava o paradigma centrado no usuário, foi selecionado para fazer parte da proposta. A saber: * Degradação de dados, na qual determinado dado torna se inútil com o passar do tempo devido à perda de precisão; * Sensibilidade de dados, que mensura quão sensível determinado dado é, ou em outras palavras, o risco de exposição desse dado; * Confiança sem interação prévia, que aproxima a reputação de uma entidade provedora de serviço baseada em outra similar (o conceito de similaridade no contexto deste trabalho será definido mais adiante); * Múltiplas identidades, na qual cada identidade é composta por um subconjunto de atributos de determinado indivíduo, assim, para consumir determinado serviço, apenas a identidade necessária será exposta; * Minimização de dados, como umas das consequências diretas das múltiplas identidades, onde apenas os dados essenciais são fornecidos; nada mais que isso. * Controle/Feedback para o usuário, este requisito compreende o ciclo de vida dos dados de um indivíduo estarem sob seu controle, bem como sua experiência no consumo de um serviço ser levada em consideração sempre que houver novas interação. * Especificação de preferência, aqui tanto provedores de serviço, quanto indivíduos consumidores de serviço podem especificar as preferências sobre as quais a interação vai ocorrer. Quando as especificações de preferências podem ser feitas por parte do usuário, a literatura dá o nome de _featurization_. **O framework de privacidade**: ![image]({{ BASE_PATH }}/images/2014-01-08-um-framework-cognitivo-para-protecao-de-dados/figura1.png) **Services Provider Manager: **Responsável por gerenciar as informações de identificação dos provedores de serviço e os serviços que eles fornecem. **Identity Manager: **Responsável por gerir os atributos primitivos (nome, data de nascimento, endereço, etc.) de cada indivíduo e gerar a identidade mais adequada para o consumo de algum serviço. **Policies Manager:** Gerencia as _policies_ dos serviços (e seus respectivos níveis de proposição de valor) providos dentro do framework. **Legal Rules Manager: **Permitir que as questões legais sobre a exposição de dados seja contemplada pelo framework. **Núcleo Cognitivo**: * **_Similarity Manager_**: Responsável por determinar a similaridade entre diferentes provedores de serviço. * **_Preference Manager_**: Responsável por permitir ao usuário impor suas preferências na forma como seus atributos serão expostos, quando, como e por quanto tempo. * **_Feedback controller_**: Responsável por permitir ao usuário manifestar sua opinião sobre serviços utilizados; * **_Transaction Manager_**: Responsável por manter o histórico de interações, a fim de fornecer informações para futuras interações. **Matcher: **Responsável por estabelecer o consenso entre o nível de proposição de valor do serviço a ser consumido (benefício), o _Identity Manager_ (que dados serão expostos)e o _Preferences Manager _(sob que condições). A ideia aqui é que, quanto menor a exposição e maior a proposição de valor, melhor o nível de privacidade e mais efetiva a interação. O estágio atual do projeto trata-se de definir o método de avaliação que poderá ser empregado. Ainda estamos na dúvida de que abordagem aplicar, já que os requisitos são implementados basicamente através de formulas matemáticas, com uma justificativa mais semântica que formal. Texto escrito por [<NAME>](http://welingtonms.wordpress.com/)<file_sep>/_posts/2014-05-09-assert-at-the-38th-annual-ieee-international.md --- layout: post title: "ASSERT at the 38th Annual IEEE International Computers, Software, and Applications Conference (COMPSAC)" categories: Artigos tag: conferencia --- A paper from ASSERT Members has been accepted for the [Industrial Session of the 38th Annual International Computers, Software & Applications Conference (COMPSAC 2014)](https://www.computer.org/web/compsac/2014/home){:target="_blank"} to be held in Västerås, Sweden, on July 2014. The paper is entitled “_**Experiences Integrating Heterogeneous Government Open Data Sources to Deliver Services and Promote Transparency in Brazil**_“, by <NAME>, <NAME>, <NAME> and <NAME>. A brief summary of the paper is following: "_The use of Government Open Data to deliver services and promote transparency is a current goal of many governments. In this paper, we briefly describe two contest winner applications with focus on these goals, and present a discussion about the difficulties of integrating Government Open Data to develop them._” This paper will be soon available on IEEE Digital Library. A new post will be done after the conference, presenting our impressions of the event and the feedback from research community about the work.<file_sep>/_posts/2012-12-28-assert-apresenta-artigos-no-icpads2012.md --- layout: post title: "ASSERT apresenta artigos no ICPADS'2012" categories: Artigos tag: conferencia --- A conferência iniciou no dia 17/12, com dois keynotes durante a manhã. O primeiro keynote foi [<NAME>](http://www.site.uottawa.ca/~ivan/) da [Universidade de Ottawa](http://www.uottawa.ca/welcome.html), que abordou o tema "Mobile Cloud And Crowd Computing And Sensing". Nesta apresentação foram citados conceitos, desafios, oportunidades e aplicações interessantes sobre a combinação de dispositivos móveis e a interação social para obter computação distribuída de larga escala, o que foi chamado de **crowd computing**. Ficou evidente que muitos trabalhos vem sem sendo feitos para o desenvolvimento de cidades inteligentes, mas que ainda há muitos desafios para tornar o uso dos dispositivos móveis eficientes para este fim. O segundo keynote foi [<NAME>](http://pcl.intel-research.net/people/Sunilsherlekar.htm) da Intel, que abordou os desafios e oportunidades na computação "_Exascale_". Desta apresentação é possível destacar o desafio no desenvolvimento de softwares que possam eficientemente explorar potencial fornecido pelos hardwares, como o uso de **[SIMD](http://en.wikipedia.org/wiki/SIMD)** e a escolha dos melhores tipos de computação com base no domínio da aplicação. Ainda no dia 17/12 foi iniciada a sessão de posters e apresentações de artigos. A sessão de poster durou oficiamente 2 horas, mas os posters permaneceram expostos durante todo o evento, o que não limitou as interações a apenas 2 horas. Durante o período oficial da sessão, estive ao lado do poster fornecendo explicações aos interessados, que perguntavam coisas sobre a arquitetura e a validação implementada. Houveram elogios sobre o trabalho realizado, mas nada mais aprofundado. Na parte da tarde assisti as sessões de Cloud Computing e MapReduce. Na sessão de cloud computing foram mostrados trabalhos relacionados com o gerenciamento de recursos e localização. Na sessão de MapReduce houve apenas uma apresentação, que fez uma avaliação de caracteristicas de diferentes workloads processados por MapReduce. Ao final desta sessão pude conversar com o autor deste artigo e o chair da sessão, Prof. [<NAME>](http://www3.ntu.edu.sg/home/bshe/), quando discutimos alguns pontos importantes sobre as pesquisas relacionadas com MapReduce, como o **tamanho do _dataset_** processado e **confiança** nos resultados obtidos. Prof. <NAME> informou que informou que estava a procura de pessoas com experiência em MapReduce para colaboração em projetos de pesquisa, me coloquei a disposição e trocamos contatos, mas ele deixou claro que achava que a distância e diferença de fuso horário poderia ser um fator complicador. O dia 18/12 iniciou com o keynote [<NAME>](http://www4.comp.polyu.edu.hk/~csjcao/) da [Universidade Politecnica de Hong Kong](http://www.polyu.edu.hk/cpa/polyu/index.php), que falou sobre desafios no processamento distribuído em redes de sensores e _ad hoc_. Nesta apresentação foram abordados problemas clássicos, variações destes sob a ótica atual, e novos problemas. Destaca-se os desafios abertos no gerenciamento de eventos, algorítimos para resolver problemas de inconsistência e resolução de conflitos. Em seguida, foi iniciada a sessão de melhores artigos, onde foram apresentados os 3 melhores artigos da conferência, para que um destes fosse escolhido como melhor artigo. Dentre estes artigos, destaco o artigo "_Two-Level Result Caching for Web Search Queries on Structured P2P Networks_" que tratava de uma solução de cache para webservers, baseada em uma uma rede P2P pura. Destaco também o artigo "_Asymptotically Optimal Load Balancing for Hierarchical Multi-Core Systems_", apresentado por um brasileiro ([<NAME>illa](http://www.researchgate.net/profile/Laercio_Lima_Pilla/)), que tratava de um algoritimo para balanceamento de carga em sistemas multi-core. Ao fim do dia 18/12 tivemos um passeio para o [Singapore Flyer](http://www.singaporeflyer.com/), este evento foi importante para conhecer algumas pessoas que estava em sessões diferentes, como os pesquisadores <NAME> e [<NAME>](http://www.gsd.inesc-id.pt/~jleitao/) do [Instituto Superior Técnico (IST) de Portugal](http://www.ist.utl.pt/), e [Guthemberg Silvestre](http://pagesperso-systeme.lip6.fr/Guthemberg.Silvestre/) da [UPMC Sorbonne Universités](http://www.upmc.fr/en/university/sorbonne_universities.html). <NAME> é pesquisador de redes _overlay_ e P2P há algum tempo, conversamos sobre pesquisas em diversos momentos e ficou em aberto um possível trabalho em conjunto. <NAME> fez mestrado no Cin, ele tem trabalhado no desenvolvimento de uma abordagem de replicação de dados baseada em popularidade, algo que pode ser de interesse para o [USTO.RE](http://usto.re).<file_sep>/_posts/2015-12-29-assert-at-noms2016.md --- layout: post title: "ASSERT @ NOMS'2016" categories: Artigos tag: conferencia --- É com prazer que informamos que os artigos “_**A Meta-Analysis for Security Threats over the Web Ecosystem**_“ e “_**Towards a Taxonomy for Security Threats on the Web Ecosystem**_” ambos de autoria de <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> e <NAME> foram aceitos para apresentação no [IEEE/IFIP Network Operations and Management Symposium (NOMS 2016)](http://noms2016.ieee-noms.org/){:target="_blank"}, que vai ser realizado entre os dias 25 a 29 de Abril de 2016 na cidade de Istambul. O abstract dos artigos são os seguintes: > A Meta-Analysis for Security Threats over the Web Ecosystem: This article presents an analysis on the attacks related to the sensitive data breach in the Web ecosystem. The study is based on an Meta-Analysis which identified the significance of 21 years of relevant contributions to the subject. Considering the results we elaborate two contributions: (i) we group attacks according to their behavior and (ii) we reveal the most serious emerging attacks. Additionally, we present our critical sense in relation to an overall perspective on the results. > Towards a Taxonomy for Security Threats on the Web Ecosystem: The aim of this paper is to present a taxonomy for security threats on the Web ecosystem. We proposes a classification model based on 21 vectors divided into 8 distinct security threats, making use of levels of abstraction and criteria for discrimination which consider propagation and similarity in vulnerabilities. We also propose to estimate the risk factor and impacts on assets, considering data breaches, human aspects and service reliability. In addition, we validate the taxonomic model proposed through the catalogues of attacks facing the public. Thus, it was possible to observe its applicability for most of the attacks which appear before the public. Maiores informações sobre o primeiro trabalho podem ser encontradas no post [Uma Meta-Análise sobre Ameaças à Segurança no Ecossistema Web](artigos/2015/12/24/uma-meta-analise-sobre-ameacas-a-seguranca-no.html){:target="_blank"}.<file_sep>/_posts/2019-01-11-cada-vez-mais-as-empresas-precisam-de-engenheiros-criativos.md --- layout: post title: "Cada vez mais as empresas precisam de engenheiros criativos" categories: Educação tag: - ieee - STEAM - engenharia - profissão - engineer - engineering - carreira - empresas - empreendedorismo - empreender - ensino - criatividade --- Pessoas que possuem a incrível capacidade de combinar suas habilidades científicas e de engenharia com uma compreensão de arte, literatura, música e outros trabalhos criativos estão se destacando no mercado de trabalho, introduzindo cada vez mais produtos de grande popularidade e gerando indústrias bilionárias! Um exemplo é <NAME>, membro do IEEE, pioneiro em gráficos digitais e que ajudou a fundar a **Pixar**. A empresa produziu o primeiro longa-metragem de animação por computador, Toy Story, e desde então vem conquistando audiências de todas as idades com sucessos como o Monsters Inc., The Incredibles e Cars. A Pixar recebeu o **Prêmio IEEE de Inovação Corporativa 2018**. O **H910 Harmonizer**, inventado pelo membro vitalício do IEEE <NAME>, é um processador de efeitos de áudio digital que dá flexibilidade aos músicos e produtores, permitindo que eles, por exemplo, alterem o tom de um instrumento, atrasem um som ou façam com que ele se repita. O trabalho de Agnello foi reconhecido com um prêmio **Grammy Técnico** este ano. Life Bellow <NAME> fundou a Bose Corp., a empresa de equipamentos de áudio. O engenheiro de som visionário, que morreu em 2013, inventou o sistema de alto-falantes 901 Direct/Reflecting, um dos primeiros alto-falantes estéreo para usar o espaço em torno de uma sala em vez de direcionar todo o som diretamente para o ouvinte. O 901 permaneceu um padrão da indústria por 25 anos. Esses são “*exemplos de tecnologia e arte que se combinam para criar experiências que nenhum deles poderia fazer sozinho*”, diz o IEEE Fellow S.K. Ramesh. Ramesh é diretor do programa AIMS2 da California State University, Northridge. Como <NAME> disse ao lançar o iPad2, *“está no DNA da Apple que a tecnologia sozinha não é suficiente; é tecnologia casada com artes liberais, casada com as humanidades, que nos dá o resultado que faz nosso coração cantar"*. “*Pode soar clichê*”, acrescenta Ramesh, “*mas eu realmente acredito que a engenharia é a disciplina renascentista do nosso século. Com a STEAM, temos a capacidade de educar de tal forma que possamos trazer mais criatividade e curiosidade aos alunos, bem como construir uma sociedade de trabalhadores mais diversificada e inclusiva. Tudo o que podemos fazer para tornar a engenharia mais significativa é a direção que precisamos seguir*”. Concorda? Mais informações: <http://bit.ly/2RovYtz> Artigo originalmente publicado em [Cada vez mais as empresas precisam de engenheiros criativos](http://viniciusgarcia.me/education/cada-vez-mais-as-empresas-precisam-de-engenheiros-criativos/) :: [viniciusgarcia.me](http://viniciusgarcia.me/) <file_sep>/_posts/2016-08-30-assert-at-sbbd2016.md --- layout: post title: "ASSERT @ SBBD'2016" categories: Artigos tag: conferencia --- É com prazer que informamos que o artigo “_**A centralized platform for access of heterogeneous data on human genome repositories for supporting clinical decisions**_”, de autoria de <NAME>, <NAME>, <NAME>, <NAME> e <NAME> foi aceito para apresentação no [Database Systems Industry Day Workshop (DSIDW'2016)](http://sbbd2016.fpc.ufba.br/en/chamada-dsidw/){:target="_blank"} do [Simpósio Brasileiro de Banco de Dados (SBBD'2016)](http://sbbd2016.fpc.ufba.br/en/){:target="_blank"} que vai ser realizado entre os dias 04 a 07 de Outubro em Salvador. O resumo seguinte descreve o trabalho: > The Data integration is a key challenge in clinical genetics area where analysts need to handle multiple heterogeneous data sources on biological and clinical domains. The research reported in this paper aims to provide unified access to these diverse data sources to support various clinical decisions. In this context, this article describes the work in progress for the construction and implementation of a platform that allows integration and unified access to sources of heterogeneous data. We detail the architecture defined for the platform and an online usage scenario for processing and annotation of clinical variants, which uses the main public data repositories genome as OMIM, Clinvar, Lovd, ExAC6500, and others. Thus, this platform helps in decision making of analysts and geneticists to release results of genetic tests.<file_sep>/_posts/2015-11-05-gerenciamento-de-dados-heterogeneos-quando-e-como.md --- layout: post title: "Gerenciamento de dados heterogêneos: quando e como começar" categories: Pesquisa tag: doutorado --- Nas últimas décadas, o aumento do poder computacional produziu um fluxo impressionante de dados que provocou uma mudança de paradigma no processamento de dados em grande escala. Assim, tivemos uma explosão no volume, velocidade e na variedade de tipos e fontes de dados, a qual podemos nos referir como Big Data. Contudo, o acesso a estes diversos tipos e fontes de dados tornou se complexo. Heterogeneidade, escala, pontualidade, complexidade, privacidade e valor são os desafios do Big Data. Heterogeneidade de dados é um desafio importante em qualquer contexto onde um software lida diretamente com os dados. Nos dias atuais, a necessidade de homogeneização está conduzindo várias técnicas e práticas da indústria, conhecidas com várias expressões similares tais como federação de dados e integração de dados empresariais, que pode ser classificada em dois tipos de abordagens gerais para o problema: gerenciamento de dados mestres (_master data management_); e transformação de dados. A maior expectativa de sistemas complexos é uma integração transparente, onde os dados possam ser acessados, recuperadas e tratados com técnicas, ferramentas e algoritmos uniformes. Dessa maneira, integração pode ser vista como o oposto da heterogeneidade. Mas passar de dados altamente heterogêneos para dados integrados é o tema principal da integração de dados, disciplina essa que estabelece, em termos formais, todos os processos e as etapas técnicas e algorítmicas necessárias para transformar dados. A heterogeneidade é um problema duplo. Ele tem uma conotação técnica e uma teórica. Os dados podem ser distribuídos em fontes de dados diferentes, memorizados em vários formatos e tipos de codificação, e serem consultados através de interfaces de programação incompatíveis. A partir de um ponto de vista técnico, todos estes tipos de problemas podem ser resolvidos com a criação de arquiteturas de adaptação adequadas, envolvendo a presença de um certo número de conectores de homogeneização. Por outro lado, o problema principal com a heterogeneidade é que os dados podem ser intrinsecamente diferentes porque diferentes modelos de dados (coleções de entidades estruturais) são adotados para os organizar. Uma instância de um banco de dados relacional é intrinsicamente diferente de um arquivo XML ou da coleção de objetos em um repositório NoSQL. As divergências não são somente técnicas mas também representacionais. Assim, para gerenciar com um grande volume de dados heterogêneos, é necessário lidar com técnicas de integração de dados sob várias perspectivas pois ela envolve soluções tanto para muitas questões técnicas, tais como a combinação de protocolos, gerenciamento de fluxo de dados (_stream_), escolha de interfaces técnicas (_drivers_) quanto para a adequação conceitual e formal dos modelos de dados envolvidos. Do ponto de vista teórico, uma opção é utilizar o gerenciamento de modelos (_Model Management_) como framework para formalizar problemas de tradução. Um esquema, instância de um determinado modelo será traduzido para outra instância do esquema de um modelo de destino. De acordo com Bernstein [1], _model management_ é um framework teórico que define uma álgebra sobre modelos de dados. Neste contexto, este trabalho identificou a necessidade de uma solução independente de modelo para tradução de esquemas e dados e para problemas de _model management_ e propõe uma plataforma baseada em uma abordagem orientada a metadados que pretende ser mais abrangente do que master data management ou integração de dados empresariais. 1. <NAME>. [Applying model management to classical meta dataproblems](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.12.2729){:target="_blank"}. In CIDR Conference, pages 209–220, 2003.<file_sep>/_posts/2015-04-14-assert-sbsi-2015.md --- layout: post title: "ASSERT @SBSI 2015" categories: Artigos tag: conferencia --- Com prazer informamos que o artigo “_**Um Modelo de Recomendação de Arquivos Para Sistemas de Armazenamento em Nuvem**_”, de autoria de <NAME>, <NAME>., <NAME>, <NAME>, <NAME> e <NAME> foi aceito para publicação na trilha principal e o artigo “_**SmartCluster: Utilizando Dados Públicos para Agrupar Cidades Inteligentes por Domínios**_” de autoria de <NAME>, <NAME>, <NAME> e <NAME> foi aceito para publicação da Trilha de Sistemas de Governo Eletrônico (SIG), ambos no [XI Simpósio Brasileiro de Sistemas de Informação (SBSI'2015)](http://www.portal.inf.ufg.br/sbsi2015/index){:target="_blank"}. Seguem os resumos dos artigos. _Um Modelo de Recomendação de Arquivos Para Sistemas de Armazenamento em Nuvem_: > O desenvolvimento tecnológico vivenciado nos últimos anos proporcionou o crescimento do universo digital de forma exponencial, e parte desse universo digital encontra-se armazenado em sistemas de armazenamento em nuvem. A cada dia surgem mais destes sistemas, que oferecem o armazenamento de dados de forma distribuída com alta taxa de disponibilidade, o que tem impulsionado cada vez mais usuários a migrarem seus dados para a nuvem. No entanto, a grande quantidade de arquivos armazenada nestes sistemas dificulta a filtragem de conteudo relevante, demandando tempo e trabalho por parte do usuário na busca por arquivos com conteudo similar as suas preferências. Diante deste cenário, este artigo propõe um modelo para recomendação de arquivos para sistemas de armazenamento em nuvem, o objetivo é utilizar características da nuvem associadas a técnica de recomendação baseada em conteúdo, recomendar arquivos similares as preferências dos usuários e proporcionar a melhor utilização dos recursos do ambiente em nuvem. _SmartCluster: Utilizando Dados Públicos para Agrupar Cidades Inteligentes por Domínios_: > Atualmente existem vários domínios e indicadores ao redor do mundo que servem para categorizar Cidades Inteligentes, entretanto, não há estudos suficientes sobre a comparação destas cidades no Brasil. As bases de dados públicos dispõem de dados sobre os mais variados indicadores e domínios, e esses dados precisam ser normalizados e agrupados para permitir uma comparação entre as cidades inteligentes brasileiras. Realizar uma análise baseada no agrupamento de similaridade de indicadores de cidades inteligentes pode trazer aos gestores municipais uma maior compreensão das possibilidades estratégicas de otimização de recursos.
ec5bd763c00c915f4e002774e74349984373ccc6
[ "Markdown" ]
130
Markdown
assertlab/assertlab.github.io
62239bb591769609d4e7fdb191889ab39293ada5
d4f70f21602b1382b3fc9e2422183f1055225629
refs/heads/master
<repo_name>knight110/hello-world<file_sep>/README.md # hello-world start start a new project
17a10e9e9290a414576c3c449fcf22a378ab2a91
[ "Markdown" ]
1
Markdown
knight110/hello-world
268013b8f158df12546065e0a77f8acd5b8654ad
028054773305f2a346dd4582c0fd8f4af23b30d4
refs/heads/master
<file_sep>package com.stepByStep.service; import com.stepByStep.domain.Item; import com.stepByStep.repository.jdbc.ItemRepositoryJDBCImpl; /** * Created by baudoux on 20/08/2016. */ public class ItemService { public void createItem(String itemlabel) { Item newItem = new Item(); newItem.setLabel(itemlabel); new ItemRepositoryJDBCImpl().createItem(newItem); } } <file_sep>package com.stepByStep.repository.jdbc; import java.sql.DriverManager; import java.sql.SQLException; /** * Created by baudoux on 20/08/2016. */ public class JDBCManager { private static JDBCManager uniqueInstance; private java.sql.Connection myBddConnection; private JDBCManager() { try { myBddConnection = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/sbs","SA",""); } catch (SQLException e) { e.printStackTrace(); } } public static JDBCManager getInstance() { if (uniqueInstance == null) { uniqueInstance = new JDBCManager(); } return uniqueInstance; } public java.sql.Connection getConnexion() { return myBddConnection; } }
c81c530f64fda293116cd782db133c6b7df77604
[ "Java" ]
2
Java
labofred/stepbystep
f0305fbc41609a981046bda2086ae7db7e5881f9
e96bc731aff5a6732b87c9c83d196452384d2764
refs/heads/main
<repo_name>Abugamil/Generating-exam-tickets<file_sep>/README.md # Generating-exam-tickets The program generates exam tickets by template prepared questions. The questions are evenly distributed in order. Conditionally divided into groups of topics and generated tickets. The first time you run the program, it asks for the path to the list of questions. Each question is written on a new line, without numbering. The first field to enter is the number of required exam tickets. The second field is the number of topics in the ticket. The questions are evenly divided into topics. Mark keywords of template @ - left align $ - right align /## - automatic numbering &&& - questions Example template and questions are presented in the data folder. <NAME> )<file_sep>/src/Unit1.pas unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Word2000, OleServer, ExtCtrls; type TForm1 = class(TForm) Button1: TButton; WordDocument1: TWordDocument; WordApplication1: TWordApplication; OpenDialog1: TOpenDialog; WordParagraphFormat1: TWordParagraphFormat; LabeledEdit1: TLabeledEdit; LabeledEdit2: TLabeledEdit; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var ItemIndex,FileName:OleVariant; vcol,vr: OleVariant; NLines,NF:integer; i,j,l,m:integer; S:array[1..200] of WideString; Format:array[1..100] of WideString; QN,ti:integer; K:integer; S1,S2:WideString; begin Randomize; K:=StrToInt(LabeledEdit1.Text); QN:=StrToInt(LabeledEdit2.Text); Wordapplication1.Visible := True; OpenDialog1.Execute; FileName:=OpenDialog1.FileName; WordApplication1.Documents.Open(FileName,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam); ItemIndex:=1; WordDocument1.ConnectTo(WordApplication1.Documents.Item(ItemIndex)); Nlines:=WordDocument1.Paragraphs.Count; For i:=1 to NLines do Begin S[i]:=WordDocument1.Paragraphs.Item(i).Range.Text; End; WordDocument1.Disconnect; OpenDialog1.Execute; FileName:=OpenDialog1.FileName; WordApplication1.Documents.Open(FileName,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam); ItemIndex:=1; WordDocument1.ConnectTo(WordApplication1.Documents.Item(ItemIndex)); NF:=WordDocument1.Paragraphs.Count; For i:=1 to NF do Begin Format[i]:=WordDocument1.Paragraphs.Item(i).Range.Text; End; //WordApplication1.Sel //WordDocument1.Range.InsertAfter('оздаем объект Range1:'); WordDocument1.Disconnect; ItemIndex:=1; vcol:=wdCollapseEnd; WordApplication1.Caption := 'Ёкзаменационные билеты'; WordApplication1.Documents.Add(EmptyParam,EmptyParam,EmptyParam,EmptyParam); WordDocument1.ConnectTo(WordApplication1.Documents.Item(ItemIndex)); WordApplication1.Options.CheckSpellingAsYouType := False; WordApplication1.Options.CheckGrammarAsYouType := False; WordApplication1.Selection.Font.Size:=14; WordParagraphFormat1.ConnectTo(WordApplication1.Selection.ParagraphFormat); WordParagraphFormat1.Alignment:=wdAlignParagraphCenter; l:=NLines div QN; For i:=1 to K do Begin for j:=1 to NF do Begin vr:=wdAlignParagraphCenter; S1:=Format[j]; If pos('&&&',format[j])>0 Then Begin S1:=''; WordApplication1.Selection.Collapse(vcol); for ti:=1 to Qn do Begin m:=random(l)+1; WordApplication1.Selection.InsertAfter(IntToStr(ti)+'. '+S[(ti-1)*l+m]); End; WordParagraphFormat1.ConnectTo(WordApplication1.Selection.ParagraphFormat); WordParagraphFormat1.Alignment:=wdAlignParagraphLeft; End Else begin If pos('##',format[j])>0 then Begin S2:=Format[j]; s1:=Copy(S2,1,pos('##',S2)-1); Delete(S2,1,pos('##',S2)+1); s1:=s1+IntToStr(i)+Copy(S2,1,Length(S2)); vr:=wdAlignParagraphCenter; End Else if pos('$',format[j])>0 then Begin Delete(S1,pos('$',S1),1); vr:=wdAlignParagraphRight; End else if pos('@',format[j])>0 then Begin Delete(S1,pos('@',S1),1); vr:=wdAlignParagraphLeft; End; WordApplication1.Selection.Collapse(vcol); WordApplication1.Selection.InsertAfter(S1); WordParagraphFormat1.ConnectTo(WordApplication1.Selection.ParagraphFormat); WordParagraphFormat1.Alignment:=vr End; End; End; WordDocument1.Disconnect; WordApplication1.Disconnect; end; end.
475a2833e1689008201a2072299e2837558f2a0e
[ "Markdown", "Pascal" ]
2
Markdown
Abugamil/Generating-exam-tickets
a5e2c39ccb8c353a5f500c634478efa02b7641c7
aff0ecdfe9bb610a0357c82cd4d370e2830408fb
refs/heads/master
<repo_name>Arnegil/Lab2<file_sep>/MethodProgLab2VM/ImageEquantions/CosVectorImageEquantion.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MethodProgLab2VM.ImageEquantions { public class CosVectorImageEquantion : IImageEquantion { public double Equals(int[,] image1, int[,] image2) { int[] vec1 = image1.ToArray(); int[] vec2 = image2.ToArray(); double norm1 = vec1.Norm(); double norm2 = vec2.Norm(); double cosAngle = 0; if (norm1 < 0.00005 && norm2 < 0.00005) cosAngle = 1; else if (norm1 != 0 && norm2 != 0) cosAngle = vec1.ScalarProduct(vec2) / (norm1 * norm2); else if (norm1 < 0.00005 || norm2 < 0.00005) cosAngle = 0; return Math.Abs(cosAngle); } } } <file_sep>/Tests/UnitTest1.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using MethodProgLab2VM.ImageEquantions; namespace Tests { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { IImageEquantion imageEquantion = new CosVectorImageEquantion(); int[,] matr1 = new int[,] { {0,1,2 }, {1,2,3 }, {0,3,2 } }; int[,] matr2 = new int[,] { {0,1,2 }, {1,2,3 }, {0,3,2 } }; var res = imageEquantion.Equals(matr1, matr2); Assert.IsTrue(Math.Abs(res - 1) < 0.00005); } [TestMethod] public void TestMethod2() { IImageEquantion imageEquantion = new CosVectorImageEquantion(); int[,] matr1 = new int[,] { {0,1,2 }, {1,2,3 }, {0,3,2 } }; int[,] matr2 = new int[,] { {0,1,2 }, {1,2,3 }, {0,0,0 } }; var res = imageEquantion.Equals(matr1, matr2); Assert.IsTrue(Math.Abs(res - 0.9) < 0.00005); } } } <file_sep>/MethodProgLab2VM/Models/EqulasMap.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace MethodProgLab2VM.Models { public class EqulasMap { public Dictionary<Region, DomainMemo> Map { get; set; } public EqulasMap() { Map = new Dictionary<Region, DomainMemo>(); } public DomainMemo this[Region key] { get { if (!Map.ContainsKey(key)) Map.Add(key, null); return Map[key]; } set { if (!Map.ContainsKey(key)) Map.Add(key, value); else Map[key] = value; } } public DomainMemo GetDomainFromPosition(Point pos) { return Map.Values.First(x => x.Domain.Position == pos); } public Region GetRegionFromPosition(Point pos) { return Map.Keys.First(x => x.Position == pos); } } } <file_sep>/MethodProgLab2VM/Iterators/RegionCollection.cs using MethodProgLab2VM.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; using System.Windows; namespace MethodProgLab2VM { public class RegionCollection : IList<Region>, ICollection<Region>, IEnumerable<Region> { private StructModel _structModel; private object _lockingObject = new object(); private List<Region> _regionList; public RegionCollection(StructModel structModel) { _structModel = structModel; _regionList = new List<Region>(); for (int i = 0; i < _structModel.Image.OriginalSize.X / _structModel.RegionSize.X; i++) { for (int j = 0; j < _structModel.Image.OriginalSize.Y / _structModel.RegionSize.Y; j++) { _regionList.Add(new Region(_structModel) { Size = _structModel.RegionSize, Position = new Point(i * _structModel.RegionSize.X, j * _structModel.RegionSize.Y) }); } } } public bool IsReadOnly { get { return false; } } public bool IsFixedSize { get { return false; } } public int Count { get { return _regionList.Count; } } public object SyncRoot { get { return _lockingObject; } } public bool IsSynchronized { get { return false; } } Region IList<Region>.this[int index] { get { return _regionList[index]; } set { _regionList[index] = value; } } public IEnumerator GetEnumerator() { return _regionList.GetEnumerator(); } IEnumerator<Region> IEnumerable<Region>.GetEnumerator() { return _regionList.GetEnumerator(); } public void Clear() { _regionList.Clear(); } public void RemoveAt(int index) { _regionList.RemoveAt(index); } public int IndexOf(Region item) { return _regionList.IndexOf(item); } public void Insert(int index, Region item) { _regionList.Insert(index, item); } public void Add(Region item) { _regionList.Add(item); } public bool Contains(Region item) { return _regionList.Contains(item); } public void CopyTo(Region[] array, int arrayIndex) { _regionList.CopyTo(array, arrayIndex); } public bool Remove(Region item) { return _regionList.Remove(item); } } } <file_sep>/MethodProgLab2VM/Iterators/DomainIterator.cs using MethodProgLab2VM.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; using System.Windows; namespace MethodProgLab2VM.Iterators { public class DomainIterator : IEnumerator<Domain> { private StructModel _structModel; private Domain _currentDomain; private Point _currentPoint; public DomainIterator(StructModel model) { _structModel = model; _currentPoint = new Point(0, 0); _currentDomain = new Domain { Position = _currentPoint, Size = model.DomainSize, Image = model.Image.Image.GetSubMatrix(_currentPoint, model.DomainSize) }; } public Domain Current { get { return _currentDomain; } } object IEnumerator.Current { get { return _currentDomain as Domain; } } public void Dispose() { } public bool MoveNext() { if (!NextPositionPoint()) return false; _currentDomain = new Domain { Position = _currentPoint, Size = _structModel.DomainSize, Image = _structModel.Image.Image.GetSubMatrix(_currentPoint, _structModel.DomainSize) }; return true; } public void Reset() { _currentPoint = new Point(0, 0); _currentDomain = new Domain { Position = _currentPoint, Size = _structModel.DomainSize, Image = _structModel.Image.Image.GetSubMatrix(_currentPoint, _structModel.DomainSize) }; } private bool NextPositionPoint() { _currentPoint.X += _structModel.RegionSize.X; if (_currentPoint.X > _structModel.DomainSize.X) { _currentPoint.X = 0; _currentPoint.Y += _structModel.RegionSize.Y; if (_currentPoint.Y > _structModel.DomainSize.Y) { _currentPoint.Y = 0; return false; } return true; } return true; } } public class DomainCollection : IEnumerable<Domain> { private StructModel _structModel; public DomainCollection(StructModel structModel) { _structModel = structModel; } public IEnumerator<Domain> GetEnumerator() { return new DomainIterator(_structModel); } IEnumerator IEnumerable.GetEnumerator() { return new DomainIterator(_structModel); } } } <file_sep>/MethodProgLab2/MainWindow.xaml.cs using PhotoViewerVM; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace PhotoViewer { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class MainWindow : Window, IMainVM { public MainVM VM { get { return this.DataContext as MainVM; } } public MainWindow() { InitializeComponent(); this.DataContext = new MainVM(this); VM.initializationViewModel(); } public void ShowMessage(string message) { MessageBox.Show(message); } } } <file_sep>/MethodProgLab2VM/Iterators/RegionIterator.cs using MethodProgLab2VM.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; using System.Windows; namespace MethodProgLab2VM.Iterators { public class RegionIterator : IEnumerator<Region> { private StructModel _structModel; private Region _currentRegion; private Point _currentPoint; public RegionIterator(StructModel model) { _structModel = model; _currentPoint = new Point(0, 0); _currentRegion = new Region { Position = _currentPoint, Size = model.RegionSize, Image = model.Image.Image.GetSubMatrix(_currentPoint, model.RegionSize) }; } public Region Current { get { return _currentRegion; } } object IEnumerator.Current { get { return _currentRegion as Region; } } public void Dispose() { } public bool MoveNext() { if (!NextPositionPoint()) return false; _currentRegion = new Region { Position = _currentPoint, Size = _structModel.RegionSize, Image = _structModel.Image.Image.GetSubMatrix(_currentPoint, _structModel.RegionSize) }; return true; } public void Reset() { _currentPoint = new Point(0, 0); _currentRegion = new Region { Position = _currentPoint, Size = _structModel.RegionSize, Image = _structModel.Image.Image.GetSubMatrix(_currentPoint, _structModel.RegionSize) }; } private bool NextPositionPoint() { _currentPoint.X += _structModel.RegionSize.X; if (_currentPoint.X > _structModel.RegionSize.X) { _currentPoint.X = 0; _currentPoint.Y += _structModel.RegionSize.Y; if (_currentPoint.Y > _structModel.RegionSize.Y) { _currentPoint.Y = 0; return false; } return true; } return true; } } public class RegionCollection : IEnumerable<Region> { private StructModel _structModel; public RegionCollection(StructModel structModel) { _structModel = structModel; } public IEnumerator<Region> GetEnumerator() { return new RegionIterator(_structModel); } IEnumerator IEnumerable.GetEnumerator() { return new RegionIterator(_structModel); } } } <file_sep>/MethodProgLab2VM/StaticArray.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MethodProgLab2VM { public class StaticArray { private int[][] _array ; public int[][] InitArray(int len1, int len2) { int[][] result = new int[len1][]; for (int i = 0; i < len1; i++) { result[i] = new int[len2]; } return result; } } public class ImgMatrix { public int[] _array { get; set; } public int Width { get; private set; } public int Height { get { return _array.Length / Width; } } public ImgMatrix(int[] array, int width) { _array = array; Width = width; } } } <file_sep>/MethodProgLab2VM/ImageEquantions/SimpleImageEquantion.cs using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MethodProgLab2VM.ImageEquantions { public class SimpleImageEquantion : IImageEquantion { static int ii = 0; public double Equals(int[,] image1, int[,] image2) { int length0 = Math.Min(image1.GetLength(0), image2.GetLength(0)); int length1 = Math.Min(image1.GetLength(1), image2.GetLength(1)); double maxValue = 255 * length0 * length1; double sum = 0; for (int i = 0; i < length0; i++) { for (int j = 0; j < length1; j++) { sum += Math.Abs(image1[i, j] - image2[i, j]); } } return 1 - (sum / maxValue); } public static void Draw(int[,] img, int part) { Bitmap img3 = new Bitmap(img.GetLength(0), img.GetLength(1)); for (int i = 0; i < img.GetLength(0); i++) { for (int j = 0; j < img.GetLength(1); j++) { img3.SetPixel(i, j, Color.FromArgb(img[i, j], img[i, j], img[i, j])); } } img3.Save("imgs\\" + (ii++) + "img" + part + ".jpg"); } } } <file_sep>/MethodProgLab2VM/Models/Region.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace MethodProgLab2VM.Models { public class Region { private StructModel _structModel; public Point Position { get; set; } public Vector Size { get; set; } public int[,] Image { get { return _structModel.Image.Image.GetSubMatrix(Position, Size); } } public Region(StructModel structModel) { _structModel = structModel; } } } <file_sep>/MethodProgLab2VM/Models/Image.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace MethodProgLab2VM.Models { public class ImageModel { public int[,] Image { get; set; } public int[,] OriginalSizedImage { get { int[,] result = new int[(int)OriginalSize.X, (int)OriginalSize.Y]; for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) { result[i, j] = Image[i, j]; } } return result; } } public Vector OriginalSize { get; set; } public static ImageModel GetFromImage(int[,] image, Vector regionSize, Vector domainSize) { return new ImageModel { OriginalSize = new Vector(image.GetLength(0), image.GetLength(1)), Image = Extend(image, regionSize, domainSize) }; } private static int[,] Extend(int[,] image, Vector regionSize, Vector domainSize) { double countXPart = image.GetLength(0) / (int)regionSize.X; double countYPart = image.GetLength(1) / (int)regionSize.Y; double countXPart2 = Math.Ceiling(image.GetLength(0) / regionSize.X) - 1; double countYPart2 = Math.Ceiling(image.GetLength(1) / regionSize.Y) - 1; int[,] result = new int[(int)regionSize.X * (int)countXPart2 + (int)domainSize.X, (int)regionSize.Y * (int)countYPart2 + (int)domainSize.Y]; for (int i = 0; i < image.GetLength(0); i++) { for (int j = 0; j < image.GetLength(1); j++) { result[i, j] = image[i, j]; } } return result; } } } <file_sep>/MethodProgLab2VM/ImagesExtends/SimpleExtendImage.cs using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace MethodProgLab2VM.ImagesExtends { public class SimpleExtendImage : IExtendImage { public int[,] Compress(int[,] imageToCompress, int[,] imageFrom) { int[,] result = new int[imageFrom.GetLength(0), imageFrom.GetLength(1)]; for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) { result[i, j] = 255; } } int offsetX = imageToCompress.GetLength(0) - imageFrom.GetLength(0); int offsetY = imageToCompress.GetLength(1) - imageFrom.GetLength(1); for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) { result[i, j] = imageToCompress[i + offsetX / 2, j + offsetY / 2]; } } return result; } public int[,] Extend(int[,] image, Vector domainSize) { throw new NotImplementedException(); } public int[,] Extend(int[,] imageToExtend, int[,] imageFrom) { int[,] result = new int[imageFrom.GetLength(0), imageFrom.GetLength(1)]; for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) { result[i, j ] = 255; } } int offsetX = imageFrom.GetLength(0) - imageToExtend.GetLength(0); int offsetY = imageFrom.GetLength(1) - imageToExtend.GetLength(1); for (int i = 0; i < imageToExtend.GetLength(0); i++) { for (int j = 0; j < imageToExtend.GetLength(1); j++) { result[i + offsetX / 2, j + offsetY / 2] = imageToExtend[i, j]; } } return result; } } } <file_sep>/MethodProgLab2VM/Models/Domain.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace MethodProgLab2VM.Models { public class Domain { private StructModel _structModel; public Point Position { get; set; } public string Name { get; set; } public Vector Size { get; set; } public int[,] Image { get { var newPos = new Point(Position.X, Position.Y); return _structModel.Image.Image.GetSubMatrix(newPos, Size); } } public Domain(StructModel structModel) { _structModel = structModel; } } } <file_sep>/MethodProgLab2VM/ImagesExtends/NativeBitmapExtendImage.cs using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows; namespace MethodProgLab2VM.ImagesExtends { public class NativeBitmapExtendImage : IExtendImage { public int[,] Compress(int[,] imageToCompress, int[,] imageFrom) { Bitmap myBitmap = new Bitmap(imageToCompress.GetLength(0), imageToCompress.GetLength(1)); LockBitmap lockBitmap = new LockBitmap(myBitmap); lockBitmap.LockBits(); for (int i = 0; i < imageToCompress.GetLength(0); i++) { for (int j = 0; j < imageToCompress.GetLength(1); j++) { lockBitmap.SetPixel(i, j, Color.FromArgb(imageToCompress[i, j], imageToCompress[i, j], imageToCompress[i, j])); } } lockBitmap.UnlockBits(); Graphics myGraphics = Graphics.FromImage(myBitmap); Rectangle sourceRectangle = new Rectangle(0, 0, imageToCompress.GetLength(0), imageToCompress.GetLength(1)); Rectangle destRectangle1 = new Rectangle(0, 0, imageFrom.GetLength(0), imageFrom.GetLength(1)); myGraphics.DrawImage(myBitmap, destRectangle1, sourceRectangle, GraphicsUnit.Pixel); lockBitmap = new LockBitmap(myBitmap); lockBitmap.LockBits(); int[,] result = new int[imageFrom.GetLength(0), imageFrom.GetLength(1)]; for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) { result[i, j] = (int)(lockBitmap.GetPixel(i, j).GetBrightness() * 255); } } lockBitmap.UnlockBits(); myBitmap.Dispose(); myGraphics.Dispose(); return result; } public int[,] Extend(int[,] image, Vector domainSize) { return Extend(image, new int[(int)domainSize.X, (int)domainSize.Y]); } public int[,] Extend(int[,] imageToExtend, int[,] imageFrom) { Bitmap myBitmap = new Bitmap(imageToExtend.GetLength(0), imageToExtend.GetLength(1)); LockBitmap lockBitmap = new LockBitmap(myBitmap); lockBitmap.LockBits(); for (int i = 0; i < imageToExtend.GetLength(0); i++) { for (int j = 0; j < imageToExtend.GetLength(1); j++) { lockBitmap.SetPixel(i, j, Color.FromArgb(imageToExtend[i, j], imageToExtend[i, j], imageToExtend[i, j])); } } lockBitmap.UnlockBits(); var newWidth = (int)(imageFrom.GetLength(0)); var newHeight = (int)(imageFrom.GetLength(1)); var newImage = new Bitmap(newWidth, newHeight); Graphics myGraphics = Graphics.FromImage(newImage); myGraphics.DrawImage(myBitmap, 0, 0, newWidth, newHeight); lockBitmap = new LockBitmap(newImage); lockBitmap.LockBits(); int[,] result = new int[imageFrom.GetLength(0), imageFrom.GetLength(1)]; for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) { result[i, j] = (int)(lockBitmap.GetPixel(i, j).GetBrightness() * 255); } } lockBitmap.UnlockBits(); myBitmap.Dispose(); myGraphics.Dispose(); newImage.Dispose(); return result; } } public class LockBitmap { Bitmap source = null; IntPtr Iptr = IntPtr.Zero; BitmapData bitmapData = null; public byte[] Pixels { get; set; } public int Depth { get; private set; } public int Width { get; private set; } public int Height { get; private set; } public LockBitmap(Bitmap source) { this.source = source; } /// <summary> /// Lock bitmap data /// </summary> public void LockBits() { try { // Get width and height of bitmap Width = source.Width; Height = source.Height; // get total locked pixels count int PixelCount = Width * Height; // Create rectangle to lock Rectangle rect = new Rectangle(0, 0, Width, Height); // get source bitmap pixel format size Depth = System.Drawing.Bitmap.GetPixelFormatSize(source.PixelFormat); // Check if bpp (Bits Per Pixel) is 8, 24, or 32 if (Depth != 8 && Depth != 24 && Depth != 32) { throw new ArgumentException("Only 8, 24 and 32 bpp images are supported."); } // Lock bitmap and return bitmap data bitmapData = source.LockBits(rect, ImageLockMode.ReadWrite, source.PixelFormat); // create byte array to copy pixel values int step = Depth / 8; Pixels = new byte[PixelCount * step]; Iptr = bitmapData.Scan0; // Copy data from pointer to array Marshal.Copy(Iptr, Pixels, 0, Pixels.Length); } catch (Exception ex) { throw ex; } } /// <summary> /// Unlock bitmap data /// </summary> public void UnlockBits() { try { // Copy data from byte array to pointer Marshal.Copy(Pixels, 0, Iptr, Pixels.Length); // Unlock bitmap data source.UnlockBits(bitmapData); } catch (Exception ex) { throw ex; } } /// <summary> /// Get the color of the specified pixel /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public Color GetPixel(int x, int y) { Color clr = Color.Empty; // Get color components count int cCount = Depth / 8; // Get start index of the specified pixel int i = ((y * Width) + x) * cCount; if (i > Pixels.Length - cCount) throw new IndexOutOfRangeException(); if (Depth == 32) // For 32 bpp get Red, Green, Blue and Alpha { byte b = Pixels[i]; byte g = Pixels[i + 1]; byte r = Pixels[i + 2]; byte a = Pixels[i + 3]; // a clr = Color.FromArgb(a, r, g, b); } if (Depth == 24) // For 24 bpp get Red, Green and Blue { byte b = Pixels[i]; byte g = Pixels[i + 1]; byte r = Pixels[i + 2]; clr = Color.FromArgb(r, g, b); } if (Depth == 8) // For 8 bpp get color value (Red, Green and Blue values are the same) { byte c = Pixels[i]; clr = Color.FromArgb(c, c, c); } return clr; } /// <summary> /// Set the color of the specified pixel /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="color"></param> public void SetPixel(int x, int y, Color color) { // Get color components count int cCount = Depth / 8; // Get start index of the specified pixel int i = ((y * Width) + x) * cCount; if (Depth == 32) // For 32 bpp set Red, Green, Blue and Alpha { Pixels[i] = color.B; Pixels[i + 1] = color.G; Pixels[i + 2] = color.R; Pixels[i + 3] = color.A; } if (Depth == 24) // For 24 bpp set Red, Green and Blue { Pixels[i] = color.B; Pixels[i + 1] = color.G; Pixels[i + 2] = color.R; } if (Depth == 8) // For 8 bpp set color value (Red, Green and Blue values are the same) { Pixels[i] = color.B; } } } } <file_sep>/MethodProgLab2VM/Models/StructModel.cs using MethodProgLab2VM.ImagesExtends; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Collections; using MethodProgLab2VM.ImageEquantions; using System.Drawing; namespace MethodProgLab2VM.Models { public class StructModel { public ImageModel Image { get; set; } public Vector RegionSize { get; set; } public Vector DomainSize { get; set; } public string Name { get; set; } public StructModel(int[,] image, Vector regionSize, Vector domainSize, string name) { RegionSize = regionSize; DomainSize = domainSize; Image = ImageModel.GetFromImage(image, RegionSize, domainSize); Name = name; } public static StructModel GetFromBitMap(Bitmap image, Vector regionSize, Vector domainSize, string name) { int[,] imgsrc = new int[image.Size.Width, image.Size.Height]; for (int i = 0; i < imgsrc.GetLength(0); i++) { for (int j = 0; j < imgsrc.GetLength(1); j++) { imgsrc[i, j] = (int)(image.GetPixel(i, j).GetBrightness() * 255); } } return new StructModel(imgsrc, regionSize, domainSize, name); } } } <file_sep>/MethodProgLab2VM/Extantions.cs using MethodProgLab2VM.ImagesExtends; using MethodProgLab2VM.Models; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace MethodProgLab2VM { public static class Extantions { public static int[,] GetSubMatrix(this int[,] matrix, System.Windows.Point pos, Vector size) { int[,] result = new int[(int)size.X, (int)size.Y]; for (int i = (int)pos.X; i < (int)pos.X + size.X; i++) { for (int j = (int)pos.Y; j < (int)pos.Y + size.Y; j++) { result[i - (int)pos.X, j - (int)pos.Y] = matrix[i, j]; } } return result; } public static void SetInSubMatrix(this int[,] matrix, System.Windows.Point pos, int[,] subMatrix) { for (int i = (int)pos.X; i < (int)pos.X + subMatrix.GetLength(0); i++) { for (int j = (int)pos.Y; j < (int)pos.Y + subMatrix.GetLength(1); j++) { matrix[i, j] = subMatrix[i - (int)pos.X, j - (int)pos.Y]; } } } public static double ScalarProduct(this int[] vec1, int[] vec2) { if (vec1.Length != vec2.Length) throw new Exception(); double sum = 0; for (int i = 0; i < vec1.Length; i++) { sum += vec1[i] * vec2[i]; } return sum; } public static double Norm(this int[] vec1) { return Math.Sqrt(vec1.Sum(x => (long)x * x)); } public static int[] ToArray(this int[,] matrix) { int[] vector = new int[matrix.Length]; for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { vector[i * matrix.GetLength(0) + j] = matrix[i, j]; } } return vector; } public static int[,] ToMatrix(this int[] vector, int length) { int[,] matrix = new int[length, vector.Length / length]; for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { matrix[i, j] = vector[i * matrix.GetLength(0) + j]; } } return matrix; } public static int[,] Rotate(this int[,] matrix, Angle angle) { if (angle == Angle.Degree0) return matrix; else if (angle == Angle.Degree90) { int[,] result = new int[matrix.GetLength(0), matrix.GetLength(1)]; Bitmap bmp = new Bitmap(matrix.GetLength(0), matrix.GetLength(1)); LockBitmap lockBitmap = new LockBitmap(bmp); lockBitmap.LockBits(); for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { lockBitmap.SetPixel(i, j, Color.FromArgb(matrix[i, j], matrix[i, j], matrix[i, j])); } } lockBitmap.UnlockBits(); bmp.RotateFlip(RotateFlipType.Rotate90FlipNone); lockBitmap = new LockBitmap(bmp); lockBitmap.LockBits(); for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { result[i, j] = (int)(lockBitmap.GetPixel(i, j).GetBrightness() * 255); } } lockBitmap.UnlockBits(); return result; } else if (angle == Angle.Degree180) { int[,] result = new int[matrix.GetLength(0), matrix.GetLength(1)]; Bitmap bmp = new Bitmap(matrix.GetLength(0), matrix.GetLength(1)); LockBitmap lockBitmap = new LockBitmap(bmp); lockBitmap.LockBits(); for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { lockBitmap.SetPixel(i, j, Color.FromArgb(matrix[i, j], matrix[i, j], matrix[i, j])); } } lockBitmap.UnlockBits(); bmp.RotateFlip(RotateFlipType.Rotate180FlipNone); lockBitmap = new LockBitmap(bmp); lockBitmap.LockBits(); for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { result[i, j] = (int)(lockBitmap.GetPixel(i, j).GetBrightness() * 255); } } lockBitmap.UnlockBits(); return result; } else if (angle == Angle.Degree270) { int[,] result = new int[matrix.GetLength(0), matrix.GetLength(1)]; Bitmap bmp = new Bitmap(matrix.GetLength(0), matrix.GetLength(1)); LockBitmap lockBitmap = new LockBitmap(bmp); lockBitmap.LockBits(); for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { lockBitmap.SetPixel(i, j, Color.FromArgb(matrix[i, j], matrix[i, j], matrix[i, j])); } } lockBitmap.UnlockBits(); bmp.RotateFlip(RotateFlipType.Rotate270FlipNone); lockBitmap = new LockBitmap(bmp); lockBitmap.LockBits(); for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { result[i, j] = (int)(lockBitmap.GetPixel(i, j).GetBrightness() * 255); } } lockBitmap.UnlockBits(); return result; } return null; } } } <file_sep>/MethodProgLab2VM/Models/DomainMemo.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MethodProgLab2VM.Models { public class DomainMemo { public Domain Domain { get; set; } public double M { get; set; } public double Q { get; set; } public Angle Angle { get; set; } } public enum Angle { Degree0, Degree90, Degree180, Degree270 } } <file_sep>/MethodProgLab2VM/ImagesExtends/IExtendImage.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace MethodProgLab2VM.ImagesExtends { public interface IExtendImage { int[,] Extend(int[,] imageToCompress, int[,] imageFrom); int[,] Extend(int[,] image, Vector domainSize); int[,] Compress(int[,] imageToExtend, int[,] imageFrom); } } <file_sep>/MethodProgLab2VM/DoAPp.cs using MethodProgLab2VM.ImageEquantions; using MethodProgLab2VM.ImagesExtends; using MethodProgLab2VM.Models; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MethodProgLab2VM { public class DoAPp { private IExtendImage _extendImage; private IImageEquantion _imageEquantion; private StructModel _structModel; private DomainCollection _domainCollection; private RegionCollection _regionCollection; public EqulasMap EqulasMap { get; set; } public DoAPp(StructModel structModel, IExtendImage extendImage, IImageEquantion imageEquantion) { _structModel = structModel; _extendImage = extendImage; _imageEquantion = imageEquantion; _domainCollection = new DomainCollection(_structModel); _regionCollection = new RegionCollection(_structModel); } public EqulasMap GetEqulasMap() { EqulasMap resultMap = new EqulasMap(); foreach (var region in _regionCollection.ToList()) { double bestEqualResult = double.MinValue; int[,] bestImg = null; foreach (var angle in Enum.GetValues(typeof(Angle))) { var regionRotate = region.Image.Rotate((Angle)angle); var extendRegion = _extendImage.Extend(regionRotate, _structModel.DomainSize); var normExtendRegion = NormCenter.NormCenterVector(extendRegion); foreach (var domain in _domainCollection.ToList()) { double currEqualResult = _imageEquantion.Equals(normExtendRegion, NormCenter.NormCenterVector(domain.Image, 0, true)); if (currEqualResult > bestEqualResult) { bestEqualResult = currEqualResult; resultMap[region] = new DomainMemo { Domain = domain, M = NormCenter.MO, Q = NormCenter.QD, Angle = (Angle)angle }; bestImg = domain.Image; } } } //GC.Collect(); //SimpleImageEquantion.Draw(bestImg, 1); //SimpleImageEquantion.Draw(_extendImage.Extend(region.Image, bestImg), 2); /*var imgg = _extendImage.Extend(region.Image, bestImg); SimpleImageEquantion.Draw(bestImg, 1); SimpleImageEquantion.Draw(imgg, 2); NormCenter.NormCenterVector(bestImg, 0, true); double M = NormCenter.MO; SimpleImageEquantion.Draw(bestImg, 3); SimpleImageEquantion.Draw(NormCenter.NormVectors(bestImg, imgg), 4); NormCenter.NormCenterVector(imgg, 0, true); M = NormCenter.MO; SimpleImageEquantion.Draw(NormCenter.NormVectors(imgg, bestImg), 5); SimpleImageEquantion.Draw(imgg, 6);*/ } return EqulasMap = resultMap; } public ImageModel Copy(int[,] sourceImage) { int[,] result = new int[sourceImage.GetLength(0), sourceImage.GetLength(1)]; var resultM = new StructModel(sourceImage, _structModel.RegionSize, _structModel.DomainSize, "newImg"); foreach (var region in new RegionCollection(resultM).ToList()) { var domain = EqulasMap[EqulasMap.GetRegionFromPosition(region.Position)]; var myDomain = new DomainCollection(resultM).First(x => x.Position == domain.Domain.Position); result.SetInSubMatrix(region.Position, NormCenter.NormVectors(domain, _extendImage.Compress(myDomain.Image, region.Image)).Rotate(domain.Angle)); } return new StructModel(result, _structModel.RegionSize, _structModel.DomainSize, "newImg").Image; } } } <file_sep>/MethodProgLab2VM/NormCenter.cs using MethodProgLab2VM.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MethodProgLab2VM { public class NormCenter { public static double MO { get; set; } public static double QD { get; set; } public static int[] NormCenterVector(int[] vec, double center = 0, bool withMemory = false) { double M = 1.0 * vec.Sum() / vec.Length; double Q = 1.0 * vec.Sum(x => (x - M) * (x - M)) / vec.Length; if (Q < 0.00005) Q = 1; if (withMemory) { MO = M; QD = Q; } var result = vec.Select(x => Math.Min((int)Math.Round((x - M) / Math.Sqrt(Q)), 255)).ToArray(); return result; } public static int[,] NormCenterVector(int[,] vec, double center = 0, bool withMemory = false) { return NormCenterVector(vec.ToArray(), center, withMemory).ToMatrix(vec.GetLength(0)); } public static int[,] NormVectors(DomainMemo domain, int[,] vecChange) { int[,] result = new int[vecChange.GetLength(0),vecChange.GetLength(1)]; var vec = domain.Domain.Image.ToArray(); double M1 = domain.M; double Q1 = domain.Q; var vec2 = vecChange.ToArray(); double M2 = 1.0 * vec2.Sum() / vec2.Length; double Q2 = 1.0 * vec2.Sum(x => (x - M2) * (x - M2)) / vec2.Length; if (Q2 < 0.00005) Q2 = 1; var result2 = vec2.Select(x => Math.Min((int)Math.Round((x - M2) / Math.Sqrt(Q2)), 255)).ToArray().ToMatrix(vecChange.GetLength(0)); for (int i = 0; i < vecChange.GetLength(0); i++) { for (int j = 0; j < vecChange.GetLength(1); j++) { result[i, j] = Math.Max(0, Math.Min((int)Math.Round(result2[i, j] * Q1 + M1), 255)); } } return result; } } } <file_sep>/MethodProgLab2VM/Iterators/DomainCollection.cs using MethodProgLab2VM.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; using System.Windows; namespace MethodProgLab2VM { public class DomainCollection : IList<Domain>, ICollection<Domain>, IEnumerable<Domain> { private StructModel _structModel; private object _lockingObject = new object(); private List<Domain> _domainList; public DomainCollection(StructModel structModel) { _structModel = structModel; _domainList = new List<Domain>(); for (int i = 0; i < _structModel.Image.OriginalSize.X / _structModel.DomainSize.X; i++) { for (int j = 0; j < _structModel.Image.OriginalSize.Y / _structModel.DomainSize.Y; j++) { _domainList.Add(new Domain(_structModel) { Size = _structModel.DomainSize, Name = _structModel.Name, Position = new Point(i * _structModel.DomainSize.X, j * _structModel.DomainSize.Y) }); } } } public bool IsReadOnly { get { return false; } } public bool IsFixedSize { get { return false; } } public int Count { get { return _domainList.Count; } } public object SyncRoot { get { return _lockingObject; } } public bool IsSynchronized { get { return false; } } Domain IList<Domain>.this[int index] { get { return _domainList[index]; } set { _domainList[index] = value; } } public IEnumerator GetEnumerator() { return _domainList.GetEnumerator(); } IEnumerator<Domain> IEnumerable<Domain>.GetEnumerator() { return _domainList.GetEnumerator(); } public void Clear() { _domainList.Clear(); } public void RemoveAt(int index) { _domainList.RemoveAt(index); } public int IndexOf(Domain item) { return _domainList.IndexOf(item); } public void Insert(int index, Domain item) { _domainList.Insert(index, item); } public void Add(Domain item) { _domainList.Add(item); } public bool Contains(Domain item) { return _domainList.Contains(item); } public void CopyTo(Domain[] array, int arrayIndex) { _domainList.CopyTo(array, arrayIndex); } public bool Remove(Domain item) { return _domainList.Remove(item); } } } <file_sep>/MethodProgLab2VM/ImageEquantions/IImageEquantion.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MethodProgLab2VM.ImageEquantions { public interface IImageEquantion { double Equals(int[,] image1, int[,] image2); //0..1 } }
0376ef67a2b50652cc27cc8e7472d97b2632bede
[ "C#" ]
22
C#
Arnegil/Lab2
01bdcfefa1e624fb3b5a274d2b73525bc7462ac5
e4841e8b11648123b11ea721d10edb264ce45aa7
refs/heads/master
<file_sep>package de.ma.hs.informatik.de.example; public class HelloWorld { public static void sayHello() { System.out.println("HelloWorld"); } }
038df1df54edb33ceb8365853d42736e64e4858a
[ "Java" ]
1
Java
scharon/Workshop
1dbab0fddad0e5dc3b01cd968cfbb1fcfa7ebaf8
37d5f69e61127e5391f4203a75c6ea70af358a76
refs/heads/master
<repo_name>zion-t/covid-19<file_sep>/README.md <html> <head> <meta charset="utf-8"> </head> <body> <h1>Coronavirus</h1> <ol> <li>What is COVID-19?</li> <li>Data and Graph</li> <li>Symptoms</li> </ol> <h2>What is COVID-19?</h2> <p>In <strong>December 2019</strong>, a type of <a href="https://www.hopkinsmedicine.org/health/conditions-and-diseases/coronavirus">coronavirus</a> never seen before in humans had begun to spread at Wuhan, a large city of China. Since then, the virus has spread all over the world, causing the <strong>World Health Organization (WHO)</strong> to declare a pandemic. Coronaviruses are a virus family that target mammals' respiratory systems. Previously, only two coronaviruses have caused global outbreaks: first being the <u>SARS(severe acute respiratory syndrome)</u> and the second being the <u>MERS(Middle East respiratory syndrome)</u>. </p><p style="margin-top:45px">So <u>how</u> does this virus spread? Usually, humans contract the coronavirus first due to contact with an <strong>infected animal</strong>. Although most common carriers are bats, they do not typically transmit coronaviruses to humans. The SARS coronavirus spread by civet cats while the Mers virus spread through dromedaries. The novel COVID-19 may have begun due to a seafood market in central Wuhan, but it has not been fully confirmed yet. Many other theories have also risen after the pandemic started spreading.</p> <h2>Data and Graph</h2> <p>Since the <strong>data and graph</strong> changes drastically over a short period of time, <a href="https://www.worldometers.info/coronavirus/">here</a> is the link that updates the COVID-19 case/death number every hour for each country. Also, <a href="http://publichealth.lacounty.gov/media/coronavirus/locations.htm" target=_blank"">here</a> is a website that shows LA County's COVID-19 data by including total and daily statistics.</p> <h2>Symptoms</h2> <p>Symptoms may appear two to 14 days after exposure to the virus. Although these symptoms may be easily mitaken for a regular cold, it is important to immediately contact medical care if anything seems concerning. Some very common symptoms include: <ul> <li>cough</li> <li>fever or chills</li> <li>shortness of breath/difficulty breathing</li> <li>fatigue</li> <li>muscle/body aches</li> <li>new loss of taste or smell</li> <li>sore throat</li> <li>congestion or runny nose</li> <li>nausea or vomiting</li> <li>diarrhea</li> </ul> Other symptoms that require emergency medical care immediately are: <ul> <li>trouble breathing</li> <li>new confusion</li> <li>bluish lips or face</li> <li>persistent pain or pressure in the chest</li> <li>inability to wake up or stay awake</li> </ul> </p> <img src="coronavirus 1.jpg" width="30%"> </body> </html>
180ea3706b2fb2baa554ec81e8e6db8c7c46c94a
[ "Markdown" ]
1
Markdown
zion-t/covid-19
e060bd2727d75c0d5fcef4a06895d340ae3e8783
71f9be3f9d6417d44b7fce0bf5f5925d88979f49
refs/heads/master
<file_sep># Beeru iOS with Parse Framework app in Swift
0f48b2be05d14f5cde7949659a1c74afe2873d0e
[ "Markdown" ]
1
Markdown
adheus/beeru-ios
f1e63c98a6da81260697427cdec74169436c450a
7bd426ebb10e05bffa2b39faec4d091fdab095fd
refs/heads/master
<repo_name>brdara/ehcache-aws<file_sep>/src/main/java/com/xarixa/ehcache/aws/discovery/AwsSecurityGroupAwareDiscoveryService.java package com.xarixa.ehcache.aws.discovery; import static com.google.common.base.Predicates.and; import static com.google.common.collect.Iterables.filter; import static org.jclouds.compute.predicates.NodePredicates.inGroup; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import org.jclouds.ContextBuilder; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.predicates.NodePredicates; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.sshj.config.SshjSshClientModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableSet; import com.xarixa.ehcache.aws.CachePeerHost; import com.xarixa.ehcache.aws.UpdateableHostBasedCacheManagerPeerProvider; /** * A discovery service that works against AWS security groups by discovering members of the security group. * This runs periodically in a thread through the {@link #run()} method. * * @author Fabric WorldWide */ public class AwsSecurityGroupAwareDiscoveryService extends AbstractScheduledIntervalDiscoveryService { private static final Logger LOG = LoggerFactory.getLogger(AwsSecurityGroupAwareDiscoveryService.class.getName()); private final UpdateableHostBasedCacheManagerPeerProvider updateableCacheManagerPeerProvider; private final String securityGroup; private ComputeServiceContext context; private AwsDiscoveryServiceConfig discoveryServiceConfig; public AwsSecurityGroupAwareDiscoveryService( UpdateableHostBasedCacheManagerPeerProvider updateableCacheManagerPeerProvider, ScheduledExecutorService discoveryServiceExecutor, AwsDiscoveryServiceConfig discoveryServiceConfig) { super(discoveryServiceExecutor, discoveryServiceConfig); this.updateableCacheManagerPeerProvider = updateableCacheManagerPeerProvider; this.discoveryServiceConfig = discoveryServiceConfig; // This is the security group to look for securityGroup = discoveryServiceConfig.getSecurityGroup(); } @Override protected void preStartDiscoveryService() { // Get an EC2 connection using JClouds context = ContextBuilder.newBuilder("aws-ec2") .credentials(discoveryServiceConfig.getAccessKey(), discoveryServiceConfig.getSecretKey()) .modules(ImmutableSet.of(new SLF4JLoggingModule(), new SshjSshClientModule())) .buildView(ComputeServiceContext.class); } @Override protected void postStopDiscoveryService() { context = null; } @Override public void run() { Set<CachePeerHost> cachePeerHosts = getHostsInSecurityGroup(); updateableCacheManagerPeerProvider.setCachePeerHosts(cachePeerHosts); } /** * Retrieves all of the {@link CachePeerHost} entries in the AWS security group * @return */ Set<CachePeerHost> getHostsInSecurityGroup() { // Create a query to list all of the nodes in this security group Iterable<? extends NodeMetadata> nodesInSecurityGroup = filter(context.getComputeService().listNodesDetailsMatching( NodePredicates.all()), and(inGroup(securityGroup), and(NodePredicates.RUNNING))); Iterator<? extends NodeMetadata> nodesInSecurityGroupIterator = nodesInSecurityGroup.iterator(); Set<CachePeerHost> cachePeerHosts = new HashSet<CachePeerHost>(); while (nodesInSecurityGroupIterator.hasNext()) { NodeMetadata nodeMetadata = nodesInSecurityGroupIterator.next(); // Pick the first public IP and add it to the list Iterator<String> publicIpIterator = nodeMetadata.getPublicAddresses().iterator(); if (publicIpIterator.hasNext()) { cachePeerHosts.add(new CachePeerHost(publicIpIterator.next(), discoveryServiceConfig.getRmiListenerPort())); } else { LOG.warn("No available public IP address for instance '{}', skipping this instance", nodeMetadata.getId()); } } return cachePeerHosts; } } <file_sep>/src/main/java/com/xarixa/ehcache/aws/discovery/DiscoveryServiceFactory.java package com.xarixa.ehcache.aws.discovery; import com.xarixa.ehcache.aws.UpdateableHostBasedCacheManagerPeerProvider; /** * A discovery service factory creates {@link DiscoveryService} instance(s) for the * {@link UpdateableHostBasedCacheManagerPeerProvider} to use to update. * * @author <NAME> */ public interface DiscoveryServiceFactory { DiscoveryService createDiscoveryService(UpdateableHostBasedCacheManagerPeerProvider updateableCacheManagerPeerProvider, DiscoveryServiceConfig discoveryServiceConfig); } <file_sep>/src/main/java/com/xarixa/ehcache/aws/AwsSecurityUtils.java package com.xarixa.ehcache.aws; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Properties; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Extracts the AWS access and secret key using either: * <ol> * <li>A property file named through the system property {@value #AWS_IDENTIFY_FILE} which contains properties for * the access key as either {@value #AWS_ACCESS_KEY_PROP} or {@value #AWS_ACCESS_KEY_PROP_2}, and the * secret key as either {@value #AWS_SECRET_KEY_PROP} or {@value #AWS_SECRET_KEY_PROP_2}. * <li>System properties which have been set for {@value #AWS_ACCESS_KEY_SYSTEM_PROP} and * {@value #AWS_SECRET_KEY_SYSTEM_PROP}. * </ol> * * @author Fabric WorldWide */ public final class AwsSecurityUtils { private static final Logger LOG = LoggerFactory.getLogger(AwsSecurityUtils.class.getName()); private static final String AWS_ACCESS_KEY_PROP = "accessKey"; private static final String AWS_ACCESS_KEY_PROP_2 = "access_key"; private static final String AWS_ACCESS_KEY_SYSTEM_PROP = "com.xarixa.ehcache.aws." + AWS_ACCESS_KEY_PROP; private static final String AWS_SECRET_KEY_PROP = "secretKey"; private static final String AWS_SECRET_KEY_PROP_2 = "secret_key"; private static final String AWS_SECRET_KEY_SYSTEM_PROP = "com.xarixa.ehcache.aws." + AWS_SECRET_KEY_PROP; private static final AwsSecurityUtils instance = new AwsSecurityUtils(); public static final String AWS_IDENTIFY_FILE = "com.xarixa.ehcache.aws.AwsIdentifyFile"; private Properties props; private AwsSecurityUtils() { props = new Properties(); String awsIdentifyFile = System.getProperty(AWS_IDENTIFY_FILE); // Attempt to load from the file if (StringUtils.isNotBlank(awsIdentifyFile)) { LOG.debug("Reading AWS security info from '" + awsIdentifyFile + "'"); try { props.load(new BufferedReader(new FileReader(awsIdentifyFile))); } catch (IOException e) { LOG.warn("Could not load AWS identify file '{}'", awsIdentifyFile, e); } } else { // Fallback to using system properties props.put(AWS_ACCESS_KEY_PROP, System.getProperty(AWS_ACCESS_KEY_SYSTEM_PROP)); props.put(AWS_SECRET_KEY_PROP, System.getProperty(AWS_SECRET_KEY_SYSTEM_PROP)); } } String getAwsAccessKey() { return StringUtils.defaultString((String)props.get(AWS_ACCESS_KEY_PROP), (String)props.get(AWS_ACCESS_KEY_PROP_2)); } String getAwsSecretKey() { return StringUtils.defaultString((String)props.get(AWS_SECRET_KEY_PROP), (String)props.get(AWS_SECRET_KEY_PROP_2)); } protected static AwsSecurityUtils getInstance() { return instance; } }<file_sep>/src/test/java/com/xarixa/ehcache/aws/AbstractAwsIntegrationTest.java package com.xarixa.ehcache.aws; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.jclouds.ContextBuilder; import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.domain.SecurityGroup; import org.jclouds.compute.extensions.SecurityGroupExtension; import org.jclouds.compute.predicates.NodePredicates; import org.jclouds.domain.Location; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.sshj.config.SshjSshClientModule; import org.junit.Assert; import com.google.common.collect.ImmutableSet; import com.xarixa.ehcache.aws.AwsSecurityUtils; public abstract class AbstractAwsIntegrationTest { private static SecurityGroup securityGroup; private static ComputeService computeService; private static String awsAccessKey; private static String awsSecretKey; private static String securityGroupId; public static final String AWS_EHCACHE_TEST_MARKER_GROUP = "awsehcachetestmarkergroup"; public static final String EU_WEST_1 = "eu-west-1"; public static void createTestSecurityGroup() { awsAccessKey = AwsSecurityUtils.getInstance().getAwsAccessKey(); awsSecretKey = AwsSecurityUtils.getInstance().getAwsSecretKey(); // Get an EC2 connection using JClouds computeService = ContextBuilder.newBuilder("aws-ec2") .credentials(awsAccessKey, awsSecretKey) .modules(ImmutableSet.of(new SLF4JLoggingModule(), new SshjSshClientModule())) .buildView(ComputeServiceContext.class) .getComputeService(); createSecurityGroup(); } private static void createSecurityGroup() { Location location = getDefaultLocation(); SecurityGroupExtension securityGroupExtension = computeService.getSecurityGroupExtension().get(); securityGroup = securityGroupExtension.createSecurityGroup(AWS_EHCACHE_TEST_MARKER_GROUP, location); Assert.assertNotNull(securityGroup); // JClouds returns a unique group identifier with the region as the first part, parse that out to // get the actual identifier securityGroupId = StringUtils.substringAfter(securityGroup.getId(), "/"); // IpPermission.builder().fromPort(fromPort) // securityGroupExtension.addIpPermission(ipPermission, securityGroup); } private static Location getDefaultLocation() { Set<? extends Location> locations = computeService.listAssignableLocations(); for (Location location : locations) { if (location.getId().equals(EU_WEST_1)) { return location; } } throw new RuntimeException("Could not find location " + EU_WEST_1); } public static void destroyTestSecurityGroup() { if (securityGroup != null) { // Destroy all of the nodes computeService.destroyNodesMatching(NodePredicates.inGroup(securityGroup.getName())); // Finally destroy the security group SecurityGroupExtension securityGroupExtension = computeService.getSecurityGroupExtension().get(); securityGroupExtension.removeSecurityGroup(securityGroup.getId()); } } public static SecurityGroup getSecurityGroup() { return securityGroup; } public static ComputeService getComputeService() { return computeService; } public static String getAwsAccessKey() { return awsAccessKey; } public static String getAwsSecretKey() { return awsSecretKey; } public static String getSecurityGroupId() { return securityGroupId; } } <file_sep>/src/main/java/com/xarixa/ehcache/aws/discovery/DiscoveryServiceConfig.java package com.xarixa.ehcache.aws.discovery; public interface DiscoveryServiceConfig { /** * Ths configured RMI listener port for the cache, assumes this is shared across all instances * @return */ Integer getRmiListenerPort(); /** * Validates the configuration and throws an exception if invalid */ void validate() throws IllegalArgumentException; } <file_sep>/src/main/java/com/xarixa/ehcache/aws/AwsSecurityGroupAwareCacheManagerPeerProviderMBean.java package com.xarixa.ehcache.aws; import java.util.Set; import com.xarixa.ehcache.aws.discovery.DiscoveryServiceConfig; public interface AwsSecurityGroupAwareCacheManagerPeerProviderMBean { /** * Gets the discovery service config * @return */ DiscoveryServiceConfig getDiscoveryServiceConfig(); /** * Gets the set of peer URL's * @return */ Set<String> getPeerUrls(); }<file_sep>/src/test/java/com/xarixa/ehcache/aws/AwsSecurityGroupAwareCacheManagerPeerProviderTest.java package com.xarixa.ehcache.aws; import java.net.MalformedURLException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.distribution.CachePeer; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.Sequence; import org.jmock.integration.junit4.JMock; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.reflect.internal.WhiteboxImpl; import com.xarixa.ehcache.aws.discovery.DiscoveryService; import com.xarixa.ehcache.aws.discovery.DiscoveryServiceConfig; import com.xarixa.ehcache.aws.discovery.DiscoveryServiceFactory; @RunWith(JMock.class) public class AwsSecurityGroupAwareCacheManagerPeerProviderTest { private static final String CACHE_PEERS_MAP_VARIABLE_NAME = "cachePeers"; private static final String PEER_URLS_SET_VARIABLE_NAME = "peerUrls"; private Mockery context = new Mockery() {{ setImposteriser(ClassImposteriser.INSTANCE); }}; private TestWithoutRmiLookupAwsSecurityGroupAwareCacheManagerPeerProvider peerProvider; private DiscoveryServiceFactory discoveryServiceFactory; private DiscoveryServiceConfig discoveryServiceConfig; @Before public void setUp() { discoveryServiceFactory = context.mock(DiscoveryServiceFactory.class); discoveryServiceConfig = context.mock(DiscoveryServiceConfig.class); context.checking(new Expectations() {{ atMost(1).of(discoveryServiceConfig).validate(); }}); peerProvider = new TestWithoutRmiLookupAwsSecurityGroupAwareCacheManagerPeerProvider( discoveryServiceConfig, discoveryServiceFactory); } @Test public void testThatInitSetsTheActiveStatusAndInitialisesTheDiscoveryService() { invokeInitAndCheckDiscoveryServiceHasBeenStarted(); } @Test public void testThatDisposeUnsetsTheActiveStatusAndStopsTheDiscoveryService() { final DiscoveryService discoveryService = context.mock(DiscoveryService.class); final Sequence seq = context.sequence("StartStopSequence"); context.checking(new Expectations() {{ atMost(1).of(discoveryServiceFactory).createDiscoveryService(peerProvider, discoveryServiceConfig); inSequence(seq); atMost(1).of(discoveryService).startDiscoveryService(); inSequence(seq); atMost(1).of(discoveryService).stopDiscoveryService(); inSequence(seq); }}); peerProvider.init(); Assert.assertTrue(peerProvider.isActive()); peerProvider.dispose(); Assert.assertFalse(peerProvider.isActive()); } @Test public void testSetCachePeerHostsSetsANewListOfHosts() { invokeInitAndCheckDiscoveryServiceHasBeenStarted(); context.checking(new Expectations() {{ allowing(discoveryServiceConfig).getRmiListenerPort(); will(returnValue(61616)); }}); // Make sure that the initial list is empty Assert.assertTrue(((Set<String>)WhiteboxImpl.getInternalState(peerProvider, PEER_URLS_SET_VARIABLE_NAME)).isEmpty()); // Set up a list of hosts. Because these hosts are actually resolved they need to be real. Set<CachePeerHost> cachePeerHosts = new HashSet<>(); cachePeerHosts.add(new CachePeerHost("www.google.com", 61616)); cachePeerHosts.add(new CachePeerHost("www.yahoo.com", 61618)); // Set the hosts peerProvider.setCachePeerHosts(cachePeerHosts); // Check that RMI URL's should be formed from the values Set<String> peerUrls = (Set<String>)WhiteboxImpl.getInternalState(peerProvider, PEER_URLS_SET_VARIABLE_NAME); Assert.assertEquals(2, peerUrls.size()); Assert.assertTrue(peerUrls.contains("//www.google.com:61616")); Assert.assertTrue(peerUrls.contains("//www.yahoo.com:61618")); } @Test public void testSetCachePeerHostsUpdatesTheSetOfHostsWhenAHostHasBeenRemoved() { invokeInitAndCheckDiscoveryServiceHasBeenStarted(); context.checking(new Expectations() {{ allowing(discoveryServiceConfig).getRmiListenerPort(); will(returnValue(61616)); }}); // Set up a list of hosts. Because these hosts are actually resolved they need to be real. Set<CachePeerHost> cachePeerHosts = new HashSet<>(); CachePeerHost googleCachePeerHost = new CachePeerHost("www.google.com", 61616); cachePeerHosts.add(googleCachePeerHost); CachePeerHost yahooCachePeerHost = new CachePeerHost("www.yahoo.com", 61618); cachePeerHosts.add(yahooCachePeerHost); // Set the hosts peerProvider.setCachePeerHosts(cachePeerHosts); // Check that RMI URL's should be formed from the values Set<String> peerUrls = (Set<String>)WhiteboxImpl.getInternalState(peerProvider, PEER_URLS_SET_VARIABLE_NAME); Assert.assertEquals(2, peerUrls.size()); Assert.assertTrue(peerUrls.contains("//www.google.com:61616")); Assert.assertTrue(peerUrls.contains("//www.yahoo.com:61618")); // Remove the first one so that we should only have one in the list and set this Assert.assertTrue(cachePeerHosts.remove(googleCachePeerHost)); peerProvider.setCachePeerHosts(cachePeerHosts); // Check that RMI URL's should be formed from the values peerUrls = (Set<String>)WhiteboxImpl.getInternalState(peerProvider, PEER_URLS_SET_VARIABLE_NAME); Assert.assertEquals(1, peerUrls.size()); Assert.assertTrue(peerUrls.contains("//www.yahoo.com:61618")); } @Test public void testListRemoteCachePeersBeforeAnythingHasBeenSetReturnsAnEmptyUnmodifiableList() { invokeInitAndCheckDiscoveryServiceHasBeenStarted(); final Ehcache cache = context.mock(Ehcache.class); context.checking(new Expectations() {{ allowing(cache).getName(); will(returnValue("myCache")); }}); // Now list the peers, which should create a new entry in the map and return a list of CachePeer's List<CachePeer> listRemoteCachePeers = peerProvider.listRemoteCachePeers(cache); Assert.assertTrue(listRemoteCachePeers.isEmpty()); try { listRemoteCachePeers.add(context.mock(CachePeer.class, "dummyCachePeer")); Assert.fail("Did not expect to be able to add a member to the cache peers list that was returned"); } catch (UnsupportedOperationException e) { // OK } } @Test public void testListRemoteCachePeersReturnsAListofPeersPerCacheAndUpdatesTheInternalMap() { invokeInitAndCheckDiscoveryServiceHasBeenStarted(); // Mock some stuff up final Ehcache cache = context.mock(Ehcache.class); final CachePeer googleCacheRemote = context.mock(CachePeer.class, "googleCacheRemote"); final CachePeer yahooCacheRemote = context.mock(CachePeer.class, "yahooCacheRemote"); // We are expecting RMI Naming.lookup calls to these URL's for the cache final String cacheName = "myCache"; peerProvider.addCachePeerPerUrl("//www.google.com:61616/" + cacheName, googleCacheRemote); peerProvider.addCachePeerPerUrl("//www.yahoo.com:61618/" + cacheName, yahooCacheRemote); context.checking(new Expectations() {{ allowing(discoveryServiceConfig).getRmiListenerPort(); will(returnValue(61616)); allowing(cache).getName(); will(returnValue(cacheName)); }}); // Make sure that the initial list is empty Assert.assertTrue(((Map<String,List<CachePeer>>)WhiteboxImpl.getInternalState(peerProvider, CACHE_PEERS_MAP_VARIABLE_NAME)).isEmpty()); // Set up a list of hosts. Because these hosts are actually resolved they need to be real. Set<CachePeerHost> cachePeerHosts = new HashSet<>(); cachePeerHosts.add(new CachePeerHost("www.google.com", 61616)); cachePeerHosts.add(new CachePeerHost("www.yahoo.com", 61618)); // Set the hosts peerProvider.setCachePeerHosts(cachePeerHosts); // Now list the peers, which should create a new entry in the map and return a list of CachePeer's List<CachePeer> listRemoteCachePeers = peerProvider.listRemoteCachePeers(cache); Assert.assertEquals(2, listRemoteCachePeers.size()); Assert.assertTrue(listRemoteCachePeers.contains(googleCacheRemote)); Assert.assertTrue(listRemoteCachePeers.contains(yahooCacheRemote)); try { listRemoteCachePeers.add(context.mock(CachePeer.class, "dummyCachePeer")); Assert.fail("Did not expect to be able to add a member to the cache peers list that was returned"); } catch (UnsupportedOperationException e) { // OK } // Check that the cache has also been populated with this list Map<String,List<CachePeer>> cachePeers = (Map<String,List<CachePeer>>)WhiteboxImpl.getInternalState(peerProvider, CACHE_PEERS_MAP_VARIABLE_NAME); Assert.assertEquals(1, cachePeers.size()); Assert.assertEquals(listRemoteCachePeers, cachePeers.get(cacheName)); // Another invocation should return exactly the same object, i.e. this list should not be recreated Assert.assertEquals(listRemoteCachePeers.hashCode(), peerProvider.listRemoteCachePeers(cache).hashCode()); } @Test public void testListRemoteCachePeersCreatesANewListWhenAHostHasBeenRemoved() { invokeInitAndCheckDiscoveryServiceHasBeenStarted(); // Mock some stuff up final Ehcache cache = context.mock(Ehcache.class); final CachePeer googleCacheRemote = context.mock(CachePeer.class, "googleCacheRemote"); final CachePeer yahooCacheRemote = context.mock(CachePeer.class, "yahooCacheRemote"); // We are expecting RMI Naming.lookup calls to these URL's for the cache final String cacheName = "myCache"; peerProvider.addCachePeerPerUrl("//www.google.com:61616/" + cacheName, googleCacheRemote); peerProvider.addCachePeerPerUrl("//www.yahoo.com:61618/" + cacheName, yahooCacheRemote); context.checking(new Expectations() {{ allowing(discoveryServiceConfig).getRmiListenerPort(); will(returnValue(61616)); allowing(cache).getName(); will(returnValue(cacheName)); }}); // Make sure that the initial list is empty Assert.assertTrue(((Map<String,List<CachePeer>>)WhiteboxImpl.getInternalState(peerProvider, CACHE_PEERS_MAP_VARIABLE_NAME)).isEmpty()); // Set up a list of hosts. Because these hosts are actually resolved they need to be real. Set<CachePeerHost> cachePeerHosts = new HashSet<>(); CachePeerHost googleCachePeerHost = new CachePeerHost("www.google.com", 61616); cachePeerHosts.add(googleCachePeerHost); CachePeerHost yahooCachePeerHost = new CachePeerHost("www.yahoo.com", 61618); cachePeerHosts.add(yahooCachePeerHost); // Set the hosts peerProvider.setCachePeerHosts(cachePeerHosts); // Now list the peers, which should create a new entry in the map and return a list of CachePeer's List<CachePeer> listRemoteCachePeers = peerProvider.listRemoteCachePeers(cache); Assert.assertEquals(2, listRemoteCachePeers.size()); Assert.assertTrue(listRemoteCachePeers.contains(googleCacheRemote)); Assert.assertTrue(listRemoteCachePeers.contains(yahooCacheRemote)); // Now remove google cache peer Assert.assertTrue(cachePeerHosts.remove(googleCachePeerHost)); peerProvider.setCachePeerHosts(cachePeerHosts); listRemoteCachePeers = peerProvider.listRemoteCachePeers(cache); Assert.assertEquals(1, listRemoteCachePeers.size()); Assert.assertTrue(listRemoteCachePeers.contains(yahooCacheRemote)); } private void invokeInitAndCheckDiscoveryServiceHasBeenStarted() { final DiscoveryService discoveryService = context.mock(DiscoveryService.class); context.checking(new Expectations() {{ atMost(1).of(discoveryServiceFactory).createDiscoveryService(peerProvider, discoveryServiceConfig); atMost(1).of(discoveryService).startDiscoveryService(); }}); peerProvider.init(); Assert.assertTrue(peerProvider.isActive()); } private class TestWithoutRmiLookupAwsSecurityGroupAwareCacheManagerPeerProvider extends AwsSecurityGroupAwareCacheManagerPeerProvider { private Map<String,CachePeer> cachePeersPerUrlMap = new HashMap<String,CachePeer>(); public TestWithoutRmiLookupAwsSecurityGroupAwareCacheManagerPeerProvider( CacheManager cacheManager) { super(cacheManager); } public TestWithoutRmiLookupAwsSecurityGroupAwareCacheManagerPeerProvider( DiscoveryServiceConfig discoveryServiceConfig, DiscoveryServiceFactory discoveryServiceFactory) { super(discoveryServiceConfig, discoveryServiceFactory); } private void addCachePeerPerUrl(String url, CachePeer cachePeer) { cachePeersPerUrlMap.put(url, cachePeer); } /** * Override this method which does RMI lookups */ @Override public CachePeer lookupRemoteCachePeer(String url) throws MalformedURLException, NotBoundException, RemoteException { CachePeer cachePeer = cachePeersPerUrlMap.get(url); Assert.assertNotNull("The cache peer for URL '" + url + "' has not been set up in the test", cachePeer); return cachePeer; } } } <file_sep>/src/main/resources/log4j.properties log4j.rootCategory=INFO, R log4j.appender.R=org.apache.log4j.ConsoleAppender log4j.appender.R.File=test.log log4j.appender.R.Append=false log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %p [%c:%L] - %m%n log4j.logger.com.xarixa.ehcache.aws=INFO <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xarixa.ehcache.aws</groupId> <artifactId>aws-ehcache-discovery</artifactId> <version>0.1</version> <name>AWS EhCache Discovery</name> <description>Discovery mechanism for EhCache across AWS environments where UDP is not available</description> <packaging>jar</packaging> <properties> <ehcache.version>2.7.1</ehcache.version> <jclouds.version>1.8.1</jclouds.version> <commons-lang.version>3.3.2</commons-lang.version> <slf4j.version>1.7.7</slf4j.version> <jmock.version>2.5.1</jmock.version> <junit.version>4.9</junit.version> <powermock.version>1.5</powermock.version> <!-- Set to true on the command line to skip the integration tests. An AWS account is required for the integration tests, see below. --> <skipIntegrationTests>false</skipIntegrationTests> <!-- Set this property on the command line to set up your own properties file which contains accessKey and secretKey to be used in the integration tests. The AwsSecurityGroupAwareDiscoveryServiceIntegrationTest sets up a security group and AWS instances to check that the security group can be read. --> <awsIdentifyFile>/Work/aws-development.properties</awsIdentifyFile> </properties> <repositories> <repository> <id>maven-central</id> <url>http://central.maven.org/maven2/</url> </repository> <repository> <id>jboss</id> <url>https://repository.jboss.org/nexus</url> </repository> </repositories> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <!-- Configure surefire to run integration tests in the verify phase only --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> <configuration> <argLine>-Dcom.xarixa.ehcache.aws.AwsIdentifyFile=${awsIdentifyFile}</argLine> </configuration> <executions> <execution> <id>unit-tests</id> <phase>test</phase> <goals> <goal>test</goal> </goals> <configuration> <skip>${skipUnitTests}</skip> <excludes> <exclude>**/*IntegrationTest.class</exclude> </excludes> </configuration> </execution> <execution> <id>integration-tests</id> <phase>integration-test</phase> <goals> <goal>test</goal> </goals> <configuration> <skip>${skipIntegrationTests}</skip> <excludes> <exclude>none</exclude> </excludes> <includes> <include>**/*IntegrationTest.class</include> </includes> </configuration> </execution> </executions> </plugin> <!-- Copy all of the dependencies --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.9</version> <executions> <execution> <id>copy-dependencies</id> <phase>install</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/jar-dependencies</outputDirectory> <overWriteReleases>false</overWriteReleases> <overWriteSnapshots>false</overWriteSnapshots> <overWriteIfNewer>true</overWriteIfNewer> <scope>runtime</scope> </configuration> </execution> </executions> </plugin> <!-- Now create a zip containing the dependencies --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.4.1</version> <configuration> <appendAssemblyId>false</appendAssemblyId> <finalName>${project.artifactId}-dependencies-${project.version}</finalName> <descriptors> <descriptor>assembly.xml</descriptor> </descriptors> </configuration> <executions> <execution> <id>make-assembly</id> <phase>install</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <dependencies> <!-- Test dependencies --> <dependency> <artifactId>junit</artifactId> <groupId>junit</groupId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jmock</groupId> <artifactId>jmock</artifactId> <version>${jmock.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jmock</groupId> <artifactId>jmock-junit4</artifactId> <version>${jmock.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jmock</groupId> <artifactId>jmock-legacy</artifactId> <version>${jmock.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-reflect</artifactId> <version>${powermock.version}</version> <scope>test</scope> </dependency> <!-- Log dependencies --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- EhCache --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> <scope>provided</scope> </dependency> <!-- Misc --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang.version}</version> </dependency> <!-- JClouds --> <dependency> <groupId>org.apache.jclouds</groupId> <artifactId>jclouds-all</artifactId> <version>${jclouds.version}</version> </dependency> <dependency> <groupId>org.apache.jclouds.driver</groupId> <artifactId>jclouds-sshj</artifactId> <version>${jclouds.version}</version> </dependency> <dependency> <groupId>org.apache.jclouds.driver</groupId> <artifactId>jclouds-slf4j</artifactId> <version>${jclouds.version}</version> </dependency> </dependencies> </project>
9a5fab213cb25d6f0efab86fcfe229b9dfc7570e
[ "Java", "INI", "Maven POM" ]
9
Java
brdara/ehcache-aws
d646616d35363be35222637e93ae6a5f6d38d4b0
2e0f3d2dcc32d3ab3353dcffa1804a8a01a7fc72
refs/heads/master
<repo_name>camilamdaniels/Redux-II-Mini<file_sep>/src/Chars.js import React from 'react'; const Chars = props => { return ( <ul> {props.chars.map(char => { return <li key={char.name}>{char.name}</li>; })} </ul> ); }; export default Chars;<file_sep>/src/components/App.js import React, { Component } from 'react'; import logo from '../logo.svg'; import '../styles/App.css'; import { connect } from 'react-redux'; // pull in actions from action/index import { IS_FETCHING, CHARS_FETCHED, ERROR_FETCHING_CHARS, getChars } from '../actions/index.js'; import Chars from '../Chars'; class App extends Component { componentDidMount() { // call our action // console.log(this.props); this.props.getChars(); } render() { const { chars } = this.props; return ( <div className="App"> {this.props.fetching ? ( <img src={logo} className="App-logo" alt="logo" /> ) : null} <Chars chars={chars} /> </div> ); } } // our mapDispatchToProps needs to have two properties inherited from state // the chars and the fetching boolean const mapDispatchToProps = state => { // console.log(state); return { chars: state.chars, fetching: state.fetching, error: state.error } } export default connect(mapDispatchToProps, { getChars })(App);
91c78e37834df08ba13ec95ecae4bf31a8ce83b3
[ "JavaScript" ]
2
JavaScript
camilamdaniels/Redux-II-Mini
4a5ba812cd025278722f9c29c2fc812dde0bad0c
40a8af8a31d41a0ee840011ca6f4274fac423df4
refs/heads/master
<repo_name>barto14753/AgarIO<file_sep>/Menu.cpp // // Created by <NAME> on 06/06/2021. // #include "Menu.h" int Menu::renderMenu(sf::RenderWindow &window) { while (window.isOpen()) { sf::Event event; sf::Vector2i pos; while (window.pollEvent(event)) { pos = sf::Mouse::getPosition(window); currentButton = getButton(pos.x, pos.y); if (event.type == sf::Event::Closed) window.close(); } if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { switch(currentButton) { case START: return 0; case QUIT: return 1; } } window.clear(); window.draw(title); window.draw(startButton); window.draw(quitButton); window.display(); } } Menu::Menu() : currentButton(NONE) { font.loadFromFile("../font.ttf"); title.setFont(font); startButton.setFont(font); quitButton.setFont(font); title.setCharacterSize(120); startButton.setCharacterSize(80); quitButton.setCharacterSize(80); title.setString("Agar.io"); startButton.setString("Start"); quitButton.setString("Quit"); title.setFillColor(sf::Color::White); startButton.setFillColor(sf::Color::White); quitButton.setFillColor(sf::Color::White); title.setPosition(700,100); startButton.setPosition(800,500); quitButton.setPosition(815, 800); } Button Menu::getButton(float x, float y) { //f("GET (%f, %f)\n", x, y); float startX = x - startButton.getPosition().x; float startY = y - startButton.getPosition().y; float quitX = x - quitButton.getPosition().x; float quitY = y - quitButton.getPosition().y; if(startX > 0 && startY > 0 && startX < startButton.getGlobalBounds().width && startY < startButton.getGlobalBounds().height) { //printf("START\n"); startButton.setFillColor(sf::Color::Red); quitButton.setFillColor(sf::Color::White); return START; } else if(quitX > 0 && quitY > 0 && quitX < quitButton.getGlobalBounds().width && quitY < quitButton.getGlobalBounds().height) { //printf("QUIT\n"); startButton.setFillColor(sf::Color::White); quitButton.setFillColor(sf::Color::Red); return QUIT; } else { startButton.setFillColor(sf::Color::White); quitButton.setFillColor(sf::Color::White); return NONE; } } <file_sep>/Highscore.cpp // // Created by <NAME> on 06/06/2021. // #include "Highscore.h" bool compareInterval(Player p1, Player p2) { return (p1.getSize() > p2.getSize()); } sf::Text Highscore::createHighscore(std::vector<Player> players, Player player) { std::sort(players.begin(), players.end(), compareInterval); bool playerOut = true; std::string text = "Highscore:"; for(int i=0; i<players.size() && i<TOP_PLAYERS; i++) { if(player.getSize() >= players[i].getSize() && playerOut) { playerOut = false; text += "\n " + player.getNick() + " : " + std::to_string(player.getSize()); if(i == players.size() - 1) break; } text += "\n " + players[i].getNick() + " : " + std::to_string(players[i].getSize()); } if(playerOut) { text += "\n " + player.getNick() + " : " + std::to_string(player.getSize()); } sf::Text highscore; highscore.setFont(font); highscore.setCharacterSize(32); highscore.setString(text); highscore.setFillColor(sf::Color::White); highscore.setPosition(POS_X, POS_Y); return highscore; } Highscore::Highscore() { font.loadFromFile("../font.ttf"); } <file_sep>/main.cpp #include <SFML/Graphics.hpp> #include "Game.h" int main() { Game game(1800,1200); game.run(); } <file_sep>/Result.cpp // // Created by <NAME> on 06/06/2021. // #include "Result.h" Result::Result(std::string message, int score) { font.loadFromFile("../font.ttf"); title.setFont(font); result.setFont(font); callToAction.setFont(font); title.setCharacterSize(120); result.setCharacterSize(80); callToAction.setCharacterSize(80); title.setString(message); result.setString("Score: " + std::to_string(score)); callToAction.setString("Press Space"); title.setFillColor(sf::Color::White); result.setFillColor(sf::Color::White); callToAction.setFillColor(sf::Color::White); title.setPosition(650,100); result.setPosition(715,500); callToAction.setPosition(675, 800); } int Result::renderResult(sf::RenderWindow &window) { while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Space) return 0; } } window.clear(); window.draw(title); window.draw(result); window.draw(callToAction); window.display(); } return 0; } <file_sep>/Menu.h // // Created by <NAME> on 06/06/2021. // #ifndef AGARIO_MENU_H #define AGARIO_MENU_H #include <SFML/Graphics.hpp> enum Button{START, QUIT, NONE}; class Menu { private: sf::Text title; sf::Text startButton; sf::Text quitButton; sf::Font font; Button currentButton; public: Menu(); int renderMenu(sf::RenderWindow& window); Button getButton(float x, float y); }; #endif //AGARIO_MENU_H <file_sep>/Dot.cpp // // Created by <NAME> on 06/06/2021. // #include "Dot.h" Dot::Dot(float x, float y, float s=10) { this->posX = x; this->posY = y; this->size = s; this->color = sf::Color(rand() % 256, rand() % 256, rand() % 256); this->dot.setRadius(size); this->dot.setPosition(x,y); this->dot.setFillColor(this->color); } void Dot::update() { this->dot.setRadius(this->size); this->dot.setPosition(this->posX, this->posY); this->dot.setFillColor(this->color); } sf::CircleShape Dot::getShape(float x, float y) { this->update(); sf::CircleShape c(size); c.setFillColor(color); c.setPosition(posX - x, posY - y); c.setOrigin(size/2, size/2); return c; } <file_sep>/Game.h // // Created by <NAME> on 06/06/2021. // #ifndef AGARIO_GAME_H #define AGARIO_GAME_H #include <SFML/Graphics.hpp> #include "Player.h" #include <stdio.h> /* printf, scanf, puts, NULL */ #include <stdlib.h> /* srand, rand */ #include <time.h> #include "Highscore.h" #include "Menu.h" #include "Result.h" #define BORDER_WIDTH 10000 #define BORDER_HEIGHT 10000 #define START_DOTS_COUNT 500 #define DOT_SIZE 10 #define FRAME_STOP 100 #define BOTS_COUNT 10 enum GameResult{WIN, LOSS, UNKNOWN}; class Game{ private: int width; int height; static int borderWidth; static int borderHeight; std::vector<Dot> dots; std::vector<Player> bots; Player player; Highscore highscore; Menu menu; bool menuOpen; public: sf::RenderWindow window; Game(int width, int height); void drawDots(); static void repairPos(float &x, float &y, float size); void run(); void collisions(); void addRandomDot(); void simulateBots(); void drawPlayers(); void endGame(GameResult result); GameResult isSomeoneWinner(); }; #endif //AGARIO_GAME_H <file_sep>/Player.cpp // // Created by <NAME> on 06/06/2021. // #include "Player.h" #include "Game.h" void Player::moveUp() { posY -= MAX_SPEED; this->repairPos(); } void Player::moveDown() { posY += MAX_SPEED; this->repairPos(); } void Player::moveLeft() { posX -= MAX_SPEED; this->repairPos(); } void Player::moveRight() { posX += MAX_SPEED; this->repairPos(); } void Player::repairPos() { Game::repairPos(this->posX, this->posY, this->size); } sf::CircleShape Player::getShape(float width, float height) { this->update(); sf::CircleShape c(size); c.setFillColor(color); c.setOrigin(size, size); c.setPosition(width/2, height/2); return c; } void Player::addSize(Dot d) { size += d.getSize() * GROWTH_RATE; if(size > MAX_SIZE) size = MAX_SIZE; } float getTangens(Dot p, Dot d) { float xDiff = p.getPosX() - d.getPosX(); float yDiff = p.getPosY() - d.getPosY(); return yDiff/xDiff; } float distance(Player p, Player d) { float xDiff = p.getPosX() - d.getPosX(); float yDiff = p.getPosY() - d.getPosY(); return sqrt(xDiff * xDiff + yDiff * yDiff); } Direction getDirection(Player p, Player d) { float tangens = getTangens(p, d); if(tangens >= tan((-1/16)*2*M_PI) && tangens <= tan((1/16)*2*M_PI)) return RIGHT; else if(tangens >= tan((1/16)*2*M_PI) && tangens <= tan((3/16)*2*M_PI)) return UPRIGHT; else if(tangens >= tan((3/16)*2*M_PI) && tangens <= tan((5/16)*2*M_PI)) return UP; else if(tangens >= tan((5/16)*2*M_PI) && tangens <= tan((7/16)*2*M_PI)) return UPLEFT; else if(tangens >= tan((7/16)*2*M_PI) && tangens <= tan((9/16)*2*M_PI)) return LEFT; else if(tangens >= tan((9/16)*2*M_PI) && tangens <= tan((11/16)*2*M_PI)) return DOWNLEFT; else if(tangens >= tan((11/16)*2*M_PI) && tangens <= tan((13/16)*2*M_PI)) return DOWN; else if(tangens >= tan((13/16)*2*M_PI) && tangens <= tan((15/16)*2*M_PI)) return DOWNRIGHT; return UP; } Direction oppositeDirection(Direction dir) { switch(dir) { case RIGHT: return LEFT; case UPRIGHT: return DOWNLEFT; case UP: return DOWN; case UPLEFT: return DOWNRIGHT; case LEFT: return RIGHT; case DOWNLEFT: return UPRIGHT; case DOWN: return UP; case DOWNRIGHT: return UPLEFT; } } bool compareAscending(Player player, Player player1, Player player2) { return distance(player, player1) < distance(player, player2); } // void Player::moveToDirection(Direction dir) { switch(dir) { case RIGHT: {moveRight(); break;} case UPRIGHT: {moveUp(); moveRight(); break;} case UP: {moveUp(); break;} case UPLEFT: {moveUp(), moveLeft(); break;} case LEFT: {moveLeft(); break;} case DOWNLEFT: {moveDown(); moveLeft(); break;} case DOWN: {moveDown(); break;} case DOWNRIGHT: {moveDown(); moveRight(); break;} } } sf::CircleShape Player::getBotShape(float x, float y) { this->update(); sf::CircleShape c(size); c.setFillColor(color); c.setPosition(posX - x, posY - y); c.setOrigin(size/2, size/2); return c; } Direction randomDirection() { return Direction(rand() % LAST); } int randomTime() { int r = rand() % (MAX_MOVE_TICKS - MIN_MOVE_TICKS); return r + MIN_MOVE_TICKS; } void Player::randomMove() { if(moveTicksLast <= 0) { currentMove = randomDirection(); moveTicksLast = randomTime(); } moveToDirection(currentMove); moveTicksLast--; } // TODO: More sophisticated randomMove() void Player::randomMove(std::vector<Player> players, int index) { std::vector<Player> weakerPlayers; int nearestStronger = index; for(int i=0; i<players.size(); i++) { if(i == index) continue; if(players[i].getSize() < this->getSize()) weakerPlayers.push_back(players[i]); if(players[i].getSize() >= players[nearestStronger].getSize()) nearestStronger = i; } //std::sort(weakerPlayers.begin(), weakerPlayers.end(), std::bind(compareAscending, this, std::placeholders::_1, std::placeholders::_2)); if(nearestStronger != index) { Direction dangerDir = getDirection(*this, players[nearestStronger]); for(unsigned int i=0; i<weakerPlayers.size(); i++) { Direction playerDir = getDirection(*this, weakerPlayers[i]); if(playerDir == dangerDir) { weakerPlayers.erase(weakerPlayers.begin() + i); i--; } else { break; } } if(!weakerPlayers.empty()) { Direction dir = getDirection(*this, weakerPlayers[0]); this->moveToDirection(dir); } else { this->moveToDirection(oppositeDirection(getDirection(*this, players[nearestStronger]))); } } else { if(!weakerPlayers.empty()) this->moveToDirection(getDirection(*this, weakerPlayers[0])); else { return; } } //TODO - sorting weakerPlayers -> founding nearest danger -> deleting weakerPlayers with } <file_sep>/Player.h // // Created by <NAME> on 06/06/2021. // #ifndef AGARIO_PLAYER_H #define AGARIO_PLAYER_H #include "Dot.h" #define MAX_SPEED 10.0 #define INIT_SIZE 30.0 #define MAX_SIZE 600.0 #define GROWTH_RATE 1.0 #define MAX_MOVE_TICKS 100 #define MIN_MOVE_TICKS 10 enum Direction{UP, DOWN, LEFT, RIGHT, UPLEFT, UPRIGHT, DOWNLEFT, DOWNRIGHT, LAST}; class Player : public Dot{ std::string nick; Direction currentMove; int moveTicksLast; public: Player(float x, float y, std::string nick) : Dot(x, y, INIT_SIZE), nick(nick), moveTicksLast(0) {} void moveUp(); void moveDown(); void moveLeft(); void moveRight(); void repairPos(); sf::CircleShape getShape(float width, float hegiht); sf::CircleShape getBotShape(float x, float y); void addSize(Dot d); void randomMove(std::vector<Player> players, int index); void randomMove(); void moveToDirection(Direction dir); std::string getNick() { return nick; }; }; #endif //AGARIO_PLAYER_H <file_sep>/Dot.h // // Created by <NAME> on 06/06/2021. // #ifndef AGARIO_DOT_H #define AGARIO_DOT_H #include <SFML/Graphics.hpp> class Dot { protected: float posX; float posY; float size; sf::Color color; sf::CircleShape dot; public: Dot(float x, float y, float s); float getPosX() { return this->posX; } float getPosY() { return this->posY; } float getSize() { return this->size; }; sf::CircleShape getShape(float x, float y); void update(); }; #endif //AGARIO_DOT_H <file_sep>/Highscore.h // // Created by <NAME> on 06/06/2021. // #ifndef AGARIO_HIGHSCORE_H #define AGARIO_HIGHSCORE_H #include <SFML/Graphics.hpp> #include "Player.h" #define TOP_PLAYERS 5 #define POS_X 30.0 #define POS_Y 10.0 class Highscore { private: sf::Font font; public: Highscore(); sf::Text createHighscore(std::vector<Player> players, Player player); }; #endif //AGARIO_HIGHSCORE_H <file_sep>/Result.h // // Created by <NAME> on 06/06/2021. // #ifndef AGARIO_RESULT_H #define AGARIO_RESULT_H #include <SFML/Graphics.hpp> class Result { private: sf::Text title; sf::Text result; sf::Text callToAction; sf::Font font; public: Result(std::string message, int score); int renderResult(sf::RenderWindow& window); }; #endif //AGARIO_RESULT_H <file_sep>/README.md # AgarIO ## Description ### Inspiration AgarIO is my own variation of popular browser game called agar.io. ### Gameplay You play as a small dot at the beginning and you can eat static dots with same size or other players(bots) to become bigger. You also can be eaten by other players so take care. ### Win/Lose conditions You win when you become last alive or you get max score first. You lose when you got eaten or someone got max score before you. ### Highscore You can see how big you and your opponents are on highscore placed in top-left corner. ### Result After win/lose it shows up result screen which inform about your result and score. ### In-game <img width="898" alt="Zrzut ekranu 2021-06-9 o 21 00 55" src="https://user-images.githubusercontent.com/56938330/121413914-77e0cb00-c966-11eb-8c9c-387b314dbcd0.png"> <img width="902" alt="Zrzut ekranu 2021-06-9 o 21 05 16" src="https://user-images.githubusercontent.com/56938330/121413938-7d3e1580-c966-11eb-9a3d-842f71b5d4f2.png"> <img width="905" alt="Zrzut ekranu 2021-06-9 o 21 05 25" src="https://user-images.githubusercontent.com/56938330/121413958-816a3300-c966-11eb-87cb-2effccbea0a9.png"> ## Technologies Project is created with: * C++14 * SFML ## Setup To run this project you need SFML * macOS ``` $ brew install sfml ``` * Linux ``` $ sudo apt-get install libsfml-dev ``` <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.14) project(AgarIO) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") set(SOURCE_FILES main.cpp Game.cpp Game.h Dot.cpp Dot.h Player.cpp Player.h Highscore.cpp Highscore.h Menu.cpp Menu.h Result.cpp Result.h) add_executable(AgarIO ${SOURCE_FILES}) include_directories(/usr/local/include) find_package(SFML 2.5 COMPONENTS system window graphics network audio REQUIRED) include_directories(${SFML_INCLUDE_DIRS}) target_link_libraries(AgarIO sfml-system sfml-window sfml-graphics sfml-audio sfml-network)<file_sep>/Game.cpp // // Created by <NAME> on 06/06/2021. // #include "Game.h" Game::Game(int width, int height) : width(width), height(height), window(sf::VideoMode(width,height,64), "Agar.io"), player(Player(2500,2500,"Player")), highscore(Highscore()), menu(Menu()), menuOpen(true) { srand(time(nullptr)); for(int i=0; i<START_DOTS_COUNT; i++) { addRandomDot(); } bots.push_back(player); for(int i=0; i<BOTS_COUNT; i++) { bots.push_back(Player(rand() % borderWidth, rand() % borderHeight, "Bot " + std::to_string(i+1))); } } int randomSign() { if(rand()%2 == 0) return 1; return -1; } void Game::run() { while (window.isOpen()) { if(menuOpen) { if(menu.renderMenu(window) == 1) return; menuOpen = false; } sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up) || sf::Keyboard::isKeyPressed(sf::Keyboard::W)) player.moveUp(); if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down) || sf::Keyboard::isKeyPressed(sf::Keyboard::S)) player.moveDown(); if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::A)) player.moveLeft(); if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right) || sf::Keyboard::isKeyPressed(sf::Keyboard::D)) player.moveRight(); window.clear(); simulateBots(); collisions(); drawPlayers(); drawDots(); window.draw(highscore.createHighscore(bots, player)); window.display(); sf::sleep(sf::microseconds(FRAME_STOP)); GameResult result = isSomeoneWinner(); if(bots.size() == 0 || result == WIN) endGame(WIN); else if(result == LOSS) endGame(LOSS); } } void Game::drawDots() { for(Dot dot: dots) { window.draw(dot.getShape(player.getPosX() - (width/2), player.getPosY() - (height/2))); } } int Game::borderWidth = BORDER_WIDTH; int Game::borderHeight = BORDER_HEIGHT; void Game::repairPos(float &x, float &y, float size) { if(x + size >= borderWidth) x = borderWidth- size; else if(x - size <= 0) x = size; if(y + size >= borderHeight) y = borderHeight - size; else if(y - size <= 0) y = size; } bool isCollision(Dot p, Dot d) { float xDiff = p.getPosX() - d.getPosX(); float yDiff = p.getPosY() - d.getPosY(); float distance = sqrt(xDiff*xDiff + yDiff*yDiff); return distance <= p.getSize() + d.getSize(); } void Game::collisions() { for(int i=0; i<dots.size(); i++) { if(isCollision(player, dots[i])) { player.addSize(dots[i]); dots.erase(dots.begin()+i); addRandomDot(); } for(int j=0; j<bots.size(); j++) { if(isCollision(bots[j], dots[i])) { bots[j].addSize(dots[i]); dots.erase(dots.begin()+i); addRandomDot(); } } } for(int i=0; i<bots.size(); i++) { if(isCollision(bots[i], player)) { if(bots[i].getSize() > player.getSize()) { bots[i].addSize(player); endGame(LOSS); } else if(bots[i].getSize() < player.getSize()) { player.addSize(bots[i]); bots.erase(bots.begin()+i); } } for(int j=i+1; j<bots.size(); j++) { if(isCollision(bots[i], bots[j])) { if(bots[i].getSize() > bots[j].getSize()) { bots[i].addSize(bots[j]); bots.erase(bots.begin()+j); } else if(bots[i].getSize() < bots[j].getSize()) { bots[j].addSize(bots[i]); bots.erase(bots.begin()+i); } } } } } void Game::addRandomDot() { dots.push_back(Dot(rand() % borderWidth, rand() % borderHeight, DOT_SIZE)); } void Game::simulateBots() { for(int i=1; i<bots.size(); i++) { bots[i].randomMove(); } } void Game::drawPlayers() { window.draw(player.getShape(width, height)); for(int i=1; i<bots.size(); i++) { window.draw(bots[i].getBotShape(player.getPosX() - (width/2), player.getPosY() - (height/2))); } } void Game::endGame(GameResult result) { if(result == WIN) { Result result("You won", player.getSize()); result.renderResult(window); } else { Result result("You lost", player.getSize()); result.renderResult(window); } menuOpen = true; bots.clear(); dots.clear(); srand(time(nullptr)); player = Player(2500,2500,"Player"); for(int i=0; i<START_DOTS_COUNT; i++) { addRandomDot(); } bots.push_back(player); for(int i=0; i<BOTS_COUNT; i++) { bots.push_back(Player(rand() % borderWidth, rand() % borderHeight, "Bot " + std::to_string(i+1))); } return; } GameResult Game::isSomeoneWinner() { if(player.getSize() >= MAX_SIZE) return WIN; for(int i=1; i<bots.size(); i++) { if(bots[i].getSize() >= (MAX_SIZE)) return LOSS; } return UNKNOWN; }
9bc724d35a69a53ebeee13d2e0b7a27d6ceec13e
[ "Markdown", "C++", "CMake" ]
15
Markdown
barto14753/AgarIO
631bda3cbab67862f7a594d98d8a456e5637b669
e8d287712054f758e3fe01c884789a6bd6aa2e32
refs/heads/master
<file_sep>[build-system] requires = ["setuptools>=42", "wheel", "read_version[toml]>=0.3.0", "pathlib2; python_version < '3'"] build-backend = "setuptools.build_meta" [read_version] version = "kaitaistruct:__version__"<file_sep>Kaitai Struct: runtime library for Python =========================================== This library implements Kaitai Struct API for Python. `Kaitai Struct <http://kaitai.io>`_ is a declarative language used for describe various binary data structures, laid out in files or in memory: i.e. binary file formats, network stream packet formats, etc. It is similar to `Python's Construct 2.9 <http://construct.readthedocs.org/>`_ but it is language-agnostic. The format description is done in YAML-based .ksy format, which then can be compiled into a wide range of target languages. Further reading: * `About Kaitai Struct <http://kaitai.io/>`_ * `About API implemented in this library <http://doc.kaitai.io/stream_api.html>`_ * `Python-specific notes <http://doc.kaitai.io/lang_python.html>`_ in KS documentation discuss installation and usage of this runtime
29fe300635131bc146756db304cba31310ce7ef9
[ "reStructuredText", "TOML" ]
2
reStructuredText
VitaliyZaharenko/kaitai_struct_python_runtime
1a9f77a85fc211a3f12ea0f81b1787001e4248dd
0e99da5edd0d1724a3132d92076156aaccc21335
refs/heads/master
<repo_name>PGiagkoulas/BullCowGame<file_sep>/Main.cpp #pragma once #include <iostream> #include <string> #include <map> #include "FBullCowGame.h" #include "MessagePrinter.h" #define TMap std::map // Unreal friendly using FText = std::string; using int32 = int; void PlayGame(); FText GetValidGuess(); bool AskReplay(); void PrintGameSummary(); FBullCowGame BCGame; int main() { MessagePrinter::IntroScreen(); MessagePrinter::PrintRules(); MessagePrinter::PrintPromptToContinue(); do { PlayGame(); } while(AskReplay()); return 0; } // game procedure void PlayGame() { BCGame.Reset(); BCGame.SetParameters(); std::cout << "Game Begins!\n"; int32 MaxTries = BCGame.GetMaxTries(); FText Guess = ""; while (!BCGame.IsGameWon() && BCGame.GetCurrentTry() <= BCGame.GetMaxTries()) { Guess = GetValidGuess(); FBullCowCount BullCowCount = BCGame.SubmitValidGuess(Guess); std::cout << "Bulls: " << BullCowCount.Bulls; std::cout << " - Cows: " << BullCowCount.Cows << std::endl << std::endl; } PrintGameSummary(); } // taking user's guess FText GetValidGuess() { EGuessStatus Status = EGuessStatus::Invalid_Status; FText Guess = ""; do { int32 CurrentTry = BCGame.GetCurrentTry(); Guess = ""; std::cout << "Try no." << CurrentTry << " of " << BCGame.GetMaxTries() << " | Enter your guess: "; std::getline(std::cin, Guess); Status = BCGame.CheckGuessValidity(Guess); switch (Status) { case EGuessStatus::Wrong_Length: std::cout << "Enter a " << BCGame.GetHiddenWordLength() << " letter word.\n\n"; break; case EGuessStatus::Not_Isogram: std::cout << "Guess should not be an isogram.\n\n"; break; case EGuessStatus::Not_Lowercase: std::cout << "Guess should be written in lowercase.\n\n"; break; default: //std::cout << "Valid guess"; break; } } while (Status != EGuessStatus::OK); return Guess; } bool AskReplay() { std::cout << "Wanna play again (y/n)? "; FText Response = ""; std::getline(std::cin, Response); std::cout << std::endl; return (tolower(Response[0]) == 'y'); } void PrintGameSummary() { if (BCGame.IsGameWon()) { std::cout << "You won!\n"; std::cout << "You found the word: \"" << BCGame.GetHiddenWord() << "\" in " << BCGame.GetCurrentTry()-1 << " tries\n"; } else { std::cout << "You failed\n"; std::cout << "The word you were looking for was: " << BCGame.GetHiddenWord() << std::endl; } std::cout << std::endl << std::endl; } <file_sep>/MessagePrinter.h #pragma once namespace MessagePrinter { void IntroScreen(); void DifficultyMenu(); void PrintRules(); void PrintPromptToContinue(); } <file_sep>/MessagePrinter.cpp /* Helper class containing methods for screen messages */ #pragma once #include "MessagePrinter.h" #include <string> #include <iostream> #include <map> #define TMap std::map // Unreal friendly using FString = std::string; using int32 = int; namespace MessagePrinter { // game intro screen void IntroScreen() { std::cout << "/~~~~~~~~~~~~Bulls & Cows~~~~~~~~~~~~~\\\n"; std::cout << std::endl; std::cout << " } { ___ " << std::endl; std::cout << " (o o) (o o) " << std::endl; std::cout << " /-------\\ / \\ /-------\\ " << std::endl; std::cout << " / | BULL |O O| COW | \\ " << std::endl; std::cout << " * |-,--- | |------| * " << std::endl; std::cout << " ^ ^ ^ ^ " << std::endl; std::cout << std::endl; std::cout << "\\____Guess the isogram word game!____/\n"; std::cout << std::endl; } // difficulty selection menu void DifficultyMenu() { TMap<int32, FString> ChoiceToDifficulty = { { 1,"Very Easy" }, { 2,"Easy" }, { 3,"Normal" }, { 4,"Hard" }, { 5,"Very Hard" } }; std::cout << "Choose difficulty level:\n"; for (int32 i = 1; i <= ChoiceToDifficulty.size(); i++) { std::cout << i << "." << ChoiceToDifficulty[i] << "\n"; } } // game rules void PrintRules() { std::cout << "~~~~~~~~~~~~~How To Play~~~~~~~~~~~~~\n"; std::cout << "Bulls and Cows is a word guessing game based on mastermind\n"; std::cout << "After choosing difficulty you will start guessing the hidden word\n"; std::cout << "The words in the game are isograms, which means no letter is used twise to form the word!\n"; std::cout << "Each time you submit a guess you get feedback, represented as Bulls and Cows\n"; std::cout << "A \"Bull\" means a letter in your guess is in the hidden word and in the same position\n"; std::cout << "A \"Cow\" means a letter in your guess is in the hidden word but at a different position\n"; std::cout << "The moment you hit all the \"Bulls\" you win!\n"; std::cout << "____________How To Play______________\n"; } // message prompting the user to continue void PrintPromptToContinue() { std::cout << std::endl; system("pause"); std::cout << std::endl; } }<file_sep>/FBullCowGame.cpp /* BullCowGame class. Functionality of the game is developed here. */ #pragma once #include "FBullCowGame.h" #include "MessagePrinter.h" #include <map> #include <iostream> #include <fstream> #include <stdlib.h> #include <time.h> #define TMap std::map // Unreal friendly using FString = std::string; using int32 = int; // constructor FBullCowGame::FBullCowGame() { Reset(); } // getters int32 FBullCowGame::GetCurrentTry() const { return MyCurrentTry; } int32 FBullCowGame::GetHiddenWordLength() const { return MyHiddenWord.length(); } bool FBullCowGame::IsGameWon() const { return bIsGameWon; } FString FBullCowGame::GetHiddenWord() const { return MyHiddenWord; } // setters void FBullCowGame::SetDifficulty(int32 SelectedDifficulty) { Difficulty = SelectedDifficulty; } // reseting game settings for new game void FBullCowGame::Reset() { MyHiddenWord = ""; MyCurrentTry = 1; bIsGameWon = false; } // asking and setting game difficulty + choosing hidden word based on chosen difficulty void FBullCowGame::SetParameters() { AskDifficulty(); MyHiddenWord = RandomHiddenWordChoice(); } // calculates&returns max tries depending on word length int32 FBullCowGame::GetMaxTries() const { TMap<int32, int32> WordLengthToMaxTries = { { 3,8 },{ 4,15 },{ 5,19 },{ 6,23 },{ 7,27 } }; return WordLengthToMaxTries[MyHiddenWord.length()]; } // checks user's guess for errors EGuessStatus FBullCowGame::CheckGuessValidity(FString Guess) const { if (!IsIsogram(Guess)) { return EGuessStatus::Not_Isogram; } else if (Guess.length() != GetHiddenWordLength()) { return EGuessStatus::Wrong_Length; } else if (!IsLowerCase(Guess)) { return EGuessStatus::Not_Lowercase; } else { return EGuessStatus::OK; } } // receives a valid guess, increments turn and returns count FBullCowCount FBullCowGame::SubmitValidGuess(FString Word) { MyCurrentTry++; FBullCowCount BullCowCount; int32 WordLength = MyHiddenWord.length(); // traverse hidden word for (int32 i = 0; i < WordLength; i++) { // traverse guess for (int32 j = 0; j < WordLength; j++) { // compare characters if (MyHiddenWord[i] == Word[j]) { // same position if (i == j) { BullCowCount.Bulls++; } // different position else { BullCowCount.Cows++; } } } } if (BullCowCount.Bulls == WordLength) { bIsGameWon = true; } else { bIsGameWon = false; } return BullCowCount; } // receives a guess and determines whether it is an isogram or not bool FBullCowGame::IsIsogram(FString Guess) const { if (Guess.length() <= 1) { return true; } TMap<char, bool> LettersSeen; for (auto Letter : Guess) { Letter = tolower(Letter); if (LettersSeen[Letter]) { return false; } else { LettersSeen[Letter] = true; } } return true; } // receives a guess and determines whether it is lowercase or not bool FBullCowGame::IsLowerCase(FString Guess) const { if (Guess.length() < 1) { return true; } for (auto Letter : Guess) { if (!islower(Letter)) { return false; } } return true; } // ask user for difficulty/word length void FBullCowGame::AskDifficulty() { TMap<int32, int32> DifficultyToWordLength = { { 1,3 },{ 2,4 } ,{ 3,5 } ,{ 4,6 } ,{ 5,7 } }; TMap<int32, FString> ChoiceToDifficulty = { { 1,"Very Easy" }, { 2,"Easy" }, { 3,"Normal" }, { 4,"Hard" }, { 5,"Very Hard" } }; // print menu for difficulty selection MessagePrinter::DifficultyMenu(); FString Choice = ""; int32 ChosenDifficulty; do { // get user choice std::getline(std::cin, Choice); // cast to integer ChosenDifficulty = std::stoi(Choice); if (!(ChosenDifficulty > 0 && ChosenDifficulty < 6)) { std::cout << "Choose proper difficulty!\n"; } } while (ChosenDifficulty && !(ChosenDifficulty > 0 && ChosenDifficulty < 6)); // set difficulty SetDifficulty(ChosenDifficulty); std::cout << "\"" << ChoiceToDifficulty[ChosenDifficulty] << "\" chosen - Playing with " << DifficultyToWordLength[Difficulty] << " letter words\n"; } // a random word is selected according to chosen difficulty // opening appropriate txt file from resources FString FBullCowGame::RandomHiddenWordChoice() { FString FileName = "diff_" + std::to_string(Difficulty) + "_words.txt"; std::ifstream WordFile(FileName); if (!WordFile) { std::cout << "Cannot open input file.\n"; return 0; } FString RandomlySelectedHiddenWord = ""; // calulating the number of lines on the file (number of lines = number of words) int32 NumberOfWords; NumberOfWords = std::count(std::istreambuf_iterator<char>(WordFile), std::istreambuf_iterator<char>(), '\n'); // reseting file scan WordFile.clear(); WordFile.seekg(0, WordFile.beg); // initialize seed srand(time(NULL)); // select random word int32 RandomIndex = rand() % NumberOfWords + 1; for (int i = 0; i < RandomIndex; i++) { //std::cout << i; getline(WordFile, RandomlySelectedHiddenWord); } WordFile.close(); return RandomlySelectedHiddenWord; } <file_sep>/README.md # BullCowGame Word game based on mastermind. Developed during "Unreal engine development" course from Udemy.
425f302bff33c3f97cd20c71fcbbff173e46cadb
[ "Markdown", "C++" ]
5
Markdown
PGiagkoulas/BullCowGame
ece1c54d474e59e6834f737daf30a9c519dcce51
661078f7e7e5f357c9f91c9e25901e6db11589f4
refs/heads/master
<repo_name>szpinc/study-python<file_sep>/day01-day15/day01/code/hello.py ''' 第一个Python程序 - hello, world! 向伟大的<NAME>先生致敬 Version: 1.0 Author: <NAME> Date: 2018-04-16 请将文件命名为hello.py并在终端通过下面的命令运行它 python hello.py ''' print("Hello World!") print("你好,世界") print('Hello','World',sep=',', end='!') print("GoodBye,World",end='!\n')<file_sep>/README.md # study-python python学习记录
cf8feed0a1f077f3017302baf39850480dce97e8
[ "Markdown", "Python" ]
2
Markdown
szpinc/study-python
63abcf1b9988171324e278167b1883a5d226a010
09e965ab8472c3829ab40734fe924ec66e7054e4
refs/heads/master
<file_sep>class Show < ActiveRecord::Base def self.highest_rating self.maximum(:rating) end # class method, so we use self. # .maximum operator expects us to provide a column in brackets that it can then select the highest value from def self.lowest_rating self.minimum(:rating) end # same thing only using min not max def self.most_popular_show self.where("rating = ?", self.highest_rating).first end # uses .where, which remember from previous labs requires a string statement. Since we are invoking an earlier method, we use a bound parameter (?) and then offer the value we wish to substitute that parameter with immediately afterwards, seperated by a comma but still within the same parentheses. # .first eensures it returns a single value. Presumably there are more than one shows with the same highest rating in the database. def self.least_popular_show self.where("rating = ?", self.lowest_rating).first end # same as above, invokes helper method 'lowest_rating' as the bound parameter for the rating = ? bound parameter def self.ratings_sum self.sum(:rating) end def self.popular_shows self.where("rating > 5") end # simple method, doesn't require bound parameter since we are not interpolating any helper methods def self.shows_by_alphabetical_order self.order(name: :asc) end # .order orders the array by the parameters we pass in brackets - in this case ordered by the name attribute and ascending end
28b21549cf7587c52f6bcf25a9c6f3a62534bf19
[ "Ruby" ]
1
Ruby
ck2e14/activerecord-tvshow-london-web-082619
e4b52a32f4252afbfa22e95d34b46152281815ef
57fb1a35b359132597e87f9e61ca1bef2344f5b9
refs/heads/master
<repo_name>inwaves/todo-python<file_sep>/README.md # todo-python An implementation of [todo-backend](https://www.todobackend.com/) in Python. <file_sep>/requirements.txt alembic==0.9.6 blinker==1.4 certifi==2017.7.27.1 chardet==3.0.4 click==6.7 dnspython==2.1.0 dominate==2.3.1 elasticsearch==7.10.1 email-validator==1.1.2 Flask==1.1.2 Flask-Bootstrap==3.3.7.1 Flask-Cors==3.0.10 Flask-HTTPAuth==4.2.0 Flask-Login==0.5.0 Flask-Mail==0.9.1 Flask-Migrate==2.5.3 Flask-Moment==0.11.0 Flask-SQLAlchemy==2.4.4 Flask-WTF==0.14.3 guess-language-spirit==0.5.3 gunicorn==19.7.1 httpie==2.4.0 idna==2.6 itsdangerous==0.24 Jinja2==2.11.2 Mako==1.0.7 MarkupSafe==1.1.1 psycopg2==2.8.6 Pygments==2.8.1 PyJWT==1.5.3 PySocks==1.7.1 python-dateutil==2.6.1 python-dotenv==0.15.0 python-editor==1.0.3 pytz==2017.2 redis==3.5.3 requests==2.25.1 requests-toolbelt==0.9.1 rq==1.8.0 six==1.11.0 SQLAlchemy==1.3.22 urllib3==1.26.2 visitor==0.1.3 Werkzeug==1.0.1 WTForms==2.1 <file_sep>/Procfile web: flask db upgrade; gunicorn iw_todo:app<file_sep>/app/api/routes.py from flask import jsonify, request from app.api import bp from app import db @bp.route("/", methods=["GET"]) def index(): pass
042053a6eb6f2a8b855a58d46076c15e45f6bae9
[ "Markdown", "Procfile", "Text", "Python" ]
4
Markdown
inwaves/todo-python
c6c725cbd6fc21781314292ba2c48450f0990d18
3b05ea3acc65133e36ac8745587d1e7be467a6e1
refs/heads/main
<file_sep># JS-BuildLogicExercises ### Operators, Branching and Loops (*completed*) [Repl.it](https://repl.it/@HalfCold/Operators-Branching-and-Loops) ### Functions (*completed*) [Repl.it](https://repl.it/@HalfCold/Functions)
130a24f20ecca7a391fbe64a74dfdbef3f99e549
[ "Markdown" ]
1
Markdown
OmkarArora/JS-BuildLogicExercises
a3289619a191549b31d6ff9fb5ff93637256b72d
0a01e7f2e0d1de29a4fd867e3c4e1ca0309b07cc
refs/heads/master
<file_sep>function = _.template var repos = { }; <file_sep>function renderTemplate(templateId, container, finalArgument) { var templateString = $('#' + templateId).text(); var templateFunction = _.template(templateString); var renderedTemplate = templateFunction(finalArgument); $(container).append(renderedTemplate); }; $.getJSON("https://api.github.com/users/plove13x").done(function(item) { var userInfo = { "avatar_url": item.avatar_url, "name": item.name, "login": item.login, "company": item.company, "location": item.location, "email": item.email, "blog": item.blog, "created_at": item.created_at && moment(item.created_at).fromNow(), "followers": item.followers, "following": item.following }; renderTemplate('headerTemplateScript', '.nB', userInfo); renderTemplate('sidebarTemplateScript', '.sidebar', userInfo); $.getJSON("https://api.github.com/users/plove13x/starred").done(function(data) { userInfo.starred = data.length; renderTemplate('followTemplateScript', '.belowProfile', userInfo); $.getJSON("https://api.github.com/users/jgoley/orgs").done(function(data) { var orgsArray = data.map(function(item) { return { "avatar_url": item.avatar_url }; }); _.each(orgsArray, function(org) { renderTemplate('orgsTemplateScript', '.orgz', org); }); }); }); }); $.getJSON("https://api.github.com/users/plove13x/repos").done(function(data) { var ploveRepos = data.map(function(item) { return { "language": item.language, "stargazers_count": item.stargazers_count, "name": item.name, "html_url": item.html_url, "fork": item.fork, /*defaults/extends?*/ "description": item.description, /*HOW WOULD I EXTRACT THIS AND IS THIS EVEN THE RIGHT PROPERTY?*/ "updated_at": moment(item.updated_at).fromNow() }; }); _.each(ploveRepos, function(repo) { renderTemplate('reposTemplateScript', '.repos', repo); }); });
f2f08e6b3024c40fc5848ed9999144879cf9ab58
[ "JavaScript" ]
2
JavaScript
plove13x/A10-GitHubRepos
25f303726981d538c15487c58445b3312a1d1dd2
72718a06d02fab3f92a45fdacc72f1bed886f89a
refs/heads/master
<file_sep><?php include_once 'includes/config.inc'; checkPermissions(); include_once 'includes/header.inc'; ?> <script src="js/jquery-1.4.2.min.js"></script> <script src="js/changepass.js"></script> <?php include_once 'includes/body.inc' ?> <form id="centerForm" onSubmit="changePass(); return false;"> <h1>Change Password</h1> <table> <tr><td>Current Password</td><td><input type="password" name="oldpass"><span id="badpasserror" class="error">Password incorrect</span></td></tr> <tr><td>New Password</p></td><td><input type="password" name="newpass"></td></tr> <tr><td>Retype Password</td><td><input type="<PASSWORD>" name="<PASSWORD>"><span id="badmatcherror" class="error">Passwords do not match</span></td></tr> <tr><td colspan="2"><input type="submit" value="change password"></td></tr> </table> </form> <?php include_once 'includes/footer.inc' ?><file_sep>#include <vector> #include "BPMatch.h" void FileParser(FlowNetwork* fn, char * s); void AddSourceSinkEdges(FlowNetwork* fn); <file_sep>$(document).ready(function() { $("input[name='oldpass']").focus(); }); function changePass() { $.post("do.php", { "action":"update_password", "oldpass":$("input[name='oldpass']").val(), "newpass":$("input[name='newpass']").val(), "rnewpass":$("input[name='rnewpass']").val() }, function(data) { $("#badpasserror").css("display","none"); $("#badmatcherror").css("display","none"); if (data.out == 1) { $("input[name='rnewpass']").val(''); $("input[name='newpass']").val(''); $("input[name='oldpass']").val('').focus(); $("#badpasserror").css("display","block"); $("#badmatcherror").css("display","none"); } else if (data.out == 2) { $("input[name='rnewpass']").val(''); $("input[name='newpass']").val('').focus(); $("#badmatcherror").css("display","block"); $("#badpasserror").css("display","none"); } else if (data.out == 0) { window.location = 'problems.php'; } else { alert("An unexpected error has occured.\nTry Logging in again."); } }, "json"); }<file_sep><?php include_once 'includes/config.inc'; checkPermissions(); include_once 'includes/header.inc'; $dates = getPublicProblems(); ?> <script src="js/publicEvents.js"></script> <script src="js/jquery-ui-1.8.10.custom.min.js"></script> <link rel="stylesheet" href="css/jquery.ui.css"> <?php include_once 'includes/body.inc' ?> <?php if (count($dates)) { ?> <div style="float:right;">Search: <input type="text" name="filterBox" <?php if (isset($_GET['q'])) { echo ' value="' . $_GET['q'] . '"'; } ?>></div> <div id="emptyEventsTable" class="emptyItemTable" style="display: none;"><p>There are no events that matched your search.</p></div> <table class="itemTable" id="publicEventsTable"> <?php foreach ($dates as $dateText => $date) { $dateTextArray = explode("-", $dateText); echo '<tr id="' . $dateText . '"><th colspan="2">' . date("l F j, Y", mktime(0,0,0,$dateTextArray[1],$dateTextArray[2],$dateTextArray[0])) . '</th></tr>'; foreach ($date as $problem) { if ($problem['name'] == '') { $problem['name'] = "[untitled]"; } $algorithm = getAlgorithmById($problem['algorithm']); $problemStatus = getProblemStatus($problem['id']); $userResponded = hasResponded($problem['id'], $current_user); $adminString = ''; $admins = getAdminsForProblem($problem['id']); foreach ($admins as $admin) { $adminString .= getNameString($admin) . ', '; } $adminString = substr($adminString, 0, -2); if (!$userResponded) { $link = '<a href="respond.php?problem=' . $problem['id'] . '">Join this Event</a>'; $class = " notresponded"; } else { $link = '<a href="respond.php?problem=' . $problem['id'] . '">Change Response</a>'; $class = ""; } if ($problemStatus == "open") { $status = "Open"; } else if ($problemStatus == "timed") { $status = expirationTime($problem['end_time']); } ?> <tr id="<?php echo $problem['id'] ?>" class="row <?php echo $dateText ?><?php echo $class ?>"> <td class="descriptionColumn"> <span class="keywords"><?php echo $problem['name'] ?> <?php echo $adminString ?></span> <?php echo $problem['name'] ?> - posted by <?php echo $adminString ?><br> <span><?php echo $link ?></span> </td> <td class="statusColumn"><?php echo $status ?></td> </tr><?php } } echo '</table>'; } else { echo '<div class="emptyItemTable"><p>There are no public events right now.</p></div>'; } ?> <div id="dialog" title="Help - Public Events"> <p>This is the <strong>Public Events page</strong>, where you can see and respond to events that are open to everyone at Carleton.</p> <p><strong>To join a public event</strong>, click on "Join this Event." You will be redirected to a page where you can mark your availability and preferences.</p> <p><strong>To filter events</strong>, enter text in the "Search" box. Sched-A-Roo will only display the events whose title or creator contains the text you entered. <p><strong>To create a public event</strong>, click "New Event" on the <a href="problems.php">home page</a> and select "Public Event" in the options.</p> <p><strong>For more help</strong>, please see the <a href="help.php">help page</a>.</p> </div> <?php include_once 'includes/footer.inc' ?> <file_sep><?php include_once 'includes/config.inc'; include_once 'includes/header.inc'; include_once 'includes/body.inc'; if (isset($_GET['user'])) { $defaultUser = $_GET['user']; } else { $defaultUser = 'e.g. smithj'; } ?> <script src="js/jquery-1.4.2.min.js"></script> <script src="js/authenticate.js"></script> <h1>New Account Authentication</h1> <div style="float:left;margin-left:10px;"> <div style="float:right;width:275px; margin-left:25px; height:225px;"> <form id="authForm" onSubmit="authenticate();return false;"> <font size="2">Activate your account using your Carleton ID</font> <table> <tr><td>Carleton Email ID</td><td><input type="text" value="<?php echo $defaultUser ?>" onclick="this.value=''"size="20" name="id"></td></tr> <tr><td colspan="2"><input type="submit" value="Activate!"></td></tr> </table> <span class="error" id="error">That ID is not in our database. This could be because you're not listed in the Carleton directory or you made a typo. Try again and if you keep having a problem, try our <a href="helpForm.php">feedback form</a></span> </form> </div> <h2>What is Scheddoodle?</h2> <p>Scheddoodle is a Carleton-only scheduling assistant, created by our "Scheddoodle" CS comps group. The idea is to make it easier to pick a date and time for your event.</p> <h2>Why use Scheddoodle?</h2> <p>Why not? Give it a shot, and we can do the work for you, whether you need to schedule a group meeting or you want to find a way to meet up with as many people as possible.</p> <h2>I got an email saying someone invited me to a schedule. What now?</h2> <p>First you have to verify your account. If you are listed in the Carleton directory, we have you in our records. Just enter your Carleton username in the form on this page, and you'll get an email with a password to log into the website.</p> </div> <?php include_once 'includes/footer.inc'; ?><file_sep><?php //Redirect our home page to the "My Schedules" page, which is currently the closest thing we have to a home page. //Note: With this page in place, it's impossible to view the contents of the web directory from the browser. //Rename this file to Index0.php or something like that to prevent the redirect. header('Location: problems.php'); ?> <file_sep>// problems.js -- javascript for problems.php var currentView = "current"; var onLink = false; var onDiv = false; var timeoutID; $(document).ready(function() { $(".editLink").mouseover(function() { var pos = $(this).offset(); problem = $(this).parent().parent().attr("id"); showBubble(pos, problem); onLink = true; }); $(".editLink").mouseout(function() { onLink = false; timeoutID = setTimeout(letBubbleClose, 200); }); $("#showAdvancedSearchButton").click(function() { $("#advancedSearchDiv").show(); $("#basicSearchDiv").hide(); }); $("#hideAdvancedSearchButton").click(function() { $("#basicSearchDiv").show(); $("#advancedSearchDiv").hide(); }); $(".infoButton").click(function() { $(this).parent().parent().find(".more").slideToggle(); $(this).parent().parent().find(".title").toggleClass("expanded"); }); //$(".statusColumn").click(function() { alert($(this).parent().attr("id")); }); }); function showBubble(pos, problem) { hideBubble(); iconPosX = pos.left; iconPosY = pos.top; var icon = '<div id="iconbubble" style="top: ' + iconPosY.toString() + 'px; left: ' + iconPosX.toString() + 'px;"><img src="images/edit.png"></div>'; var posX = pos.left - 180; var posY = pos.top + 23; var html = '<div id="bubble" style="top: ' + posY.toString() + 'px; left: ' + posX.toString() + 'px;">'; html = html + '<a href="problem.php?problem=' + problem + '">Edit Description</a>, <a href="timeslots.php?problem=' + problem + '">Edit Resources</a></div>'; $(icon).appendTo('body'); $(html).appendTo('body'); $("#iconbubble").mouseover(function() { onLink = true; }); $("#bubble").mouseover(function() { onDiv = true; }); $("#iconbubble").mouseout(function() { onLink = false; timeoutID = setTimeout(letBubbleClose, 200); }); $("#bubble").mouseout(function() { onDiv = false; timeoutID = setTimeout(letBubbleClose, 200); }); } function letBubbleClose() { clearTimeout(timeoutID); if (!onLink && !onDiv) { hideBubble(); } } function hideBubble() { $("#iconbubble").remove(); $("#bubble").remove(); } function archiveProblem(problemID, userID) { $.post("do.php", { "action": "archive_problem", "problem": problemID, "user": userID }, function(data) { if (data.out == 0) { var unArchiveText = '<a href="javascript:void(0);" onclick="unArchiveProblem(' + problemID + ', ' + userID + ');"><img src="images/unarchive.png" title="Unhide Event"></a>'; if (($("#eventsTable .row:visible").length == 1) && (currentView != "row")) { $("#eventsTable, #eventsTable #head").hide(); $("#emptyEventsTable").fadeIn("fast"); $("#" + problemID).removeClass("current"); $("#" + problemID + " .archiveLink").html(unArchiveText); } else { if (currentView == "row") { $("#" + problemID).removeClass("current"); $("#" + problemID + " .archiveLink").html(unArchiveText); } else { $("#" + problemID).fadeOut("fast", function() { $("#" + problemID).removeClass("current"); $("#" + problemID + " .archiveLink").html(unArchiveText); }); } } } else { alert("an error has occured while archiving this event"); } }, "json"); } function unArchiveProblem(problemID, userID) { $.post("do.php", { "action": "unArchive_problem", "problem": problemID, "user": userID }, function(data) { if (data.out == 0) { $("#" + problemID + " .archiveLink").html('<a href="javascript:void(0);" onclick="archiveProblem(' + problemID + ', ' + userID + ');"><img src="images/archive.png" title="Hide Event"></a>'); $("#" + problemID).addClass("current"); } else { alert("an error has occured while unarchiving this event"); } }, "json"); } function deleteProblem(problemID, problemName) { $("#" + problemID).addClass("todelete"); if (confirm("Are you sure you want to delete the event:\n\n" + problemName)) { $.post("do.php", { "action": "delete_problem", "problem": problemID }, function(data) { if (data.out == 0) { if ($("#eventsTable .row:visible").length == 1) { $("#eventsTable, #eventsTable #head").hide(); $("#emptyEventsTable").fadeIn("fast"); $("#" + problemID).remove(); } else { $("#" + problemID).fadeOut("fast", function() { $("#" + problemID).remove(); }); } } else { alert("an error has occured while deleting this event"); } }, "json"); } else { $("#" + problemID).removeClass("todelete"); } } function view(type) { $("#eventsTable, #eventsTable #head").show(); var numShowing = $("#eventsTable .row:visible").length; $("#emptyEventsTable, #eventsTable .row").hide(); if ($("#eventsTable ." + type).length == 0) { $("#eventsTable, #eventsTable #head").hide(); $("#emptyEventsTable").fadeIn("fast"); } else if (numShowing == 0) { $("#eventsTable ." + type).fadeIn("fast"); } else { $("#eventsTable ." + type).show(); } currentView = type; } function advancedView(visibility, userStatus, responseStatus, problemStatus) { //alert("entering advanced view"); var filters = new Array(); filters[0] = visibility; filters[1] = userStatus; filters[2] = responseStatus; filters[3] = problemStatus; $("#eventsTable, #eventsTable #head").show(); var numShowing = $("#eventsTable .row:visible").length; $("#emptyEventsTable, #eventsTable .row").hide(); if (($("#eventsTable ." + visibility + "." + userStatus + "." + responseStatus + "." + problemStatus).length == 0)) { $("#eventsTable, #eventsTable #head").hide(); $("#emptyEventsTable").fadeIn("fast"); } else { for (var key in filters) { if (numShowing == 0) { $("#eventsTable ." + filters[key]).fadeIn("fast"); numShowing = $("#eventsTable .row:visible").length; } else if (key == 0) { $("#eventsTable ." + filters[key]).show(); } else if (filters[key] != 'row') { $("#eventsTable .row:not(." + filters[key] + ")").hide(); } } } currentView = visibility; }<file_sep><?php include_once '../../includes/config.inc' ?> <?php include_once 'functions.php' ?> <?php checkPermissions(); if (!isset($_GET['problem'])) { die("no problem specified"); } $problem = getProblemById($_GET['problem']); checkAllowedView($problem); include_once PATH . '/includes/header.inc'; include_once PATH . '/includes/body.inc'; ?> <link rel="stylesheet" href="style.css"> <h1><?php echo $problem['name'] ?></h1> <table id="outputTable"> <tr><th>User</th><th>Assignment</th></tr> <?php list($assignments, $unassigned) = getAssignments($problem['id']); foreach ($assignments as $assignment) { if ($assignment['participant']) { $participant = getUserById($assignment['participant']); } else { $participant = NULL; } if (!$assignment['assignment']) { $assignment['assignment'] = "--"; } if ($participant['id'] == $current_user) { echo '<tr style="background-color:#738AE1;"><td><b>' . getNameString($participant) . '</td><td><b>' . $assignment['assignment'] . "</td></tr>\n"; } else { echo '<tr><td>' . getNameString($participant) . '</td><td>' . $assignment['assignment'] . "</td></tr>"; } } foreach ($unassigned as $assignment) { echo '<tr><td>' . getNameString(getUserById($assignment)) . '</td><td>--</td></tr>'; } echo '</table>'; if ($problem['comment']) { echo '<h2>Comments</h2>'; echo '<p>' . $problem['comment'] . '</p>'; } ?> <?php include_once PATH . '/includes/footer.inc' ?><file_sep><?php include_once '../../includes/config.inc'; include_once 'functions.php'; checkPermissions(); include_once PATH . '/includes/header.inc'; include_once PATH . '/includes/body.inc'; ?> <h1>Worker Hours</h1> <table style="width:50%;"> <?php for ($m=0;$m<10;$m++): ?> <tr><td>Worker <?php echo $m ?></td><td><select><?php for ($i=0;$i<12.5;$i=$i+.5) { if ($i == 10) { echo '<option selected>' . $i . '</option>'; } else { echo '<option>' . $i . '</option>'; } } ?></select></td></tr> <?php endfor; ?> <table> <?php include_once PATH . '/includes/footer.inc'; ?><file_sep><?php include_once 'includes/config.inc'; checkPermissions(); include_once 'includes/header.inc'; include_once 'includes/body.inc'; ?> <div id="right"> <h1>Feedback Form</h1> <p>Thank you for taking the time to help us improve our site. Please respond to the following questions to the best of your ability. We would love to meet with you in person if you would like to provide more specific input.</p> <form action="helpFormResults.php" method="post"> <ol> <li><p>Name <input type="text" name="name" value="<?php echo getNameString(getUserById($current_user)) ?>" size="40" disabled></p></li> <li> <p>What changes would you like see made to our site?</p> <p><textarea name="improvements" rows="10" cols="80"></textarea></p> </li> </ol> <p style="text-align:center;"><input type="submit" value="Submit"></p> </form> </div> <?php include_once 'includes/footer.inc' ?><file_sep><?php ######################################################################## ## PROBLEM FUNCTIONS ######################################################################## // returns a problem function getProblemById($id) { $result = mysql_query("SELECT * FROM `problems` WHERE id=$id"); return mysql_fetch_array($result); } // adds a problem into the database function addProblem($name, $algorithm, $description, $end_time, $status, $type) { $name = sanitize($name); $description = sanitize($description); if (!$end_time) { $end_time = 'NULL'; } else { $end_time = "'" . $end_time . "'"; } $query = sprintf("INSERT INTO `problems` (`name`, `algorithm`, `description`, `end_time`, `status`, `type`) VALUES ('%s', %d, '%s', %s, '%s', '%s')", $name, $algorithm, $description, $end_time, $status, $type); mysql_query($query); return mysql_insert_id(); } // updates a current problem in the database function updateProblem($id, $name, $description, $end_time, $status, $type) { $name = sanitize($name); $description = sanitize($description); if (!$end_time) { $end_time = 'NULL'; } else { $end_time = "'" . $end_time . "'"; } $query = sprintf("UPDATE `problems` SET name='%s', description='%s', end_time=%s, status='%s', type='%s' WHERE id=%d", $name, $description, $end_time, $status, $type, $id); mysql_query($query); } // updates a problem's comment in the database function updateProblemComment($id, $comment) { $comment = sanitize($comment); $query = sprintf("UPDATE `problems` SET comment='%s' WHERE id=%d", $comment, $id); mysql_query($query); } // delete's a problem and all associated user data function deleteProblem($problem) { mysql_query("DELETE FROM `problems` WHERE id=$problem"); mysql_query("DELETE FROM `user2problem` WHERE problemID=$problem"); mysql_query("DELETE FROM `data` WHERE problem=$problem"); } ######################################################################## ## SORT PROBLEMS ######################################################################## function sortProblemsByRelevance($problems, $user) { return sortProblemsByAdminParticipant(sortProblemsByResponded(sortProblemsByStatus($problems), $user), $user); } function sortProblemsByAdminParticipant ($problems, $user) { $adminParticipant = array(); $admin = array(); $participant = array(); $neither = array(); $problems = array_reverse($problems); // reverse order so that appending later maintains order within categories foreach ($problems as $problem) { if (isAdminForProblem($problem['id'], $user)) { if (isParticipantInProblem($user, $problem['id'])) { $adminParticipant[] = $problem; } else { $admin[] = $problem; } } else { if (isParticipantInProblem($user, $problem['id'])) { $participant[] = $problem; } else { $neither[] = $problem; } } } return array_merge($adminParticipant, $admin, $participant, $neither); } function sortProblemsByStatus($problems) { $open = array(); $closed = array(); $posted = array (); $reverse = array(); $problems = array_reverse($problems); // reverse order so that appending later maintains order within categories foreach ($problems as $problem) { $problemRow = getProblemById($problem['id']); if ($problemRow['status'] == 'open') { $open[] = $problem; } else if ($problemRow['status'] == 'closed') { $closed[] = $problem; } else { //if ($problemRow['status'] == 'posted') { $posted[] = $problem; } } return array_merge($open, $posted, $closed); } function sortProblemsByResponded($problems, $user) { $responded = array(); $notResponded = array(); $notParticipant = array(); $problems = array_reverse($problems); // reverse order so that appending later maintains order within categories foreach ($problems as $problem) { if (isParticipantInProblem($user, $problem['id'])) { if(hasResponded($problem['id'], $user)) { $responded[] = $problem; } else { $notResponded[] = $problem; } } else { $notParticipant[] = $problem; } } return array_merge($responded, $notResponded, $notParticipant); } ######################################################################## ## PROBLEM PARTICIPATION ######################################################################## // removes an admin from a problem function removeAdminFromProblem($problem, $user) { $query = "SELECT * FROM `user2problem` WHERE userID=$user AND problemID=$problem"; $result = mysql_query($query); $row = mysql_fetch_array($result); if ($row && $row['isParticipant']) { mysql_query("UPDATE `user2problem` SET isAdmin=0 WHERE userID=$user AND problemID=$problem"); } else { mysql_query("DELETE FROM `user2problem` WHERE userID=$user AND problemID=$problem"); mysql_query("DELETE FROM `data` WHERE problem=$problem AND user=$user"); // if they are not a participant, we can all data for this user } } // removes a participant from a problem function removeParticipantFromProblem($problem, $user) { $query = "SELECT * FROM `user2problem` WHERE userID=$user AND problemID=$problem"; $result = mysql_query($query); $row = mysql_fetch_array($result); if ($row && $row['isAdmin']) { mysql_query("UPDATE `user2problem` SET isParticipant=0, hasResponded=0 WHERE userID=$user AND problemID=$problem"); } else { mysql_query("DELETE FROM `user2problem` WHERE userID=$user AND problemID=$problem"); } mysql_query("DELETE FROM `data` WHERE problem=$problem AND user=$user"); // this is fine unless we want to store data for the admin } // DELETE ME function isUserInProblem($user, $problem) { // delete this return isParticipantInProblem($user, $problem); } // returns 1 if participant is a part of a problem, otherwise 0 function isParticipantInProblem($user, $problem) { $result = mysql_query("SELECT * FROM `user2problem` WHERE userID=$user AND problemID=$problem AND isParticipant=1"); if (mysql_num_rows($result)) { return 1; } else { return 0; } } // returns 1 if admin is a part of a problem, otherwise 0 function isAdminInProblem($user, $problem) { $result = mysql_query("SELECT * FROM `user2problem` WHERE userID=$user AND problemID=$problem AND isAdmin=1"); if (mysql_num_rows($result)) { return 1; } else { return 0; } } // adds a user to a problem function addParticipantToProblem($problem, $user) { $query = "SELECT * FROM `user2problem` WHERE userID=$user AND problemID=$problem"; $result = mysql_query($query); $row = mysql_fetch_array($result); if (!$row) { $insertQuery = "INSERT INTO `user2problem` (`userID`, `problemID`, `isParticipant`) VALUES ($user, $problem, 1)"; mysql_query($insertQuery); return 0; } else if ($row['isParticipant']) { return 1; } else { $updateQuery = "UPDATE `user2problem` SET isParticipant=1 WHERE userID=$user AND problemID=$problem"; mysql_query($updateQuery); return 0; } } // PHASE OUT function addUserToProblem($problem, $user) { addParticipantToProblem($problem, $user); } // phase this out // adds an admin to a problem function addAdminToProblem($problem, $user) { $query = "SELECT * FROM `user2problem` WHERE userID=$user AND problemID=$problem"; $result = mysql_query($query); $row = mysql_fetch_array($result); if (!$row) { $insertQuery = "INSERT INTO `user2problem` (`userID`, `problemID`, `isAdmin`) VALUES ($user, $problem, 1)"; mysql_query($insertQuery); return 0; } else if ($row['isAdmin']) { return 1; } else { $updateQuery = "UPDATE `user2problem` SET isAdmin=1 WHERE userID=$user AND problemID=$problem"; mysql_query($updateQuery); return 0; } } // archives a problem for a user function archiveProblem($problem, $user) { $query = sprintf("UPDATE `user2problem` SET isArchived=1 WHERE userID=%d AND problemID=%d", $user, $problem); mysql_query($query); } // un-archives a problem for a user function unArchiveProblem($problem, $user) { $query = sprintf("UPDATE `user2problem` SET isArchived=0 WHERE userID=%d AND problemID=%d", $user, $problem); mysql_query($query); } ######################################################################## ## GETTING PROBLEMS ######################################################################## // returns a list of closing problems function getClosingProblems() { $result = mysql_query("SELECT * FROM `problems` WHERE status='timed' AND TIMESTAMPDIFF(HOUR, NOW(), end_time) < 24 AND TIMESTAMPDIFF(HOUR, NOW(), end_time) > 21;"); $rows = array(); while ($row = mysql_fetch_array($result)) { $rows[] = $row; } return $rows; } // returns an array of problems for a user function getProblemsForUser($user) { $rows = array(); $result = mysql_query("SELECT * FROM `user2problem` WHERE userID=$user"); while ($row = mysql_fetch_array($result)) { $problem = getProblemById($row['problemID']); $problem["isAdmin"] = $row['isAdmin']; $problem["isParticipant"] = $row['isParticipant']; $problem["isArchived"] = $row['isArchived']; $rows[] = $problem; } return $rows; } function getRequests($user) { die("do not user getRequests function. use getProblemsForUser instead"); echo "DO NOT USER THIS FUNCTION: getRequests. User getProblemsForUser Insetad"; return getProblemsForUser($user); } function getUsers($problem) { echo "DO NOT USER THIS!!!"; return getUsersForProblem($problem); } // phasing this out function getUsersForProblem($problem) { die("do not use getUsersForProblem"); return getParticipantsForProblem($problem); } function getParticipantsForProblem($problem, $hasResponded='all') { if ($hasResponded != 'all') { $result = mysql_query("SELECT * FROM `user2problem` WHERE problemID=$problem AND isParticipant=1 AND hasResponded=$hasResponded"); } else { $result = mysql_query("SELECT * FROM `user2problem` WHERE problemID=$problem AND isParticipant=1"); } $participants = array(); while ($row = mysql_fetch_array($result)) { $participant = getUserById($row['userID']); $participant["hasResponded"] = $row["hasResponded"]; $participants[] = $participant; } usort($participants, "compareUsers"); return $participants; } function getAdminsForProblem($problem) { $result = mysql_query("SELECT * FROM `user2problem` WHERE problemID=$problem AND isAdmin=1"); $admins = array(); while ($row = mysql_fetch_array($result)) { $admins[] = getUserById($row['userID']); } usort($admins, "compareUsers"); return $admins; } // returns 1 if the user is an admin in a problem, 0 otherwise function isAdminForProblem($problem, $user) { $result = mysql_query("SELECT * FROM `user2problem` WHERE userID=$user AND problemID=$problem AND isAdmin=1"); $row = mysql_fetch_array($result); if ($row) { return 1;} return 0; } // a comparison function to compare 2 users function compareUsers($participant1, $participant2) { return strcmp($participant1['name'], $participant2['name']); } ######################################################################## ## PUBLIC PROBLEMS ######################################################################## // returns all public problems that are open function getPublicProblems() { $result = mysql_query("SELECT *, DATE(created) AS createdDate FROM `problems` WHERE (status='open' OR status='timed') AND type='public' ORDER BY created DESC"); while ($problem = mysql_fetch_array($result)) { if (!isExpired($problem['id'])) { break; } } $currentDate = $problem['createdDate']; if (!$problem) { return array(); } // if there are no problems, just return an empty array $datesArray[$currentDate] = array($problem); while ($problem = mysql_fetch_array($result)) { if ($currentDate == $problem['createdDate'] && !isExpired($problem['id'])) { $datesArray[$currentDate][] = $problem; } else if (!isExpired($problem['id'])) { $currentDate = $problem['createdDate']; $datesArray[$currentDate] = array($problem); } } return $datesArray; } ######################################################################## ## PROBLEM STATUS ######################################################################## // sets the status of a problem function setProblemStatus($problem, $status) { if ($status == "open" || $status == "closed" || $status == "timed" || $status == "posted") { $query = sprintf("UPDATE `problems` SET status='%s' WHERE id=%d", $status, $problem); mysql_query($query); } } // returns the status of a problem function getProblemStatus($problem) { if ($problem) { $result = mysql_query("SELECT `status` FROM `problems` WHERE id=$problem"); $row = mysql_fetch_array($result); return $row['status']; } else { return "open"; } } // returns counts of number responded and total participants function getResponseCount($problem) { $participants = getParticipantsForProblem($problem); $respondedCount = 0; $totalCount = 0; foreach ($participants as $participant) { if ($participant['hasResponded']) { $respondedCount = $respondedCount + 1; } $totalCount = $totalCount + 1; } return array($respondedCount, $totalCount); } ######################################################################## ## PROBLEM EXPIRATION ######################################################################## // returns 1 if expired, 0 otherwise function isExpired($problem) { $problem = getProblemById($problem); if ($problem['status'] == 'timed' && $problem['end_time'] && (date('Y', strtotime($problem['end_time'])-time()+21600) - 1970) < 0) { return 1; } else { return 0; } } // returns a text string of when the problem will expire function expirationTime($end_time) { if (!$end_time) { return "Manual Expiration"; } $year = date('Y', strtotime($end_time)-time()+21600) - 1970; if ($year < 0) { return "Expired"; } $month = date('m', strtotime($end_time)-time()+21600) -1; //FIX TIME ZONE YOU LAZY SCHED_DOODLEERS $day = date('d', strtotime($end_time)-time()+21600) - 1; $hour = date('H', strtotime($end_time)-time()+21600); $minutes = date('i', strtotime($end_time)-time()+21600); $seconds = date('s', strtotime($end_time)-time()+21600); if ($year > 1) { return "> 1 yr"; } if ($year == 1) { return "1 yr"; } if ($month > 1) { return $month . " mos"; } if ($month == 1) { return "1 mo"; } if ($day > 1) { return $day . " days"; } if ($day == 1) { return "1 day"; } if ($hour > 1) { return $hour . " hrs"; } if ($hour == 1) { return "1 hr"; } if ($minutes > 1) { return $minutes . " mins"; } if ($minutes == 1) { return "1 min."; } if ($seconds > 1) { return $seconds . " secs"; } if ($seconds <= 1) { return "closing"; } } ######################################################################## **** update ## RESPONDED ######################################################################## function hasResponded($problem, $user) { $result = mysql_query("SELECT * FROM `user2problem` WHERE userID=$user AND problemID=$problem"); $row = mysql_fetch_array($result); if ($row['hasResponded']) { return 1; } else { return 0; } } function markResponded($problem, $user) { $query = sprintf("UPDATE `user2problem` SET hasResponded=1 WHERE userID=%d AND problemID=%d", $user, $problem); mysql_query($query); } function markUnresponded($problem, $user) { $query = sprintf("UPDATE `user2problem` SET hasResponded=0 WHERE userID=%d AND problemID=%d", $user, $problem); mysql_query($query); } // if everyone has responded to a problem, return 1. else return 0 function allHaveResponded($problem) { $result = mysql_query("SELECT * FROM `user2problem` WHERE problemID=$problem AND hasResponded=0"); if (mysql_num_rows($result)) { return 0; } else { return 1; } } // returns an array of users for a problem and whether each user has responded or not function problemResponseStatus($problem) { $rows = array(); $result = mysql_query("SELECT * FROM `user2problem` WHERE problemID=$problem AND hasResponded=1"); while ($row = mysql_fetch_array($result)) { if ($row['hasResponded']) { $row = array("user" => $row['user'], "responded" => 1); // change to hasResponded } else { $row = array("user" => $row['user'], "responded" => 0); } $rows[] = $row; } return $rows; } ?><file_sep><?php include_once '../../includes/config.inc'; include_once 'functions.php'; checkPermissions(); if (!isset($_GET['problem'])) { die ("no problem specified"); } $problem = getProblemById($_GET['problem']); checkAllowedEdit($problem); $theHTML = ''; $resources = getAllResources($problem['id']); if (empty($resources)) { $theHTML .= '<li id="1">'; $theHTML .= '<input type="text" value="e.g. Monday 10:15 AM" onclick="if(this.value==\'e.g. Monday 10:15 AM\'){this.value=\'\';}">'; $theHTML .= '<a href="javascript:void(0);" onclick="addField(1);"><img src="../../images/add.png"></a>'; $theHTML .= '<a href="javascript:void(0);" onclick="deleteField(1);"><img src="../../images/delete.png"></a>'; $theHTML .= '<img src="../../images/drag.png">'; $theHTML .= '</li>'; $theHTML .= '<li id="2">'; $theHTML .= '<input type="text" value="e.g. Monday 10:30 AM" onclick="if(this.value==\'e.g. Monday 10:30 AM\'){this.value=\'\';}">'; $theHTML .= '<a href="javascript:void(0);" onclick="addField(2);"><img src="../../images/add.png"></a>'; $theHTML .= '<a href="javascript:void(0);" onclick="deleteField(2);"><img src="../../images/delete.png"></a>'; $theHTML .= '<img src="../../images/drag.png">'; $theHTML .= '</li>'; $theHTML .= '<li id="3">'; $theHTML .= '<input type="text" value="e.g. Monday 10:45 AM" onclick="if(this.value==\'e.g. Monday 10:45 AM\'){this.value=\'\';}">'; $theHTML .= '<a href="javascript:void(0);" onclick="addField(3);"><img src="../../images/add.png"></a>'; $theHTML .= '<a href="javascript:void(0);" onclick="deleteField(3);"><img src="../../images/delete.png"></a>'; $theHTML .= '<img src="../../images/drag.png">'; $theHTML .= '</li>'; $max_id = 3; } else { $max_id = 0; $theHTML = ''; foreach ($resources as $resource) { if ($resource['id'] > $max_id) { $max_id = $resource['id']; } $theHTML .= '<li id="' . $resource['id'] . '">'; $theHTML .= '<input type="text" value="' . $resource['name'] . '">'; $theHTML .= '<a href="javascript:void(0);" onclick="addField(' . $resource['id'] . ');"><img src="../../images/add.png"></a>'; $theHTML .= '<a href="javascript:void(0);" onclick="deleteField(' . $resource['id'] . ');"><img src="../../images/delete.png"></a>'; $theHTML .= '<img src="../../images/drag.png">'; $theHTML .= '</li>'; } } include_once PATH . '/includes/header.inc'; ?> <script src="<?php echo URL ?>/js/jquery-1.4.4.min.js"></script> <script src="<?php echo URL ?>/js/jquery-ui-1.8.9.custom.min.js"></script> <script src="problem.js"></script> <link type="text/css" href="../../css/jquery.ui/cupertino/jquery-ui-1.8.9.custom.css" rel="stylesheet" /> <link type="text/css" href="style.css" rel="stylesheet" /> <script> var max_id = <?php echo $max_id + 1; ?>; </script> <?php include_once PATH . '/includes/body.inc' ?> <h1><?php echo $problem['name']; ?></h1> <h3 style="text-align:center;">Add Resources</h3> <div id="dragbuttons"><ul id="sortable"><?php echo $theHTML ;?></ul></div> <div style="text-align: center;"><?php drawNotifyButton($problem['id']) ?></div> <div style="text-align:center;"><input type="button" id="saveButton" onclick="saveTimeSlots(<?php echo $problem['id'] ?>, 1);" value="Save"><input type="button" onclick="window.location='../../problems.php'" value="Discard Changes"></div> <?php include_once PATH . '/includes/footer.inc' ?> <file_sep><?php echo 'store how many people you can select. maybe some other stuff too'; ?><file_sep><?php include_once("includes/config.inc"); class custom_json { /** * Convert array to javascript object/array * @param array $array the array * @return string */ public static function encode($array) { // determine type if(is_numeric(key($array))) { // indexed (list) $output = '['; for($i = 0, $last = (sizeof($array) - 1); isset($array[$i]); ++$i) { if(is_array($array[$i])) $output .= self::encode($array[$i]); else $output .= self::_val($array[$i]); if($i !== $last) $output .= ','; } $output .= ']'; } else { // associative (object) $output = '{'; $last = sizeof($array) - 1; $i = 0; foreach($array as $key => $value) { $output .= '"'.$key.'":'; if(is_array($value)) $output .= self::encode($value); else $output .= self::_val($value); if($i !== $last) $output .= ','; ++$i; } $output .= '}'; } return $output; } /** * [INTERNAL] Format value * @param mixed $val the value * @return string */ private static function _val($val) { if(is_string($val)) return '"'.$val.'"'; elseif(is_int($val)) return sprintf('%d', $val); elseif(is_float($val)) return sprintf('%F', $val); elseif(is_bool($val)) return ($val ? 'true' : 'false'); else return 'null'; } } $return_arr = array(); /* Thoughts on whether or not the following is bad? I guess we should put this in the sql folder with everything else, both for organization */ $terms = explode(" ", $_GET['term']); $query = "("; // search through users foreach ($terms as $term) { $query .= "(firstNames LIKE '%" . $term . "%' OR lastNames LIKE '%" . $term . "%' OR name LIKE '%" . $term . "%') AND "; } $query = substr($query, 0, -5) . ")"; $fetch = mysql_query("SELECT id, firstNames, lastNames, name FROM users WHERE " . $query . " ORDER BY firstNames ASC LIMIT 20"); while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) { $row_array['id'] = $row['id']; $row_array['value'] = $row['firstNames'] . " " . $row['lastNames'] . ' (' . $row['name'] . ')'; $row_array['uid'] = $row['name']; array_push($return_arr,$row_array); } // search through groups $fetch = mysql_query("SELECT * FROM `groups` WHERE name LIKE '%" . $_GET['term'] . "%' ORDER BY name ASC"); while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) { if (!canUseGroup($row['id'], $current_user)) { continue; } // if the user cannot view the group, skip it $row_array['id'] = $row['id']; $row_array['value'] = "Group: " . $row['name']; $row_array['uid'] = $row['name']; array_push($return_arr,$row_array); } echo custom_json::encode($return_arr); ?> <file_sep><?php ######################################################################## ## DATA FUNCTIONS ######################################################################## /* * addData function: * update = 0: just insert the data without checking to see if it already exists * update = 1: if we find the data, update it and return; otherwise, add it * update = 2: if we find the data, do not update it and return; otherwise add it */ function addData($problem, $user, $key, $value, $update = 0) { $value = sanitize($value); switch ($update) { case 1: $result = mysql_query("SELECT * FROM data WHERE problem = $problem AND user = $user AND k = '$key'"); if (mysql_num_rows($result) == 1) { $query = sprintf("UPDATE `data` SET v='%s' WHERE problem=$problem AND user=$user AND k='%s'", $value, $key); mysql_query($query); return 1; } break; //Just in case. case 2: $result = mysql_query("SELECT * FROM data WHERE problem = $problem AND user = $user AND k = '$key'"); if (mysql_num_rows($result) == 1) { return 2; } break; } $query = sprintf("INSERT INTO `data` (`problem`, `user`, `k`, `v`) VALUES ('$problem', '$user', '%s', '%s')", $key, $value); mysql_query($query); return 0; } function updateData($problem, $user, $key, $value) { // maybe get rid of this function? delete this for sure. we are migrating to addData echo "do not user this function!!! update data"; $query = sprintf("UPDATE `data` SET v='%s' WHERE problem=$problem AND user=$user AND k='%s'", $value, $key); mysql_query($query); } function getData($problem, $user, $key) { $query = sprintf("SELECT * FROM `data` WHERE problem=%s AND user=%s AND k='%s'", $problem, $user, $key); $result = mysql_query($query); return mysql_fetch_array($result); } function getRawData($problem, $user, $key) { $query = sprintf("SELECT * FROM `data` WHERE problem =%s AND user=%s AND k='%s'", $problem, $user, $key); $result = mysql_query($query); return $result; } ?><file_sep>#include <stdio.h> #include <stdlib.h> #include <iostream> #include <string> #include <vector> #include <string> #include "dHall.h" #include "fileParser.h" using namespace std; /* *Takes input of the form * *UserID\HoursContracted\HoursDesired\UserID\HoursContracted\HoursDesired\...UserID\HoursContracted\HoursDesired\ *UserID\ShiftID\ShiftLength\Rank\UserID\ShiftID\ShiftLength\Rank\...UserID\ShiftID\ShiftLength\Rank\ * */ void fileParser(DiningHall* dh, char * s) { char * list1; char * list2; char * list3; string user; string hoursContracted; string hoursDesired; string shift; string rank; string shiftLength; list1 = strtok (s, "\n"); list2 = strtok (NULL, "\n"); //cout << "list1: " << list1 << endl; list1 = strtok (list1, "\\"); while (list1 != NULL) { //cout << "user obtainted" << endl; //cout << "user: " << list1 << endl; user = list1; list1 = strtok(NULL, "\\"); hoursContracted = list1; list1 = strtok(NULL, "\\"); hoursDesired = list1; dh->addSourceEdge(dh->edgeList, user, atof(hoursContracted.c_str()), atof(hoursDesired.c_str())); list1 = strtok(NULL, "\\"); //cout << "end of loop" << endl; } list2 = strtok (list2, "\\"); while (list2 != NULL) { //cout << "user obtainted" << endl; //cout << "user: " << list2 << endl; user = list2; list2 = strtok(NULL, "\\"); //cout << "shift obtainted" << endl; //cout << "shift: " << list2 << endl; shift = list2; list2 = strtok(NULL, "\\"); shiftLength = list2; list2 = strtok(NULL, "\\"); rank = list2; dh->addUserShiftEdge(dh->edgeList, user, shift, atof(shiftLength.c_str()), atof(rank.c_str())); dh->addSinkEdge(dh->edgeList, shift, atof(shiftLength.c_str())); list2 = strtok(NULL, "\\"); //cout << "end of loop2" << endl; } } <file_sep><?php include_once '../../includes/config.inc'; include_once 'functions.php'; checkPermissions(); $problem = getProblemById($_GET['problem']); include_once PATH . '/includes/header.inc'; ?> <link type="text/css" href="../../css/jquery.ui/cupertino/jquery-ui-1.8.9.custom.css" rel="stylesheet" /> <script src="../../js/jquery-1.4.4.min.js"></script> <script src="../../js/jquery-ui-1.8.9.custom.min.js"></script> <script type="text/javascript"> var i = 0; $(function(){ $('#tabs').tabs(); $.getJSON('defaults.json', function(data) { $.each(data.days, function(i, day) { $.each(day.shifts, function(i, shift) { loadShift(day.day, shift); }); }); }); }); function loadShift(day, name) { var startTimes = '<select><option>6:00am</option><option>6:15am</option><option>6:30am</option><option>6:45am</option><option>7:00am</option><option>7:15am</option><option>7:30am</option><option>7:45am</option><option>8:00am</option><option>8:15am</option><option>8:30am</option><option>8:45am</option><option>9:00am</option></select>'; var endTimes = '<select><option>6:00am</option><option>6:15am</option><option>6:30am</option><option>6:45am</option><option>7:00am</option><option>7:15am</option><option>7:30am</option><option>7:45am</option><option>8:00am</option><option>8:15am</option><option>8:30am</option><option>8:45am</option><option>9:00am</option></select>'; var radioButtons = '<div id="radio'+i+'"><input type="radio" id="radio1" name="radio'+i+'" /><label for="radio1">Breakfast</label><input type="radio" id="radio2" name="radio'+i+'" checked="checked" /><label for="radio2">Lunch</label><input type="radio" id="radio3" name="radio'+i+'" /><label for="radio3">Dinner</label><input type="radio" id="radio4" name="radio'+i+'" /><label for="radio3">Cleanup</label></div>'; var shiftText = '<tr><td><input type="text" value="' + name + '"></td><td>Start Time: ' + startTimes + '</td><td>End Time: ' + endTimes + '</td><td>' + radioButtons + '</td><td><input type="button" value="add" onclick="loadShift(\'' + day + '\', \'\');"></td></tr>'; $("#" + day + " table").append(shiftText); i++; } function saveHours() { $(".hours").each(function() { $.post("do.php", { "action":"saveContractedHours", "problem": <?php echo $problem['id'] ?>, "participant": $(this).attr("id"), "hours": $(this).val() }, function(data) { if (data.out != 0) {alert("error");} }, "json"); }); } </script> <style> .box {font-size:x-small; } table { width: 100%; } </style> <?php include_once PATH . '/includes/body.inc' ?> <h1>Dining Hall</h1> <div class="box"> <div id="tabs"> <ul> <li><a href="#start">Instructions</a></li> <li><a href="#hours">Worker Hours</a></li> <li><a href="#sun">Sun</a></li> <li><a href="#mon">Mon</a></li> <li><a href="#tues">Tues</a></li> <li><a href="#wed">Wed</a></li> <li><a href="#thurs">Thurs</a></li> <li><a href="#fri">Fri</a></li> <li><a href="#sat">Sat</a></li> <li><a href="#finish">Finish</a></li> </ul> <div id="start"> <p>Creating a dining hall schedule takes only three easy steps! Before completing each tab, make sure press save before moving on to the next tab.</p> <ol> <li>Add workers: In the “Add Workers” tab, add every worker.</li> <li>Assign Worker Hours: Assign designated hours to each worker in the “Worker Hours” tab. For each student, this number should be based on the number of hours Carleton allows the student to work per week.</li> <li>Add shifts: For each day of the week tab, add shifts by typing in a shift name and assigning a start time, end time, and meal to each shift.</li> <li> Finally, confirm that you have completed all three steps in the “Finish” tab in order to submit the schedule.</li> </ol> </div> <div id="hours"> <table style="width:50%;"> <?php $participants = getParticipantsForProblem($problem['id']); foreach ($participants as $participant) { ?> <tr> <td><?php echo getNameString($participant) ?></td> <td><select id="<?php echo $participant['id'] ?>" class="hours"> <?php $hours = getData($problem['id'], $participant['id'], 'contractedHours'); for ($i=0;$i<12.5;$i=$i+.5) { if ($i == $hours['v']) { echo '<option value="' . $i . '" selected>' . $i . '</option>'; } else { echo '<option value="' . $i . '">' . $i . '</option>'; } } ?> </select></td> </tr> <?php } ?> </table> <input type="button" value="save hours" onclick="saveHours()"> </div> <div id="sun"><table></table></div> <div id="mon"><table></table></div> <div id="tues"><table></table></div> <div id="wed"><table></table></div> <div id="thurs"><table></table></div> <div id="fri"><table></table></div> <div id="sat"><table></table></div> <div id="finish"><p>Please make sure you have completed every tab in the dining hall setup.</p><p>By clicking submit below, the set-up of your schedule will be completed.</p></div> </div> <?php include_once PATH . '/includes/footer.inc' ?><file_sep><?php include_once '../../includes/config.inc'; include_once 'functions.php'; checkPermissions(); if (!isset($_GET['problem'])) { die("no problem specified"); } $problem = getProblemById($_GET['problem']); // check to see if we find the problem $user = getUserById($current_user); checkAllowedView($problem); $resources = getAllResources($problem['id']); $preferences = getAllPreferences($problem['id']); $maxColIndex = getMaxColIndex($problem['id']); $resource = getResourceById($problem['id'], $maxColIndex); $comments = getData($problem['id'], 0, 'comments'); include_once PATH . '/includes/header.inc'; ?> <link rel="stylesheet" type="text/css" href="style.css"> <?php include_once PATH . '/includes/body.inc'; echo '<h1>' . $problem['name'] . '</h1>'; if ($problem['description']) { echo '<h2 style="text-align: center;">' . $problem['description'] . '</h2><hr>'; } echo '<h2 style="text-align: center;">Event Resource:</h2><h2 style="text-align: center; color: #009933;">' . $resource . '</h2><hr>'; if ($problem['comment']) { echo '<h2 style="text-align:center;">Comments From the Administrator:</h2>'; echo '<p style="text-align:center;">' . $problem['comment'] . '</p>'; } ?> <!-- <div style="width:100%;overflow:auto; text-align: center;"> <h2>Participant Responses</h2> <table id="viewTable"> <?php/* echo '<hr><tr><th>Name</th>'; foreach ($resources as $resource) { echo '<th>' . $resource['name'] . '</th>'; } echo "</tr>"; foreach ($preferences as $preference) { if ($preference['id'] == $user['id']) { continue; } if (!hasResponded($problem['id'], $preference['id'])) { $class = ' class="participantnotresponded"'; } else { $class = ''; } echo '<tr' . $class . '><td>' . $preference['name'] . '</td>'; foreach ($resources as $resource) { echo '<td>'; if (in_array($resource['id'], $preference['preference'])) { echo '<img src="' . URL . '/images/check.png">'; } echo '</td>'; } echo "</tr>"; } echo '</tr><tr style="background-color: #738AE1;"><td><b>' . $user['name'] . '</b></td>'; $preference = getPreferencesForParticipant($problem['id'], $user['id']); foreach ($resources as $resource) { echo '<td>'; if (in_array($resource['id'], $preference)) { echo '<img src="' . URL . '/images/check.png">'; } echo '</td>'; } */ ?> </tr> </table> </div> --> <?php include_once PATH . '/includes/footer.inc' ?> <file_sep><?php ######################################################################## ## PERMISSIONS FUNCTIONS ######################################################################## function isloggedin() { if (isset($_COOKIE['user'])) { return true; } return; // should return false here? } function checkPermissions() { // for now,this will just check to see if a user is logged in, but later it might do something else if (isloggedin() == false) { if ($_SERVER['QUERY_STRING']) { $querystring = '?' . $_SERVER['QUERY_STRING']; } echo '<script>window.location="' . URL . '/login.php?redirect=' . $_SERVER['PHP_SELF'] . $querystring . '";</script>'; } } function checkAllowedEdit($problem) { global $current_user; if (!isAdminInProblem($current_user, $problem['id'])) { die("you are not allowed to edit this event"); } else { return; } } function checkAllowedViewResponses($problem) { global $current_user; if (!isAdminInProblem($current_user, $problem['id'])) { die("you are not allowed to view user responses to this event"); } else { return; } } function checkAllowedView($problem) { global $current_user; if (!isParticipantInProblem($current_user, $problem['id'])) { die("you are not a participant"); } else if ($problem['status'] != "posted") { die(" the problem is not posted yet"); } else { return; } } function checkAllowedRespond($problem) { // also check to make sure we are responding in the right directory. aka not a many to one for bipartite global $current_user; switch ($problem['type']) { case "private": if (!isParticipantInProblem($current_user, $problem['id'])) { die("this is a private problem. you are not allowed to join"); } // do not break here since we will perform addition checks case "public": if ($problem['status'] == "open") { return; } else if ($problem['status'] == "timed") { if (isExpired($problem['id'])) { die("the schedule is expired"); } else { return; } } else if ($problem['status'] == "closed") { die("the schedule is closed"); } else if ($problem['status'] == "posted") { die("the problem is posted. you should go and view the results instead of trying to go to the respond page"); } else { die("this problem has no status. please set one on the edit problem page"); } break; default: die("error in checkAlloweResp: no problem type"); break; } } function loginlink() { if (isloggedin() == true) { $user = getUserById($_COOKIE['user']); //I added a change password link. This code is horrifically ugly. Someone help me change it please. print 'Welcome, ' . $user['name'] . '. [<a href="javascript:void(0)" onclick="logout()">logout</a>]' . ' [<a href = "' . URL . '/changepass.php">change password</a>]'; } else { print '[<a href="' . URL . '/login.php">login</a>]'; } } ?><file_sep>#include <vector> #include <string> #ifndef dHall_H #define dHall_H using namespace std; class Edge { public: float edgeType; bool fwd; float flow; float capacity; //Edge(string x, string y, int z); //Edge(); //virtual Edge oedge(); //~Edge(); virtual void useless() {}; }; class SourceEdge: public Edge { public: string user; float contracted; float desired; SourceEdge(string x, float y, float z); SourceEdge(); SourceEdge *rSourceEdge; //virtual Edge oedge(); //~Edge(); }; class UserShiftEdge: public Edge { public: string user; string shift; float shiftLength; float rank; UserShiftEdge(string w, string x, float y, float z); UserShiftEdge(); UserShiftEdge *rUserShiftEdge; //virtual Edge oedge(); //~Edge(); }; class SinkEdge: public Edge { public: string shift; float shiftLength; SinkEdge(string x, float y); SinkEdge(); SinkEdge *rSinkEdge; //virtual Edge oedge(); //~Edge(); }; class DiningHall { public: vector <Edge*> edgeList; DiningHall(vector<Edge*> & edgeList); void addSourceEdge(vector<Edge*> & edgeList, string u, float v, float w); void addUserShiftEdge(vector<Edge*> & edgeList, string u, string v, float w, float x); void addSinkEdge(vector<Edge*> & edgeList, string u, float v); ~DiningHall(); }; #endif <file_sep><?php if (isset($_COOKIE['user'])) { header("Location: problems.php"); } include_once 'includes/config.inc'; include_once 'includes/header.inc'; include_once 'includes/body.inc' ?> <script src="js/jquery-1.4.2.min.js"></script> <script> function resetpassword() { $.post("do.php", { "action":"reset_password", "user":$("input[name='user']").val()}, function(data) { $("#error").css("display","none"); if (data.out == 1) { window.location = "login.php?message=3"; } else if (data.out == 0) { $("#error").css("display","block"); } },"json"); } </script> <h1>Forgot Password</h1> <form id="centerForm" onSubmit="resetpassword(); return false;"> <table> <tr><td>Carleton User ID</td><td style="width: 200px;"><input type="text" size="20" name="user"></td></tr> <tr><td></td><td><input type="submit" name="submit" value="Email me a new password"></td></tr> <tr><td></td><td class="error" id="error">That account is not <a href="authenticateaccount.php">activated</a>, or it is not in our database.</td></tr> </table> </form> <?php include_once 'includes/footer.inc' ?> <file_sep>/* * Original Author: <NAME> * Edited 2/2011 by <NAME> */ var currentSelection = 0; var currentUrl = ''; /* google.load("jquery", "1.3.1"); google.setOnLoadCallback(function() */ $(document).ready(function() { // Register keypress events on the whole document //$('#participantBox').keypress(function(e) { $('#participantBox').live('keydown',function(e) { //alert('This code was read, at least!'); switch(e.keyCode) { // User pressed "up" arrow case 38: navigate('up'); break; // User pressed "down" arrow case 40: navigate('down'); break; // User pressed "enter" case 13: if(currentUrl != '') { window.location = currentUrl; } break; } }); // Add data to let the hover know which index they have for(var i = 0; i < $("#suggestions ul li a").size(); i++) { $("#suggestions ul li a").eq(i).data("number", i); } // Simulote the "hover" effect with the mouse $("#suggestions ul li a").hover( function () { currentSelection = $(this).data("number"); setSelected(currentSelection); }, function() { $("#suggestions ul li a").removeClass("itemhover"); currentUrl = ''; } ); }); function navigate(direction) { // Check if any of the suggestions items is selected /* if($("#suggestions ul li .itemhover").size() == 0) { currentSelection = -1; } if(direction == 'up' && currentSelection != -1) { alert('Look, I got called!'); if(currentSelection != 0) { currentSelection--; } } else if (direction == 'down') { if(currentSelection != $("#suggestions ul li").size() -1) { currentSelection++; } } */ var currentSelection = 0; if(direction == 'up' && currentSelection != -1) { alert('Someone pressed the up button!' + currentSelection); if(currentSelection != 0) { currentSelection--; } } else if (direction == 'down') { alert('Someone pressed the down button!' + currentSelection); if(currentSelection != $("#suggestions ul li").size() -1) { currentSelection++; } } setSelected(currentSelection); } function setSelected(menuitem) { $("#suggestions ul li a").removeClass("itemhover"); $("#suggestions ul li a").eq(menuitem).addClass("itemhover"); currentUrl = $("#suggestions ul li a").eq(menuitem).attr("href"); } <file_sep><?php include_once "/Accounts/scheddoodle/sched-doodle/web/includes/config.inc"; include_once "/Accounts/scheddoodle/sched-doodle/web/includes/functions.php"; $problems = getClosingProblems(); foreach ($problems as $problem) { $algorithm = getAlgorithmById($problem['algorithm']); $participants = getParticipantsForProblem($problem['id']); $to = "<EMAIL>"; } $headers = 'From: emailtest'; $body = 'this is a test'; $subject = 'test'; mail($to, $subject, $body, $headers); ?> <file_sep>CREATE TABLE users ( id integer primary key AUTO_INCREMENT, -- the user's id name text, -- the user's name email text, -- the user's email password text, -- the <PASSWORD> created date, -- the date the user was added activated integer, firstNames text, lastNames text ); CREATE TABLE groups ( id integer primary key AUTO_INCREMENT, -- the group's id name text, -- the group's name description text, -- description of the group type text -- whether the group is public, private, or admin ); CREATE TABLE user2group ( userID integer, -- the user id groupID integer, -- the group id isAdmin integer DEFAULT 0, -- 0 if not admin, 1 if admin isParticipant integer DEFAULT 0 -- 0 if not, 1 if pending, 2 if in group ); CREATE TABLE user2problem ( userID integer, problemID integer, isAdmin integer DEFAULT 0, isParticipant integer DEFAULT 0, hasResponded integer DEFAULT 0, isArchived integer DEFAULT 0 ); CREATE TABLE group2problem ( groupID integer, problemID integer, isAdmin integer DEFAULT 0, isParticipant integer DEFAULT 0 ); CREATE TABLE problems ( id integer primary key AUTO_INCREMENT, name text, -- the name of the problem algorithm text, -- the name of the algorithm description text, -- admin's description of the problem end_time datetime, -- the time that the problem expires if the status is timed (maybe convert to timestamp type) status text, -- stores the problem status comment text, -- stores comments from the admin to the participants for when they view a problem type text, -- stores the problem type (public or private) created timestamp DEFAULT NOW() -- stores when the problem was created ); CREATE TABLE data ( -- maybe make a separate table for preferences to improve speed? problem integer, -- specifies a problem id (when user=0: can hold setup information for the problem - ie specified time slots, etc) user integer, -- specifies the user id (when problem=0: can hold default user information, email address, etc) k text, -- ie: preferences, calendar_url v text -- the value ); CREATE TABLE algorithms ( id integer primary key AUTO_INCREMENT, name text, -- the name of the algorithm slug text, -- the name of the folder that the algorithm is in description text -- a description of the algorithm );<file_sep><?php include_once 'includes/config.inc'; include_once 'includes/header.inc'; checkPermissions(); $problems = getProblemsForUser($current_user); $problems = sortProblemsByRelevance($problems, $current_user); ?> <script src="js/problems.js"></script> <script src="js/jquery-ui-1.8.10.custom.min.js"></script> <!--<link rel="stylesheet" href="css/jquery.ui.css">--> <link rel="stylesheet" href="css/help.css"> <?php include_once 'includes/body.inc' ?> <div id="toolbar"> <div style="position:relative;float:left;"><input id="newEventButton" type="button" value="New Event" onclick="window.location='new_problem.php'"></div> <div style="position:relative;float:right;"> <div id="basicSearchDiv"> View Events: <select onChange="view(this.value);"> <option value="current">Visible</option> <option value="notresponded">Not Yet Responded</option> <option value="participant">You Are A Part Of</option> <option value="admin">You Created</option> <option value="row">All</option> </select> <a href="javascript:void(0)" id="showAdvancedSearchButton" title="Click for advanced filtering options.">Advanced</a> </div> <div id="advancedSearchDiv"> <table> <tr> <td>Visibility:</td> <td><select id="visibility"> <option value="current">Visible</option> <option value="row:not(.current)">Hidden</option> <option value="row">All</option> </select></td> <td><a href="javascript:void(0)" id="hideAdvancedSearchButton" title="Click for basic filtering options.">Basic</a></td> </tr> <tr> <td>Admin/Participant:</td> <td><select id= "userStatus"> <option value="row">All</option> <option value="admin">Administrator</option> <option value="participant">Participant</option> <option value="admin.participant">Admin/Participant</option> </select></td><td></td> </tr> <tr> <td>Response Status:</td> <td> <select id="responseStatus"> <option value="row">All</option> <option value="notresponded">Not Yet Responded</option> <option value="responded">Already Responded</option> </select></td><td></td> </tr> <tr> <td>Problem Status:</td> <td><select id="problemStatus"> <option value="row">All</option> <option value="open">Open</option> <option value="closed">Closed</option> <option value="posted">Posted</option> </select></td><td></td> </tr> <tr> <td></td><td colspan="2"><input id="advancedFilterButton" type="button" value="Filter" onclick='advancedView($("#visibility").val(), $("#userStatus").val(), $("#responseStatus").val(), $("#problemStatus").val());'></td> </tr> </table> </div> </div> </div> <div id="emptyEventsTable" class="emptyItemTable" style="display: none;"><p>There are no events in this category.</p></div> <?php if (!empty($problems)) { echo '<table id="eventsTable" class="itemTable"><tr><th>Event</th><th>Status</th><th>Action</th></tr>'; } // we assume there are no current problems at the start $showNone = 1; foreach ($problems as $problem) { if ($problem['name'] == '') { $problem['name'] = "[untitled]"; } $algorithm = getAlgorithmById($problem['algorithm']); $openSelected = ''; $closedSelected = ''; $timedSelected = ''; $postedSelected = ''; // deal with the status of a problem $status = ''; switch ($problem['status']) { // status // select checker // the response link case "open": $status .= "Open"; $class = "open"; $openSelected = " selected"; $respondLink = '[<a href="respond.php?problem=' . $problem['id'] . '">Respond</a>]'; break; case "closed": $status .= "Closed"; $class = "closed"; $closedSelected = " selected"; $respondLink = ''; break; case "timed": if (isExpired($problem['id'])): $status .= "Expired"; $class = "closed"; $timedSelected = " selected"; $respondLink = ''; else: $status .= expirationTime($problem['end_time']); $class = ""; $timedSelected = " selected"; $respondLink = '[<a href="respond.php?problem=' . $problem['id'] . '">Respond</a>]'; endif; break; case "posted": $status .= "Posted"; $class = "posted"; $postedSelected = " selected"; $respondLink = '[<a href="view.php?problem=' . $problem['id'] . '">View</a>]'; break; default: $status .= "No Status"; $class = "nostatus"; $respondLink = "No Status"; break; } // deal with user's role in a problem if ($problem['isAdmin'] && $problem['isParticipant']) { // if the user is an admin and participant to the problem $class .= " row admin participant"; $badges = ' <img id="admin" src="images/admin.png" title="You are the admin of this event.">'; $editLink = '<img src="images/edit.png" title="Edit Event" class="editLink">'; $deleteLink = '<a href="javascript:void(0);" onclick="javascript:deleteProblem(' . $problem['id'] . ',\'' . addslashes($problem['name']) . '\');"><img src="images/delete.png" title="Delete Event"></a>'; if (!hasResponded($problem['id'], $current_user)) { $class .= " notresponded"; } else { $class .= " responded"; } $more = '<strong>Type: </strong>' . $algorithm['name'] . '<br><strong>Description: </strong>'; if ($problem['description']) { $more .= $problem['description'] . '<br>'; } else { $more .= "[no description]"; } $respondLink .= ' [<a href="run.php?problem=' . $problem['id'] . '">Finalize Event</a>]'; list($respondedCount, $totalCount) = getResponseCount($problem['id']); $status .= '<br><a href="responses.php?problem=' . $problem['id'] . '">' . "{$respondedCount}/{$totalCount}" . ' Responded</a>'; } else if ($problem['isAdmin']) { // if the user is only an admin to the problem $class .= " row admin"; $badges = ' <img id="admin" src="images/admin.png" title="You are the admin of this event.">'; $editLink = '<img src="images/edit.png" title="Edit Event" class="editLink">'; $deleteLink = '<a href="javascript:void(0);" onclick="javascript:deleteProblem(' . $problem['id'] . ',\'' . addslashes($problem['name']) . '\');"><img src="images/delete.png" title="Delete Event"></a>'; $more = '<strong>Type: </strong>' . $algorithm['name'] . '<br><strong>Description: </strong>'; if ($problem['description']) { $more .= $problem['description'] . '<br>'; } else { $more .= "[no description]"; } $respondLink = '[<a href="run.php?problem=' . $problem['id'] . '">Finalize Event</a>]'; list($respondedCount, $totalCount) = getResponseCount($problem['id']); $status .= '<br><a href="responses.php?problem=' . $problem['id'] . '">' . "{$respondedCount}/{$totalCount}" . ' Responded</a>'; } else if ($problem['isParticipant']) { // if the user is only a participant $class .= " row participant"; $badges = ""; $editLink = '<span style="margin-left:16px;"></span>'; $deleteLink = '<span style="margin-left:16px;"></span>'; if (!hasResponded($problem['id'], $current_user)) { $class .= " notresponded"; } else { $class .= " responded"; } $adminString = ''; $admins = getAdminsForProblem($problem['id']); foreach ($admins as $admin) { $adminString .= getNameString($admin) . ', '; } $adminString = substr($adminString, 0, -2); $more = '<strong>Type: </strong>' . $algorithm['name'] . '<br><strong>From:</strong> ' . $adminString; if ($problem['description']) { $more .= '<br><strong>Description:</strong> ' . $problem['description']; } } // deal with archiving if ($problem['isArchived']) { $archiveLink = '<a href="javascript:void(0);" onclick="unArchiveProblem(' . $problem['id'] . ', ' . $current_user . ');"><img src="images/unarchive.png" title="Unhide Event"></a>'; } else { $archiveLink = '<a href="javascript:void(0);" onclick="archiveProblem(' . $problem['id'] . ', ' . $current_user . ');"><img src="images/archive.png" title="Hide Event"></a>'; $class .= " current"; $showNone = 0; } ?> <tr class="<?php echo $class ?>" id="<?php echo $problem['id'] ?>"> <td> <img class="infoButton" src="images/downarrow.png" title="Click for the event description."> <span class="title"><?php echo $problem['name'] ?><?php echo $badges ?></span> <div style="position:relative;float:right;"><?php echo $respondLink ?></div> <div class="more"><?php echo $more ?></div> </td> <td class="statusColumn"><?php echo $status ?></td> <td class="actionColumn"><?php echo $editLink ?><span class="archiveLink"><?php echo $archiveLink ?></span><?php echo $deleteLink ?></td> </tr><?php } if (!empty($problems)) { echo '</table>'; } if ($showNone) { echo '<script>view(".current");</script>'; } ?> <div id="dialog" title="Help - Main Page"> <p>This is the Main Page of <strong>Sched-A-Roo</strong>, where you can organize, create, edit, and respond to schedules.</p> <p><strong>To repond to a schedule</strong>, click on the blue "Respond" link next to the title of a schedule. If you have not yet responded to a schedule, that schedule will be highlighted in blue. Once a schedule is closed by its creator, you can no longer respond, but you may be able to view the results.</p> <p><strong>To create a new schedule</strong>, click on the "New Event" button on the upper left side of the page.</p> <p><strong>To hide a schedule</strong>, click on the eye icon in the last column. You can view hidden schedules, as well as <strong>sort schedules</strong> by your role, by using the "View Events" drop-down menu.</p> <p><strong>Advanced filtering</strong> is accessed by pressing the double arrows next to the "View Events" menu.</p> <p><strong>Creator options</strong> include: <ul> <li> <img src="images/archive.png"><strong> Delete an event</strong></li> <li> <img src="images/edit.png"><strong> Edit an event</strong></li> <li> [<span style="color:blue">Finalize Event</span>] <strong>Finalize an event</strong>.</li></ul> <p>Event creators will see a <img src="images/admin.png"> by events they have created.</p> <p><strong>For more help</strong>, please see the <a href="help.php">help page</a>.</p> </div> <?php include_once 'includes/footer.inc' ?> <file_sep><?php // updates a user's preferences function updatePreferences($problem, $user, $resources) { $problem = getProblemById($problem); if (!isUserInProblem($user, $problem['id']) && $problem['type'] == "public") { addUserToProblem($problem['id'], $user); } $preferences = ''; // initialize preferences string //$resources = $_POST['resources']; // get the list of boxes that the user checked foreach ($resources as $resource) { $preferences .= $resource . "\n"; // add the ids to the preference list for that user } $preferences = substr($preferences, 0, -1); // take off the last new line addData($problem['id'], $user, 'preference', $preferences, 1); // 1 means update or add } // runs the BPM script function calculate($problem) { $input = ''; $preferences = getPreferences($problem); foreach($preferences as $preference) { $user = $preference['user']; $resources = preg_split('[\r\n|\r|\n]', $preference['v']); foreach ($resources as $resource) { $input = $input . 'U' . $user . '\t' . 'R' . $resource . '\n'; } } exec("./BPM " . $input, $assignments); mysql_query("DELETE FROM data WHERE problem=$problem AND k='assignment'"); // make this a function maybe? $participants = getParticipantsForProblem($problem); foreach ($participants as $participant) { addData($problem, substr($participant['id'], 1), 'assignment', 0, 1); } foreach ($assignments as $assignment) { $assignment = preg_split("[\s]", $assignment); list($user, $resource) = $assignment; addData($problem, substr($user, 1), 'assignment', substr($resource, 1), 1); } } // returns an array of preferences for a participant function getPreferencesForParticipant($problem, $user) { $result = mysql_query("SELECT * FROM data WHERE problem=$problem AND user=$user AND k='preference'"); $row = mysql_fetch_array($result); return preg_split('[\r\n|\n|\r]', $row['v']); } // returns an array of every user's preferences to a particular problem.id -- phase this out function getPreferences($problem) { $preferences = array(); $query = "SELECT * FROM `data` WHERE problem=$problem AND k='preference'"; $result = mysql_query($query); while ($preference = mysql_fetch_array($result)) { $preferences[] = $preference; } return $preferences; } // returns an array of every user's preferences to a particular problem.id function getAllPreferences($problem) { // change this to get all preferences $rows = array(); $participants = getParticipantsForProblem($problem); foreach ($participants as $participant) { $preference = getPreferencesForParticipant($problem, $participant['id']); if ($preference[0]) { $participant['preference'] = $preference; } else { $participant['preference'] = array(); } $rows[] = $participant; } return $rows; } function getUsersForResource($problem,$resource) { $users = array(); $participants = getParticipantsForProblem($problem); foreach ($participants as $participant) { $preferences = getPreferencesForParticipant($problem,$participant['id']); if (in_array($resource, $preferences)) { $users[] = $participant['id']; } } return $users; } // returns the assignment for a participant function getAssignmentForParticipant($problem, $user) { $result = mysql_query("SELECT * FROM data WHERE problem=$problem AND user=$user AND k='assignment'"); $row = mysql_fetch_array($result); return getResourceById($problem, $row['v']); } // returns the stored matching of users and resources function getAssignments($problem) { $assignments = array(); $usedResources = array(); $unassignedUsers = array(); $participants = getParticipantsForProblem($problem); foreach ($participants as $participant) { $assignment = getAssignmentForParticipant($problem, $participant['id']); if (!$assignment && $assignment['id'] == 0) { $unassignedUsers[] = $participant; } else { $participant['assignment'] = $assignment; $usedResources[$assignment['id']] = 1; $assignments[] = $participant; } } $resources = getAllResources($problem); foreach ($resources as $resource) { if (!isset($usedResources[$resource['id']])) { $assignments[] = array("id" => 0, "name" => "", "firstNames" => "--", "lastNames" => "", "assignment" => $resource); } } return array($assignments, $unassignedUsers); } // returns an array of all resources function getAllResources($problem) { $query = sprintf("SELECT * FROM data WHERE problem=%d AND user=0 AND k='resources'", $problem); $result = mysql_query($query); $resources = mysql_fetch_array($result); if (!$resources || $resources == "") { return array(); } else { $resources = preg_split('[\r\n|\n|\r]', $resources['v']); $rows = array(); foreach ($resources as $resource) { if ($resource == "") { continue; } $resource = preg_split('[::]', $resource); $rows[] = array('id' => $resource[0], 'name' => $resource[1]); } return $rows; } } // returns a resource based on its ID function getResourceById($problem, $resourceID) { $resources = getAllResources($problem); foreach ($resources as $resource) { if ($resource['id'] == $resourceID) { return array('id' => $resourceID, 'name' => $resource['name']); } } return null; } ?><file_sep>#include <iostream> #include <vector> #include <algorithm> #include <string> #include <utility> // make_pair #include <stdio.h> #include <stdlib.h> #include <sstream> #include "FileParser.h" #include "BPMatch.h" using namespace std; Edge::Edge(string x, string y, int z) { fwd = -1; u=x; v=y; w=z; flow = 0; } Edge::Edge(){} //Edge::~Edge(){} string IntToString(int i) { string s; stringstream out; out << i; s = out.str(); return s; } FlowNetwork::FlowNetwork(vector<Edge*> & edgeList) { FlowNetwork::edgeList = edgeList; } FlowNetwork::~FlowNetwork() { for (vector<Edge*>::iterator iter = edgeList.begin(); iter != edgeList.end(); ++iter) { //cout << "garbage collecting edge" << endl; delete (*iter); } } void FlowNetwork::addEdge(vector<Edge*> & edgeList, string u, string v, int w) { Edge* fedge = new Edge(u, v, w); Edge* redge = new Edge(v, u, 0); fedge->redge = redge; redge->redge = fedge; edgeList.push_back(fedge); edgeList.push_back(redge); } void FlowNetwork::findPath(FlowNetwork* fn, string source, string sink) { string s; //printf("Source: %s\n", source.c_str()); //printf("Sink: %s\n", sink.c_str()); //printf("Comparing Source and Sink: %d\n", source.compare(sink)); if (source.compare(sink) == 0) { //cout << "returning newPath" << endl; return; //return newPath; } //cout << "beginning findPath recursions" << endl; for (vector<Edge*>::iterator iter = fn->edgeList.begin(); iter != fn->edgeList.end(); ++iter) { //printf("Source: %s\n", source.c_str()); //printf("Iter->u: %s\n", (*iter)->u.c_str()); //printf("Comparing Source and iter->u: %d\n", source.compare((*iter)->u)); if (source.compare((*iter)->u) == 0) { int residual = (*iter)->w - (*iter)->flow; int match = 0; for (vector<pair<int, Edge*> >::iterator i = fn->path.begin(); i != fn->path.end(); ++i) { //cout << "(*iter)->u: " << (*iter)->u << endl << "i->second->u: " << i->second->u << endl; //cout << "u_cmp: " << (i->second->u.compare((*iter)->u)) << endl; //cout << "(*iter)->v: " << (*iter)->v << endl << "i->second->v: " << i->second->v << endl; //cout << "v_cmp: " << (i->second->v.compare((*iter)->v)) << endl; //cout << "residual: " << residual << endl << "i->first: " << i->first << endl; if ((i->second->u.compare((*iter)->u) == 0) && (i->second->v.compare((*iter)->v) == 0) && residual == i->first) { match++; } } //cout << "match: " << match << endl; //cout << "residual: " << residual << endl; if (residual > 0 && !match) { pair<int, Edge*> p = make_pair(residual, (*iter)); fn->path.push_back(p); //cout << "Recursing on findPath" << endl; fn->findPath(fn, (*iter)->v, sink); //cout << "Done recursing on findPath" << endl; //cout << fn->path.end()->first << endl; if (fn->path.at(fn->path.size()-1).first) { return; } else { fn->path.pop_back(); fn->path.pop_back(); } } } } //cout << "ending findPath without a path" << endl; string y ("stringy"); string z ("stringz"); int zero = 0; Edge *fakeEdge = new Edge(y, z, zero); pair<int, Edge*> fakePair = make_pair(zero, fakeEdge); //fn->path.clear(); fn->path.push_back(fakePair); } void FlowNetwork::maxFlow(FlowNetwork* fn, string source, string sink) { int flow; vector<int> weights; //cout << "calling find path" << endl; fn->findPath(fn, source, sink); //cout << "Path found" << endl; while (1) { if (!fn->path.at(0).first) { //cout << "Returning finalPath" << endl; return; } for (vector<pair<int, Edge*> >::iterator i = fn->path.begin(); i != fn->path.end(); ++i) { weights.push_back(i->first); } flow = *(min_element(weights.begin(), weights.end())); //cout << "Altering Flow Values" << endl; for (vector<pair<int, Edge*> >::iterator iter = fn->path.begin(); iter != fn->path.end(); ++iter) { iter->second->flow += flow; iter->second->redge->flow -= flow; //cout << "Flow from " << iter->second->u << " to " << iter->second->v << " = " << iter->second->flow << endl; //cout << "Flow from " << iter->second->v << " to " << iter->second->u << " = " << iter->second->redge->flow << endl; fn->finalPath.push_back((*iter)); } //cout << "calling find path" << endl; fn->path.clear(); weights.clear(); fn->findPath(fn, source, sink); //cout << "Path found" << endl; //cout << "beginning new loop" << endl; } //cout << "ending loop" << endl; return; } /* int main() { int i; int j; vector<Edge> edgesList (11); edgesList.at(0) = Edge(string("WES"), string("1:30"), 2); edgesList.at(1) = Edge(string("NATE"), string("1:30"), 2); edgesList.at(2) = Edge(string("NATE"), string("3:30"), 2); edgesList.at(3) = Edge(string("NATE"), string("5:30"), 2); edgesList.at(4) = Edge(string("CARL"), string("3:30"), 2); edgesList.at(5) = Edge(string("source"), string("WES"), 2); edgesList.at(6) = Edge(string("1:30"), string("sink"), 2); edgesList.at(7) = Edge(string("source"), string("NATE"), 2); edgesList.at(8) = Edge(string("3:30"), string("sink"), 2); edgesList.at(9) = Edge(string("5:30"), string("sink"), 2); edgesList.at(10) = Edge(string("source"), string("CARL"), 2); for (j=0; j < edgesList.size(); j++) { cout << "u: " << edgesList.at(j).u << endl; cout << "v: " << edgesList.at(j).v << endl; cout << "weight: " << edgesList.at(j).w << endl; } FlowNetwork flownet (edgesList); vector<pair<int, Edge> > path; path = flownet.maxFlow(string("source"), string("sink")); for (i=0; i < path.size(); i++) { cout << path.at(i).second.u << ", " << path.at(i).second.v << ", " << path.at(i).second.flow << endl; } cout << "Enter Something to End"; cin >> i; path.clear(); //path2.clear(); return 0; } */ int main(int argc, char * argv[]) { int i; int j; vector<Edge*> edgesList; FlowNetwork* flownet = new FlowNetwork(edgesList); char input [strlen(argv[1])+1]; strcpy(input,argv[1]); //cout << "calling fileParser" << endl; FileParser(flownet, input); //cout << "done calling fileParser" << endl; if (flownet->edgeList.size() == 0) { //cout << "void working improperly" << endl; return 1; } //for (j=0; j < edgesList.size(); j++) //{ // cout << "u: " << edgesList.at(j).u << endl; // cout << "v: " << edgesList.at(j).v << endl; // cout << "weight: " << edgesList.at(j).w << endl; //} //cout << edgesList.size() << endl; if (flownet->edgeList.size() > 0) { vector<pair<int, Edge*> > *path; //cout << "Calling Max Flow" << endl; flownet->maxFlow(flownet, string("source"), string("sink")); //cout << "Max Flow Complete" << endl; for (j=0; j < flownet->finalPath.size(); j++) //erase source and sink edges { if (flownet->finalPath.at(j).second->u.compare(string("source")) == 0) { flownet->finalPath.erase(flownet->finalPath.begin()+j); j--; } else if (flownet->finalPath.at(j).second->v.compare(string("source")) == 0) { flownet->finalPath.erase(flownet->finalPath.begin()+j); j--; } else if (flownet->finalPath.at(j).second->v.compare(string("sink")) == 0) { flownet->finalPath.erase(flownet->finalPath.begin()+j); j--; } else if (flownet->finalPath.at(j).second->u.compare(string("sink")) == 0) { flownet->finalPath.erase(flownet->finalPath.begin()+j); j--; } } for (vector<pair<int, Edge*> >::iterator iter = flownet->finalPath.begin(); iter != flownet->finalPath.end(); ++iter) // erase edges that have been 'repealed' { for (vector<pair<int, Edge*> >::iterator i = (iter + 1); i != flownet->finalPath.end(); ++i) { //cout << "iter->second->u: " << iter->second->u << endl; //cout << "iter->second->v: " << iter->second->v << endl; //cout << "i->second->u: " << i->second->u << endl; //cout << "i->second->v: " << i->second->v << endl; if ((i->second->u.compare(iter->second->v) == 0) && (i->second->u.compare(iter->second->v) == 0)) { flownet->finalPath.erase(i, i+1); flownet->finalPath.erase(iter, iter+1); i--; iter--; break; } } } for (i=0; i < flownet->finalPath.size(); i++) { cout << flownet->finalPath.at(i).second->u << " " << flownet->finalPath.at(i).second->v << endl; } } //cout << "Enter Something to End" << endl; //cin >> i; delete flownet; return 0; } <file_sep><?php include_once 'includes/config.inc'; checkPermissions(); if (isset($_GET['problem'])) { // if we are updating an existing problem $problem = getProblemById($_GET['problem']); checkAllowedEdit($problem); $algorithm = getAlgorithmFromProblem($problem['id']); $action = "update_problem"; $users = getParticipantsForProblem($problem['id']); $theUsers = ''; foreach ($users as $user) { if (!hasResponded($problem['id'], $user['id'])) { $respondText = ' <img src="images/alert.png" title="has not responded">'; } else { $respondText = ""; } $theUsers .= '<li><input type="checkbox" name="existing_participants[]" value="' . $user['id'] . '" checked>' . getNameString($user) . $respondText . "</li>\n"; } } else { $action = "add_problem"; $problem['id'] = 0; $algorithm = getAlgorithmById($_GET['type']); } // if we are starting a new problem include_once "includes/header.inc"; ?> <link type="text/css" href="css/jquery.ui/cupertino/jquery-ui-1.8.9.custom.css" rel="stylesheet"> <script src="js/jquery-ui-1.8.9.custom.min.js"></script> <script src="js/jquery-ui-timepicker-addon.js"></script> <script src="js/problem.js"></script> <script src="js/autoComplete.js"></script> <script> var algorithm = "<?php echo $algorithm['slug'] ?>"; </script> <?php include_once "includes/body.inc" ?> <div id="output"></div> <form id="form"> <input type="hidden" name="action" value="<?php echo $action ?>"> <input type="hidden" name="algorithm" value="<?php echo $algorithm['id'] ?>"> <input type="hidden" name="problem" value="<?php echo $problem['id'] ?>"> <div class="block"> <h2>Event Name:</h2> <input type="text" name="name"<?php if ($action == "update_problem") { echo ' value="' . $problem['name'] . '"'; } ?> size="40"> <h2>Event Type:</h2> <?php echo $algorithm['name'] ?> <h2>Event Description:</h2> <textarea name="description" rows="5" cols="50"><?php if ($action == "update_problem") { echo $problem['description']; } ?></textarea> <h2>Event Type:</h2> <p class="radioBlock"> <?php $privateChecked = ''; $publicChecked = ''; if (isset($problem['type']) && $problem['type'] == "public") { $publicChecked = " checked"; } else { $privateChecked = " checked"; } ?> <input type="radio" name="type" value="private"<?php echo $privateChecked ?>>Private (Only Specified Participants Can Respond)<br> <input type="radio" name="type" value="public"<?php echo $publicChecked ?>>Public (Anyone Can Respond) </p> <h2>Event Status:</h2> <p class="radioBlock"> <?php $openChecked = ''; $closedChecked = ''; $timedChecked = ''; if ($problem['id'] && $problem['end_time']) { $timedExpiration = $problem['end_time']; } else { $timedExpiration = '0000-00-00 00:00'; } $timedDisabled = ' disabled'; $postedChecked = ''; $status = getProblemStatus($problem['id']); if (!strcmp($status,"closed")) { $closedChecked = " checked"; } else if (!strcmp($status,"timed")) { $timedChecked = " checked"; $timedDisabled = ''; } else if (!strcmp($status,"posted")) { $postedChecked = " checked"; } else { $openChecked = " checked"; } // else, we set the status to open ?> <input type="radio" name="status" value="open"<?php echo $openChecked ?>>Open (People Can Respond)<br> <?php if ($problem['id'] != 0): ?><input type="radio" name="status" value="closed"<?php echo $closedChecked ?>>Closed (People Cannot Respond)<br><?php endif; ?> <input type="radio" name="status" value="timed"<?php echo $timedChecked ?>>Close at: <input type="date" name="expiration_time" value="<?php echo $timedExpiration ?>"<?php echo $timedDisabled ?>><br> <?php if ($problem['id'] != 0): ?><input type="radio" name="status" value="posted"<?php echo $postedChecked ?>>Posted (People Can See the Results)<?php endif; ?> </p> <h2>Event Participants:</h2> <input type="text" name="username" value="Search for Participants" onfocus="this.value=''" onblur="this.value='Search for Participants'"> <br> <textarea name="participants" rows="5" cols="26"></textarea> <ul id="existing_participants" class="participants"><?php if ($action == "update_problem") { echo $theUsers; } ?></ul> </div> <div style="text-align:center;"> <?php if ($problem['id'] == 0): ?> <input type="button" value="Save and Continue" onclick="save(1);" class="button"><input type="button" onclick="window.location='problems.php'" class="button" value="Discard"> <?php else: ?> <input type="button" id="saveButton3" onclick="save(1);" class="button" value="Save and Continue"> <input type="button" onclick="window.location='problems.php'" class="button" value="Discard Changes"> <input type="button" id="saveButton2" onclick="save(3);" class="button" value="Finish Editing"> <?php endif; ?> </div> </form> <?php include_once 'includes/footer.inc' ?> <file_sep><?php include_once '../../includes/config.inc'; include_once 'functions.php'; checkPermissions(); $inputIDs = ''; if (isset($_GET['problem'])) { // check to make sure the problem type is the same. if not, die with error $problem = getProblemById($_GET['problem']); // what happens when an admin deletes a resource after a user enters a preference for it if (isset($_GET['editing'])) { $editing=true; } else { $editing=false; } $theHTML = ""; $resources = getResources($problem['id']); if ($resources['v'] == "") { $theHTML .= '<tr class="row" id="1"><td></td><td></td><td><input id="res" type = "text"></td><td><a href ="#" class="itemDelete" onclick="deleteField(1);"><img src="../../images/Delete.png"></a></td><tr>'; //For now, we're doing this as a table, but this old code may come in handy as a reference and if we want to switch back. //$theHTML .= '<div id="dragbuttons"><ul id="sortable"><li id="1"><input id ="foo_1" type="text">[<a href="#" class="itemDelete" style="color:#b00000; text-decoration:none; "onclick="deleteField();"><img src="../../images/Delete.png"></a>]</li></ul></div>'; $max_id=1; } else { $resources = preg_split('[\r\n|\n|\r]', $resources['v']); $max_id = 0; foreach($resources as $resource) { $resource = preg_split('[::]', $resource); if ($resource[0] > $max_id) {$max_id = $resource[0]; } $theHTML .= '<tr class="row" id = "' . $resource[0] . '"><td></td><td></td><td><input id="res" type="text" value = "' . $resource[1] . '"></td><td><a href="#" class="itemDelete" onclick="deleteField(' . $resource[0] . ');"><img src="../../images/Delete.png"></a></td></tr>'; } //Extra code again /* $theHTML = '<div id="dragbuttons"><ul id="sortable">'; foreach ($resources as $resource) { $resource = preg_split('[::]', $resource); if ($resource[0] > $max_id) { $max_id = $resource[0]; } $theHTML .= '<li id="' . $resource[0] . '"><input id="foo_' . $resource[0] . '" type="text" value="' . $resource[1] . '">[<a href="#" class="itemDelete" onclick="deleteField();">X</a>]</li>'; } $theHTML .= "</ul></div>"; */ } } include_once PATH . '/includes/header.inc'; ?> <script src="<?php echo URL ?>/js/jquery-1.4.2.min.js"></script> <script src="<?php echo URL ?>/js/jquery-ui-1.8.6.custom.min.js"></script> <script> $(document).ready(function() { $("form").submit(function() { var string = ""; $("#resource-table input[id*='res']").each(function() { string = string + $(this).parent().parent().attr('id') + "::" + $(this).val() + "\n"; }); string = string.substring(0, string.length-1); $("#data").val(string); //var myArray = $('#sortable').sortable('toArray'); //var string = ""; //for (var i=0, len=myArray.length; i<len; ++i) { //string = string + myArray[i].toString() + '::' + $("#foo_" + myArray[i].toString()).val() + "\n"; }); }); // should this be inside the document.ready thing? var max_id = <?php echo $max_id + 1; ?>; function addField() { $("#resource-table").append('<tr class="row" id="' + max_id + '"><td></td><td></td><td><input id = "res" type = "text"></td><td><a href ="#" class="itemDelete" onclick="deleteField(' + max_id + ');"><img src="../../images/Delete.png"></a></td><tr>'); // $("#sortable").append('<li id="' + max_id + '"><span><input id ="foo_' + max_id + '" type="text">[<a href="javascript:void()" class="itemDelete" style="color:#b00000; text-decoration:none; "onclick="deleteField();">X</a>]</span></li>'); max_id++; } function deleteField(row_id) { $("#" + row_id).remove(); } </script> <style> h1 { text-align:center; } h2 { margin-bottom: 0; } table.center {margin-left:auto; margin-right:auto;} tr.row { border-bottom: 1px solid black;} input {font-size: 18px; text-align: right; } //body {text-align:center;} #block { text-align:center; width: 90%; margin-left: auto; margin-right: auto; } #num { display:block; text-align:auto; width: 50%; margin-left:auto; margin-right:auto; margin-top: 40px; background-color: #CCCCCC; border: 1px solid black; } .button { font-size:2em;} </style> <?php include_once PATH . '/includes/body.inc' ?> <h1><?php echo 'Editing resources for ' . $problem['name']; ?></h1> <div id="num"> <form name="start" onSubmit="prepPage();"> <p>Resource set-up</p> <li><label>Number of resources: <input name="numres" type="int" value=1 min=1 max=50></label><br> <li><label>Select resource input type: <input type="checkbox" name="type" value="text"> text <input type="checkbox" name="type" value="date"> date <input type="checkbox" name="type" value="time"> time</label> </form> </div> <form name="form" method="post" action="process.php"> <input type="hidden" name="action" value="edit_problem_structure"> <input type="hidden" name="admin" value="<?php echo $_COOKIE['user'] ?>"> <input type="hidden" name="algorithm" value="<?php print $algorithm['id'] ?>"> <input type="hidden" name="problem" value="<?php echo $problem['id'] ?>"> <input type="hidden" name="data" id="data"> <div id="block"> <p> Enter the names of the resources you are trying to schedule. <table id="resource-table" class="center"> <tr align=right><td colspan=4><input type="button" style="font-size:1em" value="Add Resource" onclick="addField();"></td></tr> <?php echo $theHTML;?> </table> </p> <p> <input type="button" class="button" onclick="window.location='<?php echo URL . '/problem.php?problem=' . $_GET['problem'] ?>';" value="<- previous step"><input type="submit" class="button" value="done!"> </p> <?php drawNotifyButton($problem['id']) ?> </div> </form> <?php include_once PATH . '/includes/footer.inc' ?> <file_sep><?php # UPDATE PREFERENCES function updatePreferences($problem, $user, $preference) { $problem = getProblemById($problem); if (!isUserInProblem($user, $problem['id']) && $problem['type'] == "public") { addUserToProblem($problem['id'], $user); } // check to see if another user took the preference before the requesting user submitted the form $query = "SELECT * FROM `data` WHERE problem=" . $problem['id'] . " AND user!=$user AND k='preference' AND v='" . $preference[0] . "'"; // change this to use getData $result = mysql_query($query); if (mysql_num_rows($result) > 0) { return 1; } else { addData($problem['id'], $user, 'preference', $preference[0], 1); return 0; } } # MISC // returns an array of preferences for a participant function getPreferencesForParticipant($problem, $user) { $result = mysql_query("SELECT * FROM data WHERE problem=$problem AND user=$user AND k='preference'"); $row = mysql_fetch_array($result); return preg_split('[\r\n|\n|\r]', $row['v']); } // returns an array of every user's preferences to a particular problem.id function getAllPreferences($problem) { // change this to get all preferences $rows = array(); $participants = getParticipantsForProblem($problem); foreach ($participants as $participant) { $preference = getPreferencesForParticipant($problem, $participant['id']); if ($preference[0]) { $participant['preference'] = $preference; } else { $participant['preference'] = array(); } $rows[] = $participant; } return $rows; } function getPreference($problem, $user) { $result = mysql_query("SELECT * FROM data WHERE problem=$problem AND user=$user AND k='preference'"); $row = mysql_fetch_array($result); return $row['v']; } // returns an array of every user's preferences to a particular problem.id function getPreferences($problem) { $preferences = array(); $query = "SELECT * FROM data WHERE problem=$problem AND k='preference'"; $result = mysql_query($query); while ($preference = mysql_fetch_array($result)) { $preferences[] = $preference; } return $preferences; } // returns a resource object for a participant function getPreferenceForParticipant($problem, $user) { $result = mysql_query("SELECT * FROM data WHERE problem=$problem AND user=$user AND k='preference'"); $row = mysql_fetch_array($result); return getResourceById($problem, $row['v']); } // returns a list of all participants and resources and their matchings function getAssignments($problem) { $assignments = array(); $usedResources = array(); $unassignedUsers = array(); $participants = getParticipantsForProblem($problem); foreach ($participants as $participant) { $assignment = getPreferenceForParticipant($problem, $participant['id']); if (!$assignment) { $unassignedUsers[] = $participant['id'];} else { $usedResources[$assignment['id']] = 1; $assignments[] = array("participant" => $participant['id'], 'assignment' => $assignment['name'], 'id' => $assignment['id']); } } $resources = getAllResources($problem); foreach ($resources as $resource) { if (!isset($usedResources[$resource['id']])) { $assignments[] = array("participant" => 0, "assignment" => $resource['name'], "id" => $resource['id']); } } return array($assignments, $unassignedUsers); } // returns an array of all resources function getAllResources($problem) { $query = sprintf("SELECT * FROM data WHERE problem=%d AND user=0 AND k='resources'", $problem); $result = mysql_query($query); $resources = mysql_fetch_array($result); if (!$resources || $resources == "") { return array(); } else { $resources = preg_split('[\r\n|\n|\r]', $resources['v']); $rows = array(); foreach ($resources as $resource) { if ($resource == "") { continue; } $resource = preg_split('[::]', $resource); $rows[] = array('id' => $resource[0], 'name' => $resource[1]); } return $rows; } } /* * returns an array of user ids index by the resource id */ function getUsedResources($problem) { $resources = array(); $preferences = getPreferences($problem); foreach ($preferences as $preference) { if ($preference['v'] != NULL || $preference['v'] != '') { $resources[$preference['v']] = $preference['user']; } } return $resources; } // returns a resource based on its ID function getResourceById($problem, $resourceID) { $resources = getAllResources($problem); foreach ($resources as $resource) { if ($resource['id'] == $resourceID) { return array('id' => $resourceID, 'name' => $resource['name']); } } return null; } // swaps an assignment for first come first serve function swapAssignmentsFCFS($problem, $user1, $resource1, $user2, $resource2) { if ($user1 && $user2) { addData($problem, $user1, 'preference', $resource2, 1); addData($problem, $user2, 'preference', $resource1, 1); } else if (($user1 && !$user2) || !$resource1) { addData($problem, $user1, 'preference', $resource2 , 1); } else if ((!$user1 && $user2) || !$resource2) { addData($problem, $user2, 'preference', $resource1, 1); } } // unassigns a participant function unassignParticipantFCFS($problem, $user) { addData($problem, $user, 'preference', 0, 1); } ?><file_sep><?php include_once '../../includes/config.inc'; include_once 'functions.php'; checkPermissions(); include_once PATH . '/includes/header.inc'; include_once PATH . '/includes/body.inc'; ?> <style> #availableTable { margin-right: 100px; width:250px; text-align:center; background-color: lightblue; } #myHeaders{ border-bottom: black solid thin; border-top: black solid thin; border-left: black solid thin; border-right: black solid thin; } </style> <h1>Add Workers</h1><br> <div style="width: 300px; height: 200px; overflow: scroll; border: 5px gray; background-color: lightblue;margin-right:50px; margin-left:auto"> <table id="availableTable"> <tr> <th id="myHeaders">Worker</th> <th id="myHeaders">Available Hours</th> </tr> <tr> <td>Wes Elfman</td> <td>10</td> </tr> <tr> <td>Wes Elfman</td> <td>10</td> </tr> <tr> <td>Wes Elfman</td> <td>10</td> </tr> <tr> <td>Wes Elfman</td> <td>10</td> </tr> <tr> <td>Wes Elfman</td> <td>10</td> </tr> <tr> <td>Wes Elfman</td> <td>10</td> </tr> <tr> <td>Wes Elfman</td> <td>10</td> </tr> <tr> <td>Wes Elfman</td> <td>10</td> </tr> <tr> <td>Wes Elfman</td> <td>10</td> </tr> <tr> <td><NAME></td> <td>10</td> </tr> <tr> <td><NAME></td> <td>10</td> </tr> </table> </div> <?php include_once PATH . '/includes/footer.inc'; ?> <file_sep><?php ######################################################################## ## FUNCTIONS.PHP ######################################################################## include_once 'algorithms.inc'; // functions related to algorithms table include_once 'problems.inc'; // functions related to problems and user2problem tables include_once 'data.inc'; // functions related to data table include_once 'users.inc'; // functions related to the users table include_once 'groups.inc'; // functions related to the groups table include_once 'email.inc'; // functions related to email include_once 'permissions.inc'; // functions related to permissions ######################################################################## ## ASSIGNMENT FUNCTIONS -- move all this into BPM ######################################################################## //Checks to see if the problem has been run previously. function checkForAssignment($problem) { $query = sprintf("SELECT * FROM `data` WHERE problem=%s AND k='assignment'", $problem); $result = mysql_query($query); //return mysql_fetch_array($result); if (mysql_num_rows($result)) { return true; } return false; } function isAssigned($problem, $user) { $query = sprintf("SELECT * FROM `data` WHERE problem = %s AND k='assignment' AND user=%s", $problem, $user); $result = mysql_query($query); if (mysql_num_rows($result)) { return true;} else {return false;} } function unassignParticipant($problem, $user) { addData($problem, $user, 'assignment', 0 , 1); } function swapAssignments($problem, $user1, $resource1, $user2, $resource2) { if ($user1 && $user2) { addData($problem, $user1, 'assignment', $resource2, 1); addData($problem, $user2, 'assignment', $resource1, 1); } else if (($user1 && !$user2) || !$resource1) { addData($problem, $user1, 'assignment', $resource2 , 1); } else if ((!$user1 && $user2) || !$resource2) { addData($problem, $user2, 'assignment', $resource1, 1); } } ######################################################################## ## SANTITIZATION FUNCTIONS ######################################################################## function sanitize($data) { // remove whitespaces (not a must though) $data = trim($data); // convert special html characters $data = htmlspecialchars($data); // apply stripslashes if magic_quotes_gpc is enabled if (get_magic_quotes_gpc()) { $data = stripslashes($data); } // a mySQL connection is required before using this function $data = mysql_real_escape_string($data); return $data; } ######################################################################## ## MISCELLANEOUS FUNCTIONS ######################################################################## function splitOnNewLines($text) { $new = preg_split('[\r\n|\n|\r]', $text); if ($new[0] == "") { return array(); } // we used to return NULL, but that is not an array else { return $new; } } ?> <file_sep> $(document).ready(function() { $("#sortable").sortable(); $("input").change(function() { activateSave(); }); $("input").keyup(function() { activateSave(); }); }); function activateSave() { $("#saveButton").val("Save"); $("#saveButton").attr("disabled", false); } function getFieldText() { var text = '<li id="' + max_id + '">'; text = text + '<input type="text">'; text = text + '<a href="javascript:void(0);" onclick="addField(' + max_id + ');"><img src="../../images/add.png"></a>'; text = text + '<a href="javascript:void()" onclick="deleteField(' + max_id + ');"><img src="../../images/delete.png"></a>'; text = text + '<img src="../../images/drag.png">'; text = text + '</li>'; return text; } function parseResources() { var myArray = $("#sortable").sortable('toArray'); var string = ""; for (var i=0,len=myArray.length;i<len;++i) { string = string + myArray[i].toString() + '::' + $("#sortable #" + myArray[i].toString() + " input").val() + "\n"; } string = string.substring(0, string.length-1); return string; } function saveTimeSlots(problem) { var resources = parseResources(); $.post("do.php", { "problem": problem, "action":"update_resources", "resources": resources }, function(data) { if (data.error) { alert("an error has occured"); } else { $("#saveButton").val("Saved"); $("#saveButton").attr("disabled", true); window.location='../../problems.php'; } }); } function addField(id) { if (id) { $("#sortable #" + id).after(getFieldText()); } else { $("#sortable").append(getFieldText()); } $("#sortable #" + max_id).hide().slideDown("fast"); activateSave(); max_id++; } function deleteField(resource) { var numItems = $("#sortable li").length; if (numItems == 1) { return; } $("#sortable #" + resource).slideUp("fast", function() { $("#sortable #" + resource).remove(); }); activateSave(); } <file_sep><?php include_once 'includes/config.inc'; include_once 'includes/header.inc'; include_once 'includes/body.inc'; ?> <h1 class="blocktext">What is Sched-a-roo?</h1> <p class="blocktext">Our site is the wildly successful result of a senior comps project designed to help Carls schedule meetings and events in timely and efficient manner.</p> <br> <h1 class="blocktext">Who are we?</h1> <p> <img src="<?php echo URL ?>/images/ty2.jpg" alt="<NAME>" height=110 width=125 style="float: left; padding:5px"> Born and raised in the Minot, North Dakota, Ty decided to give up the farm life to experience big city in Northfield. In addition to heading our graphic design department, Ty likes to drink muscle milk and run fast. </p><br><br> <p><img src="<?php echo URL ?>/images/nate2.jpg" alt="<NAME>" height=100 width=125 style="float: left; padding:5px"> The Thinker (aka <NAME>) was hired by Schedaroo late in 2010. An excellent addition to the web design team, Nate has had an hand in implementing numerous parts of the site, specializing in database design. In his spare time, Nate likes to toss the 'bee with his fellow GOPers. </p><br> <p><img src="<?php echo URL ?>/images/dan2.jpg" alt="<NAME>" height=160 width=125 style="float: left; padding:5px"> Dan has dominated Sched-a-roo from day one. Thanks to his dedication, Sched-a-roo got off to a running start, and has left all other comps groups in the dust. In addition to helping transform Sched-a-roo into Google's #1 competitor, Dan also likes public transportation (especially trains). </p><br><br><br> <p><img src="<?php echo URL ?>/images/brendan2.jpg" alt="<NAME>" height=100 width=125 style="float: left; padding:5px"> Brendan hails from Modesto, home of the Nuts (MLB affiliate) and high crime rates. Brendan lead the Hack the Carleton Website team. One of the best hackers and an above-average macker, Brendan acquired much of the data required to run our site. Brendan enjoys dying his hair, and things found in nature. </p><br> <p><img src="<?php echo URL ?>/images/carl2.jpg" alt="<NAME>" height=150 width=125 style="float: left; padding:5px"> Carl 'CS' Smith decided to attend Carleton after being told that the school was actually created in his name 123 years before he was born. Through our project, Carl discovered that he is a power-user at heart, specifically through his implementation of advanced sorting and his constant "inverting of screen colors"*. In addition, Carl believes that the 'dining hall' problem is NP-complete, yet after 5 weeks has still failed to provide any sort of proof. <br>* His words </p></br><br><br> <p><img src="<?php echo URL ?>/images/wes2.jpg" alt="<NAME>" height=150 width=125 style="float: left; padding:5px"> <NAME>, esquire, the project manager of Schedaroo, pioneered its australian theme. Always encouraging us to keep our users "one hop away from scheduling their next event", it was Wes who kept us going when our color scheme was terrible and our spirits were low. He has the softest heart on the team. <NAME> gets all mushy inside when he sees him. </p><br> <?php include 'includes/footer.inc' ?> <file_sep>/* stylesheet for many to one */ /* for problem */ #dragbuttons { margin-left: auto; margin-right: auto; width: 425px; } #sortable li { list-style-type:none; } #sortable li img { border: 0; vertical-align: middle; } #sortable input { display: inline; width: 300px; margin-right: 3px; } /* for respond */ #responseTable { margin-left: auto; margin-right: auto; border-collapse: collapse; } #responseTable th {background-color:#262236; color:white;border:1px solid #000000; padding:5px;} #responseTable td { border: 1px solid #000000; padding: 5px; } #responseTable td { text-align: center; } #responseTable td img { vertical-align: middle; } #responseTable .highlight { background: darkseagreen; } /* for view */ #viewTable { margin-left:auto; margin-right:auto; border-collapse: collapse; } #viewTable, #viewTable th, #viewTable td { border: 1px solid #000000; padding: 10px; } #viewTable th { color:#FFFFFF; background-color:#292236; }<file_sep><?php # MAX COL INDEX / IMPORTANCE // returns the max_col_index function getMaxColIndex($problem) { $data = getData($problem, 0, 'max_col_index'); return $data['v']; } // gets a user's priority function getImportanceForParticipant($problem, $user) { $data = getData($problem, $user, 'importance'); return $data['v']; } ## PREFERENCES // returns an array of user preferences function getPreferencesForParticipant($problem, $user) { $result = mysql_query("SELECT * FROM data WHERE problem=$problem AND user=$user AND k='preference'"); $preferences = mysql_fetch_array($result); $preferences = preg_split('[\r\n|\n|\r]', $preferences['v']); return $preferences; } // returns an array of every user's preferences to a particular problem.id function getAllPreferences($problem) { // change this to get all preferences $rows = array(); $participants = getParticipantsForProblem($problem); foreach ($participants as $participant) { $preference = getPreferencesForParticipant($problem, $participant['id']); if ($preference[0]) { $participant['preference'] = $preference; } else { $participant['preference'] = array(); } $rows[] = $participant; } return $rows; } // updates a user's preferences after proboems.php function updatePreferencesForParticipant($problem, $user, $resources) { $problem = getProblemById($problem); if (!isUserInProblem($user, $problem['id']) && $problem['type'] == "public") { addUserToProblem($problem['id'], $user); } $preferences = ''; // initialize preferences string foreach ($resources as $resource) { $preferences .= $resource . "\n"; // add the ids to the preference list for that user } $preferences = substr($preferences, 0, -1); // take off the last new line addData($problem['id'], $user, 'preference', $preferences, 1); // 1 means update or add } // returns an array of all resources function getAllResources($problem) { $query = sprintf("SELECT * FROM data WHERE problem=%d AND user=0 AND k='resources'", $problem); $result = mysql_query($query); $resources = mysql_fetch_array($result); if (!$resources || $resources == "") { return array(); } else { $resources = preg_split('[\r\n|\n|\r]', $resources['v']); $rows = array(); foreach ($resources as $resource) { if ($resource == "") { continue; } $resource = preg_split('[::]', $resource); $rows[] = array('id' => $resource[0], 'name' => $resource[1]); } return $rows; } } // returns a resource based on its ID function getResourceById($problem, $resourceID) { $resources = getAllResources($problem); foreach ($resources as $resource) { if ($resource['id'] == $resourceID) { return $resource['name']; } } return 0; } ?>
7e90ff225c0f4f2b6a1a186405e51e6fe06cdd3c
[ "SQL", "JavaScript", "PHP", "C++", "CSS" ]
36
SQL
BrendanCassidy/Schedaroo
cac24d236808a50fc5c07bf6574ac012e328777f
db937ceff379a93a22d230e3a28404043b92f6ba
refs/heads/master
<file_sep>import React from 'react'; import { Router, Route } from 'react-router'; import Menu from "./Menu"; class App extends React.Component { constructor() { super(); this.state = { 'storeAccess': { 'store': 'login' } } this.login(); } login() { localStorage.setItem('store', JSON.stringify(this.state)); } render() { return ( <div> <header> <Menu></Menu> </header> <section class="main fluid"> {this.props.children} </section> </div> ); } } module.exports = App; <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import Modal from 'react-modal'; import classNames from "classnames"; let PropTypes = React.PropTypes; class Confirmation extends React.Component { constructor(props) { super(props); this.style = { overlay : { backgroundColor: 'rgba(0, 0, 0, 0.55)' }, content : { border: '1px solid #ccc', padding: '0px', position: 'fixed', height: '200px', width: '300px', display: 'block', top: '35%', left: '40%' } }; } render() { let content = React.DOM.div({}, React.DOM.div({className: classNames('modal-header')}, this.props.title), React.DOM.div({className: classNames('modal-content')}, this.props.message, React.DOM.br({}), React.DOM.br({}), React.DOM.button({ className: classNames('dft', 'button', 'close'), onClick: this.props.handleClickCancel }, "No"), React.DOM.button({ className: classNames('dft', 'button', 'primary'), onClick: this.props.handleClickConfirm }, 'Yes') ) ); return ( <Modal isOpen={this.props.openModal} onRequestClose={this.props.handleClickCancel} style={this.style}> {content} </Modal> ); } } Confirmation.propTypes = { title: PropTypes.string.isRequired, message: PropTypes.string.isRequired, handleClickCancel: PropTypes.func.isRequired, handleClickConfirm: PropTypes.func.isRequired, openModal: PropTypes.bool.isRequired, } export default Confirmation;<file_sep>import React from "react"; import classNames from "classnames"; import TagsInput from 'react-tagsinput' import AutosizeInput from 'react-input-autosize' import 'react-tagsinput/react-tagsinput.css' let PropTypes = React.PropTypes; class ToolSearch extends React.Component { constructor(props) { super(props); this.state = { tags: [] } this.defaultField = 'name'; this.search = this.search.bind(this); this.handleChange = this.handleChange.bind(this); } search() { this.props.handleSearch(this.state.tags); } handleChange(tags) { let error = false; let validate = /^((([nN][aA][mM][eE]|[sS][lL][uU][gG]):[a-zA-ZA-zÀ-úA-zÀ-ÿ0-9-\s]{1,})|([a-zA-ZA-zÀ-úA-zÀ-ÿ0-9-\s]{1,}))$/ let search = [] tags.forEach((tag) => { if (validate.test(tag)) { tag = (tag.indexOf(':') === -1) ? `${this.defaultField}:${tag}`: `${tag.split(':')[0].toLowerCase()}:${tag.split(':')[1]}`; search.push(tag); } }) this.setState({tags: search}, () => { this.search(); } ); } render() { return ( React.DOM.div({className: classNames('box-choose', 'fluid', 'form', 'col-md-12')}, React.DOM.div({className: classNames('col-md-3', 'search-div-field')}, <TagsInput value={this.state.tags} onChange={this.handleChange} maxTags={10} className={`tool-search`} inputProps={{placeholder: 'Search'}} /> ), React.DOM.a({className:classNames('tooltip', 'tool-search-help')}, React.DOM.i({className:classNames('fa fa-question')}), React.DOM.span({className:classNames('custom help')}, 'Brand Name', React.DOM.br({}), 'name:Brand Name', React.DOM.br({}), 'slug:brand-slug' ) ) ) ); } } ToolSearch.propTypes = { handleSearch: PropTypes.func.isRequired } export default ToolSearch;<file_sep>import React from "react"; import ReactDOM from "react-dom"; import { Router, Route, Link, IndexRoute, browserHistory, hashHistory } from "react-router"; import "./static/css/webproject.css"; import App from "./components/App"; import NoMatch from "./components/NoMatch"; import Home from "./components/Home"; import Example from "./components/Example"; import ExampleList from "./components/ExampleList"; const AppRoutes = ( <Router history={hashHistory}> <Route name="Home" path="/" component={App}> <IndexRoute component={Home}></IndexRoute> <Route name="Example" path='/example' component={Example}> <Route name="Example" path='/example/list' component={ExampleList}></Route> </Route> <Route name="404: No Match for route" path="*" component={NoMatch} /> </Route> </Router> ); ReactDOM.render(AppRoutes, document.getElementById("app")); <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import Modal from 'react-modal'; import classNames from "classnames"; let PropTypes = React.PropTypes; class AlertMessages extends React.Component { constructor(props) { super(props); this.style = { overlay : { backgroundColor: 'rgba(0, 0, 0, 0.55)' }, content : { border: '1px solid #ccc', padding: '0px', position: 'fixed', height: '200px', width: '320px', display: 'block', top: '35%', left: '40%' } }; this.handleClose = this.handleClose.bind(this); this.handleOpen = this.handleOpen.bind(this); this.handleKeyPress = this.handleKeyPress.bind(this); } handleClose(){ document.removeEventListener("keypress", this.handleKeyPress, false); this.props.handleCloseModal(); } handleOpen(){ document.addEventListener("keypress", this.handleKeyPress, false); } handleKeyPress(e) { if (e.keyCode === 27 || e.keyCode === 13) { this.handleClose(); } } render() { let content = React.DOM.div({}, React.DOM.div({className: classNames('modal-header')}, this.props.title), React.DOM.div({className: classNames('modal-content')}, this.props.message, React.DOM.br({}), React.DOM.br({}), React.DOM.button({ className: classNames('dft', 'button', 'close'), onClick: this.props.handleCloseModal }, "OK") ) ); return ( <Modal isOpen={this.props.openModal} onAfterOpen={this.handleOpen} onRequestClose={this.handleClose} style={this.style}> {content} </Modal> ); } } AlertMessages.propTypes = { title: PropTypes.string.isRequired, openModal: PropTypes.bool.isRequired, handleCloseModal: PropTypes.func.isRequired, } export default AlertMessages;<file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import Confirmation from '../../../src/components/content/elements/confirmation'; import expect from 'expect'; import expectJSX from 'expect-jsx'; expect.extend(expectJSX); describe("Confirmation", () => { it('should render header with the same title passed', () => { const renderer = TestUtils.createRenderer(); let title = "Remove Test"; let message = "Are you sure you want to remove this Test?"; let component = <Confirmation title={title} message={message} handleClickConfirm={() => {}} handleClickCancel={() => {}} openModal={true} />; renderer.render(component); const output = renderer.getRenderOutput(); const expected = <div className="modal-header">{title}</div>; expect(output).toIncludeJSX(expected); }); });<file_sep>import React from 'react'; import classNames from "classnames"; let PropTypes = React.PropTypes; class Table extends React.Component { constructor(props) { super(props); this.getExtraColumn = this.getExtraColumn.bind(this); } getExtraColumn(elementId, line_id) { if (!this.props.extraColumn) { return ""; } let extra = this.props.extraColumn.map((content, i) => { return React.DOM.div({ className: 'col-md-1 center', key: 'field_' + line_id + '_' + i }, React.DOM.a({onClick: content.event.bind(this, elementId)}, React.DOM.i({className: content.style}, content.text)) ); }); return extra; } getBodyNotFound() { return React.DOM.div({ className: 'item-accordion' }, React.DOM.div({className: 'title-accordion'}, React.DOM.div({className: 'row'}, React.DOM.div({className: 'center'}, "No records found") ) )); } getBody(content) { if (content.length === 0) { return this.getBodyNotFound(); } let body = content.map((contentData, line_i) => { return React.DOM.div({ className: 'item-accordion', key: 'line_' + line_i }, React.DOM.div({className: 'title-accordion'}, React.DOM.div({className: 'row'}, this.props.content.map((content, field_i) => { let field = content.field; let value = contentData[field]; if (content.type === 'date') { value = new Date(contentData[field]).toLocaleString(); } return React.DOM.div({ className: content.style, key: "field_" + line_i + '_' + field_i }, value) }), this.getExtraColumn(contentData.id, line_i) ) ) ) }); return body; } render() { let header = null; if (this.props.contentData.length > 0) { header = this.props.headers.map((content, i) => { let title = content.text; if (content.event !== undefined) { title = React.DOM.a({ onClick: e => content.event(content.field) }, content.text) } return React.DOM.div({ className: content.style, key: 'header_' + i }, title) }); } let body = this.getBody(this.props.contentData); let content = React.DOM.div({className: 'table-accordion'}, React.DOM.div({className: 'th-accordion'}, React.DOM.div({className: 'row'}, header ) ), body ); return (content); } } Table.contextTypes = { router: React.PropTypes.object.isRequired } export default Table; <file_sep>import React from 'react'; import ReactDOM from "react-dom"; import { Link } from 'react-router'; import classNames from "classnames"; let menuItems = [ { route: '/example', text: 'Example', style: 'fa-sitemap' }, ]; class Menu extends React.Component { constructor(props) { super(props); } getItems() { let items = menu.map((item, itinerator) => { return React.DOM.li({key: "menu_" + itinerator}, <Link to={item.route} activeClassName="active"> <i className={classNames('fa', item.style)}></i>{item.text} </Link>) }); return items; } render() { return ( React.DOM.aside({className: classNames('horizontal-menu')}, React.DOM.ul({}, React.DOM.li({}, <div class="logo"><b>Example</b> Service</div> ), this.getItems() ) ) ); } } Menu.contextTypes = { router: React.PropTypes.object.isRequired } export default Menu; <file_sep>import React from 'react'; import classNames from "classnames"; let PropTypes = React.PropTypes; class Pagination extends React.Component { constructor(props) { super(props); this.maxPage = 3; } render() { if (this.props.totalPages === 0) { return React.DOM.div({}); } let totalPages = new Array(this.props.totalPages).fill(''); let actualPage = this.props.page; let showMoreDown = null; let showMoreUp = null; let pages = totalPages.map(function(value, i) { let page = i + 1; if (page > actualPage && (page > (actualPage + this.maxPage))) { showMoreUp = true; return false; } if (page < actualPage && (page < (actualPage - this.maxPage))) { showMoreDown = true; return false; } let attr = { onClick: this.props.setCurrentPage.bind(this, page) } let link = React.DOM.a(attr, page); let active = false; if (page == this.props.page) { let active = true; link = React.DOM.span({}, page); } return React.DOM.li({key: 'page-' + page, className: classNames({'active': active})}, link); }.bind(this)); let attrFirst = { className: 'btn', onClick: this.props.setCurrentPage.bind(this, 1), key: 'first-page', id: 'pagination-first-page' }; let attrLast = { className: 'btn', onClick: this.props.setCurrentPage.bind(this, this.props.totalPages), key: 'page-back', id: 'pagination-last-page' }; let attrBack = { className: 'btn', onClick: this.props.setCurrentPage.bind(this, (parseInt(this.props.page) - 1)), key: 'page-back' }; let attrNext = { className: 'btn', onClick: this.props.setCurrentPage.bind(this, (parseInt(this.props.page) + 1)), key: 'page-next' }; let first = null; let last = null; if (showMoreDown) { showMoreDown = React.DOM.li({}, React.DOM.span({}, '...')); } if (showMoreUp) { showMoreUp = React.DOM.li({}, React.DOM.span({}, '...')); } let pagination = React.DOM.div({className: 'pagination'}, React.DOM.ul({id: 'pagination'}, React.DOM.li({}, React.DOM.a(attrFirst, React.DOM.i({className: classNames('fa', {'fa-angle-double-left': (this.props.page > 1)})}))), React.DOM.li({}, React.DOM.a(attrBack, React.DOM.i({className: classNames('fa', {'fa-angle-left': (this.props.page != 1)})}))), showMoreDown, pages, showMoreUp, React.DOM.li({}, React.DOM.a(attrNext, React.DOM.i({className: classNames('fa', {'fa-angle-right': (this.props.page != this.props.totalPages)})}))), React.DOM.li({}, React.DOM.a(attrLast, React.DOM.i({className: classNames('fa', {'fa-angle-double-right': (this.props.page < this.props.totalPages)})}))) ) ); return (pagination); } } Pagination.propTypes = { setCurrentPage: PropTypes.func.isRequired, page: PropTypes.number.isRequired, totalPages: PropTypes.number.isRequired, } export default Pagination;<file_sep>That's a Skeleton to starts ReactJS projects. Here we have just examples and for while the final project example isn't running. All components, Webpack and Docker are working, the most importants to starts an project. If I can help you, let me to know! :) <NAME> <EMAIL> ## Project Contents ## ###First Step### ``` npm install ``` ### DEV Run ### ``` npm run dev ``` ### DEV Deploy (It will be create a package and run with Docker) ### ``` npm run deploy ``` ### Test ### ``` npm run test ``` ### Generate Coverage ### ``` npm run coverage ``` ### Generate Coverage ### ``` docker-compose up -d ``` You must add in yours /etc/hosts ``` 127.0.0.1 webproject.dev ``` Browser access ``` http://webproject.dev ``` <file_sep>import React from 'react'; import { Router, Route } from 'react-router'; class Example extends React.Component { componentDidMount() { return this.setUrlParameters(); } componentDidUpdate() { return this.setUrlParameters(); } setUrlParameters() { if (!this.props.children) { this.context.router.push({ pathname: '/example/list', query: { page: 1, limit: 10 } }); } } render() { return (this.props.children); } } Example.contextTypes = { router: React.PropTypes.object.isRequired } export default Example; <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import Pagination from '../../../src/components/content/elements/pagination'; import expect from 'expect'; import expectJSX from 'expect-jsx'; expect.extend(expectJSX); describe("Pagination", () => { it('should havent pagination element', () => { const renderer = TestUtils.createRenderer(); let component = <Pagination setCurrentPage={() => {}} page={0} totalPages={0} />; renderer.render(component); const output = renderer.getRenderOutput(); const expected = <div></div>; expect(output).toIncludeJSX(expected); }); it('should have pagination element and not before element', () => { let pagination = TestUtils.renderIntoDocument( <Pagination setCurrentPage={() => {}} page={1} totalPages={10} /> ); let renderedPagination = TestUtils.scryRenderedDOMComponentsWithTag(pagination, "li"); expect(renderedPagination.length).toEqual(9); expect(renderedPagination[0].children[0].children[0].className).toEqual('fa'); }); it('should have before pagination element', () => { let pagination = TestUtils.renderIntoDocument( <Pagination setCurrentPage={() => {}} page={2} totalPages={10} /> ); let renderedPagination = TestUtils.scryRenderedDOMComponentsWithTag(pagination, "li")[1]; expect(renderedPagination.children[0].children[0].className).toEqual('fa fa-angle-left'); }); it('should have next pagination element', () => { let pagination = TestUtils.renderIntoDocument( <Pagination setCurrentPage={() => {}} page={2} totalPages={10} /> ); let renderedPagination = TestUtils.scryRenderedDOMComponentsWithTag(pagination, "li")[8]; expect(renderedPagination.children[0].children[0].className).toEqual('fa fa-angle-right'); }); });<file_sep>import React from "react"; import axios from "axios"; import { Link, browserHistory } from 'react-router'; import Breadcrumbs from 'react-breadcrumbs'; import classNames from "classnames"; import Table from "../elements/table"; import AlertMessages from '../elements/messages'; import ToolSearch from '../elements/tool-search'; import Pagination from "../elements/pagination"; import { toArray } from "lodash"; import Confirmation from '../elements/confirmation'; import Config from 'Config'; class ExampleList extends React.Component { constructor(props) { super(props); this.state = { examples: [], loading: true, page: this.props.location.query.page ? this.props.location.query.page : 1, limit: this.props.location.query.limit ? this.props.location.query.limit : 10, search: "", sort: { by: "", order: "" }, total: 0, totalPages: 0, alert: { modal: false, message: '' }, remove: { modal: false, id: '' } }; this.handleClickRemove = this.handleClickRemove.bind(this); this.openConfirmModal = this.openConfirmModal.bind(this); this.closeConfirmModal = this.closeConfirmModal.bind(this); this.handleClickEdit = this.handleClickEdit.bind(this); this.setCurrentPage = this.setCurrentPage.bind(this); this.getAlertMessage = this.getAlertMessage.bind(this); this.handleCloseModal = this.handleCloseModal.bind(this); this.handleSearch = this.handleSearch.bind(this); this.handleHeaderOrder = this.handleHeaderOrder.bind(this); this.tableHeader = [ {'text': 'Name', 'style': 'col-md-2', 'field': 'name', 'event': this.handleHeaderOrder}, {'text': 'Slug', 'style': 'col-md-2', 'field': 'slug', 'event': this.handleHeaderOrder}, {'text': 'Created', 'style': 'col-md-3', 'field': 'created_at', 'event': this.handleHeaderOrder}, {'text': 'Updated', 'style': 'col-md-3', 'field': 'updated_at', 'event': this.handleHeaderOrder}, {'text': 'Remove', 'style': 'col-md-1 center'}, {'text': 'Edit', 'style': 'col-md-1 center'} ]; this.content = [ {'field': 'name', 'style': 'col-md-2', type: 'text'}, {'field': 'slug', 'style': 'col-md-2', type: 'text'}, {'field': 'created_at', 'style': 'col-md-3 text-note', type: 'date'}, {'field': 'updated_at', 'style': 'col-md-3 text-note', type: 'date'} ]; this.extraColumn = [ {'text': '', 'style': 'fa fa-trash', 'event': this.openConfirmModal}, {'text': '', 'style': 'fa fa-pencil', 'event': this.handleClickEdit} ]; } componentWillMount() { this.setCurrentPage(this.state.page); } setCurrentPage(page) { this.context.router.push({ pathname: this.props.route.path, query: { page: page, limit: this.state.limit } }); this.getExamples(page); } handleClickRemove() { if (!this.state.remove.id) { return false; } this.closeConfirmModal(); } openConfirmModal(id) { this.setState({remove: {modal: true, id: id}}); } closeConfirmModal() { this.setState({remove: {modal: false}}); } handleClickEdit(id) { } getExamples(currentpage) { let page = currentpage; let limit = this.state.limit; let uri = `${this.uri}?`; if (Array.isArray(this.state.search)) { let param = ""; this.state.search.forEach((search, i) => { param += `&filter=${Object.keys(search)}:${search[Object.keys(search)]}`; }); uri += param; } if (this.state.sort.by !== "") { uri += `&sort=${this.state.sort.by}`; } if (this.state.sort.order !== "") { uri += `&order=${this.state.sort.order}`; } uri += `&page=${page}&limit=${limit}`; let mock = { name: "Example", slug: "Example", "created_at": new Date().now(), "updated_at": new Date().now() } this.setState({ examples: [mock], total: 100, totalPages: 10, page: page, loading: false }); } handleCloseModal() { this.setState({ alert: { modal: false, message: "" } }); } getAlertMessage(message) { return ( React.DOM.span({}, this.state.alert.message) ) } handleSearch(search) { let searchFields = []; search.forEach((value, i) => { let field = {}; field[value.split(":")[0]] = value.split(":")[1]; searchFields.push(field); }); this.setState({ search: searchFields, sort: { by: "", order: "" } }, () => { this.getExamples(1); }); } handleHeaderOrder(order) { this.setState({ sort: { by: order, order: (this.state.sort.order === 'asc' || this.state.sort.order === '') ? 'desc' : 'asc' } }, () => { this.getExamples(1); }); } render() { if (this.state.loading === true) { return React.DOM.div({className: classNames('loader')}) } let pagination = ''; if (this.state.total > 0) { pagination = <Pagination setCurrentPage={this.setCurrentPage} page={Number(this.state.page)} totalPages={Number(this.state.totalPages)} />; } let content = React.DOM.div({}, <AlertMessages title="Alert" message={this.getAlertMessage()} handleCloseModal={this.handleCloseModal} openModal={this.state.alert.modal} />, <Confirmation title="Remove Example" message="Are you sure do you want to remove this Example?" handleClickConfirm={this.handleClickRemove} handleClickCancel={this.closeConfirmModal} openModal={this.state.remove.modal} />, React.DOM.div({className: 'header-content'}, React.DOM.div({className: 'row'}, React.DOM.div({className: 'col-md-6'}, React.DOM.h2({}, 'Examples'), <Breadcrumbs routes={this.props.routes} params={this.props.params} /> ) ) ), React.DOM.div({className: 'section-content'}, <ToolSearch handleSearch={this.handleSearch} />, <Table contentData={toArray(this.state.examples)} content={this.content} extraColumn={this.extraColumn} headers={this.tableHeader} />, pagination ) ); return (content); } } ExampleList.contextTypes = { router: React.PropTypes.object.isRequired } export default ExampleList;
1a0461b82d1b9fd50db21e6fa763e12c8104400a
[ "Markdown", "JavaScript" ]
13
Markdown
lcfumes/react-skeleton
4be2ced6286866fbc49b1abc2c942575df268224
d8330a3c6bb52c374639d21d9b289859b9957488
refs/heads/main
<repo_name>Salisyal/Quotes-website-by-friends<file_sep>/README.md # Hacktoberfest-2021 Quotes website through my Friends Contribute to open source is always fun . Here beginner can contribute to open source just by doing some simple task you need to submit your name and quotes you love #################--------- Hacktoberfest is open to everyone in our global community. Whether you’re a seasoned contributor or looking for projects to contribute to for the first time, you’re welcome to participate.-----------##################### -------------------------------------------------Process to follow to contribute to open source ------------------------------------- Let's make a beautiful website full of quotes step1:signup with your Github or gitlab Account at https://hacktoberfest.digitalocean.com/ step2:go to the repository https://github.com/suman-shah/Quotes-website-by-friends step3:click on foke button to fork the project step4:add you name and your Quotes Add in this code part first copy and paste in another line and change it : <button><b>Name</b></button> <p>Quotes I Love: </p> Step5:click contribute and click on creat pull request Step6:commite your change Step7:submit
609253d04e09e3613396b8abf6d1a1b125b9c4b5
[ "Markdown" ]
1
Markdown
Salisyal/Quotes-website-by-friends
758485978872d5eb74a1fbec41839f27513cced3
bafff6438e02c5b6f19b3c8001c7b240c6d923a8
refs/heads/main
<repo_name>yus002/RFM-Analysis-on-Customers-Segmentation<file_sep>/final assignment 1 Q1-Q2.Rmd --- title: "final assignment 1" author: "<NAME>" date: "2020/12/4" output: pdf_document: default word_document: default --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r} library(readxl) df <- read_excel("C:/Users/<NAME>/Desktop/msca/fall 2020/msca 31015 consulting/final project/Final Assignment - Week 9.xlsx") View(df) ``` ```{r} # drop columns df = df[, -c(2,67:69)] ``` # 1. Perform descriptive statistics on all variables to help understand the data, the distributions and basic info you have to work with on this challenge. (Mean, Standard Deviation, Median, Min, Max and Histogram) ```{r} NROW(df$id) # there are 33713 customers summary(df) # find the outlier and remove the rows View(df) ``` ```{r} for (i in 2:65){ plot(density(unlist(df[,i])), main = sprintf("x = %s", xlab = names(df[,i])), xlab = names(df[,i])) } ``` ```{r} for (i in 2:65){ hist(unlist(df[,i]), main = sprintf("x = %s", xlab = names(df[,i])), xlab = names(df[,i])) } ``` ## 2. Create a new data set with more descriptive labels and the data needed for analysis ```{r} View(df) names(df)[names(df) == "r"] = "Recency" names(df)[names(df) == "f"] = "Frequency" names(df)[names(df) == "m"] = "Monetary Value" names(df)[names(df) == "tof"] = "Time Of Flight" which(is.na(df)) df$average.payment = df$`Monetary Value`/df$Frequency df[is.na(df)] = 0 summary(df$average.payment) #for (i in 1:30){ # df[,66 + i ] = df[,i+35] / df[, i +5] # names(df)[66 + i] = paste(names(df)[i + 35], "/", names(df[i + 5])) #} df[is.na(df)] = 0 new.df = df[, c(1:5, 66, 6:65)] new.df = new.df[-which(new.df[,6] > 1600), ] #head(new.df) View(new.df) ``` ```{r} write.csv(new.df, 'cleanned dataset average payment.csv') ``` ```{r} View(new.df) Fsort = apply(new.df[,7:36], 2, sum) Msort = apply(new.df[,37:66], 2, sum) #View(Fsort) #View(Msort) head(sort(Fsort, decreasing = TRUE)) head(sort(Msort, decreasing = TRUE)) FM = cbind(sort(Fsort, decreasing = TRUE) , sort(Msort, decreasing = TRUE) ) View(FM) names(new.df) ``` ```{r} df = new.df View(df) # r median df.test = df[(df$Recency <= 1632.7596) & (df$Recency >= 693.5915), 2] median(df.test$Recency) df.test = df[(df$Recency <= 693.5915) & (df$Recency >= 280.1592), 2] median(df.test$Recency) df.test = df[(df$Recency <= 280.1592) & (df$Recency >= 192.3353), 2] median(df.test$Recency) df.test = df[(df$Recency <= 192.3353) & (df$Recency >= 161.1333), 2] median(df.test$Recency) df.test = df[(df$Recency <= 161.1333) & (df$Recency >= 160.2685), 2] median(df.test$Recency) View(df.test) ``` ```{r} # r median # 1163.17 1 1069 # 486.8753 2 432 # 236.2472 3 233 # 176.7343 4 179 # 160.7009 5 161 # < 160.7009 6 < 161 df$Recency.score[df$Recency >= 1069] = 1 df$Recency.score[df$Recency >= 432 & df$Recency < 1069] = 2 df$Recency.score[df$Recency >= 233 & df$Recency < 432] = 3 df$Recency.score[df$Recency >= 179 & df$Recency < 233] = 4 df$Recency.score[df$Recency >= 161 & df$Recency < 179] = 5 df$Recency.score[df$Recency < 161] = 6 # f median df.test = df[(df$Frequency <= 42.388889) & (df$Frequency >= 23.652603), 3] median(df.test$Frequency) df.test = df[(df$Frequency <= 23.652603) & (df$Frequency >= 10.406760), 3] median(df.test$Frequency) df.test = df[(df$Frequency <= 10.406760) & (df$Frequency >= 3.208774), 3] median(df.test$Frequency) df.test = df[(df$Frequency <= 3.208774) & (df$Frequency >= 2.523883), 3] median(df.test$Frequency) df.test = df[(df$Frequency <= 2.523883), 3] View(df.test) median(df.test$Frequency) # Frequency mean/ median : # 2.430464 1 # 2.866329 3 # 6.807767 6 # 17.02968 14 # 33.02075 28 df$Frequncy.score[df$Frequency >= 33.02075] = 6 df$Frequncy.score[df$Frequency >= 17.02968 & df$Frequency < 33.02075] = 5 df$Frequncy.score[df$Frequency >= 6.807767 & df$Frequency < 17.02968] = 4 df$Frequncy.score[df$Frequency >= 2.866329 & df$Frequency < 6.807767] = 3 df$Frequncy.score[df$Frequency >= 2.430464 & df$Frequency < 2.866329] = 2 df$Frequncy.score[df$Frequency < 2.430464] = 1 # m median df.test = df[(df$`Monetary Value` <= 2953.79475) & (df$`Monetary Value` >= 938.05044), 4] median(df.test$`Monetary Value`) df.test = df[(df$`Monetary Value` <= 938.05044) & (df$`Monetary Value` >= 362.47937), 4] median(df.test$`Monetary Value`) df.test = df[(df$`Monetary Value` <= 362.47937) & (df$`Monetary Value` >= 98.03783), 4] median(df.test$`Monetary Value`) df.test = df[(df$`Monetary Value` <= 98.03783) & (df$`Monetary Value` >= 96.26073), 4] median(df.test$`Monetary Value`) df.test = df[(df$`Monetary Value` <= 96.26073) & (df$`Monetary Value` >= 71.71050), 4] median(df.test$`Monetary Value`) # monetary value median: # 96.26073 82.74472 # 98.03783 97.24994 # 362.4794 176.1854 # 938.0504 517.0684 # 2953.795 1249.796 df$Monetary.value.score[df$`Monetary Value` >= 1249.796] = 6 df$Monetary.value.score[df$`Monetary Value` >= 517.0684 & df$`Monetary Value` < 1249.796] = 5 df$Monetary.value.score[df$`Monetary Value` >= 176.1854 & df$`Monetary Value` < 517.0684] = 4 df$Monetary.value.score[df$`Monetary Value` >= 97.24994 & df$`Monetary Value` < 176.1854] = 3 df$Monetary.value.score[df$`Monetary Value` >= 82.74472 & df$`Monetary Value` < 97.24994] = 2 df$Monetary.value.score[df$`Monetary Value` < 82.74472] = 1 names(df) df$RFM.score = 100 * df$Recency.score + 10 * df$Frequncy.score + df$Monetary.value.score df = df[, c(1, 67:70, 2:66)] View(df) write.csv(df, 'cleanned dataset RFM score.csv') ``` ```{r} #install.packages("rfm") #library(rfm) new.df = df ``` ```{r} df = new.df df$Segment[(df$Recency.score %in% c(4,5,6)) & ((df$Frequncy.score) %in% c(1,2,3,4)) & (df$Monetary.value.score %in% c(1,2,3,4))] = "New Customers" df$Segment[(df$Recency.score %in% c(4,5,6)) & ((df$Frequncy.score) %in% c(4,5,6)) & (df$Monetary.value.score %in% c(4,5,6))] = "Loyal Customers" df$Segment[(df$Recency.score %in% c(5,6)) & ((df$Frequncy.score) %in% c(5,6)) & (df$Monetary.value.score %in% c(5,6))] = "Champions" # df$Segment[(df$Recency.score %in% c(5,3,4,6)) & ((df$Frequncy.score) %in% c(3,4,5,6)) # & (df$Monetary.value.score %in% c(3,4,5))] = "Potential Loyalists" df$Segment[(df$Recency.score %in% c(4,5)) & ((df$Frequncy.score) %in% c(1,2,4,3)) & (df$Monetary.value.score %in% c(1,2))] = "Promising" df$Segment[(df$Recency.score %in% c(3,4,5)) & ((df$Frequncy.score) %in% c(3,4,5)) & (df$Monetary.value.score %in% c(2,3))] = "Need Attention" df$Segment[(df$Recency.score %in% c(2,3)) & ((df$Frequncy.score) %in% c(1,3,2)) & (df$Monetary.value.score %in% c(1,3,2))] = "About to Sleep" df$Segment[(df$Recency.score %in% c(2,1)) & ((df$Frequncy.score) %in% c(2,3,4,5,6)) & (df$Monetary.value.score %in% c(2,3,4,5,6))] = "At Risk" # df$Segment[(df$Recency.score %in% c(1)) & ((df$Frequncy.score) %in% c(1,3,2,4)) & # (df$Monetary.value.score %in% c(3,4))] = "Hibernating" df$Segment[(df$Recency.score == 1) & (df$Frequncy.score %in% c(1,2,3,4)) & (df$Monetary.value.score %in% c(1,2,3,4))] = "Lost" df$Segment[(df$Recency.score %in% c(1)) & (df$Frequncy.score %in% c(5,6)) & (df$Monetary.value.score %in% c(5,6))] = "Can't lose" df$Segment[is.na(df$Segment)] = "Others" View(df) df = df[, c(1, 71, 2:70)] sum(is.na(df$Segment)) ``` ```{r} table(df$Segment) library(dplyr) df %>% group_by(Segment) %>% summarise(n = n())%>% mutate(proportion = n / sum(n)) %>% arrange(desc(n)) library(rfm) rfm_plot_median_recency(df$Segment) df[] debug = df[which(is.na(df$Segment)), 1:6] summary(debug) View(debug) nrow(df) sort(prop.table(table(df$Segment)), TRUE) write.csv(df, 'cleanned dataset segment 4.csv') View(df) yue = lm(df$`Monetary Value` ~ df$Recency + df$Frequency) summary(yue) ```
e0264ddb22711153c9039f60c8add74416ba4fcd
[ "RMarkdown" ]
1
RMarkdown
yus002/RFM-Analysis-on-Customers-Segmentation
f6404830cbb4d43fb67c70fce559fe28bb3bb876
7d6cc0a8f103b1338ff4a5114130a7682ee49704
refs/heads/master
<file_sep># -*- coding: utf-8 -*- __author__ = 'karan' import nltk import re import sys import csv posEmo=[] negEmo=[] def main(): dicton=[] print("Start"); tweetData=open("test.csv","r") # getting the stop words data=tweetData.read().split('\n') for i in data: tweet1=i; # tweet=i.split(',') # tweet1=tweet[0] stopWords = open("english.txt","r"); stop_word = stopWords.read().split(); AllStopWrd = [] for wd in stop_word: AllStopWrd.append(wd); #print("stop words-> ",AllStopWrd); # sample and also cleaning it #tweet1= """"Best day of my life""" #print("old tweet-> ",tweet1) tweet1 = tweet1.replace("'t","t") tweet1 = tweet1.replace("'s","") tweet1 = tweet1.lower() tweet1 = ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",tweet1).split()) #print(tweet1); tw = tweet1.split() #print(tw) #tokenize sentences = nltk.word_tokenize(tweet1) #print("tokenized ->", sentences) #remove stop words Otweet = tw #for w in tw: # if w not in AllStopWrd: # Otweet.append(w); #print("sans stop word-> ",Otweet) emoWord=[] emoMeaning=[] # get taggers for neg/pos/inc/dec/inv words taggers ={} negWords = open("neg.txt","r"); neg_word = negWords.read().split(); #print("ned words-> ",neg_word) posWords = open("pos.txt","r"); pos_word = posWords.read().split(); #print("pos words-> ",pos_word) incrWords = open("incr.txt","r"); inc_word = incrWords.read().split(); #print("incr words-> ",inc_word) decrWords = open("decr.txt","r"); dec_word = decrWords.read().split(); #print("dec wrds-> ",dec_word) invWords = open("inverse.txt","r"); inv_word = invWords.read().split('\n'); #print("inverse words-> ",inv_word) emoticons = open("emoticon.txt","r"); emoSent = emoticons.read().split("\n"); for i in emoSent: emo=i.split(" ") emoWord.append(emo[0]) emoMeaning.append(emo[1]) for nw in neg_word: taggers.update({nw:'negative'}); for pw in pos_word: taggers.update({pw:'positive'}); for iw in inc_word: taggers.update({iw:'inc'}); for dw in dec_word: taggers.update({dw:'dec'}); for ivw in inv_word: taggers.update({ivw:'inv'}); # print("tagger-> ",taggers) # print(taggers.get('little')) # get parts of speech posTagger = [nltk.pos_tag(Otweet)] #print("posTagger-> ",posTagger) dictTagger =[] for token in posTagger: tokentagger =[] #print("token--> ",token) for tok in token: tklist =[] tklist.append(tok[0]) tklist.append(tok[1]) #print(tok[0],tok[1]) if tok[0] in neg_word: tklist.append('negative') if tok[0] in pos_word: tklist.append('positive') if tok[0] in inc_word: tklist.append('inc') if tok[0] in dec_word: tklist.append('dec') if tok[0] in inv_word: tklist.append('inv') if tok[0] in emoWord: emoMeaningString=emoMeaning.index(tok[0]) if (emoMeaningString=="rolleyes" or emoMeaningString=="lol" or emoMeaningString=="sad" or emoMeaningString=="confused" or emoMeaningString=="tongue" or emoMeaningString=="angry" or emoMeaningString=="question" or emoMeaningString=="cry" or emoMeaningString=="uneasy" or emoMeaningString=="facepalm"): negEmo.append(tok[0]) elif (emoMeaningString=="lol" or emoMeaningString=="cool" or emoMeaningString=="smile" or emoMeaningString=="bigsmile" or emoMeaningString=="surprised" or emoMeaningString=="neutral" or emoMeaningString=="wink" or emoMeaningString=="exclaim" or emoMeaningString=="heart" or emoMeaningString=="martini" or emoMeaningString=="mindblown" or emoMeaningString=="star" or emoMeaningString=="blush"): posEmo.append(tok[0]) tokentagger.append(tklist) dictTagger.append(tokentagger) #print(dictTagger) Cleantweet =[] for w in dictTagger[0]: if w[0] not in AllStopWrd: Cleantweet.append(w) #print("clan tweet",Cleantweet) sum = count(Cleantweet,None,0) if len(posEmo) > len(negEmo): sum=sum+3 elif len(negEmo) > len(posEmo): sum=sum-3 elif len(negEmo) == len(posEmo): sum=sum+0 #print(sum) if sum > 0: newsomthing = [tweet1,'positive',sum] elif sum < 0: newsomthing = [tweet1,'negative',sum] elif sum ==0: newsomthing = [tweet1,'neutral',sum] dicton.append(newsomthing) #print (dicton) file2 = open('myfile2.csv','wb') writer = csv.writer(file2) writer.writerows(dicton) file2.close() def count(current,previous,sum): #print("counting") #print("current-> ",current) #print("prev-> ",previous) if len(current)==0: return sum else: first = current[0] #print("first->",first) wording = first[0] tag1 = first[1] tag2 = '' if len(first) == 3: tag2 = first[2] #print("word tag tag",wording,tag1,tag2) score =0 if tag2 is 'positive' or tag2 is 'negative': #print("either") if ('JJ' in tag1) or ('VB' in tag1) or ('RB' in tag1): if tag2 is 'positive': score =score+1 #print(score) else: score = score-1 #print(score) if previous is not None: if 'inc' in previous: if score==0: score +=2.0 else: score *= 2.0 elif 'dec' in previous: if score==0: score -=2.0 else: score /= 2.0 elif 'inv' in previous: if score==0: score +=-2.0 else: score *=-2.0 return count(current[1:], first, sum + score) main();<file_sep>Hi Sentiment Analysis using NLP
06323bd405aa0a9383adff0e619dd334f5c9a6fd
[ "Markdown", "Python" ]
2
Markdown
krs8785/Sentiment-Analysis-NLP
50d292dd589afbae7b817a3647b330b43bffeccd
5ad21bd1e68aef820beee4165d5265e7c2ece522
refs/heads/master
<repo_name>black13/win-getaddrinfo<file_sep>/appveyor.yml version: 1.0.{build} configuration: Release platform: x64 build: project: getaddrinfo.sln verbosity: minimal test: off artifacts: - path: x64/Release/getaddrinfo.exe name: Release deploy: - provider: GitHub auth_token: secure: <KEY> <file_sep>/build.sh #!/bin/bash # build the base msbuild image docker build -t msbuild -f Dockerfile.msbuild . # copy source into new image as -v does not work from mac to windows docker build -t sources -f Dockerfile.build . # build the binary and copy it back from windows to mac docker rm -vf binary docker run --name=binary sources msbuild getaddrinfo.sln /p:Configuration=Release docker cp binary:/code/win32/Release/getaddrinfo.exe getaddrinfo.exe <file_sep>/README.md # win-getaddrinfo [![Build status](https://ci.appveyor.com/api/projects/status/efdbx8ariqmchva1?svg=true)](https://ci.appveyor.com/project/StefanScherer/win-getaddrinfo) Test code to investigate the issue [nodejs/node#2578](https://github.com/nodejs/node/issues/2578) inside a Windows Docker container. The binary is used to test the AI_ADDRCONFIG hint flag on Windows Server 2016 TP3 as well as running inside a Windows Docker container. See the [MSDN getaddrinfo](https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520(v=vs.85).aspx#AI_ADDRCONFIG) article for more details. ## Test with AI_ADDRCONFIG hint flag ``` getaddrinfo.exe registry.npmjs.org 80 AI_ADDRCONFIG ``` ## Test without AI_ADDRCONFIG hint flag ``` getaddrinfo.exe registry.npmjs.org 80 0 ``` ## Build exe with Windows Docker containers Spin up a Win2016 VM and set `DOCKER_HOST` environment variable to it. Then run ```bash ./build.sh ``` The final static release binary `getaddrinfo.exe` will be copied back to your host. <file_sep>/getaddrinfo.c #undef UNICODE #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> // link with Ws2_32.lib #pragma comment (lib, "Ws2_32.lib") int __cdecl main(int argc, char **argv) { //----------------------------------------- // Declare and initialize variables WSADATA wsaData; int iResult; INT iRetval; DWORD dwRetval; int i = 1; struct addrinfo *result = NULL; struct addrinfo *ptr = NULL; struct addrinfo hints; struct sockaddr_in *sockaddr_ipv4; // struct sockaddr_in6 *sockaddr_ipv6; LPSOCKADDR sockaddr_ip; char ipstringbuffer[46]; DWORD ipbufferlength = 46; // Validate the parameters if (argc != 4) { printf("usage: %s <hostname> <servicename>\n", argv[0]); printf("getaddrinfo provides protocol-independent translation\n"); printf(" from an ANSI host name to an IP address\n"); printf("%s example usage\n", argv[0]); printf(" %s www.contoso.com 0 AI_ADDRCONFIG|0\n", argv[0]); return 1; } // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); return 1; } //-------------------------------- // Setup the hints address info structure // which is passed to the getaddrinfo() function ZeroMemory( &hints, sizeof(hints) ); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; if (! strcmp(argv[3], "AI_ADDRCONFIG")) { hints.ai_flags = AI_ADDRCONFIG; } printf("Calling getaddrinfo with following parameters:\n"); printf("\tnodename = %s\n", argv[1]); printf("\tservname (or port) = %s\n", argv[2]); printf("\thints.ai_flags = 0x%x\n\n", hints.ai_flags); //-------------------------------- // Call getaddrinfo(). If the call succeeds, // the result variable will hold a linked list // of addrinfo structures containing response // information dwRetval = getaddrinfo(argv[1], argv[2], &hints, &result); if ( dwRetval != 0 ) { printf("getaddrinfo failed with error: %d\n", dwRetval); WSACleanup(); return 1; } printf("getaddrinfo returned success\n"); // Retrieve each address and print out the hex bytes for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) { printf("getaddrinfo response %d\n", i++); printf("\tFlags: 0x%x\n", ptr->ai_flags); printf("\tFamily: "); switch (ptr->ai_family) { case AF_UNSPEC: printf("Unspecified\n"); break; case AF_INET: printf("AF_INET (IPv4)\n"); sockaddr_ipv4 = (struct sockaddr_in *) ptr->ai_addr; printf("\tIPv4 address %s\n", inet_ntoa(sockaddr_ipv4->sin_addr) ); break; case AF_INET6: printf("AF_INET6 (IPv6)\n"); // the InetNtop function is available on Windows Vista and later // sockaddr_ipv6 = (struct sockaddr_in6 *) ptr->ai_addr; // printf("\tIPv6 address %s\n", // InetNtop(AF_INET6, &sockaddr_ipv6->sin6_addr, ipstringbuffer, 46) ); // We use WSAAddressToString since it is supported on Windows XP and later sockaddr_ip = (LPSOCKADDR) ptr->ai_addr; // The buffer length is changed by each call to WSAAddresstoString // So we need to set it for each iteration through the loop for safety ipbufferlength = 46; iRetval = WSAAddressToString(sockaddr_ip, (DWORD) ptr->ai_addrlen, NULL, ipstringbuffer, &ipbufferlength ); if (iRetval) printf("WSAAddressToString failed with %u\n", WSAGetLastError() ); else printf("\tIPv6 address %s\n", ipstringbuffer); break; case AF_NETBIOS: printf("AF_NETBIOS (NetBIOS)\n"); break; default: printf("Other %ld\n", ptr->ai_family); break; } printf("\tSocket type: "); switch (ptr->ai_socktype) { case 0: printf("Unspecified\n"); break; case SOCK_STREAM: printf("SOCK_STREAM (stream)\n"); break; case SOCK_DGRAM: printf("SOCK_DGRAM (datagram) \n"); break; case SOCK_RAW: printf("SOCK_RAW (raw) \n"); break; case SOCK_RDM: printf("SOCK_RDM (reliable message datagram)\n"); break; case SOCK_SEQPACKET: printf("SOCK_SEQPACKET (pseudo-stream packet)\n"); break; default: printf("Other %ld\n", ptr->ai_socktype); break; } printf("\tProtocol: "); switch (ptr->ai_protocol) { case 0: printf("Unspecified\n"); break; case IPPROTO_TCP: printf("IPPROTO_TCP (TCP)\n"); break; case IPPROTO_UDP: printf("IPPROTO_UDP (UDP) \n"); break; default: printf("Other %ld\n", ptr->ai_protocol); break; } printf("\tLength of this sockaddr: %d\n", ptr->ai_addrlen); printf("\tCanonical name: %s\n", ptr->ai_canonname); } freeaddrinfo(result); WSACleanup(); return 0; }
b87049481a1fd47c944a7b7ee08baaa55944fcff
[ "Markdown", "Shell", "C", "YAML" ]
4
Markdown
black13/win-getaddrinfo
3afdfab3f0fb7b1223d69ead19c93dbe917afed8
4051011a4ca5aef0759b10695beefae48d101c48
refs/heads/master
<repo_name>astropoetamee/LSST<file_sep>/README.md # LSST An example of using Github for technical documentation for an interview with the LSST.
f545e5e629a896dc58422c6a499b1aa67860ed1f
[ "Markdown" ]
1
Markdown
astropoetamee/LSST
43c43373bfd7ac7e46f466ce0021dff895bfc67d
47a2da56536ae86951c74a4fb4f0d541d2c3878f
refs/heads/master
<repo_name>gabrielarotver/urlShortener<file_sep>/app/views/site/new.html.erb <h1>URL SHORTENER</h1> <p><%= alert %></p> <h3>Enter the url you want to shorten:</h3> <%= form_for @u, url: root_path do |u|%> <%= u.label :long_url %> <%= u.search_field :long_url %> <%= u.submit "shorten url!"%> <% end %> <% if notice%> <ul> <li><%= link_to "#{request.host_with_port}/#{@u.shortened_url}", @u.long_url, :target => "_blank"%></li> </ul> <% end %> <file_sep>/app/models/url.rb class Url < ApplicationRecord validates :long_url, presence: true validates_uniqueness_of :shortened_url end <file_sep>/app/controllers/site_controller.rb class SiteController < ApplicationController def new @u = Url.new end def create # url in path if !params[:words].nil? @u = Url.new @u.long_url = params[:words] begin @u.shortened_url = Randomstring.generate(4); end while(!Url.find_by(shortened_url: @u.shortened_url).nil?) if @u.save flash[:notice] = "success" render 'new' else render 'new' end # url already in db elsif (!Url.find_by(long_url: site_params[:long_url]).nil?) @u = Url.find_by(long_url: site_params[:long_url]) flash[:notice] = "success" render 'new' # create new url from form else @u = Url.new(site_params) begin @u.shortened_url = Randomstring.generate(4); end while(!Url.find_by(shortened_url: @u.shortened_url).nil?) if @u.save flash[:notice] = "success" render 'new' else render 'new' end end end private def site_params params.require(:url).permit(:long_url) end end <file_sep>/config/routes.rb Rails.application.routes.draw do root 'site#new' post '/' => 'site#create' patch '/' => 'site#create' get '/:words', to: 'site#create', :constraints => {:words => /.*/ } # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end # URI.parse("http://localhost:3000/https://www.pandora.com"). Figure it out. #validate in controller eventually.
87280d53fd043cf5ee46154b5167ef7266c3771f
[ "HTML+ERB", "Ruby" ]
4
HTML+ERB
gabrielarotver/urlShortener
883b437521785312cc3d767901e40bc071fbfcdd
d40803728ca3de48d1c2cd4c53c39399af16ab7f
refs/heads/master
<file_sep>package rx import "errors" // defines a function returning an RxFrame type FrameFactory func() RxFrame var ( errUnknownFrameApiId = errors.New("Unknown frame API ID") rxFrameFactory = make(map[byte]FrameFactory) ) func init() { // AT command response rxFrameFactory[XBEE_API_ID_RX_AT] = newAT rxFrameFactory[XBEE_API_ID_RX_ZB] = newZB } // NewRxFrameForApiId creates an appropriate RxFrame for the given API ID func NewRxFrameForApiId(id byte) (RxFrame, error) { if f, ok := rxFrameFactory[id]; ok { return f(), nil } return nil, errUnknownFrameApiId } func AddApiFactoryForId(id byte, factory FrameFactory ) { if _, ok := rxFrameFactory[id]; !ok { rxFrameFactory[id] = factory } }<file_sep>language: go go: - 1.6 - 1.7 - tip notifications: slack: secure: <KEY> <file_sep>package rx const XBEE_API_ID_RX_AT byte = 0x88 const at_command_length byte = 2 const ( at_state_frame_id = rx_frame_state(iota) at_state_frame_command_at = rx_frame_state(iota) at_state_frame_command_status = rx_frame_state(iota) at_state_frame_command_data = rx_frame_state(iota) ) type AT struct { state rx_frame_state index byte FrameId byte Command [2]byte Status byte Data []byte } func newAT() RxFrame { return &AT{ state: at_state_frame_id, } } func (f *AT) RX(b byte) error { var err error switch f.state { case at_state_frame_id: err = f.stateId(b) case at_state_frame_command_at: err = f.stateCommand(b) case at_state_frame_command_status: err = f.stateStatus(b) case at_state_frame_command_data: err = f.stateData(b) } return err } func (f *AT) stateId(b byte) error { f.FrameId = b f.state = at_state_frame_command_at return nil } func (f *AT) stateCommand(b byte) error { f.Command[f.index] = b f.index++ if f.index == at_command_length { f.state = at_state_frame_command_status } return nil } func (f *AT) stateStatus(b byte) error { f.Status = b f.state = at_state_frame_command_data return nil } func (f *AT) stateData(b byte) error { if f.Data == nil { f.Data = make([]byte, 0) } f.Data = append(f.Data, b) return nil } <file_sep>package rx const XBEE_API_ID_RX_ZB byte = 0x90 const ( rx_zb_addr64 = rx_frame_state(iota) rx_zb_addr16 = rx_frame_state(iota) rx_zb_options = rx_frame_state(iota) rx_zb_data = rx_frame_state(iota) ) type ZB struct { state rx_frame_state index byte Addr64 uint64 Addr16 uint16 Options byte Data []byte } func newZB() RxFrame { return &ZB{ state: rx_zb_addr64, } } func (f *ZB) RX(b byte) error { var err error switch f.state { case rx_zb_addr64: err = stateAddr64(f, b) case rx_zb_addr16: err = stateAddr16(f, b) case rx_zb_options: err = stateOptions(f, b) case rx_zb_data: err = stateData(f, b) } return err } func stateAddr64(f *ZB, b byte) error { f.Addr64 += uint64(b) << (56 - (8 * f.index)) f.index++ if f.index == 8 { f.index = 0 f.state = rx_zb_addr16 } return nil } func stateAddr16(f *ZB, b byte) error { f.Addr16 += uint16(b) << (8 - (8 * f.index)) f.index++ if f.index == 2 { f.index = 0 f.state = rx_zb_options } return nil } func stateOptions(f *ZB, b byte) error { f.Options = b f.state = rx_zb_data return nil } func stateData(f *ZB, b byte) error { if f.Data == nil { f.Data = make([]byte, 0) } f.Data = append(f.Data, b) return nil }<file_sep>package tx import "bytes" const api_id_tx_zb byte = 0x10 type ZB struct { ID byte DestAddr64 uint64 DestAddr16 uint16 BroadcastRadius byte Options byte Data []byte } func (f *ZB) Bytes() []byte { b := new(bytes.Buffer) b.WriteByte(api_id_tx_zb) b.WriteByte(f.ID) b.WriteByte(byte((f.DestAddr64 >> 56) & 0xFF)) b.WriteByte(byte((f.DestAddr64 >> 48) & 0xFF)) b.WriteByte(byte((f.DestAddr64 >> 40) & 0xFF)) b.WriteByte(byte((f.DestAddr64 >> 32) & 0xFF)) b.WriteByte(byte((f.DestAddr64 >> 24) & 0xFF)) b.WriteByte(byte((f.DestAddr64 >> 16) & 0xFF)) b.WriteByte(byte((f.DestAddr64 >> 8) & 0xFF)) b.WriteByte(byte(f.DestAddr64 & 0xFF)) b.WriteByte(byte((f.DestAddr16 >> 8) & 0xFF)) b.WriteByte(byte(f.DestAddr16 & 0xFF)) b.WriteByte(f.BroadcastRadius) b.WriteByte(f.Options) if len(f.Data) != 0 { b.Write(f.Data) } return b.Bytes() }<file_sep>package rx import ( "bytes" "testing" ) func Test_at_command_response(t *testing.T) { // at command response frame data response := []byte{ 0x01, 0x4e, 0x49, 0x00, 0x20, 0x5a, 0x69, 0x67, 0x42, 0x65, 0x65, 0x20, 0x43, 0x6f, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0xe5} rxf := newAT() f, ok := rxf.(*AT) if !ok { t.Error("Failed type assertion") } for _, b := range response { err := f.RX(b) if err != nil { t.Errorf("Expected no error, but got %v", err) } } if f.FrameId != response[0] { t.Errorf("Expected FrameId: 0x01, but got 0x%02X", f.FrameId) } if !bytes.Equal(f.Command[:1], response[1:2]) { t.Errorf("Expected Command: NI, but got %s", string(f.Command[:])) } if f.Status != response[3] { t.Errorf("Expected Status: 0x00, but got 0x%02X", f.Status) } if !bytes.Equal(f.Data[:], response[4:]) { t.Errorf("Expected Data: %v, but got %v", response[4:], f.Data) } } <file_sep>package tx type TxFrame interface { Bytes() []byte } <file_sep># gobee - A Go XBee Library [![Build Status](https://travis-ci.org/pauleyj/gobee.svg?branch=master)](https://travis-ci.org/pauleyj/gobee) gobee, a library for enabling support of XBee (series 2 and 3) low power radios to your Go project.<file_sep>package rx import "testing" const unknown_api_id byte = 0x00 func TestNewRxFrameForApiId(t *testing.T) { rxf, err := NewRxFrameForApiId(XBEE_API_ID_RX_AT) if err != nil { t.Errorf("Expected no error, but got: %v", err) } _, ok := rxf.(*AT) if !ok { t.Error("Failed type assertion ATCommandResponse") } _, err = NewRxFrameForApiId(unknown_api_id) if err == nil { t.Errorf("Expected error: %v, but got none", errUnknownFrameApiId) } if err != errUnknownFrameApiId { t.Errorf("Expected error: %v, but got: %v", errUnknownFrameApiId, err) } } <file_sep>package gobee_test import ( "testing" "github.com/pauleyj/gobee" "github.com/pauleyj/gobee/rx" ) type Transmitter struct{ t *testing.T expected []byte } func (xm *Transmitter) Write(p []byte) (n int, err error) { return len(p), nil } func (xm *Transmitter) SetExpectedWriteBytes(expected []byte) { xm.expected = expected } type Receiver struct { t *testing.T } func (r *Receiver) RxFrameReceiver(f rx.RxFrame) error { switch f.(type) { case *rx.AT: validateAT(r.t, f.(*rx.AT)) } return nil } func validateAT(t *testing.T, f *rx.AT) { if f.FrameId != 1 { t.Errorf("Expected FrameId: 0x01, but got 0x%02x", f.FrameId) } } func TestXBee_RX_AT(t *testing.T) { transmitter := &Transmitter{} receiver := &Receiver{t: t} xbee := gobee.NewXBee(transmitter, receiver) xbee.SetApiMode(2) // a valid AT command response response := []byte{ 0x7e, 0x00, 0x18, 0x88, 0x01, 0x4e, 0x49, 0x00, 0x20, 0x5a, 0x69, 0x67, 0x42, 0x65, 0x65, 0x20, 0x43, 0x6f, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0xe5} for _, b := range response { err := xbee.RX(b) if err != nil { t.Errorf("Expected no error, but got %v", err) } } } func TestXBee_RX_AT_Escape(t *testing.T) { transmitter := &Transmitter{} receiver := &Receiver{t: t} x := gobee.NewXBee(transmitter, receiver) x.SetApiMode(2) // a valid AT command response with escaped bytes response := []byte{ 0x7e, 0x00, 0x06, 0x88, 0x01, 0x4e, 0x49, 0x00, 0x7D, 0x31, 0xce} for _, b := range response { err := x.RX(b) if err != nil { t.Errorf("Expected no error, but got %v", err) } } }<file_sep>package tx import "bytes" const api_id_at byte = 0x08 type AT struct { ID byte Command [2]byte Parameter []byte } func (f *AT) Bytes() []byte { var b bytes.Buffer b.WriteByte(api_id_at) b.WriteByte(f.ID) b.Write(f.Command[:]) if len(f.Parameter) != 0 { b.Write(f.Parameter) } return b.Bytes() } <file_sep>package rx type rx_frame_state int type RxFrame interface { RX(byte) error } <file_sep>package gobee import ( "bytes" "errors" "github.com/pauleyj/gobee/rx" "github.com/pauleyj/gobee/tx" "io" ) /* * Frame Constants */ const FRAME_DELIMITER byte = 0x7E const XBEE_NUMBER_OF_SIZE_BYTES uint8 = 2 const XBEE_VALID_FRAME_CHECKSUM byte = 0xFF const ESC byte = 0x7D const XON byte = 0x11 const XOFF byte = 0x13 const ESC_CHAR = 0x20 /* * Address constants */ const BROADCAST_ADDR_64 uint64 = 0x000000000000FFFF const BROADCAST_ADDR_16 uint16 = 0xFFFE var ( escape_set = [...]byte{FRAME_DELIMITER, ESC, XON, XOFF} errChecksumValidation = errors.New("Frame failed checksum validation") errInvalidApiMode = errors.New("Invalid API mode") ) const ( STATE_DATA_FRAME_START = ApiState(iota) STATE_DATA_FRAME_LENGTH = ApiState(iota) STATE_DATA_FRAME_API_ID = ApiState(iota) STATE_DATA_FRAME_DATA = ApiState(iota) STATE_DATA_FRAME_CHECKSUM = ApiState(iota) ) type ApiState int type XBeeTransmitter interface { io.Writer } type XBeeReceiver interface { RxFrameReceiver(rx.RxFrame) error } type XBee struct { transmitter XBeeTransmitter receiver XBeeReceiver apiMode byte escapeNext bool rxState ApiState rxFrameDataSize uint16 rxFrameChecksum uint8 rxFrameDataSizeByteIndex uint8 rxFrameDataIndex uint16 rxFrame rx.RxFrame } func NewXBee(transmitter XBeeTransmitter, receiver XBeeReceiver) *XBee { return &XBee{ transmitter: transmitter, receiver: receiver, apiMode: 1, escapeNext: false, rxState: STATE_DATA_FRAME_START, rxFrameDataSize: 0, rxFrameChecksum: 0, rxFrameDataSizeByteIndex: 0, rxFrameDataIndex: 0, rxFrame: nil, } } func (x *XBee) RX(b byte) error { var err error if x.isApiEscapeModeEnabled() { if x.rxState != STATE_DATA_FRAME_START && b == ESC && !x.escapeNext { x.escapeNext = true return nil } if x.escapeNext { x.escapeNext = false b = escape(b) } } switch x.rxState { case STATE_DATA_FRAME_LENGTH: err = x.apiStateDataLength(b) case STATE_DATA_FRAME_API_ID: err = x.apiStateApiId(b) case STATE_DATA_FRAME_DATA: err = x.apiStateFrameData(b) case STATE_DATA_FRAME_CHECKSUM: err = x.apiStateChecksum(b) if err == nil { x.receiver.RxFrameReceiver(x.rxFrame) } default: err = x.apiStateWaitFrameDelimiter(b) } return err } func (x *XBee) TX(frame tx.TxFrame) (n int, err error) { f := frame.Bytes() var b bytes.Buffer var checksum byte = 0 len := len(f) b.WriteByte(FRAME_DELIMITER) lh := byte(len >> 8) ll := byte(len & 0x00FF) if x.isApiEscapeModeEnabled() { if shouldEscape(lh) { lh = escape(lh) b.WriteByte(ESC) } if shouldEscape(ll) { ll = escape(ll) b.WriteByte(ESC) } } b.WriteByte(lh) b.WriteByte(ll) for _, i := range f { // checksum is calculated on pre escaped value checksum += i if x.isApiEscapeModeEnabled() && shouldEscape(i) { i = escape(i) b.WriteByte(ESC) } b.WriteByte(i) } checksum = XBEE_VALID_FRAME_CHECKSUM - checksum // checksum is escaped if needed if x.apiMode == 2 && shouldEscape(checksum) { checksum = escape(checksum) b.WriteByte(ESC) } b.WriteByte(checksum) return x.transmitter.Write(b.Bytes()) } func (x *XBee) SetApiMode(mode byte) error { if mode != 1 && mode != 2 { return errInvalidApiMode } x.apiMode = mode return nil } func shouldEscape(b byte) bool { for _, v := range escape_set { if b == v { return true } } return false } func escape(b byte) byte { return (b ^ ESC_CHAR) } func (x *XBee) isApiEscapeModeEnabled() bool { return x.apiMode == 0x02 } func (x *XBee) apiStateWaitFrameDelimiter(b byte) error { if FRAME_DELIMITER == b { x.rxFrameDataSize = 0 x.rxFrameChecksum = 0 x.rxFrameDataSizeByteIndex = 0 x.rxFrameDataIndex = 0 x.rxFrame = nil x.rxState = STATE_DATA_FRAME_LENGTH return nil } x.rxState = STATE_DATA_FRAME_START return nil } func (x *XBee) apiStateDataLength(b byte) error { x.rxFrameDataSize += uint16(b << (1 - x.rxFrameDataSizeByteIndex)) x.rxFrameDataSizeByteIndex++ if x.rxFrameDataSizeByteIndex == XBEE_NUMBER_OF_SIZE_BYTES { x.rxState = STATE_DATA_FRAME_API_ID } return nil } func (x *XBee) apiStateApiId(b byte) error { var err error x.rxFrame, err = rx.NewRxFrameForApiId(b) if err != nil { x.rxState = STATE_DATA_FRAME_START return err } x.rxFrameChecksum += b x.rxFrameDataIndex++ x.rxState = STATE_DATA_FRAME_DATA return nil } func (x *XBee) apiStateFrameData(b byte) error { x.rxFrame.RX(b) x.rxFrameChecksum += b x.rxFrameDataIndex++ if x.rxFrameDataIndex == x.rxFrameDataSize { x.rxState = STATE_DATA_FRAME_CHECKSUM } return nil } func (x *XBee) apiStateChecksum(b byte) error { x.rxState = STATE_DATA_FRAME_START x.rxFrameChecksum += b if XBEE_VALID_FRAME_CHECKSUM != x.rxFrameChecksum { return errChecksumValidation } return nil }
1e2bc6d4f2791423f01f89822698b904768bc33f
[ "Markdown", "YAML", "Go" ]
13
Markdown
edwardsb/gobee
c457997a5da755d2066dc7ccd3f170404e484dae
8cd82d4f5f79cc16bf1897673babc26f110a16f6
refs/heads/master
<repo_name>yujiabao1015/1801e_exam2<file_sep>/src/main/java/com/yujiabao/common/domain/Person.java package com.yujiabao.common.domain; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; /** * 专家实体类 * @ClassName: Person * @Description: TODO * @author: www17 * @date: 2020年4月27日 上午10:32:40 */ public class Person { private BigInteger id; private String name; private Integer age; private BigDecimal money; private Date date; public BigInteger getId() { return id; } public void setId(BigInteger id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getMoney() { return money; } public void setMoney(BigDecimal money) { this.money = money; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Person() { super(); } public Person(BigInteger id, String name, Integer age, BigDecimal money, Date date) { super(); this.id = id; this.name = name; this.age = age; this.money = money; this.date = date; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", age=" + age + ", money=" + money + ", date=" + date + "]"; } } <file_sep>/src/main/java/com/yujiabao/common/utils/DateUtil.java package com.yujiabao.common.utils; import java.util.Calendar; import java.util.Date; import java.util.Random; /** * * @ClassName: DateUtil * @Description: 日期工具类 * @author: charles * @date: 2020年4月23日 下午4:38:21 */ public class DateUtil { /** * * @Title: random * @Description: 随机产生一个min 和max之间的日期 * @param min * @param max * @return * @return: Date */ public static Date random(Date min ,Date max) { long t1 = min.getTime(); long t2 = max.getTime(); long t = (long) (Math.random() * (t2 -t1) + t1); return new Date(t); } /** * 根据日期计算年龄 * @Title: getAgeByBirthday * @Description: TODO * @param birthday * @return * @return: int */ public static int getAgeByBirthday(Date birthday) { Calendar ca = Calendar.getInstance();//获取系统当前时间 int nowYear = ca.get(Calendar.YEAR);//获取系统当前年 int nowMonth = ca.get(Calendar.MONTH);//获取系统当前月 int nowDay = ca.get(Calendar.DAY_OF_MONTH);//获取系统当前日 /* * 获取生日的年月日 */ Calendar ca2 = Calendar.getInstance(); ca2.setTime(birthday); int bYear = ca2.get(Calendar.YEAR);//获取当前年 int bMonth = ca2.get(Calendar.MONTH);//获取当前月 int bDay = ca2.get(Calendar.DAY_OF_MONTH);//获取当前日 if(nowYear< bYear) { throw new RuntimeException("请输入正确的日期"); } int age = nowYear-bYear; if(nowMonth<bMonth) { age--; } if(bMonth==nowMonth && nowDay<bDay) { age--; } return age; } /** * 获取月初 * @Title: getInitMonth * @Description: TODO * @param date * @return * @return: Date */ public static Date getInitMonth(Date date) { Calendar ca = Calendar.getInstance(); ca.setTime(date); //设置当前时间为月初 ca.set(Calendar.DAY_OF_MONTH, 1); ca.set(Calendar.HOUR_OF_DAY, 0); ca.set(Calendar.MINUTE, 0); ca.set(Calendar.SECOND, 0); return ca.getTime(); } /** * 获取输入日期的月末 * @Title: getEndMonth * @Description: TODO * @param date * @return * @return: Date */ public static Date getEndMonth(Date date) { Calendar ca = Calendar.getInstance(); ca.setTime(date); //让当前月份+1 ca.add(Calendar.MONTH, 1); //获得加一月后的月初 ca.setTime(getInitMonth(ca.getTime())); //减一秒拿到月末时间 ca.add(Calendar.SECOND, -1); return ca.getTime(); } } <file_sep>/src/main/java/com/yujiabao/common/utils/StreamUtil.java package com.yujiabao.common.utils; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class StreamUtil { /** * 批量关闭流或资源 * @Title: closeAll * @Description: TODO * @param autoCloseable * @return: void */ public static void closeAll(AutoCloseable ... autoCloseable){ if(autoCloseable !=null && autoCloseable.length>0) { for (AutoCloseable autoCloseable2 : autoCloseable) { try { autoCloseable2.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * 读取文本文件对象内容 * @Title: readTextFile * @Description: TODO * @param src * @return * @return: String */ public static String readTextFile(InputStream src){ BufferedInputStream bis = new BufferedInputStream(src); byte[] bytes = new byte[1024]; int len=0; StringBuffer sbf = new StringBuffer(); try { while((len=bis.read(bytes))!=-1) { sbf.append(new String(bytes, 0, len)); } } catch (IOException e) { closeAll(bis); e.printStackTrace(); } return sbf.toString(); } /** * 读取文本文件内容 * @Title: readTextFile * @Description: TODO * @param txtFile * @return * @return: String */ public static String readTextFile(File txtFile) { String textFile =""; try { textFile = readTextFile(new FileInputStream(txtFile)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return textFile; } /** * 读取文件内容到集合里 * @Title: readTextFile2List * @Description: TODO * @param txtFile * @return * @return: List<String> */ public static List<String> readTextFile2List(File txtFile){ List<String> list = new ArrayList<String>(); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(txtFile))); String str = ""; while((str=br.readLine())!=null) { list.add(str); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } }
51060cffb06d9df2b8b00d458d5a14e90c5eb4f5
[ "Java" ]
3
Java
yujiabao1015/1801e_exam2
f44b59dd143bfa0f0f741e945bcccadaab1520b8
21252097da3eda577445424734360f2feb0623ab
refs/heads/master
<file_sep># Suggestion Box This is a web-based suggestion box for **e.near** written with the **MEAN stack** technologies Mongo, Express, Angular and Node. It is using grunt as task runner. ## starting it up - do an `npm install`; - create a **config.js** file on the root with the following settings: ```javascript process.env.PORT = 8181; //application port process.env.WEBMAIL_HOST = 'mail.<yourdomain>.<tld>'; //this is your company's webmail host, used for logging users in. process.env.MONGO_CONNECTION_STRING = 'mongodb://<host>:<port>/<db>'; ``` - on the root folder, run `grunt` and if **Mongo** is accessible to the app, it should start listening on the **port** you specified. <file_sep>var https = require('https'); var http = require('http'); var querystring = require('querystring'); module.exports = function doLogin( options, callback ) { var jsonPostData = { 'destination': 'https://' + options.webmailHost + '/owa', 'flags': 4, 'forcedownlevel': 0, 'username': options.username, 'password': <PASSWORD>, 'passwordText': '', 'isUtf8': 1 }; var postData = querystring.stringify(jsonPostData); var requestOptions = { hostname: options.webmailHost, port: options.https ? 443 : 80, path: '/owa/auth.owa', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': postData.length } }; var req = (options.https ? https : http).request( requestOptions, function(res) { if (res.headers.location === jsonPostData.destination) { callback( undefined, true ); } else { callback( undefined, false ); } }); req.on('error', function(e) { console.log('problem with request: ' + e.message); callback( e, false ); }); // write data to request body req.write(postData); req.end(); };<file_sep>angular.module('suggestionbox') .factory('Suggestion', function SuggestionFactory($resource, $http) { return { suggestions: $resource( '/suggestions/:id', {id: '@_id'}, {} ), states: function() { return $http.get('/suggestions/states'); }, getUsername: function() { return $http.get('/users/currentUser'); }, getAdmins: function() { return $http.get('/admins'); } }; }); <file_sep>var router = require('express').Router(); var mongo = require('../utils/mongoUtils'); var Admin = require('../models/admin'); var apiInitializer = require('../utils/apiInitializer'); var loginOnExchange = require('../utils/loginOnExchange'); module.exports = function(app, passport) { app.get('/login', function (req, res) { res.render('login', {title: 'Suggestion Box', title2: 'Please Log In', message: req.flash('error'), redirectTo: req.session.destinationUrl || "/" }); }); // app.post('/login', function(req, res) { // var loginData = { // webmailHost: process.env.WEBMAIL_HOST, // username: req.body.username, // password: <PASSWORD>, // https: true // }; // // loginOnExchange( loginData, function( error, success ) { // if ( success ) { // console.log('Login OK'); // req.session.username = req.body.username; // res.redirect( req.body.redirectTo || '/' ); // } else { // req.session.username = undefined; // res.render('login', {title: 'Suggestion Box', title2: 'Wrong login', redirectTo: req.session.destinationUrl || "/"}); // } // }); // // }); app.get('/auth/slack', passport.authenticate('slack')); app.get('/auth/slack/callback', passport.authenticate('slack', {failureRedirect: '/login', failureFlash: true }), function(req, res) { res.redirect('/'); }); app.get('/user', function( req, res ) { res.json(req.session.username || "please login first"); }); app.get ('/logout', function(req, res) { req.logout(); res.redirect('/'); }); app.get('/admins', function(req, res) { Admin.find({}, function(err, docs) { if(err) { console.log(err); res.json(err); } res.json(docs); }); }); /* GET home/app page. */ app.get('/', isLoggedIn, function (req, res) { res.render('app', {title: 'Suggestion Box', username: req.user.slack.username || ""}); }); }; function isLoggedIn(req, res, next) { // if user is authenticated in the session, carry on if (req.isAuthenticated()) return next(); // if they aren't redirect them to the home page res.redirect('/login'); } <file_sep>var request = require('request'); module.exports = { slackChannel: function(message, attachement, callback) { var options = { uri: process.env.SLACK_ENDPOINT, form: '{"text" : "' + message +'", "attachments":'+ JSON.stringify(attachement) +'}' }; request.post(options, callback); } }; <file_sep>angular.module('suggestionbox') .config(function($routeProvider){ $routeProvider.when('/', { templateUrl: 'suggestions/list/main.html', controller: 'SuggestionsListController', controllerAs: 'suggestionsListCtrl' }) .when('/suggestion/:id', { templateUrl: 'suggestions/detail/detail.html', controller: 'SuggestionDetailController', controllerAs: 'suggestionsDetailCtrl' }) .when('/new', { templateUrl: 'suggestions/new/new.html', controller: 'NewSuggestionController', controllerAs: 'newCtrl' }) .otherwise( { redirectTo: '/' } ); }); <file_sep>var mongoose = require('mongoose'); var suggestionStateSchema = new mongoose.Schema({ state: String }); module.exports = mongoose.model('SuggestionState', suggestionStateSchema); <file_sep>var SlackStrategy = require('passport-slack').Strategy; var apiInitializer = require('./apiInitializer'); var User = require('../models/user'); var Admin = require('../models/admin'); module.exports = function(passport) { passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); passport.use('slack', new SlackStrategy({ clientID: process.env.SLACK_CLIENTID, clientSecret: process.env.SLACK_CLIENT_SECRET, callbackURL: process.env.SLACK_CALLBACK_URL, scope: process.env.SLACK_SCOPE, extendedUserProfile: true }, function(accessToken, refreshToken, profile, done){ process.nextTick(function(){ if(profile._json.team_id !== process.env.SLACK_TEAM_ID){ return done(null, false, {message: "Please sign in to NearTeam"}); } User.findOne({'slack.id': profile.id}, function(err, user){ if(err) { return done(err); } if(user){ return done(null, user); } else { Admin.findOne({"username": profile.displayName}, function(err, doc) { if(err) { return done(err); } var newUser = new User({ slack: { id: profile.id, token: accessToken, username: profile.displayName }, isAdmin: doc ? true : false }); newUser.save(function(err) { if(err) { throw err; } return done(null, newUser); }); }); } }); }); })); }; // <file_sep>//colors $white: #fff; $black: #000; $darkGray: #434343; $lightGray: #bcbcbc ; $whiteSmoke: #f2f2f2; $orange: #EE6626; //measures $gutter: 15px; $spacing: $gutter * 2; $dashboardWidth: 250px; $titleFontSize: 20px; $headerHeight: ($titleFontSize + ($gutter * 2) + 4); //transitions duration: $standardDuration: 0.25s; <file_sep><!DOCTYPE html> <html ng-app="suggestionbox"> <head> <meta name="viewport" content="initial-scale=1.0, width=device-width, user-scalable=no"> <title><%= title %></title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" crossorigin="anonymous" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" /> <link rel='stylesheet' href='/stylesheets/style.css'/> <link rel="icon" type="image/png" href="/assets/favicon.png"> </head> <body> <div class="container-fluid mainContainer" ng-controller="mainController"> <header class="row"> <div class="col-xs-12 col-sm-2"> <a class="burgerMenu" ng-class="{open: showDashboard}" href="javascipt: void();" ng-click="manageDashboard()"><i class="fa fa-bars" aria-hidden="true"></i></a> <a href="/#/"><img src="/assets/enear-logo1.png" alt="Home" title="Home" /> </a> </div> <div class="col-xs-5 col-sm-10 hidden-xs"> <h1 class="title text-center"><%= title %></h1> </div> </header> <div id="dashboard" ng-class="{visible: showDashboard}"> <div class="col-xs-12 dashBoardSection text-center"> <i class="fa fa-user " id="user" aria-hidden="true">&nbsp;</i> <%= username %> <br /> </div> <ul class="col-xs-12 dashBoardSection navigation"> <li> <a href="/#/"><i class="fa fa-th-list" aria-hidden="true"></i>Suggestions</a> </li> <li> <a href="/#/new"><i class="fa fa-plus" aria-hidden="true"></i>New Suggestion</a> </li> <li> <a href="/logout"><i class="fa fa-sign-out" aria-hidden="true"></i>Logout</a> </li> </ul> </div> <div id="contentWrapper"> <div ng-view></div> </div> </div> <footer class="container"> <div class="row"> <div class="col-xs-12 footerText text-center"> Open Source - code: <a href="//github.com/BrunoAssuncao/suggestion-box">suggestion-box</a> </div> </div> </footer> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js" crossorigin="anonymous"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" crossorigin="anonymous"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.17/angular.min.js" crossorigin="anonymous"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.17/angular-route.min.js" crossorigin="anonymous"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.17/angular-resource.min.js" crossorigin="anonymous"></script> <script type="text/javascript" src='https://ajax.googleapis.com/ajax/libs/angularjs/1.3.17/angular-sanitize.min.js'></script> <script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/textAngular/1.1.2/textAngular.min.js'></script> <script type="text/javascript" src="/javascripts/app.js"></script> <script type="text/javascript" src="/suggestionBox/mainCtrl.js"></script> <script type="text/javascript" src="/suggestions/routes.js"></script> <script type="text/javascript" src="/suggestions/list/suggestionListCtrl.js"></script> <script type="text/javascript" src="/suggestions/detail/suggestionDetailCtrl.js"></script> <script type="text/javascript" src="/suggestions/new/suggestionNewCtrl.js"></script> <script type="text/javascript" src="/suggestions/suggestions-factory.js"></script> </body> </html> <file_sep>angular.module('suggestionbox', ['ngRoute', 'ngResource', 'textAngular']) .controller('mainController', ['$scope', function($scope) { $scope.manageDashboard = function() { $scope.showDashboard = !$scope.showDashboard; }; $scope.showDashboard = false; }]); <file_sep>var mongo = require('../utils/mongoUtils'); var slack = require('../utils/slackIntegration'); var Suggestion = require('../models/suggestion'); var handler = { getSuggestion: function(id, callback) { Suggestion.findOne({'_id': mongo.getObjectID(id)}, callback); }, vote: function(suggestion, user, res) { var like = suggestion.vote === 'like', pushQuery = like ? {"likes": user} : {"dislikes": user}, pullQuery = like ? {"dislikes": user} : {"likes": user}; Suggestion.findOneAndUpdate( {_id: mongo.getObjectID(suggestion._id)}, { $push: pushQuery, $pull: pullQuery }, {new: true}, function(err, doc) { if(err){ console.log(err); res.json(err); } res.json(doc); } ); }, state: function(suggestion, user, res) { Suggestion.findOneAndUpdate( {_id: mongo.getObjectID(suggestion._id)}, { $set: { state: suggestion.state } }, {new: true}, function(err, doc) { if(err){ console.log(err); res.json(err); } res.json(doc); } ); }, update: function(suggestion, user, res) { Suggestion.findOneAndUpdate( {_id: mongo.getObjectID(suggestion._id)}, { $push: {"updates": suggestion.update} }, {new: true}, function(err, doc) { if(err) { console.log(err); } else { slack.slackChannel("Suggestion: " + suggestion.title + " was updated", [{ "title": "by " + suggestion.update.user, "text": suggestion.update.body, "pretext": process.env.APP_ADDRESS + "#/suggestion/"+ suggestion._id }], function(error, response, body){ if (!error && response.statusCode == 200) { console.log("success"); } else { console.log('error: '+ response.statusCode + ' ' + body); } }); res.json(doc); } } ); }, delete: function(id) { Suggestion.findOneAndRemove({ _id: mongo.getObjectID(id) }); }, getMostVoted: function(callback) { Suggestion.findOne({}) .sort('-score') .exec(callback); } }; module.exports = handler; <file_sep>var CronJob = require('cron').CronJob; var mongo = require('../utils/mongoUtils'); var suggestionHandler = require('../utils/suggestionHandler'); var slack = require('../utils/slackIntegration'); module.exports = { startJob: function() { new CronJob(process.env.SLACK_TIME_HOOK, function() { suggestionHandler.getMostVoted(function(err, doc){ if(doc && doc.score > 0) { var message = "This is the top voted suggestion from last week: "; var attachement = [{ "title": doc.title, "text": process.env.APP_ADDRESS + "#/suggestion/" + doc._id , "pretext": "Score: " + doc.score }]; slack.slackChannel(message, attachement, function(error, response, body){ if (!error && response.statusCode == 200) { console.log("success"); } else { console.log('error: '+ response.statusCode + ' ' + body); } }); } }); }, null, true); } }; <file_sep>angular.module('suggestionbox') .controller('NewSuggestionController', function(Suggestion) { this.suggestion = new Suggestion.suggestions(); this.submitSuggestion = function() { this.suggestion.$save().then(function( suggestion ) { window.location = '#/suggestion/' + suggestion._id; }); }; }); <file_sep><div class="row"> <h2 class="col-xs-12 col-sm-6 listTitle">Open Suggestions</h2> <div class="actions col-xs-12 col-sm-6"> <a class="btn button" ng-href="#/new">New suggestion</a> </div> </div> <div class="row" ng-show="hasSuggestions()"> <div class="col-xs-12 suggestionsList" ng-show="hasSuggestions()"> <a class="list-group-item suggestion" ng-href="#/suggestion/{{suggestion._id}}" ng-repeat="suggestion in suggestions | orderBy:'[ -score, -createdAt]'"> <div class="col-xs-12 col-sm-1"> <p class="list-group-item-text text-center" ng-class="{negative:suggestion.score < 0, positive:suggestion.score > 0}"> Score: <br/> {{suggestion.score}} </p> </div> <div class="col-xs-12 col-sm-11"> <div class="row"> <h4 class="list-group-item-heading col-xs-12 col-sm-7">{{suggestion.title}} <span class="small">({{suggestion.state}})</span></h4> <p class="createdBy col-xs-12 col-sm-5">created by: {{suggestion.creator}} | {{suggestion.createdAt | date:"MM/dd/yyyy @ h:mma"}}</p> </div> </div> </a> </div> </div> <p ng-show="!hasSuggestions()" class="text-center" ><em>No suggestions so far... ;( Be the first to add one!</em></p> <file_sep><!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, width=device-width, user-scalable=no"> <title><%= title %></title> <link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/css/bootstrap.css" crossorigin="anonymous"> <link rel='stylesheet' href='/stylesheets/login.css'/> <link rel="icon" type="image/png" href="/assets/favicon.png"> </head> <body> <div class="container mainContainer" > <header class="row"> <img class="logo" src="/assets/enear-logo1.png" title="enear" alt="enear"/> <h1 class="text-center col-xs-12" ><%= title %></h1> </header> <div class="row"> <div class="col-xs-12 login"> <!-- <form method="POST" action="/login" class="form-signin"> <input type="hidden" name="redirectTo" value="/#<%= redirectTo %>" /> <h2 class="form-signin-heading"><%= title2 %></h2> <label for="username" class="sr-only">Username</label> <input id="username" name="username" placeholder="Username"> <label for="password" class="sr-only">Password</label> <input id="password" name="password" type="<PASSWORD>" placeholder="<PASSWORD>"> <button class="button btn btn-lg btn-primary" type="Submit">log in</button> </form> --> <a href="/auth/slack"><img src="https://api.slack.com/img/sign_in_with_slack.png" /></a> <h2 class="errorMessage"><%= message %></h2> </div> </div> </div> <footer class="container"> <div class="row"> <div class="col-xs-12"> This is the footer </div> </div> </footer> <script src="https://code.jquery.com/jquery-2.2.3.min.js" crossorigin="anonymous"></script> <script src="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/js/bootstrap.js" crossorigin="anonymous"></script> </body> </html> <file_sep>angular.module('suggestionbox') .controller('SuggestionsListController', function($scope, Suggestion) { var admins = []; $scope.suggestions = Suggestion.suggestions.query(); $scope.states = []; $scope.username = ""; Suggestion.states().success( function(data) { $scope.states = data; }) .then(Suggestion.getUsername().success(function(data) { $scope.username = data; }) ); $scope.hasSuggestions = function() { return $scope.suggestions.length > 0; }; }); <file_sep>var router = require('express').Router(); var User = require('../models/user'); router.get('/', function(req, res) { User.find({}, function(err, docs) { if(err) { console.log(err); res.json(err); } res.json(docs); }); }); router.get('/currentUser', function(req, res) { res.json(req.user || {}); }); router.get('/:id', function(req, res) { User.findOne({'_id': req.params.id}, function(err, doc) { if(err) { console.log(err); res.json(err); } res.json(doc); }); }); module.exports = router; <file_sep>angular.module('suggestionbox') .controller('SuggestionDetailController', function($scope, $routeParams, $location, $timeout, $http, Suggestion) { $scope.deleteWarning = false; $scope.isUpdating = false; var suggestion = new Suggestion.suggestions.get({id: $routeParams.id}, function() { $scope.suggestion = suggestion; $scope.data = {}; $scope.hasUpdates = $scope.suggestion.updates.length > 0; Suggestion.states().success( function(data) { $scope.states = data; }) .then(Suggestion.getUsername().success( function(data) { $scope.username = data.slack.username; $scope.getVote($scope.suggestion); $scope.isAdmin = data.isAdmin; })); }); $scope.proccessVote = function() { if($scope.suggestion.vote !== $scope.suggestion.previousVote) { $scope.saveSuggestion("vote"); } }; $scope.changeState = function() { $scope.saveSuggestion("state"); }; $scope.updateSuggestion = function() { $scope.suggestion.update.user = $scope.username; $scope.suggestion.update.date = new Date(); $scope.isUpdating = false; $scope.saveSuggestion("update"); $scope.hasUpdates = true; }; $scope.saveSuggestion = function(action){ $scope.suggestion.action = action; $scope.suggestion.$save({}, function(data, headers) { $scope.suggestion = data; $scope.getVote($scope.suggestion); }, function(data, headers) { console.log(data); }); }; $scope.deleteSuggestion = function() { $scope.suggestion.$delete(); $scope.deleteWarning = false; $location.path('/'); }; $scope.getVote = function(suggestion) { $scope.suggestion.score = getSuggestionScore(suggestion); $scope.suggestion.previousVote = suggestion.likes.includes( $scope.username ) ? 'like' : (suggestion.dislikes.includes( $scope.username ) ? 'dislike' : null); $scope.suggestion.vote = $scope.suggestion.previousVote; }; $scope.showDelete = function(show) { $scope.deleteWarning = show; }; $scope.showUpdate = function(show) { $scope.isUpdating = show; }; function getSuggestionScore(suggestion) { return suggestion.likes.length - suggestion.dislikes.length; } }); <file_sep>var SuggestionState = require('../models/state'); var Admin = require('../models/admin'); var states = [{state: "Open"}, {state: "Taking in consideration"}, {state: "Resolved"}, {state: "Ignored"}]; var admins = [{username: "goncalo.assuncao"}, {username: "gcardoso"}]; Admin.find({}, function(err, docs) { if(err) { console.log(err); } if(docs.length === 0 ) { Admin.collection.insert(admins); } }); SuggestionState.find({}, function(err, docs) { if(err) { console.log(err); } if(docs.length === 0) { SuggestionState.collection.insert(states); } });
6ee2e4d96472a24f87fb615bfd048ee3d1d9ea9d
[ "SCSS", "HTML", "Markdown", "EJS", "JavaScript" ]
20
SCSS
BrunoAssuncao/suggestion-box
7966c11f8f5da6876e2b66ddadc02277b84e87d2
3f56e4abf2fc0c339a3607ed19d886021d11beb1
refs/heads/master
<file_sep># Mi-primer-repositorio Mi primer repositorio con curso codigo facilito <file_sep>console.log("este es un test en git ");
627d0874dd7f7d8d4c4ad20d77a669958732cb24
[ "Markdown", "JavaScript" ]
2
Markdown
DeiviCode/Mi-primer-repositorio
607063880df51734a82233607ac75985ed49b68a
41e8d10b03b072a313b8174745860fcaafb2e18e
refs/heads/main
<file_sep>package src.modules.othello; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/othello") public class OthelloController { OthelloModel othelloModel = new OthelloModel(); @GetMapping() public String otheelo(Model model) { model.addAttribute("squares", othelloModel.squares); model.addAttribute("blackCount", othelloModel.blackCount); model.addAttribute("whiteCount", othelloModel.whiteCount); model.addAttribute("isBlack", othelloModel.isBlack); if (othelloModel.isFinished) { return "redirect:result"; } return "othello/index"; } @GetMapping("result") public String result(Model model) { model.addAttribute("blackCount", othelloModel.blackCount); model.addAttribute("whiteCount", othelloModel.whiteCount); model.addAttribute("isBlack", othelloModel.isBlack); return "othello/result"; } @PostMapping("{id}") public String postOthelloById(@PathVariable("id") int id, Model model) { othelloModel.turnChange(id); return "redirect:"; } @PostMapping("reset") public String reset(Model model) { othelloModel = new OthelloModel(); return "redirect:"; } }<file_sep># othello ## Require Environment - Java >= v8 - Git - Yarn ## How to start development ``` sh $ git clone https://github.com/shoMMKS/othello.git $ cd othello $ ./mvnw spring-boot:run ``` Open the http://localhost:8080 # Support Platform - Chrome
47d172f650ea06186e575ca8d2ca2467aff287ef
[ "Java", "Markdown" ]
2
Java
shoMMKS/othello
20efec7621df102bbc82ae728e8d3c74f6c3734c
13d9946b4ec3ddae3a6787a37d1dc174a0293cc7
refs/heads/master
<file_sep>#!/bin/bash module load singularity/2.5 singularity build gnets.simg docker://csherstan/gnets <file_sep>#!/bin/bash CONTAINER_NAME='gnets' count=`singularity instance.list | grep $CONTAINER_NAME | wc -l | xargs` if [ "$1" == "stop" ]; then if [[ $count -eq 1 ]]; then singularity instance.stop $CONTAINER_NAME else echo 'No container running.' fi else if [[ $count -eq 0 ]]; then echo 'No instance running, starting new one.' # at present set SINGULARITY_BINDPATH to specify mount points singularity instance.start $CONTAINER_NAME.simg $CONTAINER_NAME else echo 'Already running.' fi echo "Connecting." singularity shell instance://$CONTAINER_NAME fi
b88355112b2edf45de2526ef13523111b1487000
[ "Shell" ]
2
Shell
csherstan/scalable_agent
99ced9c95f7137291ee4367c8bde0587fdbd44ef
86401a65ceb9ced722630923e2d7948af8f51b20
refs/heads/master
<repo_name>utkarshrai2811/BeSafe<file_sep>/app/src/main/java/proj/bennett/besafe/contactList/Contact.java package proj.bennett.besafe.contactList; public class Contact { public String name, number, groupID; public Contact(String name, String number, String groupID) { this.name = name; this.number = number; this.groupID = groupID; } } <file_sep>/app/src/main/java/proj/bennett/besafe/SMSListener.java package proj.bennett.besafe; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.RingtoneManager; import android.net.Uri; import android.os.Handler; import android.provider.Telephony; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.telephony.SmsManager; import android.telephony.SmsMessage; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class SMSListener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) { Set<String> contacts = context.getSharedPreferences("conf", Context.MODE_PRIVATE).getStringSet(context.getString(R.string.var_numbers_trigger), new HashSet<String>()); String msgs = context.getSharedPreferences("conf", Context.MODE_PRIVATE).getString(context.getString(R.string.var_words_trigger), "Panic"); for(SmsMessage msg : Telephony.Sms.Intents.getMessagesFromIntent(intent)) { String[] msgParts = msg.getMessageBody().split("\n"); if(contacts.contains(msg.getOriginatingAddress()) && msgs.contains(msgParts[0])) { try { triggerAlarm(context, msg.getOriginatingAddress(), msgParts[1], msgParts[2]); break; } catch (Exception e) { triggerAlarm(context, msg.getOriginatingAddress(), null, null); } } } } } private void triggerAlarm(final Context context, String address, String latitude, String longitude) { AudioManager audioManager = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)); SmsManager smsManager = SmsManager.getDefault(); final MediaPlayer mp = new MediaPlayer(); final PendingIntent callIntent = PendingIntent.getActivity(context, 0, new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + address)), PendingIntent.FLAG_ONE_SHOT); PendingIntent mapIntent = null; if(latitude != null && longitude != null) mapIntent = PendingIntent.getActivity(context, 0, new Intent(context, MapActivity.class) .putExtra("lat", Double.parseDouble(latitude)) .putExtra("long", Double.parseDouble(longitude)), PendingIntent.FLAG_UPDATE_CURRENT); smsManager.sendTextMessage(address, null, "Panic triggered!", null, null); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { NotificationChannel ch = new NotificationChannel("Trigger", "Trigger", NotificationManager.IMPORTANCE_HIGH); ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(ch); } audioManager.setStreamVolume(AudioManager.STREAM_ALARM, audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0); try { mp.setDataSource(context, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)); //TODO: Ringtone doesn't seem to loop... mp.setLooping(true); mp.prepare(); NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "Trigger") .setSmallIcon(R.drawable.ic_sms_failed) .setContentTitle("!!! PANIC !!!") .setContentText(address + "triggered alarm! Calling in 1 minute!\n" + latitude != null && longitude != null ? "Sender is at " + latitude + "; " + longitude : "") .setPriority(NotificationCompat.PRIORITY_MAX) .addAction(R.drawable.ic_call, "Call now!", callIntent) .setContentIntent(mapIntent); NotificationManagerCompat.from(context).notify(0, builder.build()); mp.start(); Runnable cntDown = new Runnable() { @Override public void run() { NotificationManagerCompat.from(context).cancel(0); mp.stop(); mp.release(); try { callIntent.send(); } catch (PendingIntent.CanceledException e) {} } }; new Handler().postDelayed(cntDown, 60000); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/app/src/main/java/proj/bennett/besafe/utils/Utils.java package proj.bennett.besafe.utils; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import proj.bennett.besafe.R; import proj.bennett.besafe.contactList.Contact; public class Utils { //contact related stuff public static String[] getContactGroups(Context c) { Set<String> groups = new HashSet<>(); groups.add("General"); for(String contactString : c.getSharedPreferences("conf", Context.MODE_PRIVATE).getStringSet(c.getString(R.string.var_numbers_notify), new HashSet<String>())) { groups.add(getContact(contactString).groupID); } return groups.toArray(new String[groups.size()]); } public static Contact getContact(String contactString) { String[] parts = contactString.split(";"); Contact c = new Contact( (parts.length >= 2 ? parts[1] : ""), parts[0], (parts.length >= 3 ? parts[2] : "General") ); return c; } public static Contact[] getContactsByGroup(String group, Context c) { Set<Contact> contacts = new HashSet<>(); for(String contactString : c.getSharedPreferences("conf", Context.MODE_PRIVATE).getStringSet(c.getString(R.string.var_numbers_notify), new HashSet<String>())) { if(group.equals("General") || contactString.split(";")[2].equals(group)) contacts.add(getContact(contactString)); } return contacts.toArray(new Contact[contacts.size()]); } //permission related stuff public static String[] checkPermissions(Context c) { List<String> permissions = new ArrayList<>(); permissions.add(Manifest.permission.RECEIVE_SMS); permissions.add(Manifest.permission.SEND_SMS); permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION); permissions.add(Manifest.permission.ACCESS_FINE_LOCATION); permissions.add(Manifest.permission.CALL_PHONE); permissions.add(Manifest.permission.INTERNET); permissions.add(Manifest.permission.ACCESS_NETWORK_STATE); permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); List<String> permissionsToRequest = new ArrayList<>(); for(String perm : permissions) { if(c.checkSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) permissionsToRequest.add(perm); } return permissionsToRequest.toArray(new String[permissionsToRequest.size()]); } public static boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if(requestCode == 255 && grantResults.length > 0) { for (int grantResult : grantResults) { if(grantResult != PackageManager.PERMISSION_GRANTED) return false; } } return true; } } <file_sep>/Contributors.md # Contributors - [<NAME>](https://github.com/utkarshrai2811) - [<NAME>](https://github.com/IshaanVerma1130) - <NAME> - <NAME> - <NAME><file_sep>/app/src/main/java/proj/bennett/besafe/TriggerActivity.java package proj.bennett.besafe; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.os.Vibrator; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.telephony.SmsManager; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; import java.util.HashSet; import java.util.Set; import proj.bennett.besafe.contactList.Contact; import proj.bennett.besafe.utils.Utils; public class TriggerActivity extends AppCompatActivity implements View.OnClickListener, LocationListener { private Vibrator v; private Contact[] notifyContacts; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_trigger); v = (Vibrator) getSystemService(VIBRATOR_SERVICE); String[] perms; if((perms = Utils.checkPermissions(this)).length > 0) requestPermissions(perms, 255); if(!getSharedPreferences("conf", MODE_PRIVATE).getBoolean("firstStartDone", false)) { new AlertDialog.Builder(this) .setTitle("Oh, hey there!") .setMessage("Welcome! First I will tell you a little bit about the purpose of this app.\n" + "It has been made for emergency situations where you may need help or just want " + "to alarm your friends. This is especially useful e.g. if you feel like someone " + "is following you and don't want to call the police because it could cause your " + "follower to attack you.\n" + "Another example would be if you don't feel good and can't really move you only " + "need to tap this shiny red button.\n\n" + "Got it? Good! :-)\n" + "In fact this app does nothing else than sending out a special SMS to your configured " + "contacts. This triggers an alarm on their side for a minute. At this time of " + "development they will automatically call you after the alarm is over. The only " + "requirement is that your opponent has this app installed otherwise they will just " + "see a SMS with human-readable content.\n" + "Now, let's configure some contacts to notify!") .setPositiveButton("Let's do it!", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(TriggerActivity.this, SettingsActivity.class)); } }) .setNegativeButton("No thanks.", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new AlertDialog.Builder(TriggerActivity.this) .setTitle("!!! WARNING !!!") .setMessage("You decided to not configure PanicTrigger. This will " + "cause the app to call emergency services if you tap on the " + "big red button!\n\n" + "Are you SURE you don't want to configure contacts?") .setPositiveButton("NO! I tapped the wrong button.", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(TriggerActivity.this, "Alright! Let's configure some things...", Toast.LENGTH_LONG).show(); startActivity(new Intent(TriggerActivity.this, SettingsActivity.class)); } }) .setNegativeButton("Yes.", null) .show(); } }) .show(); new AlertDialog.Builder(this) .setTitle("DISCLAIMER") .setMessage("I am NOT responsible for any damage caused by this app! " + "If you come crying to me with tears in your eyes because you lost your " + "job or something I WILL POINT MY FINGER AT YOU AND LAUGH! " + "I am not responsible for ANYTHING! Period.\n\n" + "Do you agree with that?\n" + "Note: You need to agree to use this app!") .setPositiveButton("Yes.", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { getSharedPreferences("conf", MODE_PRIVATE).edit().putBoolean("firstStartDone", true).apply(); } }) .setNegativeButton("No.", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .show(); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.triggerButton: if(callEmergServices()) { Intent emergService = new Intent(Intent.ACTION_CALL, Uri.parse("tel:112")); startActivity(emergService); return; } this.v.vibrate(1000); final View content = getLayoutInflater().inflate(R.layout.content_dialog_trigger_group_select, null); final ArrayAdapter<String> ad = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, Utils.getContactGroups(this)); ((Spinner)content.findViewById(R.id.emergency_group)).setAdapter(ad); new AlertDialog.Builder(this) .setView(content) .setPositiveButton("Trigger", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { notifyContacts = Utils.getContactsByGroup(((Spinner)content.findViewById(R.id.emergency_group)).getSelectedItem().toString(), TriggerActivity.this); getCurrentLocationAndPanic(); } }) .show(); break; case R.id.configure: Intent settings = new Intent(this, SettingsActivity.class); startActivity(settings); break; } } private void sendOutPanic(Location loc) { String keyword = getSharedPreferences("conf", MODE_PRIVATE).getString(getString(R.string.var_words_keyword), "Help Me" + "\n" + "Coordinates:" ); SmsManager manager = SmsManager.getDefault(); for (Contact c : notifyContacts) { StringBuilder sb = new StringBuilder(keyword); if(loc != null) sb.append("\n" + loc.getLatitude() + "\n" + loc.getLongitude()); manager.sendTextMessage(c.number, null, sb.toString(), null, null); } } private void getCurrentLocationAndPanic() { LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE); try { if(locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) locManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, this, null); else if(locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) locManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, this, null); else sendOutPanic(locManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)); } catch (Exception e) { Toast.makeText(this, "GPS fix could not be acquired. Please check your settings!", Toast.LENGTH_LONG).show(); sendOutPanic(null); } } private boolean callEmergServices() { Set<String> contacts = getSharedPreferences("conf", MODE_PRIVATE).getStringSet(getString(R.string.var_numbers_notify), new HashSet<String>()); return contacts.isEmpty(); } @Override public void onLocationChanged(Location location) { sendOutPanic(location); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if(!Utils.onRequestPermissionsResult(requestCode, permissions, grantResults)) { new AlertDialog.Builder(TriggerActivity.this) .setTitle("Permissions") .setMessage("It looks like not all permissions have been granted.\nPlease grant them or the app will not work!") .show(); findViewById(R.id.triggerButton).setEnabled(false); } } } <file_sep>/README.md # BeSafe BeSafe is an Android app which can help you in an emergency situation. In such a case you tap on a big red button which causes the app to send out SMS to your preconfigured contacts/groups without comfirmation. So don’t tap on the wrong button ;-) >PanicTrigger runs in the background and listens for incoming SMS this is why it needs the permission to read your SMS. I won’t read your SMS :) If an ingoing SMS contains a specific word AND is from a specific number then an alarm will go off and call the sender of the SMS in one minute. Enough time for you to wake up and realize that the alarm has been triggered. Your contact(s) can trigger your alarm with a simple SMS and vice versa. If he/she/they doesn’t have this app he will only see an SMS with the text “Panic” (by default) and your current GPS coordinates. This makes this app useful regardless of if your contact has this app installed or not.
ebbc650f8da5099bd703f7eb92085f0e97c67bf9
[ "Java", "Markdown" ]
6
Java
utkarshrai2811/BeSafe
a4a1723fda2952c6149f7db1cc37f1e5e247bfb0
c30d53799a3383cd2edd70485c7ee1fcef80dd81
refs/heads/master
<repo_name>sgautam23/Auto-Park-For-Social-Robots<file_sep>/README.md # Auto-Park-For-Social-Robots <file_sep>/IR-2/DaedalusProximityDetection.ino #include <ros.h> #include <ros/time.h> #include <sensor_msgs/Range.h> ros::NodeHandle nh; //Code takes in IR Values from 3 sensors and applies Median filtering by taking 100 samples from each sensor, //Sorting them in an array and using the median values sensor_msgs::Range range_msg; ros::Publisher pub_range( "range_data", &range_msg); const int analog_pins[] = {3,6,7}; unsigned long range_timer=0; char frameid[] = "/ir_ranger"; int flag=0,distance[3],tdist=0,d; float getRange(const int pin_num) { int data = analogRead(pin_num)/4; // if the ADC reading is too low, // then we are really far away from anything if(data < 10) return 254; // max range // Magic numbers to get cm int distance= 1309/(data-3); return distance; //convert to meters } void setup() { nh.initNode(); nh.advertise(pub_range); range_msg.radiation_type = sensor_msgs::Range::INFRARED; range_msg.header.frame_id = frameid; range_msg.field_of_view = 0.01; range_msg.min_range = 0.03; range_msg.max_range = 0.4; } void loop() { // publish the range value every 50 milliseconds // since it takes that long for the sensor to stabilize flag=0; if ( (millis()-range_timer) > 100) { /* for( int j=0; j<3;j++) { d=0; d= getRange(analog_pins[j]); d+= getRange(analog_pins[j]); d+= getRange(analog_pins[j]); distance[j] =d/3; } */ // if ((distance[0]>20) && (distance[1]>20) && (distance[2]>20)) /* if(d>15) { tdist=35;} else {tdist =10;} */ // for( int j=0;j<3;j++) // { tdist= getRange(analog_pins[1]); if(tdist<50) { range_msg.range=tdist; range_msg.header.stamp = nh.now(); pub_range.publish(&range_msg); } //} } range_timer = millis() + 100; nh.spinOnce(); } <file_sep>/IR-1/IrRanger.ino #include <ros.h> #include <ros/time.h> #include <sensor_msgs/Range.h> ros::NodeHandle nh; sensor_msgs::Range range_msg; ros::Publisher pub_range( "range_data", &range_msg); const int analog_pins[] = {3,6,7}; unsigned long range_timer=0; char frameid[] = "/ir_ranger"; int flag=0,distance[3],tdist=0,d=0; float getRange(const int pin_num) { int data = analogRead(pin_num)/4; // if the ADC reading is too low, // then we are really far away from anything if(data < 10) return 254; // max range // Magic numbers to get cm int distance= 1309/(data-3); return distance; //convert to meters } void setup() { nh.initNode(); nh.advertise(pub_range); range_msg.radiation_type = sensor_msgs::Range::INFRARED; range_msg.header.frame_id = frameid; range_msg.field_of_view = 0.01; range_msg.min_range = 0.03; range_msg.max_range = 0.4; } void loop() { // publish the range value every 250 milliseconds // since it takes that long for the sensor to stabilize flag=0; if ( (millis()-range_timer) > 50) { tdist=100; for( int j=0;j<2;j++) { distance[j]= getRange(analog_pins[j]); if(distance[j]<tdist) { tdist=distance[j]; } } //tdist= getRange(analog_pins[0]); if(tdist<50) { range_msg.range=tdist; range_msg.header.stamp = nh.now(); pub_range.publish(&range_msg); } } range_timer = millis() + 100; nh.spinOnce(); }
fab9016b90c548f2a6bbbd06d45a881614ad23e4
[ "Markdown", "C++" ]
3
Markdown
sgautam23/Auto-Park-For-Social-Robots
44ccc788db442eea4f2f6a2ae3d8f6fdc1d79b73
d57db9a8db3c74ae9077e80fa16438d2b1f72411
refs/heads/master
<repo_name>sebas99cano/PruebaJava<file_sep>/src/Main.java import server.side.java.PrePOO; import server.side.java.Textos; import java.util.LinkedList; public class Main { public static void main(String[] args) { } } /* LinkedList lista = new LinkedList(); lista.add("Holi"); lista.add(33); lista.add(1,"primer numero"); lista.addLast("final"); System.out.println("El tamañao de lista es :"+ lista.size());*/ /*Textos t = new Textos(); t.leerTodasLasLineas("archivo.txt");*/<file_sep>/src/server/side/java/Textos.java package server.side.java; import java.io.*; //para la lectura y escritura de archivos public class Textos { public void leerUnaLinea(String nombreArchivo) { try { FileReader r = new FileReader(nombreArchivo); BufferedReader buffer = new BufferedReader(r); System.out.println(buffer.readLine()); // solamente lee una linea } catch (Exception e) { System.out.println(e.getMessage()); } } public void leerTodasLasLineas(String nombreArchivo) { try { FileReader r = new FileReader(nombreArchivo); BufferedReader buffer = new BufferedReader(r); String temp = null; temp = buffer.readLine(); while (temp != null) { System.out.println(temp); temp = buffer.readLine(); } } catch (Exception e) { System.out.println(e.getMessage()); } } } <file_sep>/src/server/side/java/PrePOO.java package server.side.java; import java.util.Scanner; public class PrePOO { public static void matrices() { int example[][]; example = new int[7][9]; System.out.println("length : " + example.length + " * " + example[0].length); for (int i = 0; i < example.length; i++) { System.out.print("|"); for (int j = 0; j < example[0].length; j++) { example[i][j] = (i + j) + 33; System.out.print(example[i][j]); System.out.print("|"); } System.out.println(""); } } public static void array() { int x[]; x = new int[3]; x[0] = 2; x[1] = 100; x[2] = 200; int y[] = {2, 4, 6, 8}; for (int i = 0; i < x.length; i++) { System.out.println(x[i]); } } public static void switchCase() { int x = 0; x = 0; switch (x) { case 0: { System.out.println("Option 0"); } case 1: { System.out.println("Option 1"); } default: { break; } } } public static void breakAndContinue() { for (int i = 0; i <= 10; i++) { //break; cortar un ciclo //continue; nos devuelve al inicio del ciclo sin continuar con las instrcuciones que le faltaban al ciclo } } public static void pedirDatos() { //esta clase permite leer datos por teclado Scanner read = new Scanner(System.in); //solicitamos los datos del usuario System.out.println("Nombre de usuario: "); String nombreUsuario = read.nextLine(); System.out.println("Celular: "); String celular = read.nextLine(); System.out.println("Edad: "); int age = read.nextInt(); //mostrar datos del usuario en pantalla System.out.println("Bienvenido señor " + nombreUsuario + ", es un placer para nosotros contar con una persona de " + age + " años.\n" + "\n" + "Próximamente nos comunicaremos con usted al numero " + celular + ".\n" + "\n" + "Feliz día"); } }
f7aa1e450a93ebbf17f2d2311674c2a1e92e14be
[ "Java" ]
3
Java
sebas99cano/PruebaJava
629634ddbc2497430d11b690fd57d12256fb5b2a
6979c056f335831482510a517d68f75c24683699
refs/heads/main
<repo_name>okayu8/html-lecture<file_sep>/js/action.js console.log('test'); var element = document.getElementsByClassName('js-test'); var elementResultText = document.getElementsByClassName('js-result'); var myName = 'まだ選択してないよ。'; function clickedButton () { console.log('clicked'); console.log(element[0].innerText) if(element[0].innerText === 'コアラ') { element[0].innerText = 'ラッコ'; } else { element[0].innerText = 'コアラ'; } } function selectSatou () { myName = '佐藤' } function selectTanaka () { myName = '田中' } function displayResult () { console.log('Selected' + myName) elementResultText[0].innerText = '私の名前は' + myName + 'でございマッスル!' }
4cebddc2841be5b1462a27f2b257bf1ed03b3b3e
[ "JavaScript" ]
1
JavaScript
okayu8/html-lecture
3db63ef276792b83cb7b37e5dfb7060c30946283
3d1f1dff31e0a4fe3981fa2238edd7b37621797b