text: <file_sep># Docker-Self-Nginx-with-html

branch_name: refs/heads/master

repo_language: Markdown


text:
<file_sep>package card

import "bank/pkg/bank/types"

func IssueCard(currency types.Currency, color string, name string) types.Card {
	card := types.Card{
		ID:       1000,
		PAN:      "5058 xxxx xxxx 0001",
		Balance:  0,
		Currency: currency,
		Color:    color,
		Name:     name,
		Active:   true,
	}

	return card
}

repo_language: Go


text:
<repo_name>XavierBriche/chess-engine<file_sep>/attacks.py
#!/usr/bin/env python
# Filename: attacks.py
# -*- coding: utf-8 -*-

from math import log
import bitwise as btws
import constants as const

class Attacks(object):
#    global slider
    pass

class Attack(Attacks):
    ''' returns all the attacked squares for a piece on a square (slider)
        attack_bishop = PAttack(occupied squares).bishop_attack(slider).'''
    def __init__(self, slider):
        self._slider = slider
        self._r90_slider = btws.Bitwise(self._slider).cw90
        self._ar45_slider = btws.Bitwise(self._slider).acw45

    def bpawn_right(self):
        return self._slider >> 7 & const.notafile

    def bpawn_left(self):
            return self._slider >> 9 & const.nothfile

    def wpawn_left(self):
            return self._slider << 7 & const.nothfile

    def wpawn_right(self):
                return self._slider << 9 & const.notafile

    def one_east(self):
        return self._slider << 1 & const.notafile

    def one_noea(self):
        return self._slider << 9 & const.notafile

    def one_north(self):
        return self._slider << 8

    def one_nowe(self):
        return self._slider << 7 & const.nothfile

    def one_west(self):
        return self._slider >> 1 & const.nothfile

    def one_sowe(self):
        return self._slider >> 9 & const.nothfile

    def one_south(self):
        return self._slider >> 8

    def one_soea(self):
        return self._slider >> 7 & const.notafile

    def el_noeaea(self):
        return self._slider<<10 & (const.notafile & const.notbfile)

    def el_nonoea(self):
         return self._slider<<17 & const.notafile

    def el_nonowe(self):
         return self._slider<<15 & const.nothfile

    def el_nowewe(self):
         return self._slider<<6 & (const.notgfile & const.nothfile)

    def el_sowewe(self):
         return self._slider>>10 & (const.notgfile & const.nothfile)

    def el_sosowe(self):
         return self._slider>>17 & const.nothfile

    def el_sosoea(self):
         return self._slider>>15 & const.notafile

    def el_soeaea(self):
         return self._slider>>6 & (const.notafile & const.notbfile)

#sliding pieces
    #bishop
    def mask_diag(self):
        for d in const.diag_masks:
            if btws.Bitwise(self._slider).bit_index() in d:
                break
        return btws.Bitwise(d).bit_to_int()

    def attack_adiag(self, occupied):
        self._r45_occupied = btws.Bitwise(occupied).acw45()
        self._r45_slid = btws.Bitwise(self._slider).acw45()
        self._ro_attack = self.attack_horizontal(self._r45_occupied,
                                                 self._r45_slid)
        return btws.Bitwise(self._ro_attack).cw45()

    def attack_diag(self, occupied):
        self._r135_occupied = btws.Bitwise(occupied).cw135()
        self._r135_slid = btws.Bitwise(self._slider).cw135()
        self._ro_attack = self.attack_horizontal(self._r135_occupied,
                                                 self._r135_slid)
        return btws.Bitwise(self._ro_attack).acw135()

    def mask_adiag(self):
        for d in const.adiag_masks:
            if btws.Bitwise(self._slider).bit_index() in d:
                break
        return btws.Bitwise(d).bit_to_int()

    def attack_horizontal(self, occupied, slid):
        self._rev_occupied= btws.Bitwise(occupied).rev()
        self._rev_slid = btws.Bitwise(slid).rev()
        attack = ((occupied - 2*slid)^\
                      (btws.Bitwise(self._rev_occupied - 2*self._rev_slid).rev())) &\
                      const.rank_masks[btws.Bitwise(slid).rank()]
        return attack

    def attack_vertical(self, occupied):
        self._r_occupied = btws.Bitwise(occupied).cw90()
        self._rev_r_occupied = btws.Bitwise(self._r_occupied).rev()
        self._r_slider = btws.Bitwise(self._slider).cw90()
        self._rev_r_slider = btws.Bitwise(self._r_slider).rev()
        attack = ((self._r_occupied - 2*self._r_slider)^ \
                       (btws.Bitwise(self._rev_r_occupied - 2*self._rev_r_slider).rev())) & \
                      const.rank_masks[btws.Bitwise(self._r_slider).rank()]
        return btws.Bitwise(attack).acw90()

class PAttack(Attacks):
    def __init__(self, occupied):
        self._occupied = occupied

    def bishop_attack(self, slider):
        bishop = Attack(slider)
        diag_mask = bishop.mask_diag()
        adiag_mask = bishop.mask_adiag()
        adiag_attack = bishop.attack_adiag(self._occupied)
        diag_attack = bishop.attack_diag(self._occupied)
        return (adiag_attack & adiag_mask) | (diag_attack & diag_mask)

    def rook_attack(self, slider):
        rook = Attack(slider)
        rank_attack = rook.attack_horizontal(self._occupied, slider)
        file_attack = rook.attack_vertical(self._occupied)
        return file_attack | rank_attack

    def queen_attack(self, slider):
        queen = Attack(slider)
        ranks_attack = queen.attack_horizontal(self._occupied, slider)
        files_attack = queen.attack_vertical(self._occupied)
        diag_mask = queen.mask_diag()
        adiag_mask = queen.mask_adiag()
        adiag_attack = queen.attack_adiag(self._occupied)
        diag_attack = queen.attack_diag(self._occupied)
        return files_attack | ranks_attack | \
                     (adiag_attack & adiag_mask) | (diag_attack & diag_mask)

    def knight_attack(self, slider):
        knight = Attack(slider)
        return knight.el_noeaea()|  knight.el_nonoea() | \
                    knight.el_nonowe() | knight.el_nowewe() | \
                    knight.el_sowewe() | knight.el_sosowe() | \
                    knight.el_sosoea() | knight.el_soeaea()

    def king_attack(self, slider):
        king = Attack(slider)
        return king.one_east() | king.one_noea() | king.one_soea() | \
                    king.one_north() | king.one_nowe() | king.one_west() | \
                    king.one_sowe() | king.one_west() | king.one_sowe() | \
                    king.one_south()

    def wpawn_attack(self, slider):
        white_pawn = Attack (slider)
        return (white_pawn.wpawn_left() | white_pawn.wpawn_right())

    def bpawn_attack(self, slider):
        black_pawn = Attack (slider)
        return (black_pawn.bpawn_left() | black_pawn.bpawn_right())

<file_sep>/README.md
# chess-engine
bitboard base chess engine
<file_sep>/engine.py
#!/usr/bin/env python
# Filename: engine.py
# -*- coding: utf-8 -*-

import sys
import chessboard as cb
import notation as nt
import attacks as attk

if sys.version > '3':
    unicode = str

class ChessEngine(object):
        global slider
        global board

class Initialise(ChessEngine):
    """Set rank and file masks, bitboard rotators
        bitboard =  64 bits (squares)
    """
    def __init__(self):
        # pieces starting positions
        self._wp_init = 0x000000000000ff00
        self._wn_init = 0x0000000000000042
        self._wb_init = 0x0000000000000024
        self._wr_init = 0x0000000000000081
        self._wq_init = 0x0000000000000010
        self._wk_init = 0x0000000000000008
        self._bp_init = 0xff000000000000
        self._bn_init =   0x4200000000000000
        self._bb_init = 0x2400000000000000
        self._br_init = 0x8100000000000000
        self._bq_init  = 0x1000000000000000
        self._bk_init   = 0x800000000000000
        self._board ={0 : self._bp_init,
                                  1: self._wp_init,
                                  2 : self._bn_init,
                                  3 : self._wn_init,
                                  4: self._bb_init,
                                  5 : self._wb_init,
                                  6 : self._br_init,
                                  7 : self._wr_init,
                                  8 : self._bq_init,
                                  9 : self._wq_init,
                                  10 : self._bk_init,
                                  11 : self._wk_init,
                                  12 : 0,
                                  13 : 0}

class Display(ChessEngine):

    def __init__(self, board):
        self._board = nt.Bitboard().to_fen(board)

    def chessboard(self):
            self._chessboard = cb.ChessBoard(self._board)
            self._chessboard.create_chessboard()
            self._chessboard.root.title("Chessboard")
            self._chessboard.root.mainloop()

initialised = Initialise()
board = initialised._board
board = { 0 : 0, 1 : 0, 2 : 0, 3 : 0, 4 : 2**8+2**11,
          5 : 0, 6 : 0, 7 : 0, 8: 0, 9 : 0, 10 : 0,
          11 : 0, 12 : 0, 13: 0}
ply =1
white_occupancy = 0
black_occupancy = 0
if ply & 1:
    for piece in board:
        if piece & 1:
            white_occupancy = board[piece] | white_occupancy
        else:
            black_occupancy = board[piece] | black_occupancy
board = { 0 : 0,
                  1 : 2**54+2**53+2**52+2**51+2**50+2**49,
                    2 : 0, 3 : 0, 4 : 2**8+2**11, 5 : 0, 6 : 0, 7 : 0, 8: 0, 9 : 0, 10 : 0, 11 : 0, 12 : 0, 13: 0}
board[13] = 0
board[12] = black_occupancy | white_occupancy
Display(board).chessboard()

<file_sep>/notation.py
#!/usr/bin/python
# Filename: notation.py
# -*- coding: utf-8 -*-

class Bitboard(object):
    '''Translate position recorded in FICS notation into a dictionary of bitboards
        and vice versa.'''
    def __init__(self):
        self._bb_piece = 0
        self._pieces_bb={}
        self._fen = ''
        self._FICS = ['p', 'P', 'n', 'N', 'b', 'B', 'r',
                      'R', 'q', 'Q', 'k', 'K', 'x', 'X']

    def to_fen(self, allpieces_bbs):
        for bit_ind in range(0, 64):
            for piece in range(0, len(self._FICS)):
                if (allpieces_bbs[piece] & 1 << bit_ind):
                    self._fen += self._FICS[piece]
                    break
            else:
                self._fen += '-'
        print self._fen
        return self._fen

    def bitboards(self, fen, piece): #unmaintained
        for piece in self._FICS:
            self._bb_piece = 0
            for square in range(0, 64):
                if fen[square]==FICS[piece]:
                    self._bb_piece += 2**square
            self._pieces_bb[FICS[piece]]=self._bb_piece
        return self._pieces_bb
<file_sep>/bitwise.py
#!/usr/bin/env python
# Filename: bitwise.py
# -*- coding: utf-8 -*-

import constants as const

class Bitwise(object):
    def __init__(self, bitboard):
        self._bb = bitboard
    def rev(self):
        self._rev = ((self._bb & 0x5555555555555555) << 1) |\
                            ((self._bb & 0xAAAAAAAAAAAAAAAA) >> 1)
        self._rev = ((self._rev & 0x3333333333333333) << 2) |\
                            ((self._rev & 0xCCCCCCCCCCCCCCCC) >> 2)
        self._rev = ((self._rev & 0x0F0F0F0F0F0F0F0F) << 4) |\
                            ((self._rev & 0xF0F0F0F0F0F0F0F0) >> 4)
        self._rev = ((self._rev & 0x00FF00FF00FF00FF) << 8) |\
                            ((self._rev & 0xFF00FF00FF00FF00) >> 8)
        self._rev = ((self._rev & 0x0000FFFF0000FFFF) << 16) |\
                            ((self._rev & 0xFFFF0000FFFF0000) >> 16)
        self._rev = ((self._rev & 0x00000000FFFFFFFF) << 32) |\
                            ((self._rev & 0xFFFFFFFF00000000) >> 32)
        return self._rev

    def cw90(self):
        self._rot_cw90 = 0
        for bit_ind in range(0, 64):
           self._rot_cw90 += bool(self._bb & 1 << bit_ind)*\
                                         (2**(const.ro90_squares[bit_ind]))
        return self._rot_cw90

    def acw90(self):
        self._rot_acw90 = 0
        for bit_ind in range(0, 64):
           self._rot_acw90 += bool(self._bb & 1 << bit_ind)*\
                                            (2**(const.squares_ro90[bit_ind]))
        return self._rot_acw90

    def acw45(self):
        self._rot_acw45 = 0
        for bit_ind in range(0, 64):
           self._rot_acw45 += bool(self._bb & 1 << bit_ind)*\
                                            (2**(const.squares_ro45[bit_ind]))
        return self._rot_acw45

    def cw135(self):
        self._rot_acw135 = 0
        for bit_ind in range(0, 64):
           self._rot_acw135 += bool(self._bb & 1 << bit_ind)*\
                                            (2**(const.squares_ro135[bit_ind]))
        return self._rot_acw135

    def cw45(self):
        self._rot_cw45 = 0
        for bit_ind in range(0, 64):
           self._rot_cw45 += bool(self._bb & 1 << bit_ind)*\
                                            (2**(const.ro45_squares[bit_ind]))
        return self._rot_cw45

    def acw135(self):
        self._rot_cw135 = 0
        for bit_ind in range(0, 64):
           self._rot_cw135 += bool(self._bb & 1 << bit_ind)*\
                                            (2**(const.ro135_squares[bit_ind]))
        return self._rot_cw135

    def rank(self):
        return const.bits_ranks[self.bit_index(self._bb)]

    def files(self, bb):
        return const.bits_files[self.bit_index(self._bb)]

    def bit_index(self):
        return int(log(self._bb)/log(2))

    def bit_to_int(self, array):
        num = 0
        for a in array:
            num +=2**a
        return num

languages: Markdown Python

repo_name: XavierBriche/chess-engine


text:
<file_sep>"use strict";

const Category = use("App/Models/Category");

class CategoryController {
  async register({ request, response }) {
    const { name, description } = request.body;

    try {
      const category = await Category.create({ name, description });

      return response.send({ category });
    } catch (e) {
      return response.status(406).send({ erro: e });
    }
  }

  async edit({ request, response }) {
    const category = await Category.find(request.params.id);

    if (!category) {
      return response
        .status(401)
        .send({ message: "Categoria não encontrada!" });
    }

    const { name, description } = request.body;

    category.name = name;
    category.description = description;

    try {
      await category.save();

      return response.send(category);
    } catch (e) {
      return response.status(404).send({ erro: e });
    }
  }

  async delete({ request, response }) {
    const category = await Category.find(request.params.id);

    if (!category) {
      return response
        .status(401)
        .send({ message: "Categoria não encontrada!" });
    }

    try {
      await category.delete();

      return response.send({ message: "Categoria excluída com sucesso!" });
    } catch (e) {
      return response.status(404).send({ erro: e });
    }
  }

  async show({ request, response }) {
    try {
      const category = await Category.find(request.params.id);

      if (!category) {
        return response
          .status(401)
          .send({ message: "Categoria não encontrada!" });
      }

      response.send(category);
    } catch (e) {
      return response.status(404).send({ erro: e });
    }
  }

  async list({ request, response }) {
    const categories = await Category.all();

    if (!categories) {
      return response
        .status(404)
        .send({ message: "Ocorreu algum problema na busca das categorias!" });
    }
    return response.send(categories);
  }
}

module.exports = CategoryController;
<file_sep>"use strict";
const Drive = use("Drive");
const Crypto = require("crypto");

class FotoController {
  async create({ request, response }) {
    try {
      request.multipart.file("image", {}, async (file) => {
        const ContentType = file.headers["content-type"];
        const ACL = "public-read";
        const Key =
          Crypto.randomBytes(64).toString("hex") + "-" + file.clientName;
        const url = await Drive.disk("s3").put(
          `${request.params.local}/${Key}`,
          file.stream,
          {
            ContentType,
            ACL,
          }
        );
        return response.send({ url });
      });
    } catch (erro) {
      return response.status(400).send({ erro });
    }
    await request.multipart.process();
  }

  async delete({ request, response }) {
    const { url } = request.body;
    try {
      const fragmentad = url.split("/");
      const key = fragmentad[3] + "/" + fragmentad[4];
      await Drive.disk("s3").delete(key);
      return response.send({ message: "Imagem excluída com sucesso!" });
    } catch (erro) {
      return response.status(400).send({ erro: erro.message });
    }
  }
}

module.exports = FotoController;
<file_sep>"use strict";
const PacotoFotos = use("App/Models/PacoteFoto");
const Drive = use("Drive");
const Crypto = require("crypto");

class PacoteFotoController {
  async create({ request, response }) {
    try {
      request.multipart.file("image", {}, async (file) => {
        const body = {};
        await request.multipart.field((name, value) => {
          body[name] = value;
        });
        const ContentType = file.headers["content-type"];
        const ACL = "public-read";
        const Key =
          Crypto.randomBytes(64).toString("hex") + "-" + file.clientName;
        const url = await Drive.disk("s3").put(
          `Pacote_images/${Key}`,
          file.stream,
          {
            ContentType,
            ACL,
          }
        );
        const pacotefoto = await PacotoFotos.create({
          pacote_id: body.pacote_id,
          image_url: url,
          content_type: ContentType,
        });
        return response.send({ pacotefoto });
      });
    } catch (erro) {
      return response.status(400).send({ erro });
    }
    await request.multipart.process();
  }

  async delete({ request, response }) {
    const id = request.params.id;
    try {
      const pacotefoto = await PacotoFotos.find(id);
      const url = pacotefoto.image_url;
      const fragmentad = url.split("/");
      const key = fragmentad[3] + "/" + fragmentad[4];
      await Drive.disk("s3").delete(key);
      await pacotefoto.delete();
      return response.send({ message: "Foto excluída com sucesso!" });
    } catch (erro) {
      return response.status(400).send({ erro });
    }
  }

  async getFotos({ request, response }) {
    const { pacote_id } = request.params;

    const fotos = await PacotoFotos.query()
      .where("pacote_id", "=", pacote_id)
      .select("id", "image_url")
      .fetch();

    return response.send(fotos);
  }
}

module.exports = PacoteFotoController;
<file_sep>"use strict";
const Suite = use("Test/Suite")("Guia - Auth");
const { before, beforeEach, after, afterEach, trait, test } = Suite;
const Guia = use("App/Models/Guia");
const Pacote = use("App/Models/Pacote");

trait("Test/ApiClient");
trait("Auth/Client");

before(async () => {
  await Guia.create({
    name: "Guia para testes",
    description: "Um guia para testes",
    tel: "24992859059",
    email: "<EMAIL>",
    password: "<PASSWORD>",
  });
});

test("Should login the guide", async ({ client, assert }) => {
  const response = await client
    .post("/guia/login")
    .send({
      email: "<EMAIL>",
      password: "<PASSWORD>",
    })
    .end();
  response.assertStatus(200);
});

test("Should not login the guide because the email is wrong", async ({
  client,
  assert,
}) => {
  const response = await client
    .post("/guia/login")
    .send({
      email: "<EMAIL>",
      password: "<PASSWORD>",
    })
    .end();
  response.assertStatus(400);
});

test("Should not login the guide because the password is wrong", async ({
  client,
  assert,
}) => {
  const response = await client
    .post("/guia/login")
    .send({
      email: "<EMAIL>",
      password: "<PASSWORD>",
    })
    .end();
  response.assertStatus(400);
});

test("Should verify if the guide has the notification token", async ({
  client,
  assert,
}) => {
  const guia = await Guia.find(2);
  const response = await client.get("guia/verify/2").loginVia(guia).end();
  response.assertStatus(200);
});

test("Should not verify if the guide has the notification token bencause the guide is not authenticated", async ({
  client,
  assert,
}) => {
  const response = await client.get("guia/verify/2").end();
  response.assertStatus(401);
});
<file_sep>"use strict";
const Suite = use("Test/Suite")("User - Favorites");
const { before, beforeEach, after, afterEach, trait, test } = Suite;
const User = use("App/Models/User");
const Pacote = use("App/Models/Pacote");

trait("Test/ApiClient");
trait("Auth/Client");

before(async () => {
  await User.create({
    username: "Plucks",
    email: "<EMAIL>",
    password: "<PASSWORD>",
    tel: "992859059",
  });
});

test("The user should favorite a package", async ({ client, assert }) => {
  const user = await User.find(2);

  const response = await client
    .post("/user/pacote/favorite")
    .send({
      user_id: 2,
      pacote_id: 1,
    })
    .loginVia(user)
    .end();

  response.assertStatus(200);
});

test("The user should not favorite a package because the user is not authenticated", async ({
  client,
  assert,
}) => {
  const response = await client
    .post("/user/pacote/favorite")
    .send({
      user_id: 2,
      pacote_id: 1,
    })
    .end();

  response.assertStatus(401);
});

test("The user should not favorite a package because the user do not exist", async ({
  client,
  assert,
}) => {
  const user = await User.find(2);

  const response = await client
    .post("/user/pacote/favorite")
    .send({
      user_id: 3,
      pacote_id: 1,
    })
    .loginVia(user)
    .end();

  response.assertStatus(404);
});

test("The user should not favorite a package because the package do not exist", async ({
  client,
  assert,
}) => {
  const user = await User.find(2);

  const response = await client
    .post("/user/pacote/favorite")
    .send({
      user_id: 2,
      pacote_id: 2,
    })
    .loginVia(user)
    .end();

  response.assertStatus(404);
});

test("Should get the favorited packages from a user", async ({
  client,
  assert,
}) => {
  const user = await User.find(2);

  const response = await client.get("/user/favorites/2").loginVia(user).end();

  response.assertStatus(200);
});

test("Should not get the favorited packages from a user because the user do not exist", async ({
  client,
  assert,
}) => {
  const user = await User.find(2);

  const response = await client.get("/user/favorites/3").loginVia(user).end();

  response.assertStatus(404);
});

test("Should not get the favorited packages from a user because the user is not authenticated", async ({
  client,
  assert,
}) => {
  const response = await client.get("/user/favorites/2").end();

  response.assertStatus(401);
});

test("Should check if a package is favorited for a user", async ({
  client,
  assert,
}) => {
  const user = await User.find(2);
  const response = await client
    .post("/favorited")
    .send({
      user_id: 2,
      pacote_id: 1,
    })
    .loginVia(user)
    .end();

  response.assertStatus(200);
});

test("Should not check if a package is favorited for a user because the user do not exist", async ({
  client,
  assert,
}) => {
  const user = await User.find(2);
  const response = await client
    .post("/favorited")
    .send({
      user_id: 3,
      pacote_id: 1,
    })
    .loginVia(user)
    .end();

  response.assertStatus(404);
});

test("Should not check if a package is favorited for a user because the package do not exist", async ({
  client,
  assert,
}) => {
  const user = await User.find(2);
  const response = await client
    .post("/favorited")
    .send({
      user_id: 2,
      pacote_id: 2,
    })
    .loginVia(user)
    .end();

  response.assertStatus(404);
});

test("Should not check if a package is favorited for a user because the user is not authenticated", async ({
  client,
  assert,
}) => {
  const response = await client
    .post("/favorited")
    .send({
      user_id: 2,
      pacote_id: 1,
    })
    .end();

  response.assertStatus(401);
});

test("Should unfavorite a package for a user", async ({ client, assert }) => {
  const user = await User.find(2);
  const response = await client
    .post("/unfavorite")
    .send({
      user_id: 2,
      pacote_id: 1,
    })
    .loginVia(user)
    .end();

  response.assertStatus(200);
});

test("Should not unfavorite a package for a user because the user do not exist", async ({
  client,
  assert,
}) => {
  const user = await User.find(2);
  const response = await client
    .post("/unfavorite")
    .send({
      user_id: 3,
      pacote_id: 1,
    })
    .loginVia(user)
    .end();

  response.assertStatus(404);
});

test("Should not unfavorite a package for a user because the pakcage do not exist", async ({
  client,
  assert,
}) => {
  const user = await User.find(2);
  const response = await client
    .post("/unfavorite")
    .send({
      user_id: 2,
      pacote_id: 2,
    })
    .loginVia(user)
    .end();

  response.assertStatus(404);
});

test("Should not unfavorite a package for a user because the user is not authenticated", async ({
  client,
  assert,
}) => {
  const response = await client
    .post("/unfavorite")
    .send({
      user_id: 2,
      pacote_id: 1,
    })
    .end();

  response.assertStatus(401);
});
<file_sep>"use strict";

/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use("Schema");

class GuiaSchema extends Schema {
  up() {
    this.create("guias", (table) => {
      table.increments();
      table.string("name", 80).notNullable();
      table.string("description", 350).notNullable();
      table.string("tel", 20).notNullable();
      table.timestamps();
    });
  }

  down() {
    this.drop("guias");
  }
}

module.exports = GuiaSchema;
<file_sep>"use strict";

/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use("Schema");

class PacoteSchema extends Schema {
  up() {
    this.create("pacotes", (table) => {
      table.increments();
      table
        .integer("category_id")
        .unsigned()
        .references("id")
        .inTable("categories");
      table.integer("guia_id").unsigned().references("id").inTable("guias");
      table.integer("local_id").unsigned().references("id").inTable("locals");
      table.string("name", 80).notNullable();
      table.string("description", 80).notNullable();
      table.string("price", 80).notNullable();
      table.string("date", 80).notNullable();
      table.string("image_url").notNullable();
      table.timestamps();
    });
  }

  down() {
    this.drop("pacotes");
  }
}

module.exports = PacoteSchema;
<file_sep>"use strict";

/*
|--------------------------------------------------------------------------
| CategorySeeder
|--------------------------------------------------------------------------
|
| Make use of the Factory instance to seed database with dummy data or
| make use of Lucid models directly.
|
*/

/** @type {import('@adonisjs/lucid/src/Factory')} */
const Factory = use("Factory");

class CategorySeeder {
  async run() {
    const data = [
      {
        name: "Ação",
        description: "Pacote de ação",
      },
      {
        name: "Aventura",
        description: "Pacote de aventura",
      },
      {
        name: "Casual",
        description: "Pacote casual",
      },
    ];
    const category = await Factory.model("App/Models/Category").createMany(
      3,
      data
    );
  }
}

module.exports = CategorySeeder;
<file_sep>"use strict";

const Eva = use("App/Models/Evaluation");

class EvaluationController {
  async register({ request, response }) {
    const { guia_id, description, rating } = request.body;

    try {
      const eva = await Eva.create({ guia_id, description, rating });

      return response.send({ eva });
    } catch (e) {
      return response.status(406).send({ erro: e });
    }
  }

  async show({ response }) {
    const eva = await Eva.all();

    return response.send(eva);
  }
}

module.exports = EvaluationController;
<file_sep>"use strict";
const User = use("App/Models/User");
const ForgotPassword = use("App/Models/ForgotPassword");
const Mail = use("Mail");
const crypto = require("crypto");
const Database = use("Database");

class ForgotPasswordController {
  async create({ request, response }) {
    const user = await User.findByOrFail("email", request.body.email);

    if (!user) {
      return response.status(401).send({ message: "Usuário não encontrado!" });
    }
    const token = await crypto.randomBytes(10).toString("hex");

    const forgot = await ForgotPassword.create({ user_id: user.id, token });

    await Mail.send("emails.recover", { user, token }, (message) => {
      message
        .from("<EMAIL>")
        .to(user.email)
        .subject("Troca de senha da sua conta ValeTour");
    });
    return response.send(forgot);
  }

  async validate({ request, response }) {
    const { token, id } = request.body;
    const ttoken = await ForgotPassword.findByOrFail("token", token);
    const uuser = await User.find(id);
    if (!uuser) {
      return response.status(401).send({ message: "Usuário não encontrado!" });
    }
    if (!ttoken.token) {
      return response.status(401).send({ message: "Token inválido!" });
    }
    return response.send({ message: "Ok" });
  }

  async change({ request, response }) {
    const user = await User.find(request.params.id);

    if (!user) {
      return response.status(401).send({ message: "Usuário não encontrado!" });
    }

    try {
      user.password = request.body.password;
      await user.save();
      await Database.raw(
        `DELETE FROM forgot_passwords WHERE user_id='${user.id}'`
      );

      return response.send(user);
    } catch (e) {
      return response.status(404).send({ erro: e });
    }
  }
}

module.exports = ForgotPasswordController;
<file_sep>"use strict";

const User = use("App/Models/User");
const Favorite = use("App/Models/Favorite");
const Pacote = use("App/Models/Pacote");

class UserController {
  async register({ request, response, auth }) {
    const { username, email, password, tel } = request.body;

    try {
      const user = await User.create({ username, email, password, tel });
      const token = await auth.generate(user);

      return response.send({ user, token: token.token });
    } catch (e) {
      return response.status(406).send({ erro: e });
    }
  }

  async login({ request, response, auth }) {
    const { email, password } = request.all();

    const token = await auth.attempt(email, password);

    const user = await User.findByOrFail("email", email);

    return response.send({ user_id: user.id, token: token.token });
  }

  async edit({ request, response }) {
    const user = await User.find(request.params.id);

    if (!user) {
      return response.status(401).send({ message: "Usuário não encontrado!" });
    }

    const { username, email, password, tel } = request.body;

    user.username = username;
    user.email = email;
    user.password = <PASSWORD>;
    user.tel = tel;

    try {
      await user.save();

      return response.send(user);
    } catch (e) {
      return response.status(404).send({ erro: e });
    }
  }

  async delete({ request, response }) {
    const user = await User.find(request.params.id);

    if (!user) {
      return response.status(401).send({ message: "Usuário não encontrado!" });
    }

    try {
      await user.delete();

      return response.send({ message: "Usuário excluído com sucesso!" });
    } catch (e) {
      return response.status(404).send({ erro: e });
    }
  }

  async list({ response }) {
    const users = await User.all();

    response.send(users);
  }

  async user({ request, response }) {
    const user = await User.find(request.params.id);

    if (!user) {
      return response.status(401).send({ message: "Usuário não encontrado!" });
    }
    return response.send(user);
  }

  async favorite({ request, response }) {
    const { user_id, pacote_id } = request.body;

    try {
      const user = await User.find(user_id);
      if (!user) {
        return response
          .status(404)
          .send({ message: "Usuário não encontrado!" });
      }
      const pacote = await Pacote.find(pacote_id);
      if (!pacote) {
        return response.status(404).send({ message: "Pacote não encontrado!" });
      }
      const favorite = await Favorite.create({ user_id, pacote_id });
      return response.send(favorite);
    } catch (erro) {
      return response.status(406).send({ erro: erro });
    }
  }

  async favorites({ request, response }) {
    try {
      const user = await User.find(request.params.id);
      if (!user) {
        return response
          .status(404)
          .send({ message: "Usuário não encontrado!" });
      }

      const favorites = await Favorite.query()
        .where("user_id", "=", request.params.id)
        .with("pacotes", (cb) => {
          cb.select(
            "id",
            "category_id",
            "guia_id",
            "local_id",
            "name",
            "description",
            "price",
            "date",
            "image_url"
          );
        })
        .fetch();

      const serializedFavorites = favorites.toJSON();
      let returnedPacotes = [];
      serializedFavorites.forEach((pacote) => {
        returnedPacotes.push(pacote.pacotes);
      });

      return response.send(returnedPacotes);
    } catch (erro) {
      return response.status(406).send({ erro: erro });
    }
  }
}

module.exports = UserController;
<file_sep>"use strict";
const Suite = use("Test/Suite")("Admin - Auth");
const { before, beforeEach, after, afterEach, trait, test } = Suite;
const Admin = use("App/Models/Admin");

trait("Test/ApiClient");
trait("Auth/Client");

test("Should create an admin account", async ({ client }) => {
  const response = await client
    .post("/admin/register")
    .send({
      email: "<EMAIL>",
      password: "<PASSWORD>",
    })
    .end();

  response.assertStatus(200);
});

test("Should not create an admin account, because the email already exsists", async ({
  client,
}) => {
  const response = await client
    .post("/admin/register")
    .send({
      email: "<EMAIL>",
      password: "<PASSWORD>",
    })
    .end();

  response.assertStatus(406);
});

test("Should login the admin", async ({ client }) => {
  const response = await client
    .post("/admin/login")
    .send({
      email: "<EMAIL>",
      password: "<PASSWORD>",
    })
    .end();

  response.assertStatus(200);
});

test("Should not logint the admin, because the email is wrong", async ({
  client,
}) => {
  const response = await client
    .post("/admin/login")
    .send({
      email: "<EMAIL>",
      password: "<PASSWORD>",
    })
    .end();

  response.assertStatus(401);
});

test("Should not logint the admin, because the password is wrong", async ({
  client,
}) => {
  const response = await client
    .post("/admin/login")
    .send({
      email: "<EMAIL>",
      password: "<PASSWORD>",
    })
    .end();

  response.assertStatus(401);
});
<file_sep>"use strict";

/** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */
const Model = use("Model");

/** @type {import('@adonisjs/framework/src/Hash')} */
const Hash = use("Hash");

class Guia extends Model {
  static get hidden() {
    return ["password"];
  }

  static boot() {
    super.boot();

    /**
     * A hook to hash the user password before saving
     * it to the database.
     */
    this.addHook("beforeSave", async (guiaInstance) => {
      if (guiaInstance.dirty.password) {
        guiaInstance.password = await Hash.make(guiaInstance.password);
      }
    });
  }

  evaluations() {
    return this.hasMany("App/Models/Evaluation");
  }
}

module.exports = Guia;
<file_sep># API para aplicação de TCC T&S
Essa api gerencia toda a comunicação do usuário final com o banco de dados, visando fazer isto da forma mais segura e performática possível.
<file_sep>"use strict";
const PacotoFotos = use("App/Models/PacoteFoto");
const Drive = use("Drive");

module.exports = class Help {
  async delete(id) {
    try {
      const pacotefoto = await PacotoFotos.find(id);
      const url = pacotefoto.image_url;
      const fragmentad = url.split("/");
      const key = fragmentad[3] + "/" + fragmentad[4];
      await Drive.disk("s3").delete(key);
      await pacotefoto.delete();
      return true;
    } catch (erro) {
      return erro.message;
    }
  }
};
<file_sep>"use strict";

const Admin = use("App/Models/Admin");

class AdminController {
  async register({ request, response }) {
    const { email, password } = request.body;

    try {
      const admin = await Admin.create({ email, password });

      return response.send({ admin });
    } catch (e) {
      return response.status(406).send({ erro: e });
    }
  }

  async login({ request, response, auth }) {
    const { email, password } = request.all();

    const token = await auth.authenticator("admin").attempt(email, password);

    const admin = await Admin.findByOrFail("email", email);

    return response.send({ admin_id: admin.id, token: token.token });
  }
}

module.exports = AdminController;
<file_sep>"use strict";

/*
|--------------------------------------------------------------------------
| CitySeeder
|--------------------------------------------------------------------------
|
| Make use of the Factory instance to seed database with dummy data or
| make use of Lucid models directly.
|
*/

/** @type {import('@adonisjs/lucid/src/Factory')} */
const Factory = use("Factory");

class CitySeeder {
  async run() {
    const data = [
      {
        name: "Resende",
        description: "Descrição da cidade de Resende",
        image_url:
          "https://images-valetour.s3-sa-east-1.amazonaws.com/Cidades/Resende2.jpg",
      },
      {
        name: "Itatiaia",
        description: "Descrição da cidade de Itatiaia",
        image_url:
          "https://images-valetour.s3-sa-east-1.amazonaws.com/Cidades/Itatiaia2.jpg",
      },
    ];
    const cities = await Factory.model("App/Models/City").createMany(2, data);
  }
}

module.exports = CitySeeder;
<file_sep>"use strict";
const Guia = use("App/Models/Guia");
const User = use("App/Models/User");
const Eva = use("App/Models/Evaluation");
const Axios = require("axios").default;

class GuiaController {
  async register({ request, response }) {
    const { name, description, tel, email, password } = request.body;

    try {
      const guia = await Guia.create({
        name,
        description,
        tel,
        email,
        password,
      });

      return response.send({ guia });
    } catch (e) {
      return response.status(406).send({ erro: e });
    }
  }

  async login({ request, response, auth }) {
    const { email, password } = request.all();

    try {
      const token = await auth.authenticator("guia").attempt(email, password);

      const guia = await Guia.findByOrFail("email", email);

      return response.send({ guia_id: guia.id, token: token.token });
    } catch (erro) {
      return response.status(400).send({ erro: erro.message });
    }
  }

  async edit({ request, response }) {
    const guia = await Guia.find(request.params.id);

    if (!guia) {
      return response.status(404).send({ message: "Guia não encontrado!" });
    }

    const { name, description, tel, email, password } = request.body;

    guia.name = name;
    guia.description = description;
    guia.tel = tel;
    guia.email = email;
    guia.password = <PASSWORD>;

    try {
      await guia.save();

      return response.send(guia);
    } catch (e) {
      return response.status(404).send({ erro: e });
    }
  }

  async delete({ request, response }) {
    const guia = await Guia.find(request.params.id);

    if (!guia) {
      return response.status(404).send({ message: "Guia não encontrado!" });
    }

    try {
      await guia.delete();

      return response.send({ message: "Guia excluído com sucesso!" });
    } catch (e) {
      return response.status(404).send({ erro: e });
    }
  }

  async evaluations({ request, response }) {
    const guia = await Guia.find(request.params.id);

    const eva = await guia.evaluations().fetch();

    return response.send(eva);
  }

  async rating({ request, response }) {
    const guia = await Guia.find(request.params.id);

    const avaliacoes = await Eva.query().where("guia_id", guia.id).fetch();
    const avaliacoesSerializado = avaliacoes.toJSON();

    let total = 0;
    avaliacoesSerializado.map((a) => {
      total += a.rating;
    });
    let media = total / avaliacoesSerializado.length;

    return response.send({ media });
  }

  async list({ response }) {
    const guias = await Guia.query()
      .with("evaluations")
      .orderBy("created_at")
      .fetch();
    const serializedGuias = guias.toJSON();
    const returnedGuias = [];

    serializedGuias.map((guia) => {
      guia.media = 0;
      guia.evaluations.map((eva) => {
        guia.media += eva.rating;
      });
      guia.media = guia.media / guia.evaluations.length;

      returnedGuias.push({
        id: guia.id,
        name: guia.name,
        description: guia.description,
        tel: guia.tel,
        media: guia.media,
      });
    });

    return response.send(returnedGuias);
  }

  async show({ request, response }) {
    const guia = await Guia.query()
      .where("id", request.params.id)
      .with("evaluations")
      .first();

    if (!guia) {
      return response.status(404).send({ message: "Guia não encontrado!" });
    }

    const serializedGuia = guia.toJSON();
    let media = 0;

    serializedGuia.evaluations.map((eva) => {
      media += eva.rating;
    });

    media = media / serializedGuia.evaluations.length;

    return response.send({
      id: guia.id,
      name: guia.name,
      description: guia.description,
      tel: guia.tel,
      media,
    });
  }

  async verify({ request, response }) {
    const { id } = request.params;

    try {
      const guia = await Guia.find(id);

      if (!guia) {
        return response.status(404).send({ message: "Guia não encontrado!" });
      }

      if (guia.expoToken === null) {
        return response.send({ verified: false });
      }
      return response.send({ verified: true });
    } catch (e) {
      return response.status(400).send({ erro: e.message });
    }
  }

  async verifytoken({ request, response }) {
    const { id, token } = request.body;

    try {
      const guia = await Guia.find(id);
      if (!guia) {
        return response
          .status(404)
          .send({ message: "Guia não foi encontrado!" });
      }
      guia.expoToken = token;
      await guia.save();
      return response.send({
        message: `Token inserido para o guia ${guia.name}!`,
      });
    } catch (e) {
      return response.status(400).send({ erro: e.message });
    }
  }

  async sendNotification({ request, response }) {
    const { guia_id, user_id, x, y } = request.body;

    try {
      const guia = await Guia.find(guia_id);
      const user = await User.find(user_id);

      if (!guia) {
        return response.status(404).send({ message: "Guia não encontrado." });
      }
      if (!user) {
        return response
          .status(404)
          .send({ message: "Usuário não encontrado." });
      }

      await Axios.post("https://exp.host/--/api/v2/push/send", {
        to: guia.expoToken,
        title: `Atenção Guia!`,
        body: `O membro ${user.username} se perdeu!\nAbra esta notificação para ver sua localização no mapa!`,
        priority: "high",
        sound: "default",
        data: {
          x,
          y,
        },
      });
      return response.send({ message: "ok" });
    } catch (e) {
      return response.status(400).send({ erro: e.message });
    }
  }
}

module.exports = GuiaController;
<file_sep>"use strict";

/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use("Schema");

class PurchasesSchema extends Schema {
  up() {
    this.create("purchases", (table) => {
      table.increments();
      table.integer("user_id").unsigned().references("id").inTable("users");
      table.integer("pacote_id").unsigned().references("id").inTable("pacotes");
      table.boolean("confirmed").defaultTo(false);
      table.timestamps();
    });
  }

  down() {
    this.drop("purchases");
  }
}

module.exports = PurchasesSchema;
<file_sep>"use strict";
const Suite = use("Test/Suite")("Admin - Guia");
const { before, beforeEach, after, afterEach, trait, test } = Suite;
const Admin = use("App/Models/Admin");
const Guia = use("App/Models/Guia");

trait("Test/ApiClient");
trait("Auth/Client");

test("Should create a guide", async ({ client }) => {
  const admin = await Admin.find(1);
  const response = await client
    .post("/guia/register")
    .send({
      name: "Guia para testes",
      description: "Um guia para testes",
      tel: "24992859059",
      email: "<EMAIL>",
      password: "<PASSWORD>",
    })
    .loginVia(admin)
    .end();
  response.assertStatus(200);
});

test("Should not create a guide because the admin is not authenticated", async ({
  client,
}) => {
  const response = await client
    .post("/guia/register")
    .send({
      name: "Guia para testes",
      description: "Um guia para testes",
      tel: "24992859059",
      email: "<EMAIL>",
      password: "<PASSWORD>",
    })

    .end();
  response.assertStatus(401);
});

test("Should update a guide", async ({ client }) => {
  const admin = await Admin.find(1);
  const response = await client
    .put("/guia/edit/1")
    .send({
      description: "ATUALIZAÇÃO da descrição do guia",
    })
    .loginVia(admin)
    .end();
  response.assertStatus(200);
});

test("Should not update a guide because the guide do not exist", async ({
  client,
}) => {
  const admin = await Admin.find(1);
  const response = await client
    .put("/guia/edit/111")
    .send({
      description: "ATUALIZAÇÃO da descrição do guia",
    })
    .loginVia(admin)
    .end();
  response.assertStatus(404);
});

test("Should list all guides", async ({ client }) => {
  const admin = await Admin.find(1);
  const response = await client.get("/guia/list").loginVia(admin).end();
  response.assertStatus(200);
});

test("Should not list all guides because the user is not authenticated", async ({
  client,
}) => {
  const response = await client.get("/guia/list").end();
  response.assertStatus(401);
});

test("Should show an specific guide", async ({ client }) => {
  const admin = await Admin.find(1);
  const response = await client.get("/guia/1").loginVia(admin).end();
  response.assertStatus(200);
});

test("Should not show an specific guide because the admin is not authenticated", async ({
  client,
}) => {
  const response = await client.get("/guia/1").end();
  response.assertStatus(401);
});

test("Should not show an specific guide because the guide do not exist", async ({
  client,
}) => {
  const admin = await Admin.find(1);
  const response = await client.get("/guia/111").loginVia(admin).end();
  response.assertStatus(404);
});

test("Should delete a guide", async ({ client }) => {
  const admin = await Admin.find(1);
  const response = await client.delete("/guia/delete/1").loginVia(admin).end();
  response.assertStatus(200);
});

test("Should not delete a guide because the admin is not authenticated", async ({
  client,
}) => {
  const response = await client.delete("/guia/delete/1").end();
  response.assertStatus(401);
});

test("Should not delete a guide because the guide do not exist", async ({
  client,
}) => {
  const admin = await Admin.find(1);
  const response = await client.delete("/guia/delete/1").loginVia(admin).end();
  response.assertStatus(404);
});
<file_sep>"use strict";

/*
|--------------------------------------------------------------------------
| Factory
|--------------------------------------------------------------------------
|
| Factories are used to define blueprints for database tables or Lucid
| models. Later you can use these blueprints to seed your database
| with dummy data.
|
*/

/** @type {import('@adonisjs/lucid/src/Factory')} */
const Factory = use("Factory");

Factory.blueprint("App/Models/Category", (faker, i, data) => {
  return {
    name: data[i].name,
    description: data[i].description,
  };
});

Factory.blueprint("App/Models/City", (faker, i, data) => {
  return {
    name: data[i].name,
    description: data[i].description,
    image_url: data[i].image_url,
  };
});

Factory.blueprint("App/Models/Local", (faker, i, data) => {
  return {
    city_id: data[i].city_id,
    name: data[i].name,
    description: data[i].description,
    image_url: data[i].image_url,
  };
});
<file_sep>"use strict";

/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use("Schema");

class AvaliacoesGuiasSchema extends Schema {
  up() {
    this.create("evaluations", (table) => {
      table.increments();
      table.integer("guia_id").unsigned().references("id").inTable("guias");
      table.string("description", 350).notNullable();
      table.integer("rating").notNullable();
      table.timestamps();
    });
  }

  down() {
    this.drop("evaluations");
  }
}

module.exports = AvaliacoesGuiasSchema;
<file_sep>"use strict";

const City = use("App/Models/City");

class CityController {
  async list({ response }) {
    const cities = await City.all();

    return response.send(cities);
  }
}

module.exports = CityController;
<file_sep>"use strict";
const Suite = use("Test/Suite")("Admin - Pacotes");
const { before, beforeEach, after, afterEach, trait, test } = Suite;
const Admin = use("App/Models/Admin");
const Pacote = use("App/Models/Pacote");
const Guia = use("App/Models/Guia");
const Helpers = use("Helpers");

trait("Test/ApiClient");
trait("Auth/Client");

before(async () => {
  await Guia.create({
    name: "Guia para testes",
    description: "Um guia para testes",
    tel: "24992859059",
    email: "<EMAIL>",
    password: "<PASSWORD>",
  });
});

test("Should create a package", async ({ client }) => {
  const admin = await Admin.find(1);
  const response = await client
    .post("/pacote/create")
    .send({
      category_id: 1,
      guia_id: 2,
      local_id: 1,
      name: "Pacote de teste",
      description: "Descrição do pacote de teste",
      price: 1000,
      date: "25/12/2020",
      image_url: "www.google.com",
      image: Helpers.tmpPath("aedb.png"),
    })
    .loginVia(admin)
    .end();
  response.assertStatus(200);
});

test("Should not create a package because the admin is not authenticated", async ({
  client,
}) => {
  const response = await client
    .post("/pacote/create")
    .send({
      category_id: 1,
      guia_id: 1,
      local_id: 1,
      name: "Pacote de teste",
      description: "Descrição do pacote de teste",
      price: 1000,
      date: "25/12/2020",
      image_url: "www.google.com",
      image: Helpers.tmpPath("aedb.png"),
    })
    .end();
  response.assertStatus(401);
});

test("Should not create a package because the category do not exist", async ({
  client,
}) => {
  const admin = await Admin.find(1);
  const response = await client
    .post("/pacote/create")
    .send({
      category_id: 111,
      guia_id: 1,
      local_id: 1,
      name: "Pacote de teste",
      description: "Descrição do pacote de teste",
      price: 1000,
      date: "25/12/2020",
      image_url: "www.google.com",
      image: Helpers.tmpPath("aedb.png"),
    })
    .loginVia(admin)
    .end();
  response.assertStatus(404);
});

test("Should not create a package because the guide do not exist", async ({
  client,
}) => {
  const admin = await Admin.find(1);
  const response = await client
    .post("/pacote/create")
    .send({
      category_id: 1,
      guia_id: 1,
      local_id: 1,
      name: "Pacote de teste",
      description: "Descrição do pacote de teste",
      price: 1000,
      date: "25/12/2020",
      image_url: "www.google.com",
      image: Helpers.tmpPath("aedb.png"),
    })
    .loginVia(admin)
    .end();
  response.assertStatus(404);
});

test("Should not create a package because the local do not exist", async ({
  client,
}) => {
  const admin = await Admin.find(1);
  const response = await client
    .post("/pacote/create")
    .send({
      category_id: 1,
      guia_id: 2,
      local_id: 111,
      name: "Pacote de teste",
      description: "Descrição do pacote de teste",
      price: 1000,
      date: "25/12/2020",
      image_url: "www.google.com",
      image: Helpers.tmpPath("aedb.png"),
    })
    .loginVia(admin)
    .end();
  response.assertStatus(404);
});

test("Should edit a package", async ({ client }) => {
  const admin = await Admin.find(1);
  const response = await client
    .put("/pacote/edit/1")
    .send({
      description: "Atualização da descrição do pacote de teste",
    })
    .loginVia(admin)
    .end();
  response.assertStatus(200);
});

test("Should not edit a package because the admin is not authenticated", async ({
  client,
}) => {
  const response = await client
    .put("/pacote/edit/1")
    .send({
      description: "Atualização da descrição do pacote de teste",
    })

    .end();
  response.assertStatus(401);
});

test("Should not edit a package because the package do not exist", async ({
  client,
}) => {
  const admin = await Admin.find(1);
  const response = await client
    .put("/pacote/edit/111")
    .send({
      description: "Atualização da descrição do pacote de teste",
    })
    .loginVia(admin)
    .end();
  response.assertStatus(404);
});

test("Should list a package", async ({ client }) => {
  const admin = await Admin.find(1);
  const response = await client.get("/pacote/1").loginVia(admin).end();
  response.assertStatus(200);
});

test("Should not list a package because the admin is not authenticated", async ({
  client,
}) => {
  const response = await client.get("/pacote/1").end();
  response.assertStatus(401);
});

test("Should not list a package because the package do not exist", async ({
  client,
}) => {
  const admin = await Admin.find(1);
  const response = await client.get("/pacote/111").loginVia(admin).end();
  response.assertStatus(404);
});

test("Should list all packages", async ({ client }) => {
  const admin = await Admin.find(1);
  const response = await client.get("/pacotes").loginVia(admin).end();
  response.assertStatus(200);
});

test("Should not list all packages because the admin is not authenticated", async ({
  client,
}) => {
  const response = await client.get("/pacotes").end();
  response.assertStatus(401);
});
<file_sep>"use strict";

const Favorite = use("App/Models/Favorite");
const User = use("App/Models/User");
const Pacote = use("App/Models/Pacote");

class FavoriteController {
  async isFavorited({ request, response }) {
    const { user_id, pacote_id } = request.body;

    try {
      const user = await User.find(user_id);
      if (!user) {
        return response
          .status(404)
          .send({ message: "Usuário não encontrado!" });
      }

      const pacote = await Pacote.find(pacote_id);
      if (!pacote) {
        return response.status(404).send({ message: "Pacote não encontrado!" });
      }
      const favorited = await Favorite.query()
        .where("user_id", "=", user_id)
        .where("pacote_id", "=", pacote_id)
        .select("id")
        .fetch();

      if (favorited.rows.length === 0) {
        return response.send(false);
      }

      return response.send(true);
    } catch (erro) {
      return response.status(400).send({ erro: erro.message });
    }
  }

  async unfavorite({ request, response }) {
    const { user_id, pacote_id } = request.body;
    try {
      const user = await User.find(user_id);
      if (!user) {
        return response
          .status(404)
          .send({ message: "Usuário não encontrado!" });
      }

      const pacote = await Pacote.find(pacote_id);
      if (!pacote) {
        return response.status(404).send({ message: "Pacote não encontrado!" });
      }
      await Favorite.query()
        .where("user_id", "=", user_id)
        .where("pacote_id", "=", pacote_id)
        .delete();

      return response.send({ message: "Desfavoritado!" });
    } catch (erro) {
      return response.status(400).send({ erro });
    }
  }
}

module.exports = FavoriteController;
<file_sep>"use strict";
const Purchase = use("App/Models/Purchase");
const User = use("App/Models/User");
const Pacote = use("App/Models/Pacote");

class PurchaseController {
  async create({ request, response }) {
    const { user_id, pacote_id } = request.body;

    const user = await User.find(user_id);
    if (!user) {
      return response.status(404).send({ message: "Usuário não encontrado" });
    }

    const pacote = await Pacote.find(pacote_id);
    if (!pacote) {
      return response.status(404).send({ message: "Pacote não encontrado" });
    }

    try {
      const purchase = await Purchase.create({ user_id, pacote_id });
      return response.send(purchase);
    } catch (erro) {
      return response.status(400).send({ erro });
    }
  }

  async filtered({ request, response }) {
    const { user_id } = request.params;

    const user = await User.find(user_id);
    if (!user) {
      return response.status(404).send({ message: "Usuário não encontrado" });
    }

    try {
      const purchases = await Purchase.query()
        .where("user_id", "=", user_id)
        .select(
          "p.id",
          "p.name",
          "p.description",
          "p.date",
          "p.image_url",
          "p.guia_id"
        )
        .join("pacotes as p", "p.id", "pacote_id")
        .orderBy("p.date")
        .fetch();
      return response.send(purchases);
    } catch (erro) {
      return response.status(400).send({ erro: erro });
    }
  }

  async haspurchases({ request, response }) {
    const { user_id } = request.params;
    try {
      const hasPurchase = await Purchase.query()
        .where("user_id", "=", user_id)
        .fetch();

      if (hasPurchase.rows.length !== 0) {
        return response.send(true);
      } else {
        return response.send(false);
      }
    } catch (erro) {
      return response.status(400).send({ erro });
    }
  }

  async confirmUser({ request, response }) {
    const { user_id, pacote_id } = request.body;

    try {
      await Purchase.query()
        .where("user_id", "=", user_id)
        .where("pacote_id", "=", pacote_id)
        .update({ confirmed: true });
      return response.send(true);
    } catch (erro) {
      return response.status(400).send({ erro: erro.message });
    }
  }

  async listUsers({ request, response }) {
    const { pacote_id } = request.params;

    try {
      const purchase = await Purchase.query()
        .where("pacote_id", "=", pacote_id)
        .select("u.username", "confirmed")
        .join("users as u", "u.id", "user_id")
        .fetch();
      return response.send(purchase);
    } catch (erro) {
      return response.status(400).send({ erro: erro.message });
    }
  }
}

module.exports = PurchaseController;
<file_sep>"use strict";
const Local = use("App/Models/Local");

class LocalController {
  async list({ response }) {
    const locals = await Local.all();

    return response.send(locals);
  }

  async filtered({ request, response }) {
    try {
      const locals = await Local.query()
        .where("city_id", "=", request.params.id)
        .fetch();

      return response.send(locals);
    } catch (e) {
      return response.status(404).send(e.message);
    }
  }

  async show({ request, response }) {
    const local = await Local.find(request.params.id);

    return response.send(local);
  }
}

module.exports = LocalController;
<file_sep>"use strict";

/** @type {typeof import('@adonisjs/framework/src/Route/Manager')} */
const Route = use("Route");
//User
Route.post("/user/register", "UserController.register");
Route.post("/user/login", "UserController.login");
Route.get("/user/list", "UserController.list");
Route.post("/user/pacote/favorite", "UserController.favorite").middleware("auth");
Route.get("/user/favorites/:id", "UserController.favorites").middleware("auth");
Route.put("/user/edit/:id", "UserController.edit").middleware("auth");
Route.delete("/user/delete/:id", "UserController.delete").middleware("auth");
Route.get("/user/:id", "UserController.user").middleware("auth");

//Favorite
Route.post("/favorited", "FavoriteController.isFavorited").middleware("auth");
Route.post("/unfavorite", "FavoriteController.unfavorite").middleware("auth");

//Forgot Password
Route.post("/forgotpassword", "ForgotPasswordController.create");
Route.post("/validate", "ForgotPasswordController.validate");
Route.put("/changepassword/:id", "ForgotPasswordController.change");

//Admin
Route.post("/admin/register", "AdminController.register");
Route.post("/admin/login", "AdminController.login");

//Guia
Route.post("/guia/register", "GuiaController.register").middleware("auth:admin");
Route.post("/guia/login", "GuiaController.login");
Route.put("/guia/edit/:id", "GuiaController.edit").middleware("auth:admin,auth:guia");
Route.delete("/guia/delete/:id", "GuiaController.delete").middleware("auth:admin");
Route.get("/guia/list", "GuiaController.list").middleware("auth:admin");
Route.get("/guia/:id", "GuiaController.show").middleware("auth:admin,auth:jwt");
Route.get("/guia/evaluations/:id", "GuiaController.evaluations").middleware("auth:admin");
Route.get("/guia/rating/:id", "GuiaController.rating").middleware("auth:admin");
Route.get("/guia/verify/:id", "GuiaController.verify").middleware("auth:guia");
Route.post("/guia/verify-token", "GuiaController.verifytoken").middleware("auth:guia");
Route.post("/guia/send-notification", "GuiaController.sendNotification").middleware("auth");

//Evaluation
Route.post("/evaluation/register", "EvaluationController.register");
Route.get("/evaluation/show", "EvaluationController.show");

//Category
Route.post("/category/register", "CategoryController.register").middleware("auth:admin");
Route.put("/category/edit/:id", "CategoryController.edit").middleware("auth:admin");
Route.delete("/category/delete/:id", "CategoryController.delete").middleware("auth:admin");
Route.get("/category/show/:id", "CategoryController.show").middleware("auth:admin");
Route.get("/category/list/", "CategoryController.list").middleware("auth:admin");

//Pacote
Route.post("/pacote/create", "PacoteController.create").middleware("auth:admin,auth:guia");
Route.put("/pacote/edit/:id", "PacoteController.edit").middleware("auth:admin");
Route.delete("/pacote/delete/:id", "PacoteController.delete").middleware("auth:admin");
Route.get("/pacote/:id", "PacoteController.show").middleware("auth:admin,auth:jwt");
Route.get("/pacotes", "PacoteController.list").middleware("auth:admin");
Route.get("/pacote/local/:id", "PacoteController.filtered").middleware("auth:admin,auth:jwt");
Route.get("/pacotes/guia/:guia_id", "PacoteController.guia").middleware("auth:admin,auth:guia");

//PacoteFotos
Route.post("/foto/create", "PacoteFotoController.create").middleware("auth:admin");
Route.delete("/foto/delete/:id", "PacoteFotoController.delete").middleware("auth:admin");
Route.get("/fotos/pacote/:pacote_id", "PacoteFotoController.getFotos").middleware("auth:admin,auth:jwt");

//Foto
Route.post("/envia/foto/:local", "FotoController.create").middleware("auth:admin,auth:guia");
Route.delete("/delete/foto", "FotoController.delete").middleware("auth:admin,auth:guia");

//City
Route.get("/cities", "CityController.list").middleware("auth:admin,auth:jwt");

//Local
Route.get("/locals", "LocalController.list").middleware("auth:admin,auth:jwt");
Route.get("/local/city/:id", "LocalController.filtered").middleware("auth:admin,auth:jwt");
Route.get("/local/:id", "LocalController.show").middleware("auth:admin,auth:jwt");

//Purchase
Route.post("/purchase", "PurchaseController.create").middleware("auth");
Route.get("/purchases/user/:user_id", "PurchaseController.filtered").middleware("auth");
Route.get("/purchases/haspurchases/:user_id", "PurchaseController.haspurchases").middleware("auth");
Route.post("/purchase/confirm/user", "PurchaseController.confirmUser").middleware("auth:guia");
Route.get("/purchase/list/:pacote_id", "PurchaseController.listUsers").middleware("auth:guia");

languages: Markdown JavaScript


text:
<repo_name>Fisica2014-FF/Ronch-braggPlot_v01<file_sep>/README.md
# Ronch-braggPlot_v01
<file_sep>/src/EnergyDist.h
#ifndef EnergyDist_h
#define EnergyDist_h

//... include header files ...

#include <vector>

#include "AnalysisSteering.h"
#include "Event.h"

class TH1F;

class BraggStatistic;

class EnergyDist: public AnalysisSteering {

 public:

  EnergyDist();
  virtual ~EnergyDist();

  // function to be called at execution start
  virtual void beginJob();
  // function to be called at execution end
  virtual void   endJob();
  // function to be called for each event
  virtual void process( const Event& ev );

  EnergyDist           ( const EnergyDist& x ) = delete;
  EnergyDist& operator=( const EnergyDist& x ) = delete;

 private:

  // Bragg curve information
  struct BraggCurve {
	  BraggStatistic* bragg_statistic;  // mean and rms energies
      TH1F* braggStat_graph;  // energy loss graph
  };

  // set of Bragg curves for different total energies
  std::vector<BraggCurve*> vbraggCurv;

  // create objects for a Bragg curve
  void bCreate( int id, float min, float max );

};

#endif

languages: Markdown C++


text:
<file_sep>module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: './tsconfig.json',
  },
  plugins: ['@typescript-eslint', 'prettier'],
  extends: [
    'airbnb-base',
    'plugin:import/typescript',
    'plugin:@typescript-eslint/recommended',
    'prettier',
    'prettier/@typescript-eslint',
  ],
  globals: {
    document: 'readonly',
    MutationObserver: 'readonly',
    WebKitMutationObserver: 'readonly'
  },
  rules: {
    'prettier/prettier': 'error',
    'no-console': 'off',
    'max-len': ['error', 80],
    'no-new': 'off',
    'no-underscore-dangle': 'off',
    'linebreak-style': 'off',
    'no-unused-expressions': 'off',
    'func-names': 'off',
    'class-methods-use-this': 'off',
    'prefer-destructuring': ['error', { object: true, array: false }],
    '@typescript-eslint/indent': ['error', 2],
    '@typescript-eslint/camelcase': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    '@typescript-eslint/no-var-requires': 'off',
    '@typescript-eslint/explicit-member-accessibility': [
      'error',
      {
        accessibility: 'explicit',
        overrides: {
          accessors: 'explicit',
          constructors: 'no-public',
          methods: 'off',
          properties: 'off',
          parameterProperties: 'explicit',
        },
      },
    ],
    'import/no-cycle': 'off',
  },
};
<file_sep>import gulp from 'gulp';
import ts from 'gulp-typescript';

gulp.task('default', function task() {
  return gulp
    .src('src/**/*.ts')
    .pipe(
      ts({
        module: 'commonjs',
        target: 'es5',
      })
    )
    .pipe(gulp.dest('dist'));
});
<file_sep>import Promise from '../promise';
import { isPromise, thenable } from '../utils';

export default function resolve(x: any): Promise {
  if (isPromise(x)) {
    return x;
  }

  if (thenable(x)) {
    return new Promise(x.then);
  }

  return new Promise(function callback(rsl): void {
    return rsl(x);
  });
}
<file_sep>import resolve from './static/resolve';
import reject from './static/reject';
import all from './static/all';
import race from './static/race';
import { noopFunc, isFunction, nextTick, PROMISE_ID, nextId } from './utils';

export enum Status {
  Pending,
  Fulfilled,
  Rejected,
}

class Promise {
  static resolve = resolve;

  static reject = reject;

  static all = all;

  static race = race;

  _status: Status = Status.Pending;

  _value: any;

  _onFulfilled: Function;

  _onRejected: Function;

  _next: Promise;

  _tick: boolean = false;

  constructor(callback: (resolve, reject?) => void) {
    this[PROMISE_ID] = nextId();
    callback(this._resolve, this._reject);
  }

  then(onFulfilled, onRejected?) {
    if (isFunction(onFulfilled)) {
      this._onFulfilled = onFulfilled;
    }
    if (isFunction(onRejected)) {
      this._onRejected = onRejected;
    }

    if (this._status === Status.Fulfilled) {
      !this._tick && this._resolve(this._value);
    } else if (this._status === Status.Rejected) {
      !this._tick && this._reject(this._value);
    }

    this._next = new Promise(noopFunc);

    return this._next;
  }

  catch(onRejected: (error: any) => void) {
    if (isFunction(onRejected)) {
      this._onRejected = onRejected;
    }
    if (this._status === Status.Rejected) {
      this._reject(this._value);
    }

    this._next = new Promise(noopFunc);

    return this._next;
  }

  _resolve = (value: any): void => {
    // SPEC: 2.1.2.1: When fulfilled, a promise:
    // must not transition to any other state.
    if (this._status !== Status.Pending) {
      return;
    }

    this._status = Status.Fulfilled;
    this._value = value;
    nextTick(() => {
      let nextValue;
      if (this._onFulfilled) {
        // SPEC: 2.2.5 `onFulfilled` and `onRejected`
        // must be called as functions (i.e. with no `this` value).
        const onFulfilled = this._onFulfilled;
        nextValue = onFulfilled(value);
      }
      if (this._next) {
        this._next._resolve(nextValue);
      }
      this._tick = false;
    });
    this._tick = true;
  };

  _reject = (error: any): void => {
    // SPEC: 2.1.3.1: When rejected, a promise:
    // must not transition to any other state.
    if (this._status !== Status.Pending) {
      return;
    }

    this._status = Status.Rejected;
    this._value = error;
    nextTick(() => {
      if (this._onRejected) {
        // SPEC: 2.2.5 `onFulfilled` and `onRejected`
        // must be called as functions (i.e. with no `this` value).
        const onRejected = this._onRejected;
        onRejected(null, error);
        if (this._next) {
          this._next._resolve(this._next._value);
        }
      } else if (this._next) {
        this._next._reject(error);
      }
      this._tick = false;
    });
    this._tick = true;
  };
}

export default Promise;
<file_sep>const Promise = require('../../dist/index').default;

function resolved(value) {
  return new Promise(function(resolve) {
    resolve(value);
  });
}

function rejected(error) {
  return new Promise(function(resolve, reject) {
    reject(error);
  });
}
function deferred() {
  let resolve;
  let reject;
  return {
    promise: new Promise(function(rslv, rjct) {
      resolve = rslv;
      reject = rjct;
    }),
    resolve,
    reject,
  };
}

module.exports = {
  resolved,
  rejected,
  deferred,
};
<file_sep>export function noopFunc(): void {}

export function isObject(x: any): boolean {
  return typeof x === 'object';
}

export function isFunction(x: any): boolean {
  return typeof x === 'function';
}

interface Observer {
  new (callback: MutationCallback): MutationObserver;
  prototype: MutationObserver;
}

function byObserver(Observer: Observer): Function {
  const node = document.createTextNode('');
  const queue = [];
  let i = 0;

  new Observer(function cb(): void {
    let callback: () => void;
    const currentQueue = [...queue];
    queue.length = 0;
    callback = currentQueue.shift();
    while (callback) {
      callback();
      callback = currentQueue.shift();
    }
  }).observe(node, { characterData: true });

  return function nextTick(callback: Function): void {
    queue.push(callback);
    if (queue.length > 1) {
      return;
    }
    i = (i + 1) % 2;
    node.data = i.toString();
  };
}

// imitate https://github.com/medikoo/next-tick/blob/master/index.js
export const nextTick = (function nextTick(): Function {
  if (
    process &&
    typeof process === 'object' &&
    typeof process.nextTick === 'function'
  ) {
    return process.nextTick;
  }

  if (document && typeof document === 'object') {
    let Observer: Observer;
    if (typeof MutationObserver === 'function') {
      Observer = MutationObserver;
    } else if (
      // @ts-ignore
      typeof WebKitMutationObserver === 'function'
    ) {
      // @ts-ignore
      Observer = WebKitMutationObserver;
    }
    if (Observer) {
      return byObserver(Observer);
    }
  }

  if (typeof setImmediate === 'function') {
    return setImmediate;
  }

  return function tick(callback: Function): void {
    setTimeout(callback, 0);
  };
})();

export const PROMISE_ID = Math.random()
  .toString(36)
  .substring(2);

let id = 0;

export function nextId() {
  id += 1;
  return id;
}

export function isPromise(x: any) {
  return isObject(x) && x[PROMISE_ID];
}

export function thenable(x: any) {
  return isObject(x) && isFunction(x.then);
}
<file_sep>import Promise, { Status } from '../promise';
import { noopFunc } from '../utils';

export default function race(promises: Promise[]): Promise {
  const next = new Promise(noopFunc);
  const len = promises.length;

  for (let i = 0; i < len; i += 1) {
    const promise = promises[i];
    if (promise._status === Status.Rejected) {
      next._reject(promise._value);
      break;
    } else if (promise._status === Status.Fulfilled) {
      next._resolve(promise._value);
      break;
    } else {
      promise
        .then((value: any): any => {
          if (next._status === Status.Pending) {
            next._resolve(promise._value);
          }
          return value;
        })
        .catch(
          (error: Error): Promise => {
            if (next._status === Status.Pending) {
              next._reject(promise._value);
            }
            return Promise.reject(error);
          }
        );
    }
  }

  return next;
}
<file_sep>const promisesAplusTests = require('promises-aplus-tests');
const adapter = require('./adapter');

promisesAplusTests(adapter, function(error) {
  // All done; output is in the console. Or check `err` for number of failures.
  console.log(error);
});
<file_sep>import Promise from '../promise';

export default function reject(error: any): Promise {
  return new Promise(function callback(_, rjt): void {
    return rjt(error);
  });
}
<file_sep># 从今天起，自己动手做一个`Promise`

languages: Markdown TypeScript JavaScript

repo_name: littleprincewdk/DIY-Promise


text:
<repo_name>xingrz/swiftz-android<file_sep>/README.md
swiftz-android
==============
<file_sep>/Swiftoid/src/main/java/us/xingrz/swiftz/android/SwiftzContact.java
package us.xingrz.swiftz.android;

public class SwiftzContact {

    public static final String ACTION_CONNECT = "us.xingrz.swiftz.ACTION_CONNECT";
    public static final String EXTRA_ACCOUNT = "account";

    public static final String ACTION_DISCONNECT = "us.xingrz.swiftz.ACTION_DISCONNECT";

    public static final String CONNECT_RESULT = "us.xingrz.swiftz.CONNECT_RESULT";
    public static final String EXTRA_MESSAGE = "message";
    public static final String EXTRA_TRAFFIC_TOTAL = "traffic_total";

    public static final String FORCE_DISCONNECTED = "us.xingrz.swiftz.FORCE_DISCONNECTED";
    public static final String EXTRA_REASON = "reason";

    public static final String UPDATE_CONNECTION_STATE = "us.xingrz.swiftz.UPDATE_CONNECTION_STATE";
    public static final String EXTRA_CONNECTED = "connected";

}
<file_sep>/Swiftoid/src/main/java/us/xingrz/common/SecureStream.java
package us.xingrz.common;

import android.support.annotation.NonNull;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public abstract class SecureStream {

    protected static final int BIT_1 = 0x80;
    protected static final int BIT_2 = 0x40;
    protected static final int BIT_3 = 0x20;
    protected static final int BIT_4 = 0x10;
    protected static final int BIT_5 = 0x08;
    protected static final int BIT_6 = 0x04;
    protected static final int BIT_7 = 0x02;
    protected static final int BIT_8 = 0x01;

    private final Object lock = new Object();

    private final SecureInputStream secureInputStream = new SecureInputStream();
    private final SecureOutputStream secureOutputStream = new SecureOutputStream();

    private InputStream rawInputStream;
    private OutputStream rawOutputStream;

    public SecureStream(InputStream rawInputStream, OutputStream rawOutputStream) {
        this.rawInputStream = rawInputStream;
        this.rawOutputStream = rawOutputStream;
    }

    public InputStream getInputStream() {
        return secureInputStream;
    }

    public OutputStream getOutputStream() {
        return secureOutputStream;
    }

    protected abstract void encrypt(@NonNull byte[] buffer, int offset, int count);

    protected abstract void decrypt(@NonNull byte[] buffer, int byteOffset, int byteCount);

    private class SecureInputStream extends InputStream {

        @Override
        public int read() throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public int read(@NonNull byte[] buffer) throws IOException {
            synchronized (lock) {
                if (rawInputStream == null) {
                    return -1;
                }
            }

            int read = rawInputStream.read(buffer);
            if (read == -1) {
                return read;
            }

            decrypt(buffer, 0, buffer.length);
            return read;
        }

        @Override
        public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {
            synchronized (lock) {
                if (rawInputStream == null) {
                    return -1;
                }
            }

            int read = rawInputStream.read(buffer, byteOffset, byteCount);
            if (read == -1) {
                return read;
            }

            decrypt(buffer, byteOffset, byteCount);
            return read;
        }

        @Override
        public void close() throws IOException {
            synchronized (lock) {
                if (rawInputStream == null) {
                    return;
                }
            }

            rawInputStream.close();
            rawInputStream = null;
        }

    }

    private class SecureOutputStream extends OutputStream {

        @Override
        public void write(int oneByte) throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public void write(@NonNull byte[] buffer) throws IOException {
            synchronized (lock) {
                if (rawOutputStream == null) {
                    throw new IOException("output stream closed");
                }
            }

            encrypt(buffer, 0, buffer.length);
            rawOutputStream.write(buffer);
        }

        @Override
        public void write(@NonNull byte[] buffer, int offset, int count) throws IOException {
            synchronized (lock) {
                if (rawOutputStream == null) {
                    throw new IOException("output stream closed");
                }
            }

            encrypt(buffer, offset, count);
            rawOutputStream.write(buffer, offset, count);
        }

        @Override
        public void close() throws IOException {
            synchronized (lock) {
                if (rawOutputStream == null) {
                    return;
                }
            }

            rawOutputStream.close();
            rawOutputStream = null;
        }

    }

}
<file_sep>/Swiftoid/src/main/java/us/xingrz/swiftz/android/util/WiFiHelper.java
package us.xingrz.swiftz.android.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class WiFiHelper {
    private static final int WALLED_GARDEN_SOCKET_TIMEOUT_MS = 10 * 1000;

    private boolean isWalledGardenConnection() {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("http://clients3.google.com/generate_204"); // "http://clients3.google.com/generate_204"
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setInstanceFollowRedirects(false);
            urlConnection.setConnectTimeout(WALLED_GARDEN_SOCKET_TIMEOUT_MS);
            urlConnection.setReadTimeout(WALLED_GARDEN_SOCKET_TIMEOUT_MS);
            urlConnection.setUseCaches(false);
            urlConnection.getInputStream();
            return urlConnection.getResponseCode() != 204;
        } catch (IOException e) {
            return false;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
}
<file_sep>/Swiftoid/src/main/java/us/xingrz/common/UdpOutputStream.java
package us.xingrz.common;

import android.support.annotation.NonNull;

import java.io.IOException;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UdpOutputStream extends OutputStream {

    private final int port;
    private final InetAddress address;

    private final DatagramSocket socket;

    public UdpOutputStream(int port, InetAddress address) throws SocketException {
        this.port = port;
        this.address = address;

        socket = new DatagramSocket();
    }

    @Override
    public void write(int oneByte) throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void write(@NonNull byte[] buffer) throws IOException {
        write(buffer, 0, buffer.length);
    }

    @Override
    public void write(@NonNull byte[] buffer, int offset, int count) throws IOException {
        socket.send(new DatagramPacket(buffer, offset, count, address, port));
    }

    @Override
    public void close() throws IOException {
        super.close();
    }

}
<file_sep>/Swiftoid/build.gradle
apply plugin: 'com.android.application'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 20
    buildToolsVersion '20.0.0'

    defaultConfig {
        applicationId "club.toyt.momoda"
        minSdkVersion 15
        targetSdkVersion 20
        versionCode 10000
        versionName "1.0.0"
    }

    packagingOptions {
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE.txt'
    }
}

dependencies {
	compile 'com.android.support:support-v4:20.0.0'
}
<file_sep>/settings.gradle
include ':Swiftoid'

languages: Java Markdown Gradle

repo_language: Java

repo_name: xingrz/swiftz-android