language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 1,359 | 2.9375 | 3 |
[] |
no_license
|
**Purpose**
I was inspired to write this twitter bot after learning years ago that Google would offer support numbers for people who would search for suicide related terms. I wanted to do something similar for Twitter to put a little positiveness back into the global conversation. In practice I ran this application for several days or weeks and looked for tweets from people who were sad or depressed. The bot would then respond with something uplifiting or inspirational.
**How It Works**
This is a .Net application written in C#. It uses a couple off the shelf text classification libraries in order to score/classify tweets.
This application is a WinForms GUI, several support libraries, and backed by a MSSQL database (accessed by Entity Framework).
The logic of this application is divided into jobs -- a job is composed of:
1. A list of Twitter accounts used to distribute the jobs activities.
2. A list of search terms used to search for tweets -- this is to do an initial coarse filter.
3. A training session to classify tweets.
4. A set of canned responses to send back to users if their message.
The basic usage pattern of this application is to configure the job parameters, manually retrieve tweets and classify them in order to train the bot, and then hit the go button in order for it to regularly search for tweets and respond to them.
|
JavaScript
|
UTF-8
| 5,028 | 3.296875 | 3 |
[] |
no_license
|
// 1. lancer une commande javascript pour attendre le chargement
window.onload = function() {
/* 2. première étape : je dois faire en sorte qu'un panel soit activé
par un onglet. donc je recupère les composants HTML des onglets
(les "a") et les panels ("div")
(utilisation de tableau pour le stockage des elements: donc boucle)
*/
var ongletsTab = []; // element global au script car déclaré en dehors de tout fonctio
var panelsTab = [];
function fabriqueTab() {
var onglets = document.getElementById('conteneurTabs').getElementsByTagName('a');
//htmlCollection construit par la methode getElementsbyTagName('nom du balise')
var panels = document.getElementById('conteneurTabs').getElementsByTagName('div');
//htmlCollection construit par la methode getElementsbyClassName('nom du class')
for (var i = 0; i < onglets.length; i++) {
ongletsTab.push(onglets[i]); // la methode Push permet de ranger une donnée à la fin
panelsTab.push(panels[i]);
}
}
/* Cette fonction permet de récupérer la hauteur du plus granrd panel
pour la donner ensuite aux autres */
function changeTaillePanel() {
/* Initialisation d'une variable contenant la hauteur d'un panel */
var panelTaille = panelsTab[0].offsetHeight;
for (var i = 0; i < panelsTab.length; i++) {
/* Si panelTaille est inférieure à la taille du panel correspondant
à l'index i ... */
if (panelTaille < panelsTab[i].offsetHeight) {
panelTaille = panelsTab[i].offsetHeight;
console.log(panelTaille, panelsTab[i].offsetHeight);
}
}
/* Création d'une boucle qui va permettre d'appliquer cette valeur a tous les panels */
for (var i = 0; i < panelsTab.length; i++) {
panelsTab[i].style.height = panelTaille+'px';
}
}
/*
Créer une fonction ( modifCalquePanel() ) qui va permettre de changer le z-index des panels
de facon à ce que celui qui correspond à l'index de l'onglet sur lequel
l'utilisateur soit mis devant les autres.
(déterminer les indexs de chaque composants)
(utilisation de la propriété "style" pour modifier le css.)
le stockage des elements dans des tableaux (array) permet accès
à la methode 'indexof' qui va permettre de connaitre l'index de placement
de mon objet transmis en 'this' lors du lancement de ma fonction
par l'écouteur d'evenement et donc de modifier l'objet correspondant
au meme index dans le tableau des panel.
cette fonction a besoin d'un paramètre 'this'
*/
function modifCalquePanel(pIndex) {
/* pIndex etant la veleur envoyée au moment où on lance la fonction
(une représentation symbolique de la valeur) */
for (var i = 0; i < panelsTab.length; i++) {
if (i !== pIndex) {
/* Test conditionnel permettant de définir quel est le panel qui doit
être actif on profite de cette condition pour mettre la classe active
sur l'onglet cliqué et pour le retirer aux autres onglets */
ongletsTab[i].classList.remove('active');
panelsTab[i].style.zIndex = 1;
// panelsTab[i].style.display = 'none';
} else {
ongletsTab[i].classList.add('active');
panelsTab[i].style.zIndex = 3;
// panelsTab[i].style.display = 'block';
}
}
}
/*
Placer un ecouteur d'evenement sur les onglets afin que l'utilisasteur
puisse cliquer et activer les panels.
(utilisation de addEventListener, donc possibilité de bloquer l'action
naturelle du lien et possibilité d'utiliser 'this' pour déterminer
l'onglet sur lequel l'utilisateur clique. )
l'ecouteur lance la fonction ( modifCalquePanel() ) de changement du css des panels.
l'ecouteur va donner 'this' en paramètre.
*/
function ajouteEvenement() {
/* pour mettre un evenemtn sur chaque objet, on passe par boucle */
for (var i = 0; i < ongletsTab.length; i++) {
ongletsTab[i].addEventListener('click', function(event){
/* "Event" est un objet fourni par la methode addeventlistner
lors du clique (ou tout autre type d'event tel que
'mousedown', 'mouseup', 'mouseenter', 'mouseleave', 'mousemouve'...),
on va ici se servir de cette "event" pour stopper l'action fourni
par défaut d'un lien de type 'a'. */
event.preventDefault();
/* On recupère l'index de position dans le tableau OngletsTab de l'élément
sur lequel on clique. */
var ongletsCourantIndex = ongletsTab.indexOf(this);
modifCalquePanel(ongletsCourantIndex);
});
}
}
/*
Créer une fonction d'initialisation.
*/
function init() {
fabriqueTab();
ajouteEvenement();
changeTaillePanel();
ongletsTab[0].classList.add('active');
panelsTab[0].style.zIndex = 3;
}
/*Mon Code
var ongletTab = document.getElementsByClassName('onglets');
var panelTab = document.getElementsByClassName('panel');
console.log(ongletTab);
// console.log(panelTab);
for (var i = 0; i < ongletTab.length; i++) {
ongletTab[i];
// console.log(ongletTab[i]);
}
for (var i = 0; i < panelTab.length; i++) {
panelTab[i];
// console.log(panelTab[i]);
}
function modifCalquePanel() {
}*/
init();
}
|
Swift
|
UTF-8
| 1,618 | 3.296875 | 3 |
[] |
no_license
|
//
// String.swift
// iosBank
//
// Created by Sumit Desai on 12/25/1399 AP.
//
import Foundation
extension String{
func validateEmail() -> Bool {
let emailReg = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
return applyReg(regexStr: emailReg)
}
func validatePass(mini: Int = 8, max: Int = 8) -> Bool {
//Minimum 8 characters at least 1 Alphabet and 1 Number:
var passReg = ""
if mini >= max{
passReg = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{\(mini),}$"
}else{
passReg = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{\(mini),\(max)}$"
}
return applyReg(regexStr: passReg)
}
func validName() -> Bool{
let nameReg = "^(([^ ]?)(^[a-zA-Z].*[a-zA-Z]$)([^ ]?))$"
return applyReg(regexStr: nameReg)
}
func validateCCnumber() -> Bool{
let ccNumberReg = "[0-9]{1}"
return applyReg(regexStr: ccNumberReg)
}
func validateCCcvv() -> Bool{
let ccCVVReg = "[0-9]{3}"
return applyReg(regexStr: ccCVVReg)
}
func validateAmount() -> Bool{
let amountReg = "^([1-9][0-9]{0,2}|1000)$"
return applyReg(regexStr: amountReg)
}
//https://stackoverflow.com/a/39284766/8201581
func applyReg(regexStr: String) -> Bool{
let trimmedString = self.trimmingCharacters(in: .whitespaces)
let validateOtherString = NSPredicate(format: "SELF MATCHES %@", regexStr)
let isValidateOtherString = validateOtherString.evaluate(with: trimmedString)
return isValidateOtherString
}
}
|
Markdown
|
UTF-8
| 88 | 2.53125 | 3 |
[] |
no_license
|
# react-webpack-boilerplate
Boilerplate/practice for React Webpack build for future use
|
PHP
|
UTF-8
| 5,956 | 2.75 | 3 |
[] |
no_license
|
<?php
/**
* insere o ganhador do prêmio artilheiro do mês atual na tabela av_dashboard_titulos
* @param - objeto com uma conexão aberta
* @param - string com a data do último dia do mês
*/
function insereGanhadorDoPremioArtilheiro($db, $datas)
{
$query = "SELECT codigo_jogador FROM av_jogadores_avancao ORDER BY quantidade_atendimentos_jogador DESC LIMIT 1";
# verificando se a consulta pode ser executada
if ($resultado = $db->query($query)) {
$id = $resultado->fetch_row();
$id = $id[0];
$query =
"INSERT INTO av_dashboard_colaborador_titulos VALUES (null, $id, 1, '{$datas['periodo_atual']['data_final']}');";
# inserindo ganhador
$resultado = $db->query($query);
return $resultado;
} else {
echo 'A query da função insereGanhadorDoPremioArtilheiro não está correta!';
exit;
}
}
/**
* insere o ganhador do prêmio goleiro do mês atual na tabela av_dashboard_titulos
* @param - objeto com uma conexão aberta
* @param - string com a data do primeiro dia do mês
* @param - string com a data do último dia do mês
*/
function insereGanhadorDoPremioGoleiro($db, $datas)
{
$query =
"SELECT
b.codigo_jogador AS id,
COUNT(b.conteudo_postado_base_de_conhecimento) AS conteudo_postado
FROM av_base_de_conhecimento_avancao AS b
INNER JOIN av_jogadores_avancao AS j
ON b.codigo_jogador = j.codigo_jogador
WHERE (b.data BETWEEN '{$datas['periodo_atual']['data_inicial']}' AND '{$datas['periodo_atual']['data_final']}')
GROUP BY b.codigo_jogador
ORDER BY
conteudo_postado DESC,
j.quantidade_atendimentos_jogador DESC,
j.indice_avancino_jogador DESC,
j.indice_questionario_interno_respondido_jogador DESC";
# verificando se a consulta pode ser executada
if ($resultado = $db->query($query)) {
$id = array();
# recuperando dados
while ($registro = $resultado->fetch_assoc()) {
$id[] = $registro['id'];
}
# verificando se não há ganhador
if ($resultado->num_rows == 0) {
return true;
} else {
# recuperando id do ganhador
$id = $id[0];
$query =
"INSERT INTO av_dashboard_colaborador_titulos VALUES (null, $id, 2, '{$datas['periodo_atual']['data_final']}');";
# inserindo ganhador
$resultado = $db->query($query);
return $resultado;
}
} else {
echo 'A query da função insereGanhadorDoPremioGoleiro não está correta!';
exit;
}
}
/**
* insere o ganhador do prêmio lateral do mês atual na tabela av_dashboard_titulos
* @param - objeto com uma conexão aberta
* @param - string com a data do primeiro dia do mês
* @param - string com a data do último dia do mês
*/
function insereGanhadorDoPremioLateral($db, $datas)
{
$query =
"SELECT
i.codigo_jogador AS id,
COUNT(i.conteudo_postado_info_varejo) AS pontos_info_varejo
FROM av_info_varejo_avancao AS i
INNER JOIN av_jogadores_avancao AS j
ON j.codigo_jogador = i.codigo_jogador
WHERE (i.data BETWEEN '{$datas['periodo_atual']['data_inicial']}' AND '{$datas['periodo_atual']['data_final']}')
GROUP BY i.nome_jogador
ORDER BY
pontos_info_varejo DESC,
j.quantidade_atendimentos_jogador DESC,
j.indice_avancino_jogador DESC,
j.indice_questionario_interno_respondido_jogador DESC";
# verificando se a consulta pode ser executada
if ($resultado = $db->query($query)) {
$id = array();
# recuperando dados
while ($registro = $resultado->fetch_assoc()) {
$id[] = $registro['id'];
}
# verificando se não há ganhador
if ($resultado->num_rows == 0) {
return true;
} else {
# recuperando id do ganhador
$id = $id[0];
$query =
"INSERT INTO av_dashboard_colaborador_titulos VALUES (null, $id, 3, '{$datas['periodo_atual']['data_final']}');";
# inserindo ganhador
$resultado = $db->query($query);
return $resultado;
}
} else {
echo 'A query da função insereGanhadorDoPremioLateral não está correta!';
exit;
}
}
/**
* insere o ganhador do prêmio meio campo do mês atual na tabela av_dashboard_titulos
* @param - objeto com uma conexão aberta
* @param - string com a data do último dia do mês
*/
function insereGanhadorDoPremioMeioCampo($db, $datas)
{
$query =
"SELECT
codigo_jogador AS id
FROM av_jogadores_avancao
ORDER BY
indice_avancino_jogador DESC,
quantidade_atendimentos_jogador DESC,
indice_questionario_interno_respondido_jogador DESC
LIMIT 1";
if ($resultado = $db->query($query)) {
$id = $resultado->fetch_row();
$id = $id[0];
$query =
"INSERT INTO av_dashboard_colaborador_titulos VALUES (null, $id, 4, '{$datas['periodo_atual']['data_final']}');";
# inserindo ganhador
$resultado = $db->query($query);
return $resultado;
} else {
echo 'A query da função insereGanhadorDoPremioMeioCampo não está correta!';
exit;
}
}
/**
* insere o ganhador do prêmio zagueiro do mês atual na tabela av_dashboard_titulos
* @param - objeto com uma conexão aberta
* @param - string com a data do último dia do mês
*/
function insereGanhadorDoPremioZagueiro($db, $datas)
{
$query =
"SELECT
codigo_jogador AS id
FROM av_jogadores_avancao
ORDER BY
indice_questionario_interno_respondido_jogador DESC,
quantidade_atendimentos_jogador DESC,
indice_avancino_jogador DESC
LIMIT 1";
if ($resultado = $db->query($query)) {
$id = $resultado->fetch_row();
$id = $id[0];
$query = "INSERT INTO av_dashboard_colaborador_titulos VALUES (null, $id, 5, '{$datas['periodo_atual']['data_final']}');";
# inserindo ganhador
$resultado = $db->query($query);
return $resultado;
} else {
echo 'A query da função insereGanhadorDoPremioArtilheiro não está correta!';
exit;
}
}
|
Python
|
UTF-8
| 491 | 2.671875 | 3 |
[] |
no_license
|
# coding=utf-8
# from UC Irvine
# 确定新数据集的规模
import urllib2
import sys
target_url = ("http://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/sonar.all-data")
data = urllib2.urlopen(target_url)
xList = []
labels = []
for line in data:
row = line.strip().split(",")
xList.append(row)
sys.stdout.write("Number of Rows of Data = " + str(len(xList)) + '\n')
sys.stdout.write("Number of Columns of Data = " + str(len(xList[1])))
|
Java
|
UTF-8
| 4,563 | 2.609375 | 3 |
[] |
no_license
|
package com.swe645;
import com.google.gson.Gson;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
public class StudentConsumer {
public StudentConsumer() {
System.out.println("CUNSOMER FOR TOPIC " + TOPIC );
}
static final String TOPIC = "survey-data-topic";
// static final String TOPIC = "survey";
static final String GROUP = "survey_group";
static final String HOST = "kafka-1:9092";
public static StudentBean getById(int id) {
try {
Properties props = new Properties();
props.put("bootstrap.servers", HOST);
props.put("group.id", GROUP);
props.put("enable.auto.commit", true);
props.put("auto.commit.interval.ms", "1000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("auto.offset.reset", "earliest");
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
consumer.subscribe(Arrays.asList(TOPIC));
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1500));
if (records.isEmpty()) {
consumer.seekToBeginning(consumer.assignment());
}
int i = 0;
while (i < 5000) {
for (ConsumerRecord<String, String> record : records) {
try {
Gson gson = new Gson();
StudentBean student = gson.fromJson(record.value(), StudentBean.class);
if (student.getStudentID() == id) {
consumer.close();
return student;
}
} catch (Exception e) {
System.out.println("Something went wrong consuming kafka data");
e.printStackTrace();
}
}
records = consumer.poll(Duration.ofMillis(100));
i++;
}
consumer.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static List<StudentBean> getAllSurveys() {
List<StudentBean> students = new ArrayList<>();
try {
Properties props = new Properties();
props.put("bootstrap.servers", HOST);
props.put("group.id", GROUP);
props.put("enable.auto.commit", true);
props.put("auto.commit.interval.ms", "1000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("auto.offset.reset", "earliest");
// SSL Support
// props.put("security.protocol", "SSL");
// props.put("ssl.truststore.location", "/var/certs/docker.kafka.client.truststore.jks");
// props.put("ssl.truststore.password", "swe645");
// props.put("ssl.truststore.type", "JKS");
// props.put("ssl.key.password", "swe645");
// props.put("ssl.endpoint.identification.algorithm", "");
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
consumer.subscribe(Arrays.asList(TOPIC));
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1500));
if (records.isEmpty()) {
consumer.seekToBeginning(consumer.assignment());
}
int i = 0;
while (i < 5000) {
for (ConsumerRecord<String, String> record : records) {
try {
Gson gson = new Gson();
StudentBean student = gson.fromJson(record.value(), StudentBean.class);
students.add(student);
System.out.println(student.getStudentID() + " " + student.getfName() + " " + student.getlName() + "consumed");
} catch (Exception e) {
System.out.println("Something went wrong consuming kafka data");
e.printStackTrace();
}
}
if (!students.isEmpty()) {
consumer.close();
return students;
}
records = consumer.poll(Duration.ofMillis(100));
i++;
}
consumer.close();
System.out.println("Consumer connection is closed");
} catch (Exception e) {
e.printStackTrace();
}
return students;
}
}
|
Java
|
UTF-8
| 201 | 2.375 | 2 |
[] |
no_license
|
package abstract_factory;
import abstract_factory.product.color.Color;
import abstract_factory.product.jewel.Jewel;
public interface PropertyFactory {
Color getColor();
Jewel getJewel();
}
|
Java
|
UTF-8
| 790 | 2.140625 | 2 |
[] |
no_license
|
package com.kingcontext.divolte.kafka.serializer;
import java.util.Map;
import io.divolte.server.DivolteIdentifier;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.serialization.StringSerializer;
public class DivolteStringSerializer implements Serializer<DivolteIdentifier> {
private StringSerializer ser;
public DivolteStringSerializer() {
super();
ser = new StringSerializer();
}
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
ser.configure(configs, isKey);
}
@Override
public byte[] serialize(String topic, DivolteIdentifier data) {
return ser.serialize(topic, data.value);
}
@Override
public void close() {
ser.close();
}
}
|
Java
|
UTF-8
| 6,092 | 3.40625 | 3 |
[] |
no_license
|
/* version = 0.7.0 */
import java.util.Scanner;
/**
* Главный класс консольной версии игрового приложения "Быки и коровы".
*/
public class BullsAndCowsMain
{
/**
* Количество цифр в числе заданное пользователем при выборе уровня сложности.
*/
private byte numberCount = 0;
/**
* Введенное пользователем число.
*/
private int inputedNumeric = 0;
/**
* Количество попыток отгадать число.
*/
private int attemptsCount = 0;
/**
* Конструктор.
*/
BullsAndCowsMain()
{
startDialod();
guessingDialog();
}
/**
* Первоначальный диалог с пользователем.
*/
public void startDialod()
{
System.out.println("Добро пожаловать в игру \"Быки и коровы\" !\n");
System.out.println("Правила игры: Вы должны угадать загаданное число.");
System.out.println("Задайте сложность игры (3, 4 или 5).");
Scanner in = new Scanner(System.in);
numberCount = in.nextByte();
if (BullsAndCowsDifficultyLevel.HARD.isValidInputedValue(numberCount) == false)
{
System.out.println("Вы ввели некорректное значение.");
System.out.println("Осуществляется выход из игры.");
System.exit(0);
}
else
{
System.out.println("Вы выбрали ".concat(BullsAndCowsDifficultyLevel.getDescription(numberCount)));
}
}
/**
* Диалог отгадывания числа.
*/
public void guessingDialog()
{
attemptsCount ++;
System.out.println("Число загадано, попробуйте его отгадать.");
System.out.println("Попытка № " + attemptsCount);
System.out.println("Введите число равное " + numberCount + " цифрам.");
BullsAndCowsHiddenNumeric hiddenNumeric = new BullsAndCowsHiddenNumeric(numberCount);
guessingProcess(hiddenNumeric);
System.out.println("Поздравляем Вы победили!" );
System.out.println("Загаданное число действительно " + hiddenNumeric.getNumeric());
System.out.println("Вы угадали это число с " + attemptsCount + " попыток.");
}
/**
* Процесс угадывания числа.
* @param hiddenNumeric - загаданное число.
*/
public void guessingProcess(BullsAndCowsHiddenNumeric hiddenNumeric)
{
boolean win = false;
while (win == false)
{
Scanner in = new Scanner(System.in);
boolean isInt = in.hasNextInt();
String line = in.nextLine();
boolean isValidInputedNumeric = false;
if ((line.length() == numberCount &&
isInt == true &&
line.charAt(0) != 48) ||
line.equals("сдаюсь"))
{
isValidInputedNumeric = true;
}
while(isValidInputedNumeric == false)
{
System.out.println("Введенное число не соответствует условию.");
System.out.println("Попробуйте еще раз.\n");
System.out.println("Введите число равное " + numberCount + " цифрам.");
isInt = in.hasNextInt();
line = in.nextLine();
if ((line.length() == numberCount &&
isInt == true &&
line.charAt(0) != 48) ||
line.equals("сдаюсь"))
{
isValidInputedNumeric = true;
}
}
if (line.equals("сдаюсь"))
{
System.out.println("Очень жаль что Вы не смогли отгадать число!");
System.out.println("Было загаданно число " + hiddenNumeric.getNumeric());
System.out.println("Осуществляется выход из программы.");
System.exit(0);
}
Scanner input = new Scanner(line);
inputedNumeric = input.nextInt();
BullsAndCowsInputedNumeric userNumeric = new BullsAndCowsInputedNumeric(inputedNumeric);
BullsAndCowsCompareNumerics compare = new BullsAndCowsCompareNumerics(
hiddenNumeric.getNumericList(), userNumeric.getInputedNumericList());
win = compare.isWin();
if (win == false)
{
attemptsCount ++;
System.out.println("К сожалению Вы не угадали загаданное число.");
System.out.println("В введенном Вами числе:");
System.out.println(compare.getBulls() + " цифр(ы) находятся на правильных позициях.");
System.out.println(compare.getCows() + " цифр(ы) находядятся на не правильных позициях.\n");
System.out.println("=====================================");
System.out.println("Попытка № " + attemptsCount);
System.out.println("Попробуйте еще раз. Введите число равное " + numberCount + " цифрам.");
System.out.println("Если не хотите больше делать попыток, ведите \"сдаюсь\"");
}
}
}
public static void main (String [] args)
{
new BullsAndCowsMain();
}
}
|
Ruby
|
UTF-8
| 1,765 | 3.390625 | 3 |
[] |
no_license
|
require_relative '../enumerable_cardio.rb'
require_relative '../data.rb'
require 'rspec'
context do "Enumerable Cardio!"
describe "#longest_quote" do
it "gets the longest quote on the list" do
correct_answer = {:text=> "“The critical ingredient is getting off your butt and doing something. It’s as simple as that. A lot of people have ideas, but there are few who decide to do something about them now. Not tomorrow. Not next week. But today. The true entrepreneur is a doer, not a dreamer.”",
:from=>"Nolan Bushnell, entrepreneur."}
expect(longest_quote(QUOTES)).to eq(correct_answer)
end
end
describe "#count_fail_quotes" do
it "fetches the total number of quotes containing the string 'fail'" do
correct_answer = 16
expect(count_fail_quotes(QUOTES)).to eq(correct_answer)
end
end
describe "#count_fail_quotes" do
it "fetches the total number of quotes containing the string 'fail'" do
correct_answer = 16
expect(count_fail_quotes(QUOTES)).to eq(correct_answer)
end
end
describe "#find_a_quote" do
it "gets the right quote for Albert Einstein"
correct_answer = {:text=>"Imagination is more important than knowledge.", :from=>"Albert Einstein"}
expect(find_a_quote(QUOTES, "Albert Einstein")).to eq(correct_answer)
correct_answer_two = {:text=>"“Hire character. Train skill.", :from=>"Peter Schultz"}
expect(find_a_quote(QUOTES, "Albert Einstein")).to eq(correct_answer_two)
end
describe "#number_of_quotes_grouped_by_author" do
it "gets the right group when queried for authors with more than 3 quotes" do
correct_answer = [{"Aristotle" => 4, "Napoleon Hill" => 6}]
expect(number_of_quotes_grouped_by_author(QUOTES, 3)).to eq correct_answer
end
end
end
|
Java
|
UTF-8
| 1,078 | 2.875 | 3 |
[] |
no_license
|
package sample;
import javafx.scene.image.Image;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Rectangle;
import java.io.Serializable;
import java.util.Random;
public class Choco implements Serializable {
public Rectangle choco;
public double x;
public double y;
public long timeCreated;
public boolean taken = false;
public Choco(int row, int column) {
x = (column * (Block.getWidth())) + Block.getPaddingH() + (Block.getWidth() / 2) - 15;
y = (row * (Block.getHeight())) + Block.getPaddingTop() + (Block.getHeight() / 2) - 15;
draw();
}
private void draw() {
choco = new Rectangle();
choco.setWidth(30);
choco.setHeight(30);
choco.setX(x);
choco.setY(y);
String url;
if (new Random().nextInt(20) % 2 == 0) {
url = "sample/assets/c1.png";
} else {
url = "sample/assets/c2.png";
}
choco.setFill(new ImagePattern(new Image(url)));
}
}
|
Ruby
|
UTF-8
| 624 | 3.375 | 3 |
[] |
no_license
|
#Mentorクラス定義
class Mentor
#インスタンス変数
attr_accessor :name
def initialize(name)
self.name = name
end
#インスタンスメソッド
def job
puts "#{self.name}です。私は現役のITプロフェッショナルです。"
end
end
#RailsMentorクラス定義(Mentorクラス継承)
class RailsMentor < Mentor
def job
puts "#{self.name}です。私はRubyとRailsでWebアプリケーションを作ります。"
end
end
#インスタンス生成
kirameki = Mentor.new('煌木')
akaide = RailsMentor.new('赤出')
#job呼び出し
kirameki.job
akaide.job
|
Python
|
UTF-8
| 885 | 3.0625 | 3 |
[] |
no_license
|
def decode_boarding_pass(bp):
binary = bp.translate(bp.maketrans('FBLR', '0101'))
id_ = int(binary, base=2)
row = id_ >> 3
col = id_ & int('111', base=2)
return row, col, id_
if __name__ == '__main__':
puzzle_input = [line for line in open('day_05.in').read().split('\n')]
# Part 1
assert decode_boarding_pass('BFFFBBFRRR') == (70, 7, 567)
assert decode_boarding_pass('FFFBBBFRRR') == (14, 7, 119)
assert decode_boarding_pass('BBFFBBFRLL') == (102, 4, 820)
seats = []
highest = 0
for code in puzzle_input:
_, __, seat_id = decode_boarding_pass(code)
seats.append(seat_id)
highest = max(seat_id, highest)
print(highest)
# Part 2
sorted_seats = sorted(seats)
for i in range(128 * 8):
if i not in sorted_seats and i - 1 in sorted_seats and i + 1 in sorted_seats:
print(i)
|
Python
|
UTF-8
| 586 | 2.53125 | 3 |
[] |
no_license
|
import socket
import argparse
parser=argparse.ArgumentParser()
parser.add_argument("IP",help="IP Addr",type=str)
parser.add_argument("Port",help="IP Addr",type=int)
parser.add_argument("file",help="IP Addr",type=str)
args=parser.parse_args()
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host =args.IP
port =args.Port
#remoteip=socket.gethostbyname(host)
s.connect((host,port))
s.send("GET /%s"%args.file+" HTTP/1.1 \n\n")
data=s.recvfrom(1024)
#print data
#data=data.replace("> ","\n")
for i in range(0, len(data)):
print (data[i].encode())
print("\r\n".encode())
s.close()
|
JavaScript
|
UTF-8
| 1,227 | 2.765625 | 3 |
[] |
no_license
|
import React, { useState } from 'react';
import classes from './FormInput.module.css';
const FormInput = (props) => {
const [enteredTodo, setEnteredTodo] = useState('');
const [isValid, setIsValid] = useState(true);
const inputChangeHandler = (event) => {
if (event.target.value.trim().length > 0) {
setIsValid(true);
}
setEnteredTodo(event.target.value);
};
// const inputBlurHandler = () => {
// if (enteredTodo.trim().length === 0) {
// setIsValid(false);
// }
// };
const submitHandler = (event) => {
event.preventDefault();
if (enteredTodo.trim().length === 0) {
setIsValid(false);
return;
}
props.onAddTodo(enteredTodo);
setEnteredTodo('');
};
return (
<form onSubmit={submitHandler}>
<label htmlFor='addTodo'>Add a Todo</label>
<div className={classes.addTodo}>
<input
type='text'
id='addTodo'
onChange={inputChangeHandler}
// onBlur={inputBlurHandler}
value={enteredTodo}
className={`${!isValid && classes.invalid}`}
autoFocus
/>
<button>
<i className={`fa fa-plus ${classes['fa-plus']}`}></i>
</button>
</div>
{!isValid && <p>Please enter a valid todo</p>}
</form>
);
};
export default FormInput;
|
Markdown
|
UTF-8
| 936 | 3.125 | 3 |
[] |
no_license
|
### Composite
###### Padrão Estrtutural
Este padrão tem como principio montar uma árvore onde objetos individuais (folhas) e grupos de objetos (compostos) sejam tratados de maneira igual, ou seja, através da aplicação do polimorfismo realizamos chamadas de objetos na árvore sem se preocupar se o objeto trata-se de uma folha ou de um composto.
##### INTENÇÃO
>“Compor objetos em estruturas de árvore para representarem hierarquias parte-todo. Composite permite aos clientes tratarem de maneira uniforme objetos individuais e composições de objetos.”
Design Patterns: Elements of Reusable Object-Oriented Software
##### ESTRUTURA/EXEMPLO
Component - Leaf - Composite - Client
Podemos criar um sistema de gerenciamento de arquivos (Component). Com arquivos concretos (vídeos, textos, imagens, etc.)(Leaf) e arquivos pastas, que armazenam outros arquivos (Composite).
[Exemplo](src)

|
Python
|
UTF-8
| 3,785 | 3.25 | 3 |
[] |
no_license
|
import requests
from bs4 import BeautifulSoup
from docx import Document
import re
def get_html(url): # забираем страницу
r = requests.get(url) # проверяем доступ
r.encoding = 'cp1251' # применяем нужную кодировку ибо вместо русского случаются крякозябры
return r.text
def get_total_pages(html): # список сылок
soup = BeautifulSoup(html, 'lxml') # парсим страницу
pages = soup.find_all('a') # ищем все с тегом "a"
tmp = [link.get('href') for link in pages] # переводим во временный список ссылки
output = [s for s in tmp if s.find('dialog_') != -1] # переводим в список ссылок которые начинаются на "dialog_"
return output
def get_page_data(html): # данные страниц
try: # фильтруем ошибки доступа к атрибуту
soup = BeautifulSoup(html, 'lxml') # парсим страницу
pages = soup.find('table', class_='table').find_all('td') # ищем все с тегом "td" в классе table
data = [d.text for d in pages] # создаем список данных, оставляем нужный нам текст
except AttributeError: return False
return data
def eng_rus(data): # разделяем диалоги на русские и английские
e = re.compile("[a-zA-Z]+")
r = re.compile("[а-яА-Я]+")
eng = [w for w in filter(e.match, data)]
rus = [w for w in filter(r.match, data)]
return eng, rus # передаем кортеж
def new_document(dialog, en, ru): # генерируем новый word документ, печатаем данные
document = Document() # создаем новый word документ
document.add_heading(dialog, 0) # печатем загаловок с названием диалога
table = document.add_table(rows=1, cols=2) # создаем таблицу
hdr_cells = table.rows[0].cells # создаем заглавные ячейки таблицы
hdr_cells[0].text = ru[0] # из диалогов на русском "По-английски" "название столбца"
hdr_cells[1].text = ru[1] # из диалогов на русском "Перевод на русский" "название столбца"
for a, b in zip(range(len(en)), range(2, len(ru))): # печатаем дилоги
row_cells = table.add_row().cells # добавляем ячеки таблицы
row_cells[0].text = en[a] # из диалогов на русском
row_cells[1].text = ru[b] # из диалогов на английском
document.save(dialog + '.docx')
def main():
url = 'https://www.en365.ru/dialogi.htm' # страница с сылками на диалоги
base_url = 'https://www.en365.ru/' # корневая ссылка
out_url = get_total_pages(get_html(url)) # собираем список сылок(дилогов)
try:
for dialog in out_url: # перебираем список сылок(диалогов)
url_gen = base_url + dialog # генерируем сылки с диалогами
html = get_html(url_gen) # получаем данные по сылкам
en, ru = eng_rus(get_page_data(html)) # собираем список данных со страниц и обрабатываем данные
new_document(dialog, en, ru) # создаем новый word документ с полученными данными
except TypeError: return False
if __name__ == '__main__':
main()
|
Python
|
UTF-8
| 161 | 3.234375 | 3 |
[] |
no_license
|
mat=float(input('Whats your math score?'))
geo=float(input('Whats your geography score?'))
m=(mat+geo)/2
print('Your average between this notes is {}'.format(m))
|
SQL
|
UTF-8
| 1,745 | 3.234375 | 3 |
[] |
no_license
|
INSERT INTO `regions`(`region_id`, `region_name`) VALUES (1,'Latinoamérica');
INSERT INTO `regions`(`region_id`, `region_name`) VALUES (2,'Europa');
INSERT INTO `countries`(`country_id`, `country_name`, `region_id`) VALUES (1,'Argentina',1);
INSERT INTO `countries`(`country_id`, `country_name`, `region_id`) VALUES (2,'España',2);
INSERT INTO `countries`(`country_id`, `country_name`, `region_id`) VALUES (3,'Uruguay',1);
INSERT INTO `locations`(`location_id`, `street_address`, `postal_code`, `city`,
`state_province`, `country_id`) VALUES (1,"Fake street 123","123","BA","BA",1) ;
INSERT INTO `departments`(`department_id`, `department_name`, `manager_id`, `location_id`)
VALUES (1,"Sales",null,1);
INSERT INTO `jobs`(`job_id`, `job_title`, `min_salary`, `max_salary`)
VALUES (100,"Programador",10000,20000);
INSERT INTO `employees`(`employee_id`, `first_name`, `last_name`, `email`,
`phone_number`, `hire_date`, `job_id`, `salary`, `commission_pct`,
`manager_id`, `department_id`)
VALUES (100,"Valeria","Gomez","valeria@mail.com","1111-2222","2018-11-01",
100,10000,20,null,1);
INSERT INTO `job_history`(`employee_id`, `start_date`, `end_date`, `job_id`, `department_id`)
VALUES (100,"2010-01-01","2015-01-01",100,1) ;
INSERT INTO `jobs`(`job_id`, `job_title`, `min_salary`, `max_salary`)
VALUES (102,"Programador",10000,20000);
INSERT INTO `employees`(`employee_id`, `first_name`, `last_name`, `email`, `phone_number`,
`hire_date`, `job_id`, `salary`, `commission_pct`, `manager_id`, `department_id`)
VALUES (101,"Juan","Perez","juan@mail.com","1111-2222","2018-10-01",102,10000,20,100,1);
INSERT INTO `job_history`(`employee_id`, `start_date`, `end_date`, `job_id`, `department_id`)
VALUES (101,"2010-01-01","2016-01-01",102,1) ;
|
Java
|
UTF-8
| 679 | 2.296875 | 2 |
[] |
no_license
|
package com.rifat.storeapps.ui.view.Factory;
import android.content.Context;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import com.rifat.storeapps.Data.Model.User;
import com.rifat.storeapps.ui.view.ViewModel.UserViewModel;
public class UserViewModelFactory extends ViewModelProvider.NewInstanceFactory {
private User user;
private Context context;
public UserViewModelFactory(Context context, User user)
{
this.context = context;
this.user = user;
}
@Override
public <T extends ViewModel> T create(Class<T> modelClass)
{
return (T) new UserViewModel(context, user);
}
}
|
Java
|
UTF-8
| 2,901 | 1.828125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2014 the original author or authors.
*
* 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 ratpack.spring;
import static org.junit.Assert.assertTrue;
import static ratpack.groovy.Groovy.groovyMarkupTemplate;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import ratpack.groovy.template.MarkupTemplateModule;
import ratpack.handling.Context;
import ratpack.handling.Handler;
import ratpack.server.RatpackServer;
import ratpack.spring.MarkupTests.Application;
import ratpack.spring.config.EnableRatpack;
import ratpack.spring.config.RatpackProperties;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@IntegrationTest("server.port=0")
public class MarkupTests {
private TestRestTemplate restTemplate = new TestRestTemplate();
@Autowired
private RatpackServer server;
@Test
public void contextLoads() {
String body = restTemplate.getForObject("http://localhost:" + server.getBindPort(), String.class);
assertTrue("Wrong body" + body, body.contains("<body>Home"));
}
@Configuration
@EnableRatpack
@EnableAutoConfiguration
protected static class Application {
@Bean
public Handler handler() {
return new Handler() {
@Override
public void handle(Context context) throws Exception {
context.render(groovyMarkupTemplate("markup.html"));
}
};
}
@Bean
public MarkupTemplateModule markupTemplateGuiceModule(RatpackProperties ratpack) {
MarkupTemplateModule module = new MarkupTemplateModule();
module.configure(config -> {
config.setTemplatesDirectory(ratpack.getTemplatesPath());
});
return module;
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
}
|
Java
|
UTF-8
| 2,355 | 1.945313 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package acoes.vista;
import acoes.entidades.ENVIOS;
import acoes.entidades.HISTORIAL_APADRINAMIENTO;
import acoes.entidades.JOVEN_NIÑO;
import acoes.entidades.Role;
import acoes.entidades.USUARIO;
import acoes.negocio.ACOESException;
import acoes.negocio.ApadrinamientoException;
import acoes.negocio.Negocio;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
/**
*
* @author Andres
*/
@Named(value="historiales")
@RequestScoped
public class Historiales {
@Inject
private InfoSesion sesion;
@Inject
private Negocio negocio;
private HISTORIAL_APADRINAMIENTO historial;
public Historiales() {
historial = new HISTORIAL_APADRINAMIENTO();
}
public InfoSesion getSesion() {
return sesion;
}
public void setSesion(InfoSesion sesion) {
this.sesion = sesion;
}
public HISTORIAL_APADRINAMIENTO getHistorial() {
return historial;
}
public void setHistorial(HISTORIAL_APADRINAMIENTO historial) {
this.historial = historial;
}
public String getPadrino(JOVEN_NIÑO n){
String padrino = negocio.getPadrinoNegocio(n);
return padrino;
}
public String apadrinar() throws ACOESException {
try{
if(sesion.getUsuario().getRole()== Role.SOCIO){
historial.setSocio_apadrina(sesion.getUsuario());
int numNinios = negocio.obtenerNiniosSinPadrino().size();
if(numNinios<=0){
return "errorApadrinamiento.xhtml";
}
negocio.insertarHistorial(historial, sesion.getUsuario());
}
sesion.refrescarUsuario();
return "ninios.xhtml";
}catch (ApadrinamientoException e){
FacesMessage fm = new FacesMessage("No quedan niños para apadrinar");
FacesContext.getCurrentInstance().addMessage("historiales:user", fm);
}
return null;
}
}
|
Java
|
UTF-8
| 6,678 | 2.140625 | 2 |
[] |
no_license
|
package za.co.jericho.contractor;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.apache.log4j.LogManager;
import za.co.jericho.contractor.domain.Contractor;
import za.co.jericho.contractor.domain.Contractor;
import za.co.jericho.contractor.search.ContractorSearchCriteria;
import za.co.jericho.contractor.service.ManageContractorService;
import za.co.jericho.security.domain.User;
import za.co.jericho.session.SessionServices;
import za.co.jericho.util.JerichoWebUtil;
import za.co.jericho.util.JsfUtil;
/**
*
* @author Jaco Koekemoer
* Date: 2015-12-29
*/
@ManagedBean(name = "contractorBean")
@SessionScoped
public class ContractorBean implements Serializable {
private Contractor contractor;
private ContractorSearchCriteria contractorSearchCriteria = new
ContractorSearchCriteria();
private List<Contractor> contractors = null;
@EJB
private ManageContractorService manageContractorService;
public ContractorBean() {
}
@PostConstruct
public void init() {
}
/* Getters and Setters */
public Contractor getContractor() {
return contractor;
}
public void setContractor(Contractor contractor) {
this.contractor = contractor;
}
public ContractorSearchCriteria getContractorSearchCriteria() {
return contractorSearchCriteria;
}
public void setContracorSearchCriteria(ContractorSearchCriteria
contractorSearchCriteria) {
this.contractorSearchCriteria = contractorSearchCriteria;
}
public List<Contractor> getContractors() {
return contractors;
}
public void setContractors(List<Contractor> contractors) {
this.contractors = contractors;
}
public ManageContractorService getManageContractorService() {
return manageContractorService;
}
public void setManageContractorService(ManageContractorService manageContractorService) {
this.manageContractorService = manageContractorService;
}
/* Service calls */
public Contractor prepareAdd() {
LogManager.getRootLogger().info(new StringBuilder()
.append("ContractorBean: prepareAdd")
.toString());
contractor = new Contractor();
return contractor;
}
public void addContractor() {
try {
if (contractor != null) {
SessionServices sessionServices = new SessionServices();
User currentUser = sessionServices.getUserFromSession();
contractor.setCreatedBy(currentUser);
contractor.setCreateDate(new Date());
contractor = manageContractorService.addContractor(contractor);
if (!JsfUtil.isValidationFailed()) {
contractors = null;
}
JerichoWebUtil.addSuccessMessage(ResourceBundle
.getBundle("/JerichoWebBundle")
.getString("ContractorAdded"));
}
else
{
JerichoWebUtil.addErrorMessage("Error occured. The Contractor was not created.");
}
}
catch (EJBException ex) {
JerichoWebUtil.addEJBExceptionMessage(ex);
}
catch (Exception e) {
JerichoWebUtil.addGeneralExceptionMessage(e);
}
}
public void updateContractor() {
LogManager.getRootLogger().info(new StringBuilder()
.append("ContractorBean: updateContractor").toString());
try {
if (contractor != null) {
SessionServices sessionServices = new SessionServices();
User currentUser = sessionServices.getUserFromSession();
contractor.setLastModifiedBy(currentUser);
contractor.setLastModifyDate(new Date());
contractor = manageContractorService.updateContractor(contractor);
JerichoWebUtil.addSuccessMessage(ResourceBundle
.getBundle("/JerichoWebBundle")
.getString("ContractorUpdated"));
}
}
catch (EJBException ex) {
JerichoWebUtil.addEJBExceptionMessage(ex);
}
catch (Exception e) {
JerichoWebUtil.addGeneralExceptionMessage(e);
}
}
public void deleteContractor() {
LogManager.getRootLogger().info(new StringBuilder()
.append("ContractorBean: deleteContractor").toString());
try {
if (contractor != null) {
SessionServices sessionServices = new SessionServices();
User currentUser = sessionServices.getUserFromSession();
contractor.setLastModifiedBy(currentUser);
contractor.setLastModifyDate(new Date());
contractor = manageContractorService.markContractorDeleted(contractor);
JerichoWebUtil.addSuccessMessage(ResourceBundle
.getBundle("/JerichoWebBundle")
.getString("ContractorDeleted"));
if (!JsfUtil.isValidationFailed()) {
contractor = null; // Remove selection
contractor = null;
}
}
}
catch (EJBException ex) {
JerichoWebUtil.addEJBExceptionMessage(ex);
}
catch (Exception e) {
JerichoWebUtil.addGeneralExceptionMessage(e);
}
}
public void searchContractors() {
LogManager.getRootLogger().info(new StringBuilder()
.append("ContractorBean: searchContractors").toString());
try {
if (contractorSearchCriteria != null) {
SessionServices sessionServices = new SessionServices();
User currentUser = sessionServices.getUserFromSession();
contractorSearchCriteria.setServiceUser(currentUser);
contractors = manageContractorService.searchContractors(contractorSearchCriteria);
}
}
catch (EJBException ex) {
JerichoWebUtil.addEJBExceptionMessage(ex);
}
catch (Exception e) {
JerichoWebUtil.addGeneralExceptionMessage(e);
}
}
}
|
Python
|
UTF-8
| 7,245 | 2.578125 | 3 |
[] |
no_license
|
import sys
import math
import random
from sklearn.svm import LinearSVC
from sklearn.metrics import balanced_accuracy_score
################ DATA PRE-PROCESSING ################
dataFile = sys.argv[1]
labelFile = sys.argv[2]
trainFile = sys.argv[3]
#data = open("/Users/pavanghuge/Downloads/ML/Assignment9A/qsar.data").readlines()
data =open(dataFile)
data = [line.strip().split() for line in data]
data = [list(map(float, line)) for line in data]
rows = len(data)
cols = len(data[0])
#labels = open("/Users/pavanghuge/Downloads/ML/Assignment9A/qsar.labels").readlines()
labels = open(labelFile)
labels = [line.strip().split(' ') for line in labels]
labels = [list(map(int, line)) for line in labels]
#trainlabels = open("/Users/pavanghuge/Downloads/ML/Assignment9A/qsar.trainlabels.0").readlines()
trainlabels = open(trainFile)
trainlabels = [line.strip().split(' ') for line in trainlabels]
trainlabels = [list(map(int, line)) for line in trainlabels]
trainX1, trainY1 = [], []
trainIndex = []
for (label, i) in trainlabels:
trainX1.append(data[i])
if label == 1:
trainY1.append(1)
else:
trainY1.append(0)
trainIndex.append(i)
testX1 = []
testIndex = [i for i in range(len(data)) if i not in trainIndex]
if len(testIndex) == 0:
testIndex = trainIndex
else:
for i in testIndex:
testX1.append(data[i])
if len(testX1) == 0:
testX1 = trainX1
testY1=[]
testIndex = [i for i in range(len(labels)) if i not in trainIndex]
if len(testIndex) == 0:
testIndex = trainIndex
else:
for val,i in labels:
if i in testIndex:
testY1.append(val)
def create_train_test(trainX, testX,k):
if len(trainX[0]) != len(testX[0]):
raise ValueError('Training and Testing data should contain same number of features')
new_trainX = []
for X in trainX:
temp = [1.0]
temp.extend(X)
new_trainX.append(temp)
new_testX = []
for X in testX:
temp = [1.0]
temp.extend(X)
new_testX.append(temp)
Z_train, Z_test = [], []
for i in range(k):
weights = create_weights(trainX)
zi = create_zi(new_trainX, weights)
new_colm = get_new_column(zi)
Z_train.append(new_colm)
zi = create_zi(new_testX, weights)
new_colm = get_new_column(zi)
Z_test.append(new_colm)
Z_train = list(map(list, list(zip(*Z_train))))
Z_test = list(map(list, list(zip(*Z_test))))
return Z_train, Z_test
def dot_product(P, Q):
res = 0
for val_a, val_b in zip(P, Q):
res += val_a * val_b
return res
def get_w0(data, weights):
dot = []
for val in data:
dot.append(dot_product(val, weights))
min_dot = min(dot)
max_dot = max(dot)
return random.uniform(min_dot, max_dot)
def create_weights(data):
weights = []
for _ in range(len(data[0])):
weights.append(random.uniform(-1, 1))
w0 = get_w0(data, weights)
new_weights = [w0]
new_weights.extend(weights)
return new_weights
def create_zi(data, weights):
zi = []
for val in data:
zi.append(dot_product(val, weights))
return zi
def sign(val):
if val < 0 :
return -1
else:
return 1
def get_obj(val):
num = 1 + sign(val)
return num/2
def get_new_column(zi):
colm = []
for val in zi:
colm.append(sign(val))
return colm
def getbestC(train,labels):
random.seed()
allCs = [.001, .01, .1, 1, 10, 100]
error = {}
for j in range(0, len(allCs), 1):
error[allCs[j]] = 0
rowIDs = []
for i in range(0, len(train), 1):
rowIDs.append(i)
nsplits = 10
for x in range(0,nsplits,1):
#### Making a random train/validation split of ratio 90:10
newtrain = []
newlabels = []
validation = []
validationlabels = []
random.shuffle(rowIDs) #randomly reorder the row numbers
#print(rowIDs)
for i in range(0, int(.9*len(rowIDs)), 1):
newtrain.append(train[i])
newlabels.append(labels[i])
for i in range(int(.9*len(rowIDs)), len(rowIDs), 1):
validation.append(train[i])
validationlabels.append(labels[i])
#### Predict with SVM linear kernel for values of C={.001, .01, .1, 1, 10, 100} ###
for j in range(0, len(allCs), 1):
C = allCs[j]
clf = LinearSVC(C=C)
clf.fit(newtrain, newlabels)
prediction = clf.predict(validation)
err = 0
for i in range(0, len(prediction), 1):
if(prediction[i] != validationlabels[i]):
err = err + 1
err = err/len(validationlabels)
error[C]+=err
bestC = 0
minerror=100
keys = list(error.keys())
for i in range(0, len(keys), 1):
key = keys[i]
error[key] = error[key]/nsplits
if(error[key] < minerror):
minerror = error[key]
bestC = key
return [bestC,minerror]
newdata_train =[]
#filename= sys.argv[3]
#f = open(filename,'w')
f = open("results_qsar.txt","w")
best_C, min_error = getbestC(trainX1, trainY1)
clf = LinearSVC(C= best_C, max_iter=10000)
clf.fit(trainX1, trainY1)
org_predictions = clf.predict(testX1)
org_error = 1-balanced_accuracy_score(testY1, org_predictions)
planes=[10, 100, 1000,10000]
for k in planes:
new_trainX, new_testX = create_train_test(trainX1, testX1,k)
best_C, min_error = getbestC(new_trainX, trainY1)
clf = LinearSVC(C= best_C, max_iter=10000)
clf.fit(new_trainX, trainY1)
predictions = clf.predict(new_testX)
balanced_error=1-balanced_accuracy_score(testY1, predictions)
print("\n******************************************************\n")
print("For",k,"random planes")
print("Best C:",best_C)
print("Error for new features data: \n",balanced_error*100,"%")
print("Error for original data: \n",org_error*100,"%")
print("\n******************************************************\n")
f.write("\n******************************************************* \n")
f.write("For %d random planes \n" %k)
f.write(" Best C:"+ "\n")
f.write(str(best_C)+"\n")
f.write("\n")
f.write("Error for new features data "+ "\n")
f.write(str(balanced_error*100) +"\n")
f.write("\n")
f.write(" Error for original data: "+ "\n")
f.write(str(org_error*100) +"\n")
f.write("\n*******************************************************\n")
f.close()
|
Python
|
UTF-8
| 2,919 | 3.125 | 3 |
[] |
no_license
|
from urllib.request import urlopen
import pathlib
import zipfile
from corpus import *
def fetch_testcases(path) -> [(str, [(str, [Location])])]:
'''Returns completion test cases read from path.
path may be local or online.
A list of test cases is returned.
- Each test case is of the form: (query, result)
- Each result is a list of candidates.
- Each candidate is of the form: (completion, [Location]).
'''
# Read content from path.
if path.startswith("http"):
lines = [line.decode('utf-8').strip()
for line in urlopen(path).readlines()]
else:
lines = [line.strip() for line in open(path).readlines()]
# Parse for test cases and store.
itr = iter(lines)
completions = []
try:
while query := next(itr):
num_results = int(next(itr))
locs = dict()
for _ in range(num_results):
word, doc_id, start, stop = next(itr).split()
start, stop = int(start), int(stop)
locs[word] = locs.get(word, []) + \
[Location(doc_id, start, stop)]
completions.append((query, list(locs.items())))
except StopIteration:
pass
return completions
path = 'https://waqarsaleem.github.io/cs201/hw4/'
cases = fetch_testcases(path + 'cases.txt')
# Read and initialize corpus.
zipfilename = 'articles.zip'
open(zipfilename, 'wb').write(urlopen(path + zipfilename).read())
zipfile.ZipFile(zipfilename, 'r').extractall()
corpus = Corpus('articles/')
def test_index():
'''Tests search results through some sanity tests.
COVID-19: does not check the accuracy of scoring.
Performs various checks:
- The result must be sorted by score.
- The result must contain unique documents.
- Results must not exceed corpus size.
- The query term appears in the retrieved document.
'''
# Inverted Index.
corpus_size = len(list(pathlib.Path('./articles/').glob('*.txt')))
for query in ['Pakistan', 'corona', 'virus', 'distance']:
result = corpus.search(query)
if not result:
continue
docs, scores = zip(*result)
# Result is sorted by score.
assert list(scores) == sorted(scores, reverse=True), \
f'Obtained search results below are not ranked:\n{result}'
# Result contains unique documents.
assert len(docs) == len(set(docs)), \
f'Obtained search results below are not unique:\n{result}'
# Sanity check - results do no exceed corpus size.
assert len(docs) <= corpus_size, \
f'Obtained search results exceed corpus size:\n{len(result)}'
# query appears in each result document
for doc in docs:
assert query in open(f'articles/{doc}.txt', errors='replace').read(), \
f'query {query} does not appear in result document {doc}'
|
Markdown
|
UTF-8
| 3,590 | 3.40625 | 3 |
[] |
no_license
|
Yarden Ne'eman
Web Science Lab 9
4/19/18
Things to note for this lab:
1) I got this dataset from Kaggle: https://www.kaggle.com/mylesoneill/game-of-thrones/data. The dataset is battles.csv
2) I chose this dataset for multiple reasons. First, I really like Game of Thrones so that drew my eye to this dataset. Second, I thought a smaller dataset would be beneficial for this assignment. Since I'm just learning how to use R and igraph I didn't want to handle a very large dataset where it would be really hard to read the output of the graph. I also thought that the nature of the dataset would lend itself to a really nice directed graph.
3) The structure of the graph is as follows. The dataset contains a list of battles from Game of Thrones where each battle has several attributes. Two of these attributes are "attacked_1" and "defender_1" which represent the house that attacked the defending house for this battle. Also listed were any supporting houses that attacked or defended, but I just focused on the main houses of the battle. Each node represents a house in the dataset. Edges are drawn between nodes such that an edge comes out of the attacking house and points to the defending house. The edge labels are the name of the battle.
4) Creating the graph in such a way lets us understand the house dynamics of this data set. The connected components of the graph can show us which houses are tightly related through battles and which engage in their own separate battles. Based on the number of edges coming out of a node, we can also see how often it attacks other houses, and vice versa. We can also see which houses fight often based on the edges between them, for example the Starks and the Lannisters.
5) I was having some problems displaying the edge labels. Ultimately, I had to set the edge weight as the name of the battle and then display the edge weights as the label for it to appear on the graph. In doing so, some warning was generated about coercing types. Since this was a warning, I wrapped the plot() function call in a suppressWarnings() call. Since this was only a warning and the output generated was what I expected, I felt that this was okay to do.
6) I had a lot of issues with plotting the graph. Each time you run the plot command it generates a different graph, and some of the graphs had the nodes and edges overlapping and overall it was very hard to read with even a few nodes. This also made it hard to see the connected components because the nodes were placed pretty randomly when they were plotted. I had to play around with the font and node sizes to get the best output possible. I also needed to save the image of the plot in a higher resolution so that when you zoom in you can actually read the edge labels. This plot is saved under GOT_Plot.png
7) A few interesting things came up from this graph. The first thing is that in one of the battles, it has no defender listed. When the graph was generated, this was represented as an empty node, so in this battle it is listed that The Brave Companions fought no one. Another intereting thing was that in two battles, the Baratheons apparently fought themselves. This is represented as a reflexive edge in the graph which has two different labels.
8) When there are a lot of edges coming in and going out of a node it's sometimes hard to tell in which direction the arrows are pointing. This is particularly evident with the edges between the Starks and Lannisters, where there are so many edges that the arrows are bunched up and it's hard to tell which battle was fought in which direction.
|
Python
|
UTF-8
| 1,290 | 3.234375 | 3 |
[] |
no_license
|
import numpy as np
import pandas as pd
#Add unknown values present in the variables
unknown_values = ['Unknown', 'nan','NaN','NA', 'None', '--None--', 'NaT']
def convert_all_nas(df):
df=df.replace(unknown_values, np.nan)
return df
#checks for null values and returns either missing_values list or no_missing_values list
def missingvalues_check(df, no_nas=False):
has_missing_values = []
no_missing_values = []
for i in list(df.columns):
if df[i].hasnans == True:
has_missing_values.append(i)
elif df[i].hasnans == False:
no_missing_values.append(i)
if no_nas==True:
return no_missing_values
else:
return has_missing_values
#checks if percentaqge of null values is less that 20% and creates a list of these features.
def NAcalculator(df, has_Na):
percentage = []
some_missing_values = []
for i in has_Na:
perc = "{0:.2f}".format((df[i].isnull().sum()) / float(len(df[i])) * 100)
#print i + " " + perc +"%"
percentage.append((i,perc))
if perc < 20:
some_missing_values.append(i)
df=pd.DataFrame(data=percentage, columns = ['feature_name', '%']).sort_values(['%'], ascending=False)
return df
|
TypeScript
|
UTF-8
| 297 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
import { State } from "./news-state";
import { Action } from "./news-action";
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "news / Load news request":
return { ...state, news: action.payload };
default:
return state;
}
};
|
PHP
|
UTF-8
| 593 | 2.6875 | 3 |
[] |
no_license
|
<?php
/**
* User: dmitriy
* Date: 9/27/19
* Time: 8:37 AM
*/
namespace App\Validator\Validators;
use App\Helpers\Lang;
class ValidateRequired implements ValidateInterface
{
/**
* @param string $field
* @param array $request
* @param $additional
* @return mixed
*/
public function __invoke(string $field, array $request, $additional = null)
{
if (key_exists($field, $request) && !empty($request[$field])) {
return true;
}
return [
'error' => Lang::get('validator_error_required'),
];
}
}
|
Java
|
UTF-8
| 816 | 3.25 | 3 |
[
"MIT"
] |
permissive
|
package cn.geekhall.gof.behavior.strategy;
/**
* @author yiny
* @Type StrategySample.java
* @Desc
* @date 5/1/21 11:15 AM
*/
public class StrategySample {
public static void execute() {
System.out.println("==================== 行为型模式 2 : 策略模式(Strategy) Sample START =====================");
Context c = new Context();
Strategy strategyA = new ConcreteStrategyA();
c.setStrategy(strategyA);
c.strategyMethod();
System.out.println("--------------");
Strategy strategyB = new ConcreteStrategyB();
c.setStrategy(strategyB);
c.strategyMethod();
System.out.println("==================== 行为型模式 2 : 策略模式(Strategy) Sample END =====================");
System.out.println();
}
}
|
Python
|
UTF-8
| 1,035 | 3.8125 | 4 |
[] |
no_license
|
class User:
def __init__(self, nameOfUser, depositAmount, withdrawalAmount, balance):
self.name = nameOfUser
self.depositAmount = depositAmount
self.withdrawalAmount = withdrawalAmount
self.balance = balance
def make_deposit(self):
print(f"{self.name} makes deposits {self.depositAmount}")
return self
def make_withdrawal(self):
print(f"{self.name} makes withdrawal {self.withdrawalAmount}")
return self
def display_user_balance(self):
print(f"{self.name} checks balance {self.balance}")
return self
jaime = User("Jaime", "10", "1", "29")
christian = User("Christian", "10", "5", "10")
shiloh = User("Shiloh", "5", "1", "1")
jaime.make_deposit().make_deposit().make_deposit().make_withdrawal().display_user_balance()
christian.make_deposit()
christian.make_deposit().make_withdrawal().make_withdrawal().display_user_balance()
shiloh.make_deposit().make_withdrawal().make_withdrawal().make_withdrawal().display_user_balance()
|
PHP
|
UTF-8
| 1,806 | 3.03125 | 3 |
[] |
no_license
|
<?php
function generate($rowCount, $placesCount, $avaliableCount) {
if ($rowCount * $placesCount > $avaliableCount) {
return false;
}
$map = [];
for ($i = 0; $i < $rowCount; $i++) {
for ($j = 0; $j < $placesCount; $j++) {
$map[$i][$j] = false;
}
}
$map[1][2] = true;
$map[1][3] = true;
$map[0][5] = true;
$map[0][2] = true;
return $map;
}
function reserve(&$map, $requirePlace, $rowCount, $placesCount) {
$ending = 0;
$reservation = [];
for ($i = 0; $i < $rowCount; $i++) {
$ending = 0;
for ($j = 0; $j < $placesCount - $requirePlace + 1; $j++) {
if ($ending < $requirePlace) {
if ($map[$i][$j] === false) {
$map[$i][$j] = true;
$ending++;
}
}
if ($ending === $requirePlace) {
$reservation[0] = $i+1;
$reservation[1] = $j+1;
break 2;
}
}
}
return $reservation;
}
//проверка
$chairs = 50;
$rowCount = 5;
$placesCount = 8;
$map = generate($rowCount, $placesCount, $chairs);
$requirePlace = 3;
$reverve = reserve($map, $requirePlace, $rowCount, $placesCount);
logReserve($reverve, $requirePlace);
$reverve = reserve($map, $requirePlace, $rowCount, $placesCount);
logReserve($reverve, $requirePlace);
function logReserve(&$reservation, $requirePlace){
if ($ending = $requirePlace) {
echo "Ваши места забронированы! $requirePlace свободных мест найдено в $reservation[0] ряду, начиная с $reservation[1] места <br>".PHP_EOL;
} else {
echo "Что-то пошло не так=( Бронь не удалась".PHP_EOL;
}
}
|
JavaScript
|
UTF-8
| 412 | 2.59375 | 3 |
[] |
no_license
|
$(document).ready(function(){
$('.menu').on('click', function(event){
$('html').toggleClass('menu-active');
event.preventDefault();
});
$('#itens ul li').on('click', function(){
toggle(this);
});
$('ul #doctor').on('click', function(){
toggle(this);
});
function toggle(clickedElement) {
$(clickedElement).siblings().removeClass('active');
$(clickedElement).toggleClass('active');
}
})
|
Java
|
UTF-8
| 3,494 | 2.203125 | 2 |
[] |
no_license
|
package com.freelancerLink.config.auth;
import com.freelancerLink.config.auth.dto.OAuthAttributes;
import com.freelancerLink.config.auth.dto.SessionUser;
import com.freelancerLink.domain.user.UserInfo;
import com.freelancerLink.domain.user.UserRepository;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.Collections;
@RequiredArgsConstructor
@Service
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
/**
* (1)
* - 현재 로그인 진행 중인 서비스를 구분하는 코드
* - 지금은 구글만 사용하는 불필요한 값이지만 이후 넨이버 로그인 연동 시에 네이버 로그인인지 구글 로그인인지 구분하기 위해 사용한다.
*
* (2) userNameAttributeName
* - OAuth2 로그인 진행 시 키가 되는 필드값을 이야기한다. Primary Key와 같은 의미
* - 구글의 경우 기본적으로 코드를 지원하지만 네이버 카카오 등은 기본 지원하지 않습니다. 구글의 기본 코드는 "sub"이다.
* - 이후 네이버 로그인과 구글 로그인을 동시 지원할 때 사용된다.
*
* (3) SessionUser
* - 세션에 사용자 정보를 저장하기 위한 Dto클래스.
*
*/
private final UserRepository userRepository;
private final HttpSession httpSession;
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2UserService<OAuth2UserRequest, OAuth2User> delegate = new DefaultOAuth2UserService();
OAuth2User oAuth2User = delegate.loadUser(userRequest);
String registrationId = userRequest
.getClientRegistration().getRegistrationId();
String userNameAttributeName = userRequest // (1)
.getClientRegistration().getProviderDetails()
.getUserInfoEndpoint()
.getUserNameAttributeName();
OAuthAttributes attributes = OAuthAttributes
.of(registrationId, userNameAttributeName, //(2)
oAuth2User.getAttributes());
UserInfo user = saveOrUpdate(attributes);
httpSession.setAttribute("user", new SessionUser(user)); //(3) SessionUser
return new DefaultOAuth2User(
Collections.singleton(new SimpleGrantedAuthority(user.getRoleKey())),
attributes.getAttributes(),
attributes.getNameAttributeKey());
}
private UserInfo saveOrUpdate(OAuthAttributes attributes){
UserInfo user = userRepository.findByEmail(attributes.getEmail())
.map(entity -> entity.update(attributes
.getName(), attributes.getPicture()))
.orElse(attributes.toEntity());
return userRepository.save(user);
}
}
|
C
|
UTF-8
| 21,447 | 2.546875 | 3 |
[] |
no_license
|
//================================================================
//================================================================
// File: fm2dSubGradiend.h
// (C) 02/2010 by Fethallah Benmansour
//================================================================
//================================================================
#include "fm.h"
#define kDead -1
#define kOpen -2
#define kFar -3
#define kBorder -4
/* Global variables */
int nx; // real size on X
int ny; // real size on Y
int Nx, Ny; // size for computing
int size;
float hx, hy;// spacing
float hx2, hy2;
float hx2hy2;
float hx2_plus_hy2;
float* U = NULL;// action map
float* dUx = NULL;
float* dUy = NULL;
short* S = NULL; // states
float* W = NULL; // potential
bool* Obstacle = NULL;
float* OutputGradient = NULL;
double* WW = NULL;
int connectivity_small;
int* NeighborhoodSmall = NULL;
float w; // regularisation parameter
double* start_points = NULL;
int START_POINT;
int* END_POINTS = NULL;
double* end_points = NULL;
int nb_start_points;
int nb_end_points;
//================================================================
struct POINT{
float* Grad;
unsigned short nb_dead_neighbors;
};
POINT* Gradients = NULL;
//================================================================
// min-heap
int* Tree;
int* Trial;
int* PtrToTrial;
//================================================================
// MIN-HEAP
//================================================================
//================================================================
int Tree_GetFather(int position)
//================================================================
{
if(position)
{
if (ceil((float)position/2)==((float)position/2))
return (position/2 -1);
else
return((position-1)/2);
}
else
return -1;
};
//================================================================
// Tree_PushIn
/*
COMMENTS :
The tree is updated, since the value at the bottom is no longer
necessarily greater than the value of its father. Starting from
the bottom of the tree (the node we have just pushed in), the
value of each node is compared with the value of its father. If
the value of the father is greater, the two nodes are permuted.
The process stops when the top of the tree has been reached.
*/
//================================================================
int Tree_PushIn(int NewPosition)
{
*(++PtrToTrial) = NewPosition;
int position = (int)(PtrToTrial - Trial);
Tree[NewPosition] = position;
int s_idx = Trial[position];
int f_idx = Trial[Tree_GetFather(position)];
while((position!=0)&&(U[s_idx]<U[f_idx]))
{
int buffer = Trial[position];
Tree[Trial[position]] = Tree_GetFather(position);
Trial[position] = Trial[Tree_GetFather(position)];
Tree[Trial[Tree_GetFather(position)]] = position;
Trial[Tree_GetFather(position)] = buffer;
position = Tree_GetFather(position);
s_idx = Trial[position];
f_idx = Trial[Tree_GetFather(position)];
}
return (PtrToTrial - Trial +1);
};
//================================================================
bool Tree_IsEmpty()
//================================================================
{
return ((PtrToTrial - Trial + 1) == 0);
};
//================================================================
int Tree_GetRightSon(int position)
//================================================================
{
if ((2*position+2) < (int)(PtrToTrial - Trial +1))
return 2*position+2 ;
else
return -1;
};
//================================================================
int Tree_GetLeftSon(int position)
//================================================================
{
if ((2*position+1) < (int)(PtrToTrial - Trial +1))
return 2*position+1 ;
else
return -1;
};
//================================================================
// Tree_UpdateDescent
/*
COMMENTS :
The tree is updated in order to extract the head by marching down
the tree. Starting from the head of the tree, the value of a
node is compared with the values of its two sons and replaced by
the smallest one. This process is iterated from the son with the
smallest value, until a leaf has been reached.
*/
//================================================================
void Tree_UpdateDescent()
{
int position = 0;
bool stop = false;
while((position >= 0)&&(!stop))
{
if((Tree_GetRightSon(position)>0)&&(Tree_GetLeftSon(position)>0))
{
int ls_idx = Trial[Tree_GetLeftSon(position)];
int rs_idx = Trial[Tree_GetRightSon(position)];
if( U[ls_idx] <= U[rs_idx] )
{
Trial[position] = Trial[Tree_GetLeftSon(position)];
Tree[Trial[position]] = position;
position = Tree_GetLeftSon(position);
}
else
{
Trial[position] = Trial[Tree_GetRightSon(position)];
Tree[Trial[position]] = (position);
position = Tree_GetRightSon(position);
}
}
else
if(Tree_GetLeftSon(position)>0)
{
Trial[position] = Trial[Tree_GetLeftSon(position)];
Tree[Trial[position]] = (position);
position = Tree_GetLeftSon(position);
}
else
stop = true;
}
if(position != (PtrToTrial - Trial))
{
Tree[*PtrToTrial] = position;
Trial[position]=*PtrToTrial;
int s_idx = Trial[position];
int f_idx = Trial[Tree_GetFather(position)];
while((position!=0)&&(U[s_idx]<U[f_idx]))
{
int buffer = Trial[position];
Tree[Trial[position]] = Tree_GetFather(position);
Trial[position] = Trial[Tree_GetFather(position)];
Tree[Trial[Tree_GetFather(position)]] = position;
Trial[Tree_GetFather(position)] = buffer;
position = Tree_GetFather(position);
s_idx = Trial[position];
f_idx = Trial[Tree_GetFather(position)];
}
}
};
//================================================================
int Tree_PopHead()
//================================================================
{
if(PtrToTrial - Trial + 1)
{
int first = *Trial;
Tree[first] = -1;
Tree_UpdateDescent();
PtrToTrial--;
return first;
}
else
return NULL;
};
//================================================================
void Tree_UpdateChange(int position)
//================================================================
{
int s_idx = Trial[position];
int f_idx = Trial[Tree_GetFather(position)];
while((position!=0)&&(U[s_idx]<U[f_idx]))
{
int buffer = Trial[position];
Tree[Trial[position]] = Tree_GetFather(position);
Trial[position] = Trial[Tree_GetFather(position)];
Tree[Trial[Tree_GetFather(position)]] = position;
Trial[Tree_GetFather(position)] = buffer;
position = Tree_GetFather(position);
s_idx = Trial[position];
f_idx = Trial[Tree_GetFather(position)];
}
};
//================================================================
void Tree_PullFromTree(int point)
//================================================================
{
float Uv = U[point];
U[point] = 0;
Tree_UpdateChange(Tree[point]);
U[Tree_PopHead()]=Uv;
};
//================================================================
int Tree_GetSize()
//================================================================
{
return PtrToTrial - Trial + 1;
};
//================================================================
//================================================================
//================================================================
//================================================================
void InitializeNeighborhoods()
//================================================================
{
connectivity_small = 4;
NeighborhoodSmall = new int[connectivity_small];
NeighborhoodSmall[ 0]= -Nx;
NeighborhoodSmall[ 1]= -1;
NeighborhoodSmall[ 2]= 1;
NeighborhoodSmall[ 3]= Nx;
};
//================================================================
void InitializeArrays()
//================================================================
{
int x, y, point;
//copy the weight list and initialize
W = new float[size];
S = new short[size];
Gradients = new POINT[size];
dUx = new float[size];
dUy = new float[size];
Tree = new int[size];
Trial = new int[size];
//------------------------------------------------------------
for(x = 0; x < nx; x++){
for(y = 0; y < ny; y++){
point = (x+1) + (y+1)*Nx;
W[point] = WW[x + y*nx] + w; S[point] = kFar;
}
}
for(x = 0; x < size; x++){
U[x] = INFINITE;
Tree[x]=-1;
Gradients[x].nb_dead_neighbors = 0;
if(Obstacle[x])
S[x] = kDead;
}
//------------------------------------------------------------
PtrToTrial = Trial - 1;
//------------------------------------------------------------
// Initialize Borders
for(x = 0; x < Nx; x++){
y = 0;
point = x + y*Nx;
S[point] = kBorder;
y = Ny-1;
point = x + y*Nx;
S[point] = kBorder;
}
for(y = 0; y < Ny; y++){
x = 0;
point = x + y*Nx;
S[point] = kBorder;
x = Nx-1;
point = x + y*Nx;
S[point] = kBorder;
}
};
//================================================================
void InitializeOpenHeap()
//================================================================
{
int k, i, j, s, npoint;
for( s=0; s<nb_start_points; ++s ){
i = round(start_points[2*s]);
j = round(start_points[1+2*s]);
START_POINT = i + j*Nx;
//--------------------------------------------------------
if(START_POINT >=size)
mexErrMsgTxt("start_points should in the domaine.");
//--------------------------------------------------------
if( U[START_POINT]==0 )
mexErrMsgTxt("start_points should not contain duplicates.");
//--------------------------------------------------------
U[START_POINT] = 0.0; S[START_POINT] = kOpen;
Gradients[START_POINT].Grad = new float[size];
Gradients[START_POINT].nb_dead_neighbors = 0;
for(k = 0; k < size; k++)
Gradients[START_POINT].Grad[k] = 0.0;
for(k=0; k<connectivity_small; k++){
npoint = START_POINT+NeighborhoodSmall[k];
if( (S[npoint]==kDead) || (S[npoint]==kBorder) )
Gradients[START_POINT].nb_dead_neighbors++;
}
//--------------------------------------------------------
// add to heap
Tree_PushIn(START_POINT);
//--------------------------------------------------------
}
END_POINTS = new int[nb_end_points];
//--------------------------------------------------------
for( s=0; s<nb_end_points; s++ ){
i = round(end_points[2*s]);
j = round(end_points[1+2*s]);
END_POINTS[s] = i + j*Nx;
if(END_POINTS[s] >=size)
mexErrMsgTxt("start_points should be in the domaine.");
}
};
//================================================================
float SethianQuadrant(float Pc,float Ux,float Uy)
//================================================================
{
float Ua,Ub,qa,qb,Delta;
float result;
if (Ux<Uy){
Ua = Ux; qa = hx2;
Ub = Uy; qb = hy2;
}
else{
Ua = Uy; qa = hy2;
Ub = Ux; qb = hx2;
}
result = INFINITE;
if ((sqrt(qa)*Pc)>(Ub-Ua)){
Delta = (qa*qb)*((qa+qb)*Pc*Pc-(Ua-Ub)*(Ua-Ub));
if (Delta>=0)
result = ((qb*Ua+qa*Ub)+sqrt(Delta))/ hx2_plus_hy2;
}
else
result = Ua+sqrt(qa)*Pc;
return result;
};
//================================================================
void SethianQuadrantGradient(float* result_gradient, float Pc,float Ux,float Uy)
//================================================================
{
float qx, qy, Delta;
bool is_quadratic = 0;
float Gx = Ux+hx*Pc;
float Gy = Uy+hy*Pc;
if (Gx<Gy){
result_gradient[0]=Gx;
result_gradient[1]=Pc;
result_gradient[2]=0;
}
else{
result_gradient[0]=Gy;
result_gradient[1]=0;
result_gradient[2]=Pc;
}
if (Ux<Uy)
is_quadratic= (Gx>Uy);
else
is_quadratic= (Gy>Ux);
if (is_quadratic){
qx=hx2;
qy=hy2;
Delta = hx2hy2*(hx2_plus_hy2*Pc*Pc-(Ux-Uy)*(Ux-Uy));
if (Delta>=0){
float result = ((qx*Uy+qy*Ux)+sqrt(Delta)) / hx2_plus_hy2;
result_gradient[0] = result;
result_gradient[1] = (result-Ux)/hx;
result_gradient[2] = (result-Uy)/hy;
}
}
};
//================================================================
bool SethianUpdate(int point)
/*
COMMENTS :
*/
//================================================================
{
int npoint, npoint1, npoint2;
float* neighborU= new float [connectivity_small];
float* q_gradient = new float [3];
float Pc = W[point];
float Ur = U[point];
float dUxr = dUx[point];
float dUyr = dUy[point];
bool is_updated = false;
//--------------------------------------------------------------
// Get the U & L values for each neighbor.
for (int i=0;i<connectivity_small;i++){
npoint=point+NeighborhoodSmall[i];
if (S[npoint]==kDead){
neighborU[i]=U[npoint];
}
else{
neighborU[i]=INFINITE;
}
}
//--------------------------------------------------------------
// Quadrant 1 : (x-1,y);(x,y);(x,y-1).
SethianQuadrantGradient(q_gradient, Pc, neighborU[1], neighborU[0]);
if (q_gradient[0]<Ur){
Ur = q_gradient[0];
dUxr = q_gradient[1];
dUyr = q_gradient[2];
is_updated = true;
}
//--------------------------------------------------------------
// Quadrant 2 : (x+1,y);(x,y);(x,y-1).
SethianQuadrantGradient(q_gradient, Pc, neighborU[2], neighborU[0]);
if (q_gradient[0]<Ur){
Ur = q_gradient[0];
dUxr = -q_gradient[1];
dUyr = q_gradient[2];;
is_updated = true;
}
//--------------------------------------------------------------
// Quadrant 3 : (x-1,y);(x,y);(x,y+1).
SethianQuadrantGradient(q_gradient, Pc, neighborU[1], neighborU[3]);
if (q_gradient[0]<Ur){
Ur = q_gradient[0];
dUxr = q_gradient[1];
dUyr = -q_gradient[2];
is_updated = true;
}
//--------------------------------------------------------------
// Quadrant 4 : (x+1,y);(x,y);(x,y+1).
SethianQuadrantGradient(q_gradient, Pc, neighborU[2], neighborU[3]);
if (q_gradient[0]<Ur){
Ur = q_gradient[0];
dUxr = -q_gradient[1];
dUyr = -q_gradient[2];
is_updated = true;
}
//--------------------------------------------------------------
if (is_updated){
U[point]=Ur;
dUx[point]=dUxr;
dUy[point]=dUyr;
}
//--------------------------------------------------------------
delete [] q_gradient;
delete [] neighborU;
//--------------------------------------------------------------
return is_updated;
};
//================================================================
void ComputeGradient(int point)
//================================================================
{
//--------------------------------------------------------------
int k, s, npointX, npointY;
bool parentX, parentY;
float alpha, beta;
float dUxr = dUx[point];
float dUyr = dUy[point];
bool delete_condi = false;
//--------------------------------------------------------------
Gradients[point].Grad = new float[size];
for(k = 0; k < size; k++)
Gradients[point].Grad[k] = 0.0;
//--------------------------------------------------------------
if(dUxr > 0){
npointX = point + NeighborhoodSmall[1];
parentX = true;
}
else if(dUxr < 0){
npointX = point + NeighborhoodSmall[2];
parentX = true;
}
else parentX = false;
//--------------------------------------------------------------
if(dUyr > 0){
npointY = point + NeighborhoodSmall[0];
parentY = true;
}
else if(dUyr < 0){
npointY = point + NeighborhoodSmall[3];
parentY = true;
}
else parentY = false;
//--------------------------------------------------------------
Gradients[point].nb_dead_neighbors = 0;
for(k=0; k < connectivity_small; k++)
if(S[point + NeighborhoodSmall[k]] == kBorder)
Gradients[point].nb_dead_neighbors++;
//--------------------------------------------------------------
if(parentX && parentY){
if( (S[npointX]!=kDead) || (S[npointY]!=kDead) )
mexErrMsgTxt("Parents must be kDead");
alpha = (U[point] - U[npointX])/hx2;
beta = (U[point] - U[npointY])/hy2;
for(k=0; k < size; k++)
if(S[k] == kDead)
Gradients[point].Grad[k] = ((k==point)*W[point] + alpha*Gradients[npointX].Grad[k]+ beta*Gradients[npointY].Grad[k])
/ (alpha + beta);
Gradients[point].nb_dead_neighbors = Gradients[point].nb_dead_neighbors + 2;
Gradients[npointX].nb_dead_neighbors++;
Gradients[npointY].nb_dead_neighbors++;
delete_condi = (Gradients[npointX].nb_dead_neighbors == 4);
for(s=0; s <nb_end_points; s++)
delete_condi = delete_condi && (npointX != END_POINTS[s]);
if(delete_condi)
DELETEARRAY(Gradients[npointX].Grad);
delete_condi = (Gradients[npointY].nb_dead_neighbors == 4);
for(s=0; s <nb_end_points; s++)
delete_condi = delete_condi && (npointY != END_POINTS[s]);
if(delete_condi)
DELETEARRAY(Gradients[npointY].Grad);
}
//--------------------------------------------------------------
else if(parentX){
if( S[npointX]!=kDead )
mexErrMsgTxt("Parents must be kDead");
for(k=0; k < size; k++)
if(S[k] == kDead)
Gradients[point].Grad[k] = hx*(k==point) + Gradients[npointX].Grad[k];
Gradients[point].nb_dead_neighbors++;
Gradients[npointX].nb_dead_neighbors++;
delete_condi = (Gradients[npointX].nb_dead_neighbors == 4);
for(s=0; s <nb_end_points; s++)
delete_condi = delete_condi && (npointX != END_POINTS[s]);
if(delete_condi)
DELETEARRAY(Gradients[npointX].Grad);
}
//--------------------------------------------------------------
else if(parentY){
if( S[npointY]!=kDead )
mexErrMsgTxt("Parents must be kDead");
for(k=0; k < size; k++)
if(S[k] == kDead)
Gradients[point].Grad[k] = hy*(k==point) + Gradients[npointY].Grad[k];
Gradients[point].nb_dead_neighbors++;
Gradients[npointY].nb_dead_neighbors++;
delete_condi = (Gradients[npointY].nb_dead_neighbors == 4);
for(s=0; s <nb_end_points; s++)
delete_condi = delete_condi && (npointY != END_POINTS[s]);
if(delete_condi)
DELETEARRAY(Gradients[npointY].Grad);
}
//--------------------------------------------------------------
else{
mexErrMsgTxt("recently fixed point must have at least one parent: could not be an orphen");
}
};
//================================================================
void CorrectMaps()
//================================================================
{
int point;
for (point=0;point<size;point++)
if (S[point]!=kDead || Obstacle[point])
U[point]=0;
};
//================================================================
void RunPropagation()
//================================================================
{
int point,npoint,k, s;
bool is_updated = false;
bool end_points_reached = false;
//--------------------------------------------------------------
while ( (Tree_GetSize()>0) && (!end_points_reached) ){
point = Tree_PopHead();
if(S[point]!=kOpen)
mexErrMsgTxt("err : point must be Open");
S[point]=kDead;
//--------------------------------------------------------------
end_points_reached = ( S[END_POINTS[0]] == kDead );
for(k = 1; k < nb_end_points; k++)
end_points_reached = end_points_reached && (S[END_POINTS[k]] == kDead) ;
//--------------------------------------------------------------
if(point!=START_POINT)
ComputeGradient(point);
if(end_points_reached){
for(s = 0; s < nb_end_points; s++)
for(k=0; k < size; k++)
OutputGradient[k + s*size] = Gradients[END_POINTS[s]].Grad[k];
}
//--------------------------------------------------------------
for (k=0;k<connectivity_small;k++){
npoint = point+NeighborhoodSmall[k];
//--------------------------------------------------------------
if (S[npoint]==kOpen){
is_updated = SethianUpdate(npoint);
if(is_updated)
Tree_UpdateChange(Tree[npoint]);
}
//--------------------------------------------------------------
else if (S[npoint]==kFar){
S[npoint] = kOpen;
SethianUpdate(npoint);
Tree_PushIn(npoint);
}
//--------------------------------------------------------------
}
}
//--------------------------------------------------------------
CorrectMaps();
};
//================================================================
void resize()
//================================================================
{
int x, y, s, point, Point;
for(y=0;y<ny;y++)
for(x=0;x<nx;x++){
point = x+y*nx;
Point = (x+1)+(y+1)*Nx;
U[point] = U[Point];
dUx[point] = dUx[Point];
dUy[point] = dUy[Point];
}
int ss = nx*ny;
for(s = 0; s < nb_end_points; s++)
for(y=0;y<ny;y++)
for(x=0;x<nx;x++){
point = x+y*nx + s*ss;
Point = (x+1)+(y+1)*Nx + s*size;
OutputGradient[point] = OutputGradient[Point];
}
};
//================================================================
void cleanGradients(){
//================================================================
int k;
for(k=0; k<size; k++)
if(Gradients[k].nb_dead_neighbors > 0)
DELETEARRAY(Gradients[k].Grad);
};
|
Python
|
UTF-8
| 3,737 | 2.75 | 3 |
[] |
no_license
|
import sys, math, mpmath, numpy as N
def HB(z1, z2):
u = z1/z2
return (u**4 - 3*u**3 - u**2 + 3*u + 1) *\
(u**8 + 4*u**7 + 7*u**6 + 2*u**5 + 15*u**4 - 2*u**3 + 7*u**2 - 4*u + 1)
def B(z1, z2):
u = z1/z2
return -1 - u - 7*(u**2 - u**3 + u**5 + u**6) + u**7 - u**8
def D(z1, z2):
u = z1/z2
return -1 + u * (2 + u * (5 + u*u * (5 + u * (-2 - u))))
def f(z1, z2):
u = (z1/z2)**5
return z1/z2 * (-1 + u * (11 + u))
def H(z1, z2):
u = (z1/z2)**5
return -1 + u * (-228 + u * (-494 + u * (228 - u)))
def T(z1, z2):
u = (z1/z2)**5
return 1 + u * (-522 + u * (-10005 + u * u * (-10005 + u * (522 + u))))
def f1f2(a, b, c):
return a**4 - b**3 + a*b*c
def H1H2(a, b, c):
return c**4 + 40*a**2*b*c**2 - 192*a**5*c - 120*a*b**3*c + 640*a**4*b**2 - 144*b**5
def T1T2(a, b, c):
return c**6 + 60*a**2*b*c**4 + 576*a**5*c**3 - 180*a*b**3*c**3 + 648*b**5*c**2 - 2760*a**4*b**2*c**2 +\
7200*a**7*b*c - 1728*a**10 + 9360*a**3*b**4*c - 2080*a**6*b**3 - 16200*a**2*b**6
def nablasq(a, b, c):
return 108*a**5*c - 135*a**4*b**2 + 90*a**2*b*c**2 - 320*a*b**3*c + 256*b**5 + c**4
def p(a, b, c):
return (12**3*f1f2(a, b, c)**5 + H1H2(a, b, c)**3/(12**3) - T1T2(a, b, c)**2/(12**3)) / 2
def q(a, b, c):
return (-8*a**5*c - 40*a**4*b**2 + 10*a**2*b*c**2 + 45*a*b**3*c - 81*b**5 - c**4) *\
(64*a**10 + 40*a**7*b*c - 160*a**6*b**3 + a**5*c**3 - 5*a**4*b**2*c**2 +\
5*a**3*b**4*c - 25*a**2*b**6 - b**5*c**2) / 2
def r(a, b, c):
return (a**2*c**5 - a*b**2*c**4 + 53*a**4*b*c**3 + 64*a**7*c**2 - 7*b**4*c**3 - 225*a**3*b**3*c**2 -\
12*a**6*b**2*c + 216*a**9*b + 717*a**2*b**5*c - 464*a**5*b**4 - 720*a*b**7) / 2
def s(a, b, c):
return (-a**2*c**3 + 3*a*b**2*c**2 - 9*b**4*c - 4*a**4*b*c - 8*a**7 - 80*a**3*b**3) / 2
def H1cubf2fiv(a, b, c, nabla):
return p(a, b, c) + nabla * q(a, b, c)
def M1f2(a, b, c, nabla):
return (11*a**3*b + 2*b**2*c - a*c**2 - a*nabla) / 2
def N1f1sqT2(a, b, c, nabla):
return r(a, b, c) + nabla * s(a, b, c)
def Z(a, b, c, nabla):
return H1cubf2fiv(a, b, c, nabla) / (1728 * f1f2(a, b, c)**5)
def I(z1, z2):
return H(z1, z2)**3 / (1728*f(z1, z2)**5)
def KZ(a, b, c, nabla):
m = (11*a**3*b + 2*b**2*c - a*c**2 + a*nabla) / (24*(a**4 - b**3 + a*b*c))
return (48*a*m**2 - 12*b*m - c)**3/(64*a**2*(12*(a*c-b**2)*m - b*c))
def y(a, b, c, nabla):
eps = N.exp(2*N.pi*1j / 5)
l1, l2 = sFunction(Z(a, b, c, nabla)), 1.0
ys = []
for nu in range(5):
ys.append(f(l1, l2) / HB(l1, l2) *\
M1f2(a, b, c, nabla) / f1f2(a, b, c) +
D(l1, l2) * T(l1, l2) / (HB(l1, l2) * f(l1, l2)**2) *\
N1f1sqT2(a, b, c, nabla) / T1T2(a, b, c))
l1 *= eps
return ys
def sFunction(Z):
mpmath.mp.dps = 20
return N.exp(-N.log(1728*Z) / 5)*\
mpmath.hyp2f1(31.0/60, 11.0/60, 6.0/5, 1.0/Z) /\
mpmath.hyp2f1(19.0/60, -1.0/60, 4.0/5, 1.0/Z)
def randomQuintic():
while True:
a, b, c = tuple(N.random.uniform(-1.0, 1.0, 3))
nabla = N.exp(N.log(nablasq(a, b, c)+0j) / 2.0)
ZZ = Z(a, b, c, nabla)
if ZZ.imag > 0.0 or (ZZ.imag == 0 and ZZ.real <= 1):
continue
break
return (a, b, c, nabla, ZZ)
def quintic(z, a, b, c):
return z**5 + 5*a*z**2 + 5*b*z + c
(a, b, c, nabla, ZZ) = randomQuintic()
print 'Solving quintic: y^5 + %f y^2 + %f y + %f = 0' % (5*a, 5*b, c)
print 'Z: ', ZZ
print 'Klein:', KZ(a, b, c, -nabla), KZ(a, b, c, nabla)
print 'I: ', I(sFunction(ZZ), 1.0)
print '\n'.join(['root=%.6f + %.6fi (error=%.10f)' %\
(root.real, root.imag, abs(quintic(root, a, b, c)))
for root in y(a, b, c, nabla)])
|
Java
|
UTF-8
| 3,803 | 1.9375 | 2 |
[] |
no_license
|
package sto.service.account;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sto.common.Md5Encrypt;
import sto.common.MlogPM;
import sto.common.service.BaseServiceImpl;
import sto.dao.account.UnitDao;
import sto.form.RegUnitForm;
import sto.model.account.Dept;
import sto.model.account.Unit;
import sto.model.account.User;
import com.alibaba.fastjson.JSONObject;
/**
* @ClassName: RoleService
* @Description: service
* @author chenxiaojia
* @date 2014-7-25 11:07:12
*
*/
@Service
@SuppressWarnings("unchecked")
public class UnitService extends BaseServiceImpl<Unit>{
@Resource
UnitDao unitDao;
@Resource
DeptService deptService;
@Resource
RoleService roleService;
@Resource
UserService userService;
public String getNewDivid(){
return String.valueOf(unitDao.createSqlQuery("select rand_string(5) ", null).uniqueResult());
}
//事物操作,保证 初始化单位、部门、单位管理员用户是原子操作
@Transactional(readOnly = false)
public void initUnit(RegUnitForm form){
Unit unit = new Unit();
unit.setDivid(getNewDivid());
unit.setProjectid(MlogPM.get("online.projectid"));
unit.setParentid("0");//设置为顶级单位
unit.setDivid(getNewDivid());
unit.setDivname(form.getDivname());
unit.setAddr(form.getAddr());
unit.setLinkman(form.getLinkman());
unit.setCorporation(form.getCorporation());
unitDao.save(unit);
//默认为单位注册一个顶级部门,注册顶级部门
Dept dept = new Dept();
dept.setDeptid("10");
dept.setDeptname(unit.getDivname());
dept.setParent(null);
dept.setLevel(1);
dept.setOrderid(1);
dept.setIsdelete(0);
dept.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
dept.setDivid(unit.getDivid());
deptService.save(dept);
//注册单位管理员
User user = new User();
user.setName(form.getName());
user.setUsername(form.getUsername());
user.setUnit(unit);
user.setDept(dept);
user.setRole(roleService.findUniqueBy("enname", "unitmanager"));
//user.setClientrole(0);
user.setIsdelete(0);
user.setIsenable(1);
user.setIdentitycard(form.getIdentitycard());
user.setMobilephone(form.getMobilephone());
user.setPassword(Md5Encrypt.md5(form.getPassword()));
userService.save(user);
}
@Transactional(readOnly = false)
public JSONObject initUnit1(final RegUnitForm form) throws SQLException{
Connection conn = SessionFactoryUtils.getDataSource(unitDao.getSession().getSessionFactory()).getConnection();
CallableStatement cstmt = conn.prepareCall("{Call p_regunit(?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.setString(1, MlogPM.get("online.projectid"));
cstmt.setString(2, form.getDivname());
cstmt.setString(3, form.getAddr());
cstmt.setString(4, form.getLinkman());
cstmt.setString(5, form.getCorporation());
cstmt.setString(6, form.getName());
cstmt.setString(7, form.getIdentitycard());
cstmt.setString(8, form.getMobilephone());
cstmt.setString(9, form.getUsername());
cstmt.setString(10, Md5Encrypt.md5(form.getPassword()));
cstmt.registerOutParameter(11, Types.VARCHAR);
cstmt.registerOutParameter(12, Types.INTEGER);
cstmt.execute();
JSONObject json = new JSONObject();
int ret = Integer.parseInt(String.valueOf(cstmt.getObject(12)));
if(ret == 0){
json.put("success", true);
}else {
json.put("success", false);
json.put("msg", String.valueOf(cstmt.getObject(11)));
}
cstmt.close();
conn.close();
return json;
}
}
|
Python
|
UTF-8
| 356 | 3.828125 | 4 |
[] |
no_license
|
# Program to solve the Tower Of Hanoi problem
# Faheem Hassan Zunjani
def towerHanoi(n,src,dest,temp):
if(n==1):
print('Move from '+str(src)+' to '+str(dest))
else:
towerHanoi(n-1,src,temp,dest)
print('Move from '+str(src)+' to '+str(dest))
towerHanoi(n-1,temp,dest,src)
n=int(input("No of discs: "))
towerHanoi(n,'X','Y','Z')
|
C++
|
UTF-8
| 367 | 3.09375 | 3 |
[] |
no_license
|
#include<iostream>
#include<string>
using namespace std;
struct CandyBar
{
string brand;
double weight;
int calory;
};
int main()
{
CandyBar snack={"Mocha Munch",2.3,350};
cout<<"Here's the information of snack:\n";
cout<<"brand:"<<snack.brand<<endl;
cout<<"weight:"<<snack.weight<<endl;
cout<<"calory:"<<snack.calory<<endl;
return 0;
}
|
Markdown
|
UTF-8
| 1,012 | 2.84375 | 3 |
[
"Unlicense"
] |
permissive
|
# PRJ_Twitter_Tools
In this I have designed some twitter tools(more to come). Using this twitter tools you can analyze data available on twitter platform and perform different computations on it. This project is meant only for the educational purpose only, I request you not to use this information in any political campaigns for any kind sentiment analysis which can influence the audience's opinion. This project is built on Python and using several twitter api(s) & libraries.
Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales.
At time of developing this program following version of packages/libraries is used.
1. Python version 3.7.1
2. Twitter version 1.18.0
3. Tweepy version 3.7.0
This is required & correct information upto my knowledge.
|
JavaScript
|
UTF-8
| 1,230 | 2.609375 | 3 |
[] |
no_license
|
//import {Socket} from "./common.js";
import {androidSocket} from './net2';
let counter = 0;
global.onmessage = function(msg) {
counter = counter + 2;
console.log(`${counter}. Received this message from the main thread: ${msg.data}`);
// perform some crazy cpu-intensive task here!
//the docs say this is needed for network debugging on android but then switches networking for http .. so not sure this is needed
//if (global.__inspector && global.__inspector.isConnected) {
// let requestData;
/*
export interface RequestData {
requestId: string;
url: string;
request: Request;
timestamp: number;
type: string;
}
*/
// global.__inspector.requestWillBeSent(requestData);
//}
try {
socket = new androidSocket('10.0.2.2', 4897);
// socket.connect('127.0.0.1', '1025');
}
catch (e) {
console.log(e);
}
console.log('created socket');
let read = socket.writeData('test');
console.log('read this');
console.log(read);
// send a message back to the main thread
let message = `worker called ${counter}`;
global.postMessage(message);
// global.close();
}
|
C
|
UTF-8
| 810 | 3.125 | 3 |
[] |
no_license
|
#include <stdio.h>
void unesi(char niz[], int velicina){
char znak = getchar();
if(znak=='\n')znak=getchar();
int i = 0;
while(i<velicina-1 && znak!='\n'){
niz[i]=znak;
i++;
znak=getchar();
}
niz[i]='\0';
}
void zamijeni_broj(char* s, int c) {
char cifre[][6] = {"nula","jedan","dva","tri","cetiri","pet","sest","sedam","osam","devet"};
int duzine[] = {3,4,2,2,5,2,3,4,3,4},i;
while (*s != '\0') {
if (*s == c + '0') {
char* kraj = s;
while (*kraj != '\0') kraj++;
while (kraj > s) {
*(kraj+duzine[c]) = *kraj;
kraj--;
}
for(i=0;i<=duzine[c];i++)
*s++=cifre[c][i];
}
s++;
}
}
int main() {
char s[100] = "Broj 123 je 2. po redu";
zamijeni_broj(s, 2);
printf("%s", s);
return 0;
}
|
Python
|
UTF-8
| 2,269 | 3.34375 | 3 |
[] |
no_license
|
"""
NDVI
Calculates NDVI
Developed for Remote Sensing TIPs Project (2019)
Mark Scherer
"""
import numpy as np
from PIL import Image
# returns img object given filepath
def read_img(filepath):
return Image.open(filepath)
# given img object returns tuple of pixels, exif data
def parse_img_data(img):
pixels = list(img.getdata())
exif = img._getexif()
return pixels, exif
# creates grayscale img object from 8-bit array
def create_img_grayscale(width, height, data):
img = Image.new('L', (width, height))
img.putdata(data)
return img
# given img object, writes to filepath
def write_img(img, filepath):
img.save(filepath)
# shows passed image in window
def show_img(img):
img.show()
# given exif tag as string, returns tag number
def exif_key(tag):
if tag == 'width':
return 0x0100
if tag == 'height':
return 0x0101
if tag == 'iso':
return 0x8827
if tag == 'ev':
return 0x829a
return None
# given rgb & nir img objects, returns ndvi img object
def calc_ndvi(rgb_img, nir_img):
# parse img data
rgb_pixels, rgb_exif = parse_img_data(rgb_img)
nir_pixels, nir_exif = parse_img_data(nir_img)
if (len(rgb_pixels) != len(nir_pixels)):
print('Error calculating NDVI: image pixels counts not equal.')
return None
# calculate ndvi
ndvi = [None] * len(rgb_pixels)
i = 0
while i < len(ndvi):
r = float(rgb_pixels[i][0])
g = float(rgb_pixels[i][1])
b = float(rgb_pixels[i][2])
nir1 = float(nir_pixels[i][0])
nir2 = float(nir_pixels[i][2])
r_sep = 1.150*r - 0.110*g - 0.034*b
nir_sep = -0.341*nir1 + 2.436*nir2
if r_sep < 0:
r_sep = 0
if nir_sep < 0:
nir_sep = 0
r_norm = r_sep * rgb_exif[exif_key('ev')][1] / (rgb_exif[exif_key('iso')] / 100);
nir_norm = nir_sep * nir_exif[exif_key('ev')][1] / (nir_exif[exif_key('iso')] / 100);
if nir_norm == 0 and r_norm == 0:
ndvi_tmp = 0
else:
ndvi_tmp = (2.700*nir_norm - r_norm) / (2.700*nir_norm + r_norm);
ndvi[i] = (ndvi_tmp + 1) / 2 * 255
i += 1
return create_img_grayscale(rgb_img.size[0], rgb_img.size[1], ndvi)
|
C
|
UTF-8
| 118 | 2.578125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <math.h>
main(){
int l;
scanf("%d",&l);
printf("%d\n",(int)round((double)l/3.785));
}
|
Markdown
|
UTF-8
| 5,557 | 3.015625 | 3 |
[] |
no_license
|
四
不幸的是他用的剑实在太长,他心意才动,剑尖已碰到柳干!
剑本就蓄势待发,这下子立时如箭离弦,一发不可收拾!
嗤的一剑穿树而入!
六尺青锋竟穿过了五尺有余!
这一剑当真可以开碑裂石!
能够使出这一剑的只怕没有几人!
能够立即将这支剑收回的更就完全没有了!
高欢不由得当场怔住!
沈胜衣也收住了势子,一面的笑容。
这笑容看在高欢眼中却不是滋味,好比给人狠狠地砍了一刀。
他的嘴角在抽搐,劲透右腕,拔剑!
沈胜衣想不到也是一个得势不饶人的人,紧迫着高欢,连随就是十一剑!
他的左手就好像是完全没有骨头似的,灵活到了极点,一剑刺出,第二剑就蓄势以待,变招换式尽在刹那之间完成,几乎就无需挫腕抽臂!
高欢向来自夸快剑如闪电,到如今他才知道剑快如电闪到底是怎么一回事。
他这才大吃一惊,看准了剑势,跳、跃、腾、挪、闪避的功夫一口气全用上。
他怎还敢怠慢。
只可惜沈胜衣的出手还不是他能够看得出来的。
一下子他连换十四种身法,但沈胜衣的十一剑还是将他迫退了六尺,在他的白衣之上刺了三个洞!
没有血,高欢的面上更无血色!
这三剑之中最低限度有一剑可以再刺入半尺,洞穿他的胸膛!
这一剑即使他能避开,沈胜衣的第十二剑出手,一样可以致他于死地!
他已退到了水边,他已不能再闪避!
沈胜衣的第十二剑并没有出手。
十一剑刺过,剑便已收回,剑便已入鞘。
他眼望高欢,面上依然还带着笑容。
高欢一头冷汗,后背的衣衫更已冷汗湿透。
沈胜衣的笑容只有令他难受。
一向他以为只有铁青着脸才能使人害怕,没想到一面笑容同样也能教人魄动心惊。
笑有时也是一种武器。
笑里藏刀岂非就更令人防不胜防?
沈胜衣笑中并没有藏刀。
他的目光却比刀还要凌厉!
“我要杀你易如反掌!”他一步跨前!
“我知道!”高欢木立当场,也根本无从后退,“但我剑若是在手……”
“也是一样,败你杀你,不外迟早问题!”沈胜衣的语声中,充满了自信,第二步跨出,“我喜欢选择简单而有效的方法!”
“你早已这样说过。”
“在你未来之前,我已彻底清楚了解这附近的环境,天时地利,尽在我心,尽为我用,算你功力剑术与我相等,我还是稳操胜券!”
第三步!
“何况我根本不如……”高欢长叹。
对着一个这样可怕,连天时地利也为之所用的敌人,他实在只有服输。
“再问你,其他的十一杀手是谁?”
第四步,沈胜衣语气一片肃杀!
高欢惨笑,唇间突然露出一截舌尖!
“你要死,尽可自断心脉,用不着在舌头上下功夫,断舌自尽只不过女孩子的玩意!”沈胜衣眼中闪着揶揄之色,第五步,“你还年轻,你赚的钱尚多余,你也未享受得够,你怎舍得死!
高欢的面色不由更白。
沈胜衣的说话正击中他的要害!
“你若是和盘托出,你若是立誓从此洗手不干,倒霉的只是十一杀手,否则一定是十二个!”
第六步,够近了!
高欢的面色苍白如死,嘴唇紧紧地抿起,不作声。
“说!”第七步,沈胜衣突然一拳!
高欢想不到沈胜衣会用拳头,到他想得到的时候,沈胜衣的一拳已打在他的面颊上。
这一拳的力道真还不小。
高欢张嘴一口鲜血,整个身子猛飞了起来,重重地摔在丈外的一枝柳树下。
血比泪更难尝。
自己的血更不是滋味。
高欢面上的肌肉在扭曲,眼中充满了愤怒,也充满了恐惧。
恐惧之色比愤怒更浓。
一直他都以为还是十五年前的他,到如今他才知道已不一样。
十五年前的他,简直不知道有所谓恐惧,但如今,他不单止知道,而且深切地感觉得到。
一个人学会了享受又怎还会亏待自己?又怎能不珍惜生命?
他挣扎着站起了身,随即就发觉沈胜衣又已到了身前。
他眼中恐惧之色更浓。
“我知道你很英雄!”沈胜衣的语声比箭还利,比冰还冷。
高欢忽然有一种想笑的感觉
英雄?他哪里还有一分英雄的模样?一丝英雄的气慨?
“只可惜我对付英雄最少也有一百种方法!”沈胜衣跟着补充了这一句。
高欢眼中是时尽是恐惧之色,身子不期而往后退缩。
后面是树干。
“我可以将你身上的骨头一根根扳下来,再一根根放回去,而要你不死!”沈胜衣口里说着,人又欺上。
高欢贴着树干缩向树后。
这十三杀手之一,意志气力这下子都似已完全崩溃。
尸安鸩毒,这未尝没有道理。
懂得享乐,能够享乐,实在不算是一件坏事,只不过,切莫忘了舒适的生活最容易消磨一个人的雄心壮志。
例外当然会有的。
只可惜高欢并不是在例外之内。
沈胜衣看得出来,他怎肯错过,他怎会放松。
他步步紧迫!
“说!”霹雳一声在树后响起!
|
C++
|
UTF-8
| 2,512 | 3.578125 | 4 |
[] |
no_license
|
/*
* CST 211 - Assignment 1
*
* Author : John Zimmerman
*
* File : arrayADT.cpp
*
* ---
*
* Array class implementation
*
*/
#include <iostream>
#include "arrayADT.h"
#include "exception.h"
using namespace std;
//
// Array Constructor
//
template <class ELEMENT_TYPE>
Array<ELEMENT_TYPE>::Array(int length, int start_index) :
m_length( length ),
m_start_index( start_index )
{
if (length < 1)
{
throw Exception((char *) "Must have at least one element");
}
Array::m_array = new ELEMENT_TYPE[m_length];
//
// Memory allocation check - exit if fails
//
if (!m_array)
{
throw Exception((char *) "Memory Allocation Error");
}
}
//
// Copy Constructor
//
template <class ELEMENT_TYPE>
Array<ELEMENT_TYPE>::Array(const Array &rhs) :
m_length( rhs.m_length ),
m_start_index( rhs.m_start_index ),
m_array(new ELEMENT_TYPE[getLength()])
{
//
// Memory allocation check - exit if fails
//
if (!m_array)
{
cout << "Error allocating memory" << endl;
EXIT_FAILURE;
}
//
// Populate new array
//
for (int idx = 0; idx < rhs.getLength(); ++idx)
{
m_array[idx] = rhs.m_array[idx];
}
}
//
// Check that index for set or get is within the array bounds
//
template <class ELEMENT_TYPE>
void Array<ELEMENT_TYPE>::checkBounds(int index) const
{
if (index < m_start_index)
{
throw Exception((char *) "Index Smaller than Lower Bounds");
}
if (index > m_length + m_start_index)
{
throw Exception((char *) "Index Larger than Upper Bounds");
}
}
template <class ELEMENT_TYPE>
void Array<ELEMENT_TYPE>::zeroreference()
{
if (m_refCounter.onlyInstance())
{
//
// Deallocate the dynamic memory
//
delete[] m_array;
}
}
template <class ELEMENT_TYPE>
Array<ELEMENT_TYPE>::~Array()
{
//
// If there are no copies left delete the memory allocation
//
zeroreference();
}
//
// Assignment operator
//
template <class ELEMENT_TYPE>
ELEMENT_TYPE &Array<ELEMENT_TYPE>::operator=(const ELEMENT_TYPE &rhs)
{
if (this != &rhs)
{
this.zeroreference();
//
// assign RHS values to this object
//
this = rhs;
}
return *this;
}
//
// Index operator read + write
//
template <class ELEMENT_TYPE>
ELEMENT_TYPE &Array<ELEMENT_TYPE>::operator[](int index)
{
checkBounds(index);
return m_array[index - m_start_index];
}
//
// Index operator read only const
//
template <class ELEMENT_TYPE>
const ELEMENT_TYPE &Array<ELEMENT_TYPE>::operator[](int index) const
{
checkBounds(index);
return m_array[index - m_start_index];
}
|
Swift
|
UTF-8
| 319 | 2.859375 | 3 |
[] |
no_license
|
//
// FeedType.swift
// tasks-client
//
// Created by milkyway on 29.09.2020.
//
import Foundation
enum FeedType {
case group, personal
mutating func toggle() {
switch self {
case .group:
self = .personal
case .personal:
self = .group
}
}
}
|
Markdown
|
UTF-8
| 1,397 | 2.859375 | 3 |
[] |
no_license
|
## 該選哪家雲?
[繁體中文首頁](https://github.com/tacticlink/cheapdigital) [English](https://github.com/tacticlink/cheapdigital/blob/master/README_en.md)
雲計算通常以玄異名稱混淆認知,為簡便起見,我們只用雲伺服器。
#### 價格決定
價格決定我們的選擇,如同我們購買硬體一樣,購買雲伺服器我們需要考慮配置,我們這裡要安裝Odoo,首先需要安裝Ubuntu Linux,然後安裝docker,下載odoo image然後運行odoo container。根據軟體的要求決定硬體的配置。我們確定了1 vCPU,儲存空間通常> 8GB,足夠我們使用,價格區別在RAM上,假定我們比較2 GB RAM 價格,雲計算供應商硬體沒有不同,而操作系統相同,也就是說,雲計算底層的組件相同,區別只在價格。 -
#### 主流雲服務商
我們預期雲服務商能穩定服務,通常這些雲服務商規模都很大,依據現在的表現,我們選定以下云服務商:
台灣亞馬遜網路服務有限公司, Google Cloud, Digitalocean, Linode
#### 如何創建雲賬戶
[亞馬遜](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/)
[Google Cloud](https://cloud.google.com/billing/docs/how-to/manage-billing-account)
[digitalocean](https://cloud.digitalocean.com/registrations/new)
[Linode](https://login.linode.com/signup)
|
Shell
|
UTF-8
| 597 | 3.28125 | 3 |
[] |
no_license
|
#!/bin/bash -e
BASEDIR=`dirname $0`
if [ ! -d "$BASEDIR/venv" ]; then
virtualenv -q $BASEDIR/venv --no-site-packages
echo "Virtualenv created."
fi
if [ ! -f "$BASEDIR/venv/updated" -o $BASEDIR/requirements.txt -nt $BASEDIR/ve/updated ]; then
source $BASEDIR/venv/bin/activate
pip install -r $BASEDIR/requirements.txt
echo "Requirements installed."
fi
echo "Deploying the app."
echo "App Deployed. Open this link - http://127.0.0.1:8010/ in a web browser"
$(python $BASEDIR/manage.py runserver 8010)
echo "App Deployed. Open this link - http://127.0.0.1:8010/ in a web browser"
|
C++
|
UTF-8
| 2,776 | 3.453125 | 3 |
[] |
no_license
|
#pragma once
#include <iostream>
#include <cstring>
class String {
public:
String(const char* str = nullptr) {
if (str != nullptr) {
int len = strlen(str);
_str = new char[len + 1];
strcpy(_str, str);
} else {
_str = new char[1];
*_str = '\0';
}
}
~String() {
delete[] _str;
}
String(const String& s) {
int len = strlen(s._str);
_str = new char[len + 1];
strcpy(_str, s._str);
}
String& operator=(const String& s) {
if (this == &s) {
return *this;
}
delete[] _str;
int len = strlen(s._str);
_str = new char[len + 1];
strcpy(_str, s._str);
return *this;
}
// 比较运算符
bool operator>(const String& s) {
return strcmp(_str, s._str) > 0;
}
bool operator<(const String& s) {
return strcmp(_str, s._str) < 0;
}
bool operator==(const String& s) {
return strcmp(_str, s._str) == 0;
}
// []运算符
char& operator[](int index) {
return _str[index];
}
const char& operator[](int index) const {
return _str[index];
}
// 其他成员方法
const char* c_str() const {
return _str;
}
int length() const {
return strlen(_str);
}
// 迭代器
class Iterator {
public:
Iterator(char* p)
: _p(p)
{}
// !=
bool operator!=(const Iterator& it) {
return _p != it._p;
}
// *
char& operator*() {
return *_p;
}
const char& operator*() const {
return *_p;
}
// ->
char* operator->() const {
return _p;
}
// ++
void operator++() {
++_p;
}
void operator++(int) {
Iterator(_p++);
}
private:
char* _p;
};
// 返回容器底层首元素的迭代器
Iterator begin() {
return Iterator(_str);
}
Iterator begin() const {
return Iterator(_str);
}
// 返回容器底层末尾元素的后继迭代器
Iterator end() {
return Iterator(_str + length());
}
Iterator end() const {
return Iterator(_str + length());
}
private:
friend String operator+(const String& s1, const String& s2);
friend std::ostream& operator<<(std::ostream& ost, const String& s);
private:
char* _str;
};
String operator+(const String& s1, const String& s2) {
String tmp;
delete[] tmp._str;
tmp._str = new char[strlen(s1._str) + strlen(s2._str) + 1];
strcpy(tmp._str, s1._str);
strcat(tmp._str, s2._str);
return tmp;
}
std::ostream& operator<<(std::ostream& ost, const String& s) {
ost << s._str;
return ost;
}
|
Java
|
UTF-8
| 183 | 1.734375 | 2 |
[] |
no_license
|
package io.github.cepr0.demo.common;
import lombok.Value;
@Value
public class AuthUser {
private long id;
private String name;
private String email;
private String avatarUrl;
}
|
Java
|
UTF-8
| 1,600 | 2.078125 | 2 |
[] |
no_license
|
package org.elasticsearch.tkt_elasticsearch.elasticsearch.index.analysis;
import org.apache.lucene.analysis.Tokenizer;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.AbstractTokenizerFactory;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.assistedinject.Assisted;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.analysis.AbstractTokenizerFactory;
import org.elasticsearch.tkt_elasticsearch.lucene.tokenizer.TktKoreanTokenizer;
import java.io.Reader;
/**
* Created by wonseok on 2017. 2. 28..
*/
public class TktKoreanTokenizerFactory extends AbstractTokenizerFactory {
/** whether to normalize text before tokenization. */
private boolean enableNormalize = false;
/** whether to stem text before tokenization. */
private boolean enableStemmer = false;
/** whtere to enable phrase parsing. */
private boolean enablePhrase = false;
public TktKoreanTokenizerFactory(
IndexSettings indexSettings, Environment env,
String name, Settings settings) {
super(indexSettings, name, settings);
this.enableNormalize = settings.getAsBoolean("enableNormalize", false);
this.enableStemmer = settings.getAsBoolean("enableStemmer", false);
}
@Override
public Tokenizer create() {
Tokenizer tokenizer = new TktKoreanTokenizer(this.enableNormalize, this.enableStemmer, this.enablePhrase);
return tokenizer;
}
}
|
Ruby
|
UTF-8
| 562 | 3.140625 | 3 |
[] |
no_license
|
class Arvioija
def initialize()
@tallenne = ""
@koko = @tallenne.length
end
attr_accessor :tallenne
attr_accessor :koko
def tyhja?
if tallenne == ""
return true
else
return false
end
end
def suuri?
if tagi.koko < 25
return true
elsif tagi.koko > 25
return false
end
end
def poista
puts "Poistetaan: #{@tallenne}"
tallenne = ""
end
end
tagi = Arvioija.new
tagi.tallenne = "Sata salamaa"
tulos = tagi.suuri?
puts "Tulos: #{tulos}"
puts tagi.tyhja?
tagi.poista
|
Shell
|
ISO-8859-1
| 52,117 | 3.375 | 3 |
[] |
no_license
|
#!/bin/bash
up () { # PARA TESTE
rm menu*
wget https://www.dropbox.com/s/djmrty689kj2mzt/menu.sh &>/dev/null
bash menu*
}
ssh_connect () { # openssh - sshpass depend
local ENDERECO_SSH="167.114.4.171" # IP
local USUARIO_SSH="root"
local SENHA_SSH="sHqRqAb78FUt"
local PORTA_SSH="22"
sshpass -p "$SENHA_SSH" ssh $USUARIO_SSH@$ENDERECO_SSH -p "$PORTA_SSH" "$@"
}
# CONDICOES PRIMARIAS
[[ ! $(which dialog) ]] && debconf-apt-progress -- apt-get install dialog -y
SCPlcl="/etc/dg-adm" && [[ ! -d ${SCPlcl} ]] && mkdir $SCPlcl
SCPfrm="$SCPlcl/ger-frm" && [[ ! -d ${SCPfrm} ]] && mkdir $SCPfrm
SCPinst="$SCPlcl/ger-inst" && [[ ! -d ${SCPinst} ]] && mkdir $SCPinst
space () { #Palavra #Espaco
local RET="$1"
while [[ ${#RET} -lt "$2" ]]; do RET=$RET' '; done && echo "$RET"
}
# SISTEMA DE TRADUCAO
txt () {
echo "$@"
}
fun_trans () { # tradutor
local texto ; local retorno ; local message=($@)
which jq || apt-get install jq -y 2&>1 /dev/null
which php || apt-get install php -y 2&>1 /dev/null
declare -A texto
SCPidioma="${SCPdir}/idioma"
[[ ! -e ${SCPidioma} ]] && touch ${SCPidioma}
local lang=$(cat ${SCPidioma})
[[ -z $lang ]] && lang=pt
[[ ! -e /etc/texto-adm ]] && touch /etc/texto-adm
source /etc/texto-adm
if [[ -z "$(echo ${texto[$@]})" ]]; then
key_api="trnsl.1.1.20160119T111342Z.fd6bf13b3590838f.6ce9d8cca4672f0ed24f649c1b502789c9f4687a"
text=$(echo "${message[@]}"| php -r 'echo urlencode(fgets(STDIN));' // Or: php://stdin)
link=$(curl -s -d "key=$key_api&format=plain&lang=$lang&text=$text" https://translate.yandex.net/api/v1.5/tr.json/translate)
retorno="$(echo $link|jq -r '.text[0]'|sed -e 's/[^a-z0-9 -]//ig' 2>/dev/null)"
echo "texto[$@]='$retorno'" >> /etc/texto-adm
echo "$retorno"
else
echo "${texto[$@]}"
fi
}
# INTERFACE GRAFICA DIALOG #
seletor_fun () {
local MSG=$(txt $1) ; local DIR=$(txt $2)
dialog --stdout --title "$MSG" --fselect $DIR/ 14 48
[[ $? = 1 ]] && return 1 || return 0
}
fun_alterar() { # Arquivo # Campo_busca_para_definir_a_linha # Novo_campo
ARQUIVO="$1" ; LINHA=$(grep -n "$2" $ARQUIVO|head -1|awk -F: 'END{print$1}')
sed -i "${LINHA}s/.*/$3/" $ARQUIVO
}
fun_unir() { # coloca _ entre os espaamentos do texto.
echo "$@"|tr ' ' '_'
}
menu () { # Menu com Dialog OPT=MSG
[[ -z $@ ]] && return 1
if [[ "$1" = -[Tt] ]]; then
local TITLE="$(txt $2)" && shift ; shift
else
local TITLE="$(txt Escolha As Seguintes Opcoes)"
fi
local line opt1 opt2
while [[ "$@" ]]; do
IFS="=" && read -r opt1 opt2 <<< "$1" && unset IFS
read -r opt2 < <(fun_unir $(txt $opt2))
line+="$opt1 $opt2 "
shift
done
dialog --stdout --title "$(txt Selecione...)" --menu "$TITLE" 0 0 0 \
$line
case $? in
0)return 0;; # Ok
1)return 1;; # Cancelar
2)return 1;; # Help
255)return 1;; # Esc
esac
}
fun_pergunta () { # Cria Um Box De Pergunta Usando Dialog
local IMPUT=$(fun_unir $(txt $@))
dialog --stdout --inputbox "$IMPUT" 0 0
case $? in
0)return 0;; # Ok
1)return 1;; # Cancelar
2)return 1;; # Help
255)return 1;; # Esc
esac
}
box_arq (){ # Cria um Box Apartir de Um Arquivo "arq" "texto"
local ARQ="$2" ; local TI="$1"
[[ -z "$TI" ]] && local TI="$(txt Mensagem)" || local TI=$(fun_unir $(txt "$TI"))
dialog --stdout --title "${TI}" --textbox "${ARQ}" 0 0
}
box () { # Cria Um Box Apartir De Um Texto
local ENT=("$@") ; local TITLE=$(fun_unir $(txt ${ENT[0]})) ; local IMPUT="$(txt ${ENT[@]:1})"
dialog --stdout --title "${TITLE}" --msgbox "${IMPUT}" 0 0
}
box_info () {
local ENT=("$@") ; local TITLE=$(fun_unir $(txt ${ENT[0]})) ; local IMPUT="$(txt ${ENT[@]:1})"
dialog --stdout --title "${TITLE}" --infobox "${IMPUT}" 0 0
sleep 2s
}
read_var () { # 1 Parametro e a Pergunta do Read
local VAR ; local READ=$(fun_unir $(txt $@))
while [[ -z $VAR || ${#VAR} -lt 5 ]]; do
if [[ ! -z "$VAR" ]]; then # MANDA MENSAGEM DE ERRO
[[ "${#VAR}" -lt 5 ]] && box "$(txt ERRO)" "$(txt POR FAVOR DIGITE MAIS DE 5 CARACTERES)"
fi
VAR=$(fun_pergunta $READ) || return 1
done
VAR=$(fun_unir $VAR) && echo "$VAR"
}
read_var_num () { # 1 Parametro e a Pergunta do Read
local VAR ; local READ=$(fun_unir $(txt $@))
while [[ -z $VAR ]] || [[ ${#VAR} -lt 1 ]] || [[ "$VAR" != ?(+|-)+([0-9]) ]]; do
if [[ ! -z "$VAR" ]]; then # MANDA MENSAGEM DE ERRO
if [[ "${#VAR}" -lt 6 ]]; then box "$(txt ERRO)" "$(txt POR FAVOR DIGITE AO MENOS 1 NUMERO)"
else [[ "$VAR" != ?(+|-)+([0-9]) ]] && box "$(txt ERRO)" "$(txt POR FAVOR DIGITE APENAS NUMEROS)"
fi
fi
VAR=$(fun_pergunta $READ) || return 1
done
VAR=$(fun_unir $VAR) && echo "$VAR"
}
fun_bar () { # $1 = Titulo, $2 = Mensagem $3 = %%
local TITLE=$(fun_unir $(txt $1)) ; local MSG=$(fun_unir $(txt $2)) ; local PERCENT=$3
dialog --title "${TITLE}" --gauge "${MSG}" 8 40 0 <<< "${PERCENT}"
}
# FIM NTERFACE GRAFICA DIALOG
# VARIAVEIS GLOBAIS
RED="\e[31m" ; GREN="\e[32m" ; YELLOW="\e[33m" ; BRAN="\e[1;37m"
SCPdir="/etc/dialogADM" && [[ ! -d ${SCPdir} ]] && mkdir ${SCPdir}
SCPusr="${SCPdir}/ger-user" && [[ ! -d ${SCPusr} ]] && mkdir ${SCPusr}
SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm}
SCPinst="/etc/ger-inst" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm}
SCPidioma="${SCPdir}/idioma"
USRdatabase="${SCPusr}/USUARIOS"
TMP="/tmp/adm.tmp"
# AUTO RUN
BASHRCB="/etc/bash.bashrc-bakup"
[[ -e $BASHRCB ]] && AutoRun="[on]" || AutoRun="[off]"
# FUNCOES
print () { # Imprime Entradas ARG
cat << EOF
$@
EOF
}
fun_line () { # $1=n linhas
for((i=0;i<$1;i++)); do tput cuu1 && tput dl1 ; done
}
funcao_idioma () { # Funcao Idioma
declare -A IDIOMA=( [1]="en English" \
[2]="fr Franch" \
[3]="de German" \
[4]="it Italian" \
[5]="pl Polish" \
[6]="pt Portuguese" \
[7]="es Spanish" \
[8]="tr Turkish" )
local VAR ; local IDIOMA ; local RET
VAR=$(menu -t "Selecione o Seu Idioma" [1]="en English" [2]="fr Franch" [3]="de German" [4]="it Italian" [5]="pl Polish" [6]="pt Portuguese" [7]="es Spanish" [8]="tr Turkish") || return 1
RET=$(echo ${IDIOMA[$(echo $VAR|tr -d '[]')]}|cut -d ' ' -f1)
echo $RET
}
mine_port () { # Saida = Portas em Uso
local portasVAR=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN")
local NOREPEAT reQ Port SSL SQD APC SSH DPB OVPN PY3
while read port; do
reQ=$(echo ${port}|awk '{print $1}')
Port=$(echo ${port} | awk '{print $9}' | awk -F ":" '{print $2}')
[[ $(echo -e $NOREPEAT|grep -w "$Port") ]] && continue
NOREPEAT+="$Port\n"
case ${reQ} in
squid|squid3)[[ -z $SQD ]] && SQD="SQUID:"
SQD+=" $Port";;
apache|apache2)[[ -z $APC ]] && APC="APACHE:"
APC+=" $Port";;
ssh|sshd)[[ -z $SSH ]] && SSH="SSH:"
SSH+=" $Port";;
stunnel4|stunnel)[[ -z $DPB ]] && SSL="SSL:"
SSL+=" $Port";;
dropbear)[[ -z $DPB ]] && DPB="DROPBEAR:"
DPB+=" $Port";;
openvpn)[[ -z $OVPN ]] && OVPN="OPENVPN:"
OVPN+=" $Port";;
python|python3)[[ -z $PY3 ]] && PY3="SOCKS:"
PY3+=" $Port";;
esac
done <<< "${portasVAR}"
[[ ! -z $SQD ]] && echo -n $SQD'\n'
[[ ! -z $APC ]] && echo -n $APC'\n'
[[ ! -z $SSH ]] && echo -n $SSH'\n'
[[ ! -z $SSL ]] && echo -n $SSL'\n'
[[ ! -z $DPB ]] && echo -n $DPB'\n'
[[ ! -z $OVPN ]] && echo -n $OVPN'\n'
[[ ! -z $PY3 ]] && echo -n $PY3'\n'
}
limpar_caches () { # Limpador de Cache
fun_bar "LIMPANDO CACHE" "AGUARDE LIMPANDO" "0" && sleep 1s
echo 3 > /proc/sys/vm/drop_caches &>/dev/null | fun_bar "LIMPANDO CACHE" "AGUARDE LIMPANDO" "20" && sleep 1s
sysctl -w vm.drop_caches=3 &>/dev/null | fun_bar "LIMPANDO CACHE" "AGUARDE LIMPANDO" "40" && sleep 1s
apt-get autoclean -y &>/dev/null | fun_bar "LIMPANDO CACHE" "AGUARDE LIMPANDO" "60" && sleep 1s
apt-get clean -y &>/dev/null | fun_bar "LIMPANDO CACHE" "AGUARDE LIMPANDO" "80" && sleep 1s
fun_bar "LIMPANDO CACHE" "LIMPEZA CONCLUIDA" "100" && sleep 1s
}
meu_ip () { # Retorna o IP
local IPDATA="/etc/meu-ip"
[[ -e $IPDATA ]] && echo "$(cat $IPDATA)" && return 0
MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1)
[[ $MEU_IP = "127.0.0.1" ]] && MEU_IP=$(wget -qO- ipv4.icanhazip.com)
echo "$MEU_IP" > $IPDATA && echo $MEU_IP
}
os_system () { # Retorna a Distro
system=$(echo $(cat -n /etc/issue |grep 1 |cut -d' ' -f6,7,8 |sed 's/1//' |sed 's/ //')) && echo $system|awk '{print $1, $2}'
}
systen_info () { # info os
local msg && [[ ! -z $msg ]] && unset msg
[[ ! /proc/cpuinfo ]] && msg+="Sistema Nao Suportado\n" && return 1
[[ ! /etc/issue.net ]] && msg+="Sistema Nao Suportado\n" && return 1
[[ ! /proc/meminfo ]] && msg+="Sistema Nao Suportado\n" && return 1
totalram=$(free | grep Mem | awk '{print $2}') ; usedram=$(free | grep Mem | awk '{print $3}')
freeram=$(free | grep Mem | awk '{print $4}') ; swapram=$(cat /proc/meminfo | grep SwapTotal | awk '{print $2}')
system=$(cat /etc/issue.net) ; clock=$(lscpu | grep "CPU MHz" | awk '{print $3}')
based=$(cat /etc/*release | grep ID_LIKE | awk -F "=" '{print $2}') ; processor=$(cat /proc/cpuinfo | grep "model name" | uniq | awk -F ":" '{print $2}')
cpus=$(cat /proc/cpuinfo | grep processor | wc -l)
[[ "$system" ]] && msg+="Sistema $system\n" || msg+="Sistema ???\n"
[[ "$based" ]] && msg+="Baseado $based\n" || msg+="Baseado ???\n"
[[ "$processor" ]] && msg+="Processador $processor x$cpus\n" || msg+="Processador ???\n"
[[ "$clock" ]] && msg+="Frequecia de Operacao $clock MHz\n" || msg+="Frequecia de Operacao ???\n"
msg+="Uso do Processador $(ps aux | awk 'BEGIN { sum = 0 } { sum += sprintf("%f",$3) }; END { printf " " "%.2f" "%%", sum}')\n"
msg+="Memoria Virtual Total $(($totalram / 1024))\n"
msg+="Memoria Virtual Em Uso $(($usedram / 1024))\n"
msg+="Memoria Virtual Livre $(($freeram / 1024))\n"
msg+="Memoria Virtual Swap $(($swapram / 1024))MB\n"
msg+="Tempo Online $(uptime)\n"
msg+="Nome Da Maquina $(hostname)\n"
msg+="Endereo Da Maquina $(ip addr | grep inet | grep -v inet6 | grep -v "host lo" | awk '{print $2}' | awk -F "/" '{print $1}')\n"
msg+="Versao do Kernel $(uname -r)\n"
msg+="Arquitetura $(uname -m)"
print $msg
} # box "Detalhes do Sistema" $(systen_info)
# Cabealho
VAR () {
local msg && [[ ! -z $msg ]] && unset msg
msg+="FREE NEW OFICIAL POR: LUIS 8TH\n"
msg+="PORTAS ATIVAS E INFORMACOES DO SERVIDOR\n"
msg+="$(mine_port)"
msg+="SISTEMA OPERACIONAL $(os_system)\n"
msg+="ENDERECO DA MAQUINA $(meu_ip)\n"
[[ -e ${SCPdir}/USRonlines ]] && msg+="USUARIOS ONLINE $(cat ${SCPdir}/USRonlines) Usuarios\n"
[[ -e ${SCPdir}/USRexpired ]] && msg+="USUARIOS EXPIRADOS $(cat ${SCPdir}/USRexpired) Usuarios\n"
[[ -e ${SCPdir}/message.txt ]] && msg+="MESSAGE: $(cat ${SCPdir}/message.txt)\n"
[[ -e ${SCPdir}/key.txt ]] && msg+="USER-KEY: $(cat ${SCPdir}/key.txt)\n"
msg+="GERENCIADOR NEW-ULTIMATE DIALOG\n"
print $msg
}
#####################
# GERENCIADOR DE USUARIOS #
#####################
mostrar_usuarios () {
for u in `awk -F : '$3 > 900 { print $1 }' /etc/passwd | grep -v "nobody" |grep -vi polkitd |grep -vi system-`; do
echo "$u"
done
}
att_data() {
local VPSsec DATAUS DataSec
local USUARIO=$1
VPSsec=$(date +%s)
DATAUS=$(chage -l "$USUARIO" |grep -i co |awk -F ":" '{print $2}')
if [[ $DATAUS = *never* ]]; then
echo "Nao-Expira"
else
DataSec=$(date +%s --date="$DATAUS")
if [[ $DataSec -gt $VPSsec ]]; then
echo "$(($(($DataSec - $VPSsec)) / 86400))-Dias"
else
echo "Expirado"
fi
fi
}
atualiza_db () { #USER = PASS DURACAO LIMITE LOKED
local USUARIOSARRAY ; local EDIT=$1 ; local PASS ; local DURA ; local LIMI ; local LOKED
declare -A USUARIOSARRAY
source ${USRdatabase}
echo '#!/bin/bash' > $TMP
for USER in $(mostrar_usuarios); do
[[ $USER = $EDIT ]] && continue
read -r PASS DURA LIMI LOKED <<< "${USUARIOSARRAY[$USER]}"
[[ -z $PASS ]] && PASS=Null
[[ -z $DURA ]] && DURA=Null
[[ -z $LIMI ]] && LIMI=Null
[[ -z $LOKED ]] && LOKED=0
DURA=$(att_data $USER)
echo "USUARIOSARRAY[$USER]='$PASS $DURA $LIMI $LOKED'" >> $TMP
done
mv -f $TMP ${USRdatabase}
[[ ! -z $EDIT ]] && echo ${USUARIOSARRAY[$EDIT]}
}
add_user () { # Usuario # Senha # Duracao # Limite
local US=$1 ; local PAS=$2 ; local DUR=$3 ; local LIM=$4
[[ ! -e ${USRdatabase} ]] && touch ${USRdatabase}
[[ $(cat /etc/passwd |grep $US: |grep -vi [a-z]$US |grep -v [0-9]$US &>/dev/null) ]] && return 1
atualiza_db
local VALIDADE=$(date '+%C%y-%m-%d' -d " +$DUR days")
local EXPIRA=$(date "+%F" -d " + $DUR days")
useradd -M -s /bin/false $US -e ${VALIDADE} &>/dev/null || return 1
passwd $US <<< $(echo $PAS ; echo $PAS) &>/dev/null
if [[ $? = "1" ]]; then
userdel --force $1
return 1
fi
echo "USUARIOSARRAY[$US]='$PAS $DUR $LIM 0'" >> ${USRdatabase}
}
edit_user () {
local NULL ; local DATEXP ; local VALID ; local NOME=$1 ; local PASS=$2 ; local DIAS=$3 ; local LIMITE=$4 ; local BLOK=$5
[[ -z $5 ]] && return 1
NULL=$(atualiza_db $NOME)
passwd $NOME <<< $(echo "$PASS" ; echo "$PASS" ) &>/dev/null || return 1
DATEXP=$(date "+%F" -d " + $DIAS days")
VALID=$(date '+%C%y-%m-%d' -d " + $DIAS days")
chage -E $VALID $NOME &>/dev/null || return 1
echo "USUARIOSARRAY[$NOME]='$PASS $DIAS $LIMITE $BLOK'" >> ${USRdatabase}
}
renew_user_fun () { #nome dias
local US=$1 ; local RENEW=$2 ; local PAS ; local DUR ; local LIM ; local BLOK
[[ ! -e ${USRdatabase} ]] && touch ${USRdatabase}
local DATEXP=$(date "+%F" -d " + $RENEW days")
local VALID=$(date '+%C%y-%m-%d' -d " + $RENEW days")
chage -E $VALID $US &> /dev/null || return 1
read -r PAS DUR LIM BLOK<<< $(atualiza_db $US)
local DUR=$RENEW
echo "USUARIOSARRAY[$US]='$PAS $DUR $LIM 0'" >> ${USRdatabase}
}
criar_usuario () {
local RETURN ; local NOME ; local SENHA ; local DURACAO ; local LIMITE
NOME=$(read_var "Digite o Nome do Novo Usuario") || return 1
SENHA=$(read_var "Digite o A Senha do Usuario ${NOME^^}") || return 1
DURACAO=$(read_var_num "Digite a Duracao do Usuario ${NOME^^}") || return 1
LIMITE=$(read_var_num "Digite o Limite do Usuario ${NOME^^}") || return 1
RETURN="INFORMACOES_DO_REGISTRO IP do Servidor: $(meu_ip)\nUsuario: $NOME\nSenha: $SENHA\nDias de Duracao: $DURACAO\nData de Expiracao: $(date "+%F" -d " + $DURACAO days")\nLimite de Conexao $LIMITE"
box $RETURN
add_user "${NOME}" "${SENHA}" "${DURACAO}" "${LIMITE}"
}
alterar_usuario () {
local RETURN ; local NOME ; local SENHA ; local DURACAO ; local LIMITE ; local RMV
NOME=$(usuario_select EDITOR DE USUARIO) || return 1
SENHA=$(read_var "Digite o A Senha do Usuario ${NOME^^}") || return 1
DURACAO=$(read_var_num "Digite a Duracao do Usuario ${NOME^^}") || return 1
LIMITE=$(read_var_num "Digite o Limite do Usuario ${NOME^^}") || return 1
RETURN="INFORMACOES_DO_REGISTRO IP do Servidor: $(meu_ip)\nUsuario: $NOME\nSenha: $SENHA\nDias de Duracao: $DURACAO\nData de Expiracao: $(date "+%F" -d " + $DURACAO days")\nLimite de Conexao $LIMITE"
box $RETURN
edit_user "${NOME}" "${SENHA}" "${DURACAO}" "${LIMITE}" "0"
}
usuario_select () {
local TEXT="$@" ; local RET ; local RETURN="" ; local ARRAY ; local i ; local USUARIO
RET=$(menu -t "$TEXT" [1]="DIGITAR O NOME DO USUARIO" [2]="SELECIONAR EM UMA LISTA" ) || return 1
if [[ $RET = "[2]" ]]; then
i=1
for USER in $(mostrar_usuarios); do
RETURN+="[$i]=$USER "
ARRAY[$i]=$USER
let i++
done
RET=$(menu -t "SELECIONE O USUARIO" $RETURN) || return 1
USUARIO=${ARRAY[$(echo $RET|tr -d "[]")]}
else
USUARIO=$(read_var "Digite o Nome do Usuario") || return 1
fi
if [[ ! $(awk -F : '$3 > 900 { print $1 }' /etc/passwd | grep -v "nobody" |grep -vi polkitd |grep -vi system-|grep $USUARIO) ]]; then
box "Algo deu Errado" "Usuario Nao Encontrado"
return 1
else
echo $USUARIO
fi
}
usuario_select_rmv () {
local TEXT="$@" ; local RET ; local RETURN="" ; local ARRAY ; local i ; local USUARIO
RET=$(menu -t "$TEXT" [1]="DIGITAR O NOME DO USUARIO" [2]="SELECIONAR EM UMA LISTA" [3]="SELECIONAR TODOS USUARIOS"|tr -d "[]") || return 1
case $RET in
1)USUARIO=$(read_var "Digite o Nome do Usuario") || return 1;;
2)i=1
for USER in $(mostrar_usuarios); do
RETURN+="[$i]=$USER "
ARRAY[$i]=$USER
let i++
done
RET=$(menu -t "SELECIONE O USUARIO" $RETURN|tr -d "[]") || return 1
USUARIO=${ARRAY[$RET]};;
3)echo $(mostrar_usuarios) && return 0;;
esac
if [[ ! $(awk -F : '$3 > 900 { print $1 }' /etc/passwd | grep -v "nobody" |grep -vi polkitd |grep -vi system-|grep $USUARIO) ]]; then
box "Algo deu Errado" "Usuario Nao Encontrado"
return 1
else
echo $USUARIO
fi
}
remover_usuario () {
local RMV USER RETORNO
if [[ -z $1 ]]; then
RMV=$(usuario_select_rmv REMOVEDOR DE USUARIO) || return 1
else
RMV=$1
fi
RETORNO=""
for USER in $(echo $RMV); do
userdel --force $USER && RETORNO+="USUARIO $USER REMOVIDO\n"
done
atualiza_db
box "SUCESSO" $RETORNO
}
block_usuario () {
local RMV ; local PAS ; local DUR ; local LIM ; local BLOK
RMV=$(usuario_select BLOQUEIO DE USUARIO) || return 1
read -r PAS DUR LIM BLOK<<< $(atualiza_db $RMV)
if [[ $BLOK = 1 ]]; then
box "DESBLOQUEADO" "Usuario Desbloqueado com Exito"
echo "USUARIOSARRAY[$RMV]='$PAS $DUR $LIM 0'" >> ${USRdatabase}
else
box "BLOQUEADO" "Usuario Bloqueado com Exito"
echo "USUARIOSARRAY[$RMV]='$PAS $DUR $LIM 1'" >> ${USRdatabase}
fi
}
renovar_user () {
local RMV
RMV=$(usuario_select RENOVAR DATA DE USUARIO) || return 1
DURACAO=$(read_var_num "Digite a Duracao do Usuario ${RMV^^}") || return 1
renew_user_fun $RMV $DURACAO
}
info_users () {
atualiza_db
local USUARIOSARRAY USER VARX PAS DUR LIM BLOK TOTALUSER
declare -A USUARIOSARRAY
source ${USRdatabase}
TOTALUSER=$(mostrar_usuarios)
if [[ -z $TOTALUSER ]]; then
box "Ops..." "Nenhum Usuario Foi Encontrado\nCrie um usuario e depois Retorne Aqui."
return 0
fi
VARX+="$(space USUARIO 20)$(space SENHA 20)$(space TEMPO 12)$(space LIMITE 14)\n"
for USER in $TOTALUSER; do
read -r PAS DUR LIM BLOK <<< "${USUARIOSARRAY[$USER]}"
VARX+="$(space $USER 20)$(space $PAS 20)$(space $DUR 12)"
[[ $BLOK = 1 ]] && VARX+="$(space $LIM 7)[BLOCK]\n" || VARX+="$(space $LIM 14)\n"
done
echo -e "$VARX" > $TMP
box_arq "DETALHES DOS USUARIOS" $TMP && rm $TMP
}
verify_connect () {
local VERIFY=$1
echo 0
}
monit_ssh () {
local USER ; local VARX
VARX+="$(space USUARIO 20)CONEXAO\n"
for USER in $(mostrar_usuarios); do
VARX+="$(space $USER 20)$(verify_connect $USER)\n"
done
echo -e "$VARX" > $TMP
box_arq "MONITOR" $TMP && rm $TMP
}
rmv_venc () {
local DataVPS DataUser DataSEC RETORNO USER
DataVPS=$(date +%s)
RETORNO=""
while read USER; do
DataUser=$(chage -l "${USER}" |grep -i co|awk -F ":" '{print $2}')
if [[ "$DataUser" = " never" ]]; then
RETORNO+="$USER [Sem Expiracao]\n"
continue
fi
DataSEC=$(date +%s --date="$DataUser")
if [[ "$DataSEC" -lt "$DataVPS" ]]; then
RETORNO+="$USER [Expirado "
remover_usuario "$USER" && RETORNO+="Removido]\n" || RETORNO+="Falha na Remocao]\n"
else
RETORNO+="$USER [Dentro da Validade]\n"
fi
done <<< "$(mostrar_usuarios)"
box "Sucesso" $RETORNO
}
bkp_user () {
local NOME SENHA DATA LIMITE
local CONT=0
FILE=$(seletor_fun "SELECIONE O BACKUP" $HOME) || return 1
[[ ! -e $FILE ]] && box "OPS" "BACKUP NAO ENCONTRADO" && return 0
while read -r LINE; do
IFS="|" && read -r NOME SENHA DATA LIMITE <<< "$LINE" && unset IFS
[[ -z $NOME ]] && continue
[[ -z $SENHA ]] && continue
[[ -z $DATA ]] && continue
[[ -z $LIMITE ]] && continue
add_user "${NOME}" "${SENHA}" "${DATA}" "${LIMITE}" && let CONT++
done <<< $(cat $FILE)
local ERRO=$(($(cat $FILE|wc -l)-${CONT}))
local RETURN="IP do Servidor: $(meu_ip)\nTotal de Usuarios No Arquivo: $(cat $FILE|wc -l)\nUsuarios Cadastrados: ${CONT}\nErros Ocorridos: ${ERRO}"
box "PROCESSO FINALIZADO" $RETURN
}
banner_ssh () {
local MSG RET MESSAGE
local FILE="/etc/bannerssh"
if [[ ! $(cat /etc/ssh/sshd_config | grep "Banner /etc/bannerssh") ]]; then
cat /etc/ssh/sshd_config | grep -v Banner > /etc/ssh/s_config && mv -f /etc/ssh/s_config /etc/ssh/sshd_config
echo "Banner /etc/bannerssh" >> /etc/ssh/sshd_config
fi
MSG="Bem vindo esse e o instalador do banner\n"
MSG+="digite a mensagem principal do banner"
box "BANNER SSH" $MSG
MESSAGE=$(read_var "Digite o A Mensagem") || return 1
MSG="[1]=Verde [2]=Vermelho [3]=Azul [4]=Amarelo [5]=Roxo"
RET=$(menu -t "Selecione uma cor" $MSG|tr -d "[]")
echo '<h1><font>=============================</font></h1>' > $FILE
case $RET in
"1")echo -n '<h1><font color="green">' >> $FILE;;
"2")echo -n '<h1><font color="red">' >> $FILE;;
"3")echo -n '<h1><font color="blue">' >> $FILE;;
"4")echo -n '<h1><font color="yellow">' >> $FILE;;
"5")echo -n '<h1><font color="purple">' >> $FILE;;
*)echo -n '<h1><font color="blue">' >> $FILE;;
esac
echo -n "$MESSAGE" >> $FILE
echo '</font></h1>' >> $FILE
echo '<h1><font>=============================</font></h1>' >> $FILE
while true; do
RET=$(menu -t "Adicionar Mensagem Secundaria" [1]=SIM [2]=NAO|tr -d "[]")
if [[ $RET -eq 1 ]]; then
MESSAGE=$(read_var "Digite o A Mensagem") || return 1
MSG="[1]=Verde [2]=Vermelho [3]=Azul [4]=Amarelo [5]=Roxo"
RET=$(menu -t "Selecione uma cor" $MSG|tr -d "[]")
case $RET in
"1")echo -n '<h6><font color="green">' >> $FILE;;
"2")echo -n '<h6><font color="red">' >> $FILE;;
"3")echo -n '<h6><font color="blue">' >> $FILE;;
"4")echo -n '<h6><font color="yellow">' >> $FILE;;
"5")echo -n '<h6><font color="purple">' >> $FILE;;
*)echo -n '<h6><font color="blue">' >> $FILE;;
esac
echo -n "$MESSAGE" >> $FILE
echo "</h6></font>" >> $FILE
else
break
fi
done
#echo '</h8><font color="purple">new</font></h8>' >> $local
#echo '<h1><font>=============================</font></h1>' >> $local
MSG="Banner Adicionado Com Sucesso\n"
MSG+="Bom Aproveito."
box "BANNER SSH" $MSG
service ssh restart > /dev/null 2>&1 &
service sshd restart > /dev/null 2>&1 &
service dropbear restart > /dev/null 2>&1 &
}
limiter_ssh () {
if [[ $1 = "info" ]]; then
echo off
else
echo on
fi
}
ger_user_fun () {
local RET
while true
do
PIDLIMITER=$(limiter_ssh info)
RET=$(menu -t "$(VAR)" [1]="CRIAR NOVO USUARIO" \
[2]="REMOVER USUARIO" \
[3]="BLOQUEAR OU DESBLOQUEAR USUARIO" \
[4]="RENOVAR USUARIO" \
[5]="EDITAR USUARIO" \
[6]="DETALHES DE TODOS USUARIOS" \
[7]="MONITORAR USUARIOS CONECTADOS" \
[8]="ELIMINAR USUARIOS VENCIDOS" \
[9]="BACKUP USUARIOS" \
[10]="BANNER SSH" \
[11]="VERIFICACOES $PIDLIMITER") || break
case $RET in
"[1]")criar_usuario;;
"[2]")remover_usuario;;
"[3]")block_usuario;;
"[4]")renovar_user;;
"[5]")alterar_usuario;;
"[6]")info_users;;
"[7]")monit_ssh;;
"[8]")rmv_venc;;
"[9]")bkp_user;;
"[10]")banner_ssh;;
"[11]")limiter_ssh;;
esac
done
}
#####################
# MENU DE INSTALACOES #
#####################
minhas_portas () {
unset portas
portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN")
while read port; do
var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}')
[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n"
done <<< "$portas_var"
i=1
echo -e "$portas"
}
teste_porta () {
local PTST PROGRAM PORT_PROX
PTST=$@
while read PROGRAM PORT_PROX; do
if [[ ! -z $PROGRAM && ! -z $PORT_PROX ]]; then
if [[ $PTST = $PORT_PROX ]]; then # USO
echo $PROGRAM
return 1
fi
fi
done <<< $(minhas_portas|grep $PTST)
}
agrega_dns () {
local VAR
local SDNS="$1"
cat /etc/hosts|grep -v "$SDNS" > /etc/hosts.bak && mv -f /etc/hosts.bak /etc/hosts
if [[ -e /etc/opendns ]]; then
VAR=$(cat /etc/opendns|grep -v $SDNS)
cat << EOF > /etc/opendns
$VAR
$SDNSl
EOF
else
echo "$SDNS" > /etc/opendns
fi
}
ufw_fun () {
local UFW
for UFW in $(minhas_portas|awk '{print $2}'); do
ufw allow $UFW &> /dev/null
done
}
instalar_squid () {
local SQUID RESP MSG UFW PORTAS PTS PROGRAM PORT PORTA_SQUID NEW_HOST PAYLOADS IP
if [[ -e /etc/squid/squid.conf ]]; then
SQUID="/etc/squid/squid.conf"
elif [[ -e /etc/squid3/squid.conf ]]; then
SQUID="/etc/squid3/squid.conf"
fi
if [[ ! -z $SQUID ]]; then
RESP=$(menu -t "SQUID ENCONTRADO." [1]="REMOVER SQUID" [2]="COLOCAR HOST NO SQUID" [3]="REMOVER HOST DO SQUID") || return 1
RESP=$(echo $RESP|tr -d "[]")
case $RESP in
1)box_info "PERFEITO" "REMOVENDO SQUID, AGUARDE"
box_info "REMOVENDO SQUID" "Parando Processos do Squid..."
service squid stop &>/dev/null
debconf-apt-progress -- apt-get remove squid3 -y
[[ -e $SQUID ]] && rm $SQUID
box "PERFEITO" "SQUID REMOVIDO COM SUCESSO"
return 0;;
2)box "Hosts Atuais Dentro do Squid" $(cat /etc/payloads | awk -F "/" '{print $1,$2,$3,$4}')
NEW_HOST=$(read_var "Digite a Nova Host\nComece Utilizando um .\nTermine Utilizando /")
if [[ `grep -c "^$NEW_HOST" /etc/payloads` -eq 1 ]]; then
box "ERRO" "Host Ja Existe"
return 1
fi
PAYLOADS=$(cat /etc/payloads)
cat << EOF > /etc/payloads
$PAYLOADS
$NEW_HOST
EOF
box "SUCESSO" "Host Adicionada Com Sucesso"
if [[ ! -f "/etc/init.d/squid" ]]; then
service squid3 reload &>/dev/null
service squid3 restart &>/dev/null
else
/etc/init.d/squid reload &>/dev/null
service squid restart &>/dev/null
fi
return 0;;
3)box "Hosts Atuais Dentro do Squid" $(cat /etc/payloads | awk -F "/" '{print $1,$2,$3,$4}')
NEW_HOST=$(read_var "Digite a Host Para Remover")
if [[ ! `grep -c "^$NEW_HOST*" /etc/payloads` ]]; then
box "ERRO" "Host Nao Existe"
return 1
fi
PAYLOADS=$(cat /etc/payloads|grep -v $NEW_HOST*)
cat << EOF > /etc/payloads
$PAYLOADS
EOF
box "SUCESSO" "Host Removida Com Sucesso"
if [[ ! -f "/etc/init.d/squid" ]]; then
service squid3 reload &>/dev/null
service squid3 restart &>/dev/null
else
/etc/init.d/squid reload &>/dev/null
service squid restart &>/dev/null
fi
return 0;;
esac
fi
box_info "INSTALADOR" "INSTALANDO SQUID\nINICIANDO CONFIGURACAO"
while [[ -z $PORTA_SQUID ]]; do
PORTAS=$(read_var "Digite as Portas do SQUID\nEx: 8080 80 8989"|tr "_" " ") || return 1
PORTA_SQUID="" && MSG=""
for PTS in $PORTAS; do
if [[ -z $(teste_porta $PTS) ]]; then
PORTA_SQUID+="$PTS "
MSG+="PORTA: [$PTS] OK\n"
else
MSG+="PORTA: [$PTS] USADA POR: $(teste_porta $PTS)\n"
fi
done
box "INSTALADOR" "PORTAS TESTADAS:\n${MSG}"
[[ -z $PORTA_SQUID ]] && box "ERRO" "NENHUMA PORTA VALIDA FOI SELECIONADA"
done
box_info "INSTALADOR" "INSTALANDO SQUID"
debconf-apt-progress -- apt-get install squid3 -y
echo -e ".bookclaro.com.br/\n.claro.com.ar/\n.claro.com.br/\n.claro.com.co/\n.claro.com.ec/\n.claro.com.gt/\n.cloudfront.net/\n.claro.com.ni/\n.claro.com.pe/\n.claro.com.sv/\n.claro.cr/\n.clarocurtas.com.br/\n.claroideas.com/\n.claroideias.com.br/\n.claromusica.com/\n.clarosomdechamada.com.br/\n.clarovideo.com/\n.facebook.net/\n.facebook.com/\n.netclaro.com.br/\n.oi.com.br/\n.oimusica.com.br/\n.speedtest.net/\n.tim.com.br/\n.timanamaria.com.br/\n.vivo.com.br/\n.rdio.com/\n.compute-1.amazonaws.com/\n.portalrecarga.vivo.com.br/\n.vivo.ddivulga.com/" > /etc/payloads
box_info "INSTALADOR" "APLICANDO CONFIGURACOES TRADICIONAIS..."
unset SQUID
if [[ -d /etc/squid ]]; then
SQUID="/etc/squid/squid.conf"
elif [[ -d /etc/squid3 ]]; then
SQUID="/etc/squid3/squid.conf"
fi
read IP <<< $(curl ifconfig.me 2>/dev/null)
cat << EOF > $SQUID
#ConfiguracaoSquiD
acl url1 dstdomain -i $IP
acl url2 dstdomain -i 127.0.0.1
acl url3 url_regex -i '/etc/payloads'
acl url4 url_regex -i '/etc/opendns'
acl url5 dstdomain -i localhost
acl all src 0.0.0.0/0
http_access allow url1
http_access allow url2
http_access allow url3
http_access allow url4
http_access allow url5
http_access deny all
#portas
EOF
for PTS in $PORTA_SQUID; do
echo -e "http_port $PTS" >> $SQUID
done
cat << EOF >> $SQUID
#nome
visible_hostname ADM-MANAGER
via off
forwarded_for off
pipeline_prefetch off
EOF
touch /etc/opendns
box_info "INSTALADOR" "SQUID CONFIGURADO\nREINICIANDO SERVICOS"
squid3 -k reconfigure &> /dev/null
squid -k reconfigure &> /dev/null
service ssh restart &> /dev/null
if [[ ! -f "/etc/init.d/squid" ]]; then
service squid3 reload &>/dev/null
service squid3 restart &>/dev/null
else
/etc/init.d/squid reload &>/dev/null
service squid restart &>/dev/null
fi
ufw_fun
box "FINALIZADO" "SQUID INSTALADO COM SUCESSO\nPORTAS INSTALADAS: $PORTA_SQUID"
}
instalar_dropbear () {
local RESP PORTA_DROPBEAR MSG PROGRAM PORT PORTAS PTS DROP
if [[ -e /etc/default/dropbear ]]; then
RESP=$(menu -t "DROPBEAR ENCONTRADO." [1]="REMOVER DROPBEAR" [2]="MANTER DROPBEAR") || return 1
[[ $RESP != "[1]" ]] && return 0
box "INSTALADOR" "REMOVENDO DROPBEAR"
service dropbear stop &>/dev/null &
debconf-apt-progress -- apt-get remove dropbear -y
box "INSTALADOR" "Dropbear Removido"
[[ -e /etc/default/dropbear ]] && rm /etc/default/dropbear
return 0
fi
box_info "INSTALADOR" "INSTALADOR DROPBEAR ADM-NEW"
while [[ -z $PORTA_DROPBEAR ]]; do
PORTAS=$(read_var "Digite as Portas do DROPBEAR\nEx: 8080 80 8989"|tr "_" " ") || return 1
PORTA_DROPBEAR="" && MSG=""
for PTS in $PORTAS; do
if [[ -z $(teste_porta $PTS) ]]; then
PORTA_DROPBEAR+="$PTS "
MSG+="PORTA: [$PTS] OK\n"
else
MSG+="PORTA: [$PTS] USADA POR: $(teste_porta $PTS)\n"
fi
done
box "INSTALADOR" "PORTAS TESTADAS:\n${MSG}"
[[ -z $PORTA_DROPBEAR ]] && box "ERRO" "NENHUMA PORTA VALIDA FOI SELECIONADA"
done
[[ ! $(cat /etc/shells|grep "/bin/false") ]] && echo -e "/bin/false" >> /etc/shells
box_info "INSTALADOR" "INSTALANDO DROPBEAR"
debconf-apt-progress -- apt-get install dropbear -y
cat << EOF > /etc/ssh/sshd_config
Port 22
Protocol 2
KeyRegenerationInterval 3600
ServerKeyBits 1024
SyslogFacility AUTH
LogLevel INFO
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication yes
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
UsePAM yes
EOF
touch /etc/bannerssh
# Capta Distro # $(cat -n /etc/issue |grep 1 |cut -d' ' -f6,7,8 |sed 's/1//' |sed 's/ //' | grep -o Ubuntu)
cat <<EOF > /etc/default/dropbear
NO_START=0
DROPBEAR_EXTRA_ARGS="VAR"
DROPBEAR_BANNER="/etc/bannerssh"
DROPBEAR_RECEIVE_WINDOW=65536
EOF
for DROP in $PORTA_DROPBEAR; do
sed -i "s/VAR/-p $DROP VAR/g" /etc/default/dropbear
done
sed -i "s/VAR//g" /etc/default/dropbear
service ssh restart &> /dev/null
service dropbear restart &> /dev/null
ufw_fun
box "FINALIZADO" "DROPBEAR INSTALADO COM SUCESSO\nPORTAS INSTALADAS: $PORTA_DROPBEAR"
}
# Instalador openvpn
instalar_openvpn () {
local OS VERSION_ID IPTABLES SYSCTL RESP NIC PORT PROTOCOL DNS dns PLUGIN OVPN_PORT PROGRAM PORT_PROX PPROXY NEWDNS DENESI DDNS pid tuns RET
if [[ ! -e /dev/net/tun ]]; then
box_info "INSTALADOR" "TUN nao esta disponivel"
return 1
fi
if [[ ! -e /etc/debian_version ]]; then
box_info "INSTALADOR" "Parece que voce nao esta executando este instalador em um sistema Debian ou Ubuntu"
return 1
fi
OS="debian"
VERSION_ID=$(cat /etc/os-release | grep "VERSION_ID")
IPTABLES='/etc/iptables/iptables.rules'
SYSCTL='/etc/sysctl.conf'
read IP <<< $(curl ifconfig.me 2>/dev/null)
if [[ -e /etc/openvpn/server.conf ]]; then
if [[ $(minhas_portas|grep -w openvpn) ]]; then
local OPEN="ONLINE"
else
local OPEN="OFFLINE"
fi
RET=$(menu -t "OPENVPN JA ESTA INSTALADO" \
[1]="Remover Openvpn" \
[2]="Editar Cliente Openvpn (comand nano)" \
[3]="Trocar Hosts do Openvpn" \
[4]="Ligar/Parar OPENVPN [$OPEN]") || return 1
case $RET in
"[1]")RET=$(menu -t "CONFIRMA REMOCAO DO OPENVPN" [1]="SIM" [2]="NAO") || return 1
[[ $RET = "[2]" ]] && return 0
if [[ "$OS" = 'debian' ]]; then
debconf-apt-progress -- apt-get purge openvpn -y
else
debconf-apt-progress -- yum remove openvpn -y
fi
tuns=$(cat /etc/modules | grep -v tun) && echo -e "$tuns" > /etc/modules
rm -rf /etc/openvpn && rm -rf /usr/share/doc/openvpn*
box "Sucesso" "Procedimento Concluido"
;;
"[2]")nano /etc/openvpn/client-common.txt
;;
"[3]")while [[ $RESP != "[2]" ]]; do
RESP=$(menu -t "Adicionar DNS" [1]="SIM" [2]="NAO") || break
[[ $RESP != "[1]" ]] && break
DDNS=$(read_var "INSTALADOR" "Digite o DNS") || break
agrega_dns $DDNS
[[ -z $NEWDNS ]] && NEWDNS="$DDNS" || NEWDNS="$NEWDNS $SDNS"
done
if [[ ! -z $NEWDNS ]]; then
sed -i "/127.0.0.1[[:blank:]]\+localhost/a 127.0.0.1 $NEWDNS" /etc/hosts
for DENESI in $NEWDNS; do
sed -i "/remote ${SERVER_IP} ${PORT} ${PROTOCOL}/a remote ${DENESI} ${PORT} ${PROTOCOL}" /etc/openvpn/client-common.txt
done
fi
;;
"[4]")if [[ $OPEN = "ONLINE" ]]; then
ps x |grep openvpn |grep -v grep|awk '{print $1}' | while read pid; do kill -9 $pid; done
killall openvpn &>/dev/null
systemctl stop openvpn@server.service &>/dev/null
service openvpn stop &>/dev/null && box "SUCESSO" "OPENVPN PARADO COM SUCESSO" || box "ERRO" "OPENVPN NAO FOI PARADO"
else
cd /etc/openvpn
screen -dmS ovpnscr openvpn --config "server.conf" > /dev/null 2>&1 && box "SUCESSO" "OPENVPN INICIADO" || box "ERRO" "OPENVPN NAO FOI INICIADO"
cd $HOME
fi
;;
esac
return 0
fi
if [[ "$VERSION_ID" != 'VERSION_ID="7"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="8"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="9"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="14.04"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="16.04"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="17.10"' ]]; then
box_info "INSTALADOR" "Sua versao do Debian ou Ubuntu nao e suportada."
RET=$(menu -t "PROSEGUIR COM INSTALACAO." [1]=SIM [2]=NAO) || return 1
[[ $RET != "[1]" ]] && return 0
fi
# INSTALACAO E UPDATE DO REPOSITORIO
if [[ "$VERSION_ID" = 'VERSION_ID="7"' ]]; then # Debian 7
echo "deb http://build.openvpn.net/debian/openvpn/stable wheezy main" > /etc/apt/sources.list.d/openvpn.list
wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1
elif [[ "$VERSION_ID" = 'VERSION_ID="8"' ]]; then # Debian 8
echo "deb http://build.openvpn.net/debian/openvpn/stable jessie main" > /etc/apt/sources.list.d/openvpn.list
wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1
elif [[ "$VERSION_ID" = 'VERSION_ID="14.04"' ]]; then # Ubuntu 14.04
echo "deb http://build.openvpn.net/debian/openvpn/stable trusty main" > /etc/apt/sources.list.d/openvpn.list
wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1
fi
box_info "INSTALADOR" "Sistema Preparado Para Receber o OPENVPN"
#Pega Interface
NIC=$(ip -4 route ls | grep default | grep -Po '(?<=dev )(\S+)' | head -1)
[[ ! -d /etc/iptables ]] && mkdir /etc/iptables
[[ ! -e $IPTABLES ]] && touch $IPTABLES
box_info "INSTALADOR" "Responda as perguntas para iniciar a instalacao\nResponda corretamente"
RESP=$(menu -t "Primeiro precisamos do ip de sua maquina, este ip esta correto\nIP: $IP" [1]="SIM" [2]="NAO")
if [[ $RESP = "[2]" ]]; then
IP=$(read_var "Digite o IP Correto") || return 1
fi
#PORTA
while [[ -z $PORT ]]; do
PORT=$(read_var_num "Qual porta voce deseja usar\nPadrao: [1194]") || return 1
if [[ ! -z $(teste_porta $PORT) ]]; then
box "ERRO" "PORTA: [$PORT] Esta Sendo Usada Por: [$(teste_porta $PORT)]"
unset PORT
fi
done
#PROTOCOLO
RESP=$(menu -t "Qual protocolo voce deseja para as conexoes OPENVPN\nA menos que o UDP esteja bloqueado, voce nao deve usar o TCP (mais lento)" [1]=UDP [2]=TCP ) || return 1
RESP=$(echo $RESP|tr -d "[]")
[[ $RESP = "1" ]] && PROTOCOL=udp
[[ $RESP = "2" ]] && PROTOCOL=tcp
#DNS
RESP=$(menu -t "Qual DNS voce deseja usar" [1]="Usar padroes do sistema" [2]="Cloudflare" [3]="Quad" [4]="FDN" [5]="DNS WATCH" [6]="OpenDNS" [7]="Google DNS" [8]="Yandex Basic" [9]="AdGuard DNS" ) || return 1
DNS=$(echo $RESP|tr -d "[]")
#CIPHER
RESP=$(menu -t "Escolha qual codificacao voce deseja usar para o canal de dados:" [1]="AES-128-CBC" [2]="AES-192-CBC" [3]="AES-256-CBC" [4]="CAMELLIA-128-CBC" [5]="CAMELLIA-192-CBC" [6]="CAMELLIA-256-CBC" [7]="SEED-CBC") || return 1
case $RESP in
"[1]")CIPHER="cipher AES-128-CBC";;
"[2]")CIPHER="cipher AES-192-CBC";;
"[3]")CIPHER="cipher AES-256-CBC";;
"[4]")CIPHER="cipher CAMELLIA-128-CBC";;
"[5]")CIPHER="cipher CAMELLIA-192-CBC";;
"[6]")CIPHER="cipher CAMELLIA-256-CBC";;
"[7]")CIPHER="cipher SEED-CBC";;
esac
box_info "INSTALADOR" "Instalando OpenVPN"
[[ ! -d /etc/openvpn ]] && mkdir /etc/openvpn
debconf-apt-progress -- apt-get update -y
debconf-apt-progress -- apt-get upgrade -y
debconf-apt-progress -- apt-get install -qy openvpn curl
debconf-apt-progress -- apt-get install openssl -y
debconf-apt-progress -- apt-get install screen -y
SERVER_IP="$IP" # IP Address
[[ -z "${SERVER_IP}" ]] && SERVER_IP=$(ip a | awk -F"[ /]+" '/global/ && !/127.0/ {print $3; exit}')
box_info "INSTALADOR" "Gerando Server Config" # Gerando server.con
(
if [[ $DNS -eq 1 ]]; then
i=0 ; grep -v '#' /etc/resolv.conf | grep 'nameserver' | grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | while read line; do
dns[$(($DNS+$i))]="push \"dhcp-option DNS $line\"" && let i++
done
[[ ! "${dns[@]}" ]] && dns[0]='push "dhcp-option DNS 8.8.8.8"' && dns[1]='push "dhcp-option DNS 8.8.4.4"'
elif [[ $DNS -eq 2 ]]; then
dns[$DNS]='push "dhcp-option DNS 1.0.0.1"'
dns[$(($DNS+1))]='push "dhcp-option DNS 1.1.1.1"'
elif [[ $DNS -eq 3 ]]; then
dns[$DNS]='push "dhcp-option DNS 9.9.9.9"'
dns[$(($DNS+1))]='push "dhcp-option DNS 1.1.1.1"'
elif [[ $DNS -eq 4 ]]; then
dns[$DNS]='push "dhcp-option DNS 80.67.169.40"'
dns[$(($DNS+1))]='push "dhcp-option DNS 80.67.169.12"'
elif [[ $DNS -eq 5 ]]; then
dns[$DNS]='push "dhcp-option DNS 84.200.69.80"'
dns[$(($DNS+1))]='push "dhcp-option DNS 84.200.70.40"'
elif [[ $DNS -eq 6 ]]; then
dns[$DNS]='push "dhcp-option DNS 208.67.222.222"'
dns[$(($DNS+1))]='push "dhcp-option DNS 208.67.220.220"'
elif [[ $DNS -eq 7 ]]; then
dns[$DNS]='push "dhcp-option DNS 8.8.8.8"'
dns[$(($DNS+1))]='push "dhcp-option DNS 8.8.4.4"'
elif [[ $DNS -eq 8 ]]; then
dns[$DNS]='push "dhcp-option DNS 77.88.8.8"'
dns[$(($DNS+1))]='push "dhcp-option DNS 77.88.8.1"'
elif [[ $DNS -eq 9 ]]; then
dns[$DNS]='push "dhcp-option DNS 176.103.130.130"'
dns[$(($DNS+1))]='push "dhcp-option DNS 176.103.130.131"'
fi
echo 01 > /etc/openvpn/ca.srl
while [[ ! -e /etc/openvpn/dh.pem || -z $(cat /etc/openvpn/dh.pem) ]]; do
openssl dhparam -out /etc/openvpn/dh.pem 2048 &>/dev/null
done
while [[ ! -e /etc/openvpn/ca-key.pem || -z $(cat /etc/openvpn/ca-key.pem) ]]; do
openssl genrsa -out /etc/openvpn/ca-key.pem 2048 &>/dev/null
done
chmod 600 /etc/openvpn/ca-key.pem &>/dev/null
while [[ ! -e /etc/openvpn/ca-csr.pem || -z $(cat /etc/openvpn/ca-csr.pem) ]]; do
openssl req -new -key /etc/openvpn/ca-key.pem -out /etc/openvpn/ca-csr.pem -subj /CN=OpenVPN-CA/ &>/dev/null
done
while [[ ! -e /etc/openvpn/ca.pem || -z $(cat /etc/openvpn/ca.pem) ]]; do
openssl x509 -req -in /etc/openvpn/ca-csr.pem -out /etc/openvpn/ca.pem -signkey /etc/openvpn/ca-key.pem -days 365 &>/dev/null
done
cat << EOF > /etc/openvpn/server.conf
server 10.8.0.0 255.255.255.0
verb 3
duplicate-cn
key client-key.pem
ca ca.pem
cert client-cert.pem
dh dh.pem
keepalive 10 120
persist-key
persist-tun
comp-lzo
float
push "redirect-gateway def1 bypass-dhcp"
${dns[$DNS]}
${dns[$(($DNS+1))]}
user nobody
group nogroup
${CIPHER}
proto ${PROTOCOL}
port $PORT
dev tun
status openvpn-status.log
EOF
updatedb
PLUGIN=$(locate openvpn-plugin-auth-pam.so | head -1)
if [[ ! -z $(echo ${PLUGIN}) ]]; then
echo "client-to-client
client-cert-not-required
username-as-common-name
plugin $PLUGIN login" >> /etc/openvpn/server.conf
fi
)
if [[ $? = 1 ]]; then
box "ERRO" "Algo de Errado nao Esta Certo!"
return 1
fi
box_info "INSTALADOR" "Gerando CA Config" # Generate CA Config
(
while [[ ! -e /etc/openvpn/client-key.pem || -z $(cat /etc/openvpn/client-key.pem) ]]; do
openssl genrsa -out /etc/openvpn/client-key.pem 2048 &>/dev/null
done
chmod 600 /etc/openvpn/client-key.pem
while [[ ! -e /etc/openvpn/client-csr.pem || -z $(cat /etc/openvpn/client-csr.pem) ]]; do
openssl req -new -key /etc/openvpn/client-key.pem -out /etc/openvpn/client-csr.pem -subj /CN=OpenVPN-Client/ &>/dev/null
done
while [[ ! -e /etc/openvpn/client-cert.pem || -z $(cat /etc/openvpn/client-cert.pem) ]]; do
openssl x509 -req -in /etc/openvpn/client-csr.pem -out /etc/openvpn/client-cert.pem -CA /etc/openvpn/ca.pem -CAkey /etc/openvpn/ca-key.pem -days 365 &>/dev/null
done
)
if [[ $? = 1 ]]; then
box "ERRO" "Algo de Errado nao Esta Certo!"
return 1
fi
box_info "INSTALADOR" "Agora Precisamos da Porta Que Esta Seu Proxy Squid(Socks)"
while [[ -z $OVPN_PORT ]]; do
OVPN_PORT=$(read_var_num "Digite a Porta do Proxy\nEx: 8080 80 8989"|tr "_" " ") || return 1
if [[ -z $(teste_porta $OVPN_PORT) ]]; then
box "ERRO" "PORTA: [$OVPN_PORT] Nao Esta Aberta"
unset OVPN_PORT
fi
done
PPROXY=$OVPN_PORT
cat <<EOF > /etc/openvpn/client-common.txt
# OVPN_ACCESS_SERVER_PROFILE=New-Ultimate
client
nobind
dev tun
redirect-gateway def1 bypass-dhcp
remote-random
remote ${SERVER_IP} ${PORT} ${PROTOCOL}
http-proxy ${SERVER_IP} ${PPROXY}
$CIPHER
comp-lzo yes
keepalive 10 20
float
auth-user-pass
EOF
# Iptables
local INTIP N_INT
if [[ ! -f /proc/user_beancounters ]]; then
INTIP=$(ip a | awk -F"[ /]+" '/global/ && !/127.0/ {print $3; exit}')
N_INT=$(ip a |awk -v sip="$INTIP" '$0 ~ sip { print $7}')
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o $N_INT -j MASQUERADE
else
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source $SERVER_IP
fi
iptables-save > /etc/iptables.conf
cat << EOF > /etc/network/if-up.d/iptables
#!/bin/sh
iptables-restore < /etc/iptables.conf
EOF
chmod +x /etc/network/if-up.d/iptables
# Enable net.ipv4.ip_forward
sed -i 's|#net.ipv4.ip_forward=1|net.ipv4.ip_forward=1|' /etc/sysctl.conf
echo 1 > /proc/sys/net/ipv4/ip_forward
# Regras de Firewall
if pgrep firewalld; then
if [[ "$PROTOCOL" = 'udp' ]]; then
firewall-cmd --zone=public --add-port=$PORT/udp
firewall-cmd --permanent --zone=public --add-port=$PORT/udp
elif [[ "$PROTOCOL" = 'tcp' ]]; then
firewall-cmd --zone=public --add-port=$PORT/tcp
firewall-cmd --permanent --zone=public --add-port=$PORT/tcp
fi
firewall-cmd --zone=trusted --add-source=10.8.0.0/24
firewall-cmd --permanent --zone=trusted --add-source=10.8.0.0/24
fi
if iptables -L -n | grep -qE 'REJECT|DROP'; then
if [[ "$PROTOCOL" = 'udp' ]]; then
iptables -I INPUT -p udp --dport $PORT -j ACCEPT
elif [[ "$PROTOCOL" = 'tcp' ]]; then
iptables -I INPUT -p tcp --dport $PORT -j ACCEPT
fi
iptables -I FORWARD -s 10.8.0.0/24 -j ACCEPT
iptables -I FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables-save > $IPTABLES
fi
if hash sestatus 2>/dev/null; then
if sestatus | grep "Current mode" | grep -qs "enforcing"; then
if [[ "$PORT" != '1194' ]]; then
if ! hash semanage 2>/dev/null; then
yum install policycoreutils-python -y
fi
if [[ "$PROTOCOL" = 'udp' ]]; then
semanage port -a -t openvpn_port_t -p udp $PORT
elif [[ "$PROTOCOL" = 'tcp' ]]; then
semanage port -a -t openvpn_port_t -p tcp $PORT
fi
fi
fi
fi
box_info "INSTALADOR" "Ultima Etapa, Configuracoes DNS"
#Liberando DNS
while [[ $RESP != "[2]" ]]; do
if [[ -z $NEWDNS ]]; then
RESP=$(menu -t "Adicionar um DNS" [1]="SIM" [2]="NAO") || break
else
RESP=$(menu -t "Adicionar Outro DNS" [1]="SIM" [2]="NAO") || break
fi
[[ $RESP != "[1]" ]] && break
DDNS=$(read_var "INSTALADOR" "Digite o DNS") || break
agrega_dns $DDNS
[[ -z $NEWDNS ]] && NEWDNS="$DDNS" || NEWDNS="$NEWDNS $SDNS"
done
if [[ ! -z $NEWDNS ]]; then
sed -i "/127.0.0.1[[:blank:]]\+localhost/a 127.0.0.1 $NEWDNS" /etc/hosts
for DENESI in $NEWDNS; do
sed -i "/remote ${SERVER_IP} ${PORT} ${PROTOCOL}/a remote ${DENESI} ${PORT} ${PROTOCOL}" /etc/openvpn/client-common.txt
done
fi
box_info "INSTALADOR" "Reiniciando Servicos OPENVPN"
# REINICIANDO OPENVPN
(
if [[ "$OS" = 'debian' ]]; then
if pgrep systemd-journal; then
sed -i 's|LimitNPROC|#LimitNPROC|' /lib/systemd/system/openvpn\@.service
sed -i 's|/etc/openvpn/server|/etc/openvpn|' /lib/systemd/system/openvpn\@.service
sed -i 's|%i.conf|server.conf|' /lib/systemd/system/openvpn\@.service
#systemctl daemon-reload
systemctl restart openvpn
systemctl enable openvpn
else
/etc/init.d/openvpn restart
fi
else
if pgrep systemd-journal; then
systemctl restart openvpn@server.service
systemctl enable openvpn@server.service
else
service openvpn restart
chkconfig openvpn on
fi
fi
[[ -e /etc/squid/squid.conf ]] && service squid restart &>/dev/null
[[ -e /etc/squid3/squid.conf ]] && service squid3 restart &>/dev/null
) &> /dev/null
ufw_fun
box "SUCESSO" "Openvpn Instalado Com Exito"
}
instalar_ssl () {
local PORT PROGRAM PORT_PROX EPORT RET
if [[ $(mportas|grep stunnel4|head -1) ]]; then
RET=$(menu -t "CONFIRMA REMOCAO DO SSL" [1]=SIM [2]=NAO)
[[ $RET != "[1]" ]] && return 1
rm -rf /etc/stunnel
debconf-apt-progress -- apt-get purge stunnel4 -y
box_info "INSTALADOR" "Parado Com Sucesso"
return 0
fi
box_info "INSTALADOR" "SSL Stunnel\nIniciando A Instalacao do SSL em Sua Maquina."
while [[ -z $PORT ]]; do
PORT=$(read_var_num "PORTA INTERNA" "Selecione Uma Porta De Redirecionamento INTERNA")
if [[ -z $(teste_porta $PORT) ]]; then
box "ERRO" "PORTA: [$PORT] Nao Esta Aberta"
unset PORT
fi
done
while [[ -z $EPORT ]]; do
EPORT=$(read_var_num "PORTA EXTERNA" "Selecione Uma Porta De Redirecionamento EXTERNA")
if [[ ! -z $(teste_porta $EPORT) ]]; then
box "ERRO" "PORTA: [$EPORT] Esta sendo Usada Por [$(teste_porta $EPORT)]"
unset EPORT
fi
done
box_info "INSTALADOR" "Instalando SSL"
debconf-apt-progress -- apt-get install stunnel4 -y
cat << EOF > /etc/stunnel/stunnel.conf
cert = /etc/stunnel/stunnel.pem
client = no
socket = a:SO_REUSEADDR=1
socket = l:TCP_NODELAY=1
socket = r:TCP_NODELAY=1
[stunnel]
connect = 127.0.0.1:${PORT}
accept = ${EPORT}
EOF
openssl genrsa -out key.pem 2048 &>/dev/null
openssl req -new -x509 -key key.pem -out cert.pem -days 1095 <<< $(echo br; echo br; echo uss; echo speed; echo adm; echo ultimate; echo @admultimate) &>/dev/null
cat key.pem cert.pem >> /etc/stunnel/stunnel.pem
sed -i 's/ENABLED=0/ENABLED=1/g' /etc/default/stunnel4
service stunnel4 restart &> /dev/null
box_info "INSTALADOR" "INSTALADO COM SUCESSO"
}
instalar_shadowsocks () {
local ENCRIPT s RETURN CRIPTO PORT PROGRAM PORT_PROX
if [[ -e /etc/shadowsocks.json ]]; then
[[ $(kill -9 $(ps x|grep ssserver|grep -v grep|awk '{print $1}') 2>/dev/null) ]] && ssserver -c /etc/shadowsocks.json -d stop > /dev/null 2>&1
rm /etc/shadowsocks.json && box_info "INSTALADOR" "SHADOWSOCKS PARADO"
return 0
fi
box_info "INSTALADOR" "Esse e o Instalador SHADOWSOCKS"
ENCRIPT=(aes-256-ctr aes-192-ctr aes-128-ctr aes-256-cfb aes-192-cfb aes-128-cfb camellia-128-cfb camellia-192-cfb camellia-256-cfb chacha20 rc4-md5)
RETURN=""
for((s=0; s<${#ENCRIPT[@]}; s++)); do
RETURN+="[${s}]=${ENCRIPT[${s}]} "
done
CRIPTO=$(menu -t "Qual Criptografia, Escolha uma Opcao" $RETURN) || return 1
CRIPTO="$(echo ${ENCRIPT[$(echo $CRIPTO|tr -d '[]')]})"
while [[ -z $PORT ]]; do
PORT=$(read_var_num "PORTA EXTERNA SHADOWSOCKS")
if [[ ! -z $(teste_porta $PORT) ]]; then
box "ERRO" "PORTA: [$PORT] Esta em Uso Por [$(teste_porta $PORT)]"
unset PORT
fi
done
MESSAGE=$(read_var "SENHA do SHADOWSOCKS") || return 1
debconf-apt-progress -- apt-get install python-pip python-m2crypto -y
pip install shadowsocks &>/dev/null
cat << EOF > /etc/shadowsocks.json
{
"server":"0.0.0.0",
"server_port":$PORT,
"local_port":1080,
"password":"$MESSAGE",
"timeout":600,
"method":"$CRIPTO"
}
EOF
box_info "INSTALADOR" "Iniciando Shadowsocks"
ssserver -c /etc/shadowsocks.json -d start > /dev/null 2>&1
if [[ $(ps x |grep ssserver|grep -v grep) ]]; then
box_info "SUCESSO" "Shadowsocks Ja Esta Rodando"
else
box_info "FALHA" "Shadowsocks Nao Funcionou"
fi
return 0
}
# SOCKS
pid_kill () {
local pids pid
[[ -z $1 ]] && refurn 1
pids="$@"
for pid in $(echo $pids); do
kill -9 $pid &>/dev/null
done
}
tcpbypass_fun () {
[[ -e $HOME/socks ]] && rm -rf $HOME/socks &> /dev/null
[[ -d $HOME/socks ]] && rm -rf $HOME/socks &> /dev/null
mkdir $HOME/socks &> /dev/null
cd $HOME/socks &> /dev/null
local PATCH="https://www.dropbox.com/s/ks45mkuis7yyi1r/backsocz"
local ARQ="backsocz"
wget $PATCH -o /dev/null
unzip $ARQ &> /dev/null
mv -f ./ssh /etc/ssh/sshd_config &>/dev/null
service ssh restart &>/dev/null
mv -f sckt$(python3 --version|awk '{print $2}'|cut -d'.' -f1,2) /usr/sbin/sckt &>/dev/null
mv -f scktcheck /bin/scktcheck &>/dev/null
chmod +x /bin/scktcheck &>/dev/null
chmod +x /usr/sbin/sckt &>/dev/null
cd $HOME &>/dev/null && rm -rf $HOME/socks &>/dev/null
local MSG="$2"
[[ -z $MSG ]] && MSG="BEM VINDO"
local PORTXZ="$1"
[[ -z $PORTXZ ]] && PORTXZ="8080"
screen -dmS sokz scktcheck "$PORTXZ" "$MSG" &> /dev/null
if [[ $(ps x | grep "scktcheck" | grep -v "grep" | awk -F "pts" '{print $1}') ]]; then
box "TCP Bypass Iniciado com Sucesso"
else
box_info "TCP Bypass nao foi iniciado"
fi
}
gettunel_fun () {
local SERVICE PORT
echo "master=ADMMANAGER" > ${SCPinst}/pwd.pwd
while read -r SERVICE PORT; do
echo "127.0.0.1:$PORT=$SERVICE" >> ${SCPinst}/pwd.pwd
done <<< "$(minhas_portas)"
# Iniciando Proxy
screen -dmS getpy python ${SCPinst}/PGet.py -b "0.0.0.0:$1" -p "${SCPinst}/pwd.pwd"
if [[ "$(ps x | grep "PGet.py" | grep -v "grep" | awk -F "pts" '{print $1}')" ]]; then
box "Gettunel Iniciado com Sucesso Sua Senha Gettunel e:\n ADMMANAGER"
else
box_info "Gettunel nao foi iniciado"
fi
}
instalar_pysocks () {
local pidproxy pidproxy2 pidproxy3 pidproxy4 pidproxy5 pidproxy6
local RET PORT TEXT
local IP=$(meu_ip)
pidproxy=$(ps x | grep -w "PPub.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy ]] && P1="[ATIVO]"
pidproxy2=$(ps x | grep -w "PPriv.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy2 ]] && P2="[ATIVO]"
pidproxy3=$(ps x | grep -w "PDirect.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy3 ]] && P3="[ATIVO]"
pidproxy4=$(ps x | grep -w "POpen.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy4 ]] && P4="[ATIVO]"
pidproxy5=$(ps x | grep "PGet.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy5 ]] && P5="[ATIVO]"
pidproxy6=$(ps x | grep "scktcheck" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy6 ]] && P6="[ATIVO]"
RET=$(menu -t "SELECIONE O PROXY PYTHON" [1]="Socks Python SIMPLES $P1" \
[2]="Socks Python SEGURO $P2" \
[3]="Socks Python DIRETO $P3" \
[4]="Socks Python OPENVPN $P4" \
[5]="Socks Python GETTUNEL $P5" \
[6]="Socks Python TCP BYPASS $P6" \
[7]="PARAR TODOS SOCKETS PYTHON")
if [[ $RET -eq "[7]" ]]; then
[[ ! -z $pidproxy ]] && pid_kill $pidproxy
[[ ! -z $pidproxy2 ]] && pid_kill $pidproxy2
[[ ! -z $pidproxy3 ]] && pid_kill $pidproxy3
[[ ! -z $pidproxy4 ]] && pid_kill $pidproxy4
[[ ! -z $pidproxy5 ]] && pid_kill $pidproxy5
[[ ! -z $pidproxy6 ]] && pid_kill $pidproxy6
return 0
fi
# Porta
while [[ -z $PORT ]]; do
PORT=$(read_var_num "PORTA EXTERNA SOCKS")
if [[ ! -z $(teste_porta $PORT) ]]; then
box "ERRO" "PORTA: [$PORT] Esta em Uso Por [$(teste_porta $PORT)]"
unset PORT
fi
done
TEXT=$(read_var "Escolha Um Texto de Conexao")
case $RET in
[1])screen -dmS screen python ${SCPinst}/PPub.py "$PORT" "$TEXT";;
[2])screen -dmS screen python3 ${SCPinst}/PPriv.py "$PORT" "$TEXT" "$IP";;
[3])screen -dmS screen python ${SCPinst}/PDirect.py "$PORT" "$TEXT";;
[4])screen -dmS screen python ${SCPinst}/POpen.py "$PORT" "$TEXT";;
[5])gettunel_fun "$PORT";;
[6])tcpbypass_fun "$PORT" "$TEXT";;
esac
box_info "Procedimento Concluido"
}
instala_menu_fun () {
local RET SQUID_VERIF DROP_VERIF OPEN_VERIF SHADOW_VERIF
while true
do
############
# VERIFICAOES #
############
[[ -e /etc/shadowsocks.json ]] && SHADOW_VERIF="[INSTALADO] DESINSTALAR SHADOWSOCKS" || SHADOW_VERIF="INSTALAR SHADOWSOCKS"
[[ -e /etc/squid/squid.conf || -e /etc/squid3/squid.conf ]] && SQUID_VERIF="[INSTALADO] ADMINISTRAR SQUID" || SQUID_VERIF="INSTALAR SQUID PROXY"
[[ -e /etc/default/dropbear ]] && DROP_VERIF="[INSTALADO] DESINSTALAR DROPBEAR" || DROP_VERIF="INSTALAR DROPBEAR"
[[ -e /etc/openvpn/server.conf ]] && OPEN_VERIF="[INSTALADO] ADMINISTRAR OPENVPN" || OPEN_VERIF="INSTALAR OPENVPN"
[[ -e /etc/stunnel/stunnel.conf ]] && SSL_VERIF="[INSTALADO] DESINSTALAR SSL" || SSL_VERIF="INSTALAR SSL"
############
RET=$(menu -t "$(VAR)" [1]="$SQUID_VERIF" \
[2]="$DROP_VERIF" \
[3]="$OPEN_VERIF" \
[4]="$SSL_VERIF" \
[5]="$SHADOW_VERIF" \
[6]="INSTALAR/REMOVER PROXY SOCKS") || break
case $RET in
"[1]")instalar_squid;;
"[2]")instalar_dropbear;;
"[3]")instalar_openvpn;;
"[4]")instalar_ssl;;
"[5]")instalar_shadowsocks;;
"[6]")contruc_fun;;
esac
done
}
contruc_fun() {
box "EM DESENVOLVIMENTO" "ESSA OPCAO ESTA EM DESENVOLVIMENTO E BREVE ESTARA DISPONIVEL"
return 0
}
##################
# L O O P P R I N C I P A L. #
##################
main () {
while true
do
RET=$(menu -t "$(VAR)" [1]="GERENCIAR USUARIOS" \
[2]="FERRAMENTAS" \
[3]="MENU DE INSTALACOES" \
[4]="ATUALIZAR" \
[5]="DESINSTALAR" \
[6]="AUTO INICIALIZACAO $AutoRun" \
[7]="TROCAR IDIOMA") || break
case $RET in
"[1]")ger_user_fun;;
"[2]")contruc_fun;;
"[3]")instala_menu_fun;;
"[4]")contruc_fun;;
"[5]")contruc_fun;;
"[6]")contruc_fun;;
"[7]")contruc_fun;;
esac
done
}
main
|
C++
|
UTF-8
| 974 | 3.25 | 3 |
[] |
no_license
|
#ifndef FACTORY_H_BD0CAAF7_87FA_46e9_9917_0AC6E4B3734D
#define FACTORY_H_BD0CAAF7_87FA_46e9_9917_0AC6E4B3734D
namespace Util
{
/// @class AbstractFactory
/// @brief Abstract base class for Factory objects
template <typename T>
class AbstractFactory
{
public:
/// @brief Destructor
virtual ~AbstractFactory() {}
/// @brief Create an instance of the type for which this Factory is specialized.
virtual T* create() = 0;
};
/// @class ConcreteFactory
/// @brief Factory class used for creating polymorphic objects of type DerivedType
template <typename BaseType, typename DerivedType>
class ConcreteFactory : public AbstractFactory<BaseType>
{
/// @brief Create an instance of DerivedType
/// @returns A pointer to BaseType pointing to the newly created object of DeriveType
BaseType* create() { return new DerivedType(); }
};
}
#endif
|
Markdown
|
UTF-8
| 12,745 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: "Intentional Complexity"
date: 2013-08-24 15:21
comments: true
categories:
---
> John Duns Scotus' (1265-1308) book Ordinatio: "Pluralitas non est ponenda sine necessitate", i.e., "Plurality is not to be posited without necessity"
> William of Ockham's Razor, modern science version: "The simplest solution is often the best."
*Intentional Complexity* is a manufactured situation where product configuration and operation are intentionally made difficult. It occurs when a software vendor exposes all the innards of their products to systems operators and end users.
It's great for marketing to Managers and sales to CTO's, but it's rubbish for operations and business. In this post I will talk about what this is, why this is, how it comes to be, how this is bad for you and the fleeting signs of improvement that I am seeing.
But first, how does one detect it?
## How is Intentional Complexity Presented?
Just look any marketing for enterprise systems and you will see some classic CIO friendly phrases (which I shall translate for you):
* **Fully Configurable** - there are hundreds of settings you can change, but only a few combinations really work, we just don't know which.
* **Fully Customizable** - you can change how the system works using code (or pay us lots of money to 'mod' the system) and then you'll have to wait for us on each upgrade to create the 'mod' for that too.
* **Fully Featured** - we have so many features that you can use (and very likely will never need) in the product that we need lots of menus, toolbars, icons, fields and wizards just to get our heads around it, we have no idea how you will.
* **Integrates with any Product** - even more settings and parameters to enable you to integrate this system with others, where settings are visible for all potential integrations, and only a few settings really work.
* **Supports -INSERT LIST HERE- protocols** - if you think we have a lot of settings now, just wait until you see all the settings for all the protocols we support that you will never need or use but some small firm in Botswana needs.
* **Installation included** - The product is so complex that we could not create a setup program for it. You need specialists just to install it and to create the initial settings.
*If you buy a piece of software that can do anything, expect it to be able to do nothing out-the-box.* You will need to configure it, customize it, choose the features to use, set up your integrations and choose your protocols, and then, only then, will it *start* working.
Software that can do anything is made intentionally that way, and is therefore intentionally complex to set up and use.
## What is Intentional Complexity?
So what does this really mean? Well, lets take something as simple as setting up a Wi-Fi network. All you really need is to set the network name, the access user name and a password. That's not complex at all.
But *nooooooo*, almost all Wi-Fi router setups also involve choosing frequencies (2.5GHz or 5GHz), channels (0-11), choosing protocols (B, G, N or a combination thereof), choosing the type of encryption of the password (WPA, WPA2, WP-SEC) and choosing the IP network range. That is some serious complexity. The router is fully capable of knowing which frequencies are better, which channels are less crowded, supporting the necessary protocols as and when they crop up, choosing the best encryption and making sure the network range does not conflict.
But the designers of the router have chosen *not* to make these decisions for the user, they have made it intentionally complex to force the user to make these decisions.
*I am not saying these decisions should be taken away from users, just that they should not be forced on users. An advanced user should still have the ability to access the complexity and change things. But a regular user, or lazy advanced user like me, should be able to do the least amount of work and still get it up and running quickly.*
## Why create Intentionally Complex Products?
There are a lot of reasons for complexity in products, including:
* Customers have different needs and if a vendor wants to sell its product to them, it needs to support those needs.
* Customers have different workflows and processes which require configurable flows within the product.
* Customers run different product mixes which requires complex integrations to be created.
* The problem the product solves may be complex, requiring complex interfaces.
* There may be thousands of users or millions of transactions, requiring complex webs of software and hardware to keep it all flowing.
Complexity in itself is not a bad thing when the problem space is, in fact, complex.
But why *intentionally* create complexity?
* One reason is the expectation that enterprise software needs to look and feel complex. Selling what looks like a simple product against a what-looks-like-complex product is hard.
* If you are selling your software for a lot of money, you want the customer to perceive they are getting value for that money. Intentional complexity makes your product look just that more expensive because it has just that more visible stuff in it.
* If you sell your software to professionals or experts, you think you need to give them all the power you can, which means exposing the innards of the product. That decision to expose the guts of the product intentionally creates intentional complexity.
* To encourage the vicious circle of training and sales. If you can train professionals to use your complex product, when they consult or change jobs, they will want to leverage that training for more money, leading to more sales. And customers who buy these products need these trained professionals to use these products. Cisco was very successful with this strategy with its IOS routers and certifications. So is Microsoft and Oracle and SAP. Their intentionally complex software requires certified professionals, and their certified professionals push their products.
* Simple image and exclusivity. People who understand and use intentionally complex software feel smug compared to the rest of us who do not. Just try getting a SAP or Certified Network Engineer to speak in normal, it just does not happen.
## How does Intentional Complexity even happen?
This is where is starts:
* Marketing wants to compete feature-for-feature with a competitor which means the developers need to intentionally add features just for marketing.
* Sales wants to sell to the largest audience which means selling the product to customers who have different needs, or may be in even different industries, requiring additional complexity in the product.
* Product design has no idea what they are creating so they create a product that does everything and hope something sells.
* Management hears an idea at the golf course and wants that added to the product.
* Customers who have no intention of buying say they *just have to have* a feature, so that gets squeezed into the product, just for a sale that will never happen.
* New business partners and vendors enter the market, requiring developers to create new interfaces for them, just in case a customer one day, someday, maybe needs them.
* Customers want new features to mod the product for their needs, leading to more and more settings and changes to the core product. And as they upgrade, these mods become core.
* Technology changes, protocols change and to remain relevant, the software has to support these new changes, while not losing support for old technologies and protocols.
But the main reason Intentional Complexity remains is this: **nothing gets removed.** Excuses range from the difficulty in removal to backwards compatibility to just-in-case to some random customer still uses this feature. Which means all current and future customers have to intentionally bypass this feature every time they use the system.
And then there is the straw-man argument that users should be able to use the product their way and systems operators should be able to set the product up they way they want, so the product should support that. The software should be un-opinionated. Just because users *can* set something up some way does not mean that they *should*.
There is an army of certified professionals who run around setting things up the most complex way because they *can*, not because they *should* and not because that's the best way for the business. Staff and consultants want to create job security and Intentional Complexity used just right can guarantee that.
## Why is Intentional Complexity Bad?
Once again, in this post, I am not arguing that complexity is good or bad, just that Intentional Complexity is.
* Companies need certified and trained personnel to do what they need on the product. These people usually cost more and are harder to find.
* It takes a lot more time to set things up because systems operators have to go through all this complexity just to get it started.
* It takes an even longer time to figure out when things go wrong because the fault may lie in any of a hundred places or with different people or vendors.
* Once it's working, it encourages people to resist change because the complexity of the system makes change difficult or risky.
* It's confusing as anything as to how to get things done, how things are done, how things have been done and how things should be done. The too many choices that Intentional Complexity leads to difficulties in deciding what to do and how to set things up.
* It enables customers to continue to run their businesses using inefficient workflows and protocols which are supported by the intentional complexity of the system, instead of running optimized better workflows supported by a simpler, best-practices system.
* It requires a lot of time and effort to train staff to use the product.
* Users use a small portion of the product because it's too hard and complex to use other features, or the user simply has no idea the feature exists, it gets lost in all the Intentional Complexity. Consider something like MS Word which is an intentionally complex word processor where 99% of users use less than 5% of its features yet have to wade through 100% of its features to do so.
* And people start to base software and implementation decisions on myths and on institutional knowledge (which is basically just a memory of what worked at least once before) because these intentionally complex products do not indicate in any way what is better.
## Is anyone trying to be less Intentionally Complex?
Fortunately, there is light at the end of this tunnel. Cisco's incomprehensible iOS and CNE's have been replaced at the bottom and medium ends with very easy to use web interfaces on their routers. SAP has created a significantly simpler version of their product for smaller and medium businesses by removing thousands of unnecessary settings and complexities. Citrix has created an easier to use GUI for their Xen virtualization servers, hiding the complexity of their maddening command-lines.
But some have not. Microsoft continues to add Intentional Complexity to Windows server and management infrastructure. ISP's and colocation firms still need CNE's to get things going. Accounting products get more and more intentionally complex by the day. And the ultimate in intentional complexity, Bloomberg, remains the grand master.
## What can we do?
We, the users and the buyers and the writers of checks, have to start to demand simpler, easier to use systems and products. We need to demand routers that are self configuring, we need to demand the removal or hiding of unnecessary features in products, we need to adjust our own workflows and choose the simpler products that support those flows. We need to push our vendors into making the 5% of the product we do use into the best 5% of the product and to hide the rest. We need to standardize our interfaces and all write to the same integration formats.
We need to break the mindset that Intentionally Complex software is better than complex software where the complexity is hidden behind intelligent defaults or unnecessary complexity is removed.
We need to realize that we do not do things that much differently to everyone else and that all this intentional complexity required to support our perceived uniqueness is unnecessary in the product, bad for business and bad for all our users and partners.
Unlike Occam's Razor, the simplest solution may not be the best, but the most intentionally complex one is certainly always the worst.
*Follow the author as [@hiltmon](https://twitter.com/hiltmon) on Twitter and [@hiltmon](http://alpha.app.net/hiltmon) on App.Net. Mute `#xpost` on one.*
|
Java
|
UTF-8
| 7,764 | 2.03125 | 2 |
[
"ISC"
] |
permissive
|
/*
* Certissim pre-payment scoring - copilot webservice -
* Sample JAVA call implementation.
*
* This file has been written for the sole purpose of demonstrating how to
* call the copilot.cgi web-service and handle errors, as described in
* the Technical Integration Guide.
*
* Copyright (c) FIA-NET 2014
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
* OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
*/
package com.fianet.certissim.copilot.example;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.Charsets;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.apache.commons.io.IOUtils;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
*
*/
public class CopilotRequest {
CopilotConfig cfg;
public CopilotRequest(CopilotConfig cfg) {
this.cfg = cfg;
}
/**
* Compute the "auth" parameter value for a request, with the HMAC-SHA1
* algorithm.
* Uses Apache Common Codec package.
*
* @param mySiteID my identifier (as provided by Fia-Net)
* @param myAuthKeyHex my secret key (as provided by Fia-Net) in hexadecimal
* @param payload the payload XML document.
* @return the hexadecimal HMAC-SHA1 digest, as expected by copilot.
* @throws Exception if a problem arises during the HMAC computation.
*/
private String computeAuthParameter (int mySiteID, String myAuthKeyHex, String payload, Charset charset) throws Exception {
byte[] k = Hex.decodeHex(myAuthKeyHex.toCharArray());
SecretKeySpec key = new SecretKeySpec(k, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(key);
return Hex.encodeHexString(mac.doFinal(payload.getBytes(charset)));
}
/**
* Call copilot through an http POST request, using the CopilotConfig
* instance for "siteid" and "auth" HTTP parameters.
*
* @param payload the XML document containing the request data, as a string.
* @param charset the Charset used by the payload string. It is required
* for HMAC computation. Only UTF-8 and ISO-8859-1 are supported by the
* web-service.
* @return a CopilotResponse object, containing the authentication level
* and some status information.
*
* @throw RuntimeException when the charset parameter is neither UTF-8 not
* ISO-8859-1, or when SiteID or AuthKeyHex are undefined in the owned
* CopilotConfig instance.
*/
public CopilotResponse execute (String payload, Charset charset) throws RuntimeException {
if (cfg.getSiteId() == 0 || cfg.getAuthKeyHex().isEmpty()) {
throw new RuntimeException ("CopilotConfig instance is missing siteid or auth key values.");
}
return this.execute (cfg.getSiteId(), cfg.getAuthKeyHex(), payload, charset);
}
/**
* Call copilot through an http POST request, according to the
* Technical Integration Guide.
*
* @param mySiteID my identifier (as provided by Fia-Net).
* @param myAuthKeyHex my secret key (as provided by Fia-Net) in hexadecimal
* @param payload the XML document containing the request data, as a string.
* @param charset the character set used by the payload string. It is
* required for HMAC computation. Only UTF-8 and ISO-8859-1 are supported
* by the web-service.
* @return a CopilotResponse object, containing the authentication level
* and some status information.
* @throw RuntimeException when the charset parameter is neither UTF-8 not ISO-8859-1
*/
public CopilotResponse execute (int mySiteID, String myAuthKeyHex, String payload, Charset charset) throws RuntimeException {
if (!charset.equals(Charsets.ISO_8859_1) && !charset.equals(Charsets.UTF_8)) {
throw new RuntimeException ("Charset "+charset.name()+" not supported !");
}
// The response contains our default authentication level at first. It will be updated accordingly on successful HTTP requests.
CopilotResponse response = new CopilotResponse(cfg.getDefaultAuthLevel());
Request httpReq = org.apache.http.client.fluent.Request.Post(cfg.getUri());
try {
String auth = computeAuthParameter(mySiteID, myAuthKeyHex, payload, charset);
httpReq.connectTimeout(cfg.getTimeoutMs());
httpReq.socketTimeout(cfg.getTimeoutMs());
httpReq.bodyForm (
Form.form()
.add("siteid", String.valueOf(mySiteID)).add("auth", auth)
.add("payload", payload)
.build(),
charset
);
HttpResponse httpResp = httpReq.execute().returnResponse();
response.setStatusCode(httpResp.getStatusLine().getStatusCode());
response.setStatusText(httpResp.getStatusLine().getReasonPhrase());
ContentType ctype = ContentType.getOrDefault(httpResp.getEntity());
// Responses containing an XML document are parsed further.
if (ctype.getMimeType().equals ("text/xml") || ctype.getMimeType().equals ("application/xml")) {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse (httpResp.getEntity().getContent());
XPath xpath = XPathFactory.newInstance().newXPath();
String version = (String) xpath.evaluate ("/paymentAuthResponse/@version", doc, XPathConstants.STRING);
if (!version.equals("1.0")) {
System.err.println ("WARNING: Unexpected copilot response version "+version);
}
response.setTechnicalId ((String) xpath.evaluate ("/paymentAuthResponse/@id", doc, XPathConstants.STRING));
response.setAuthLevel ((String) xpath.evaluate ("/paymentAuthResponse/authLevel/text()", doc, XPathConstants.STRING));
// Other content-types are copied "as-is" in the CopilotResponse.documentBody property.
} else {
System.err.println ("ERROR: Did not receive XML data!");
String str = IOUtils.toString (httpResp.getEntity().getContent(), ContentType.getOrDefault(httpResp.getEntity()).getCharset());
response.setDocumentBody(str);
}
// Modify this section to match your exception-handling requirements !
} catch (SocketTimeoutException e) {
httpReq.abort();
System.err.println ("ERROR: Socket timeout.");
response.setDocumentBody(e.getMessage());
} catch (ClientProtocolException e) {
httpReq.abort();
System.err.println ("ERROR: Client protocol error.");
response.setDocumentBody(e.getMessage());
} catch (IOException e) {
httpReq.abort();
System.err.println ("ERROR: I/O error.");
response.setDocumentBody(e.getMessage());
} catch (SAXException e) {
System.err.println ("ERROR: XML parse error.");
response.setDocumentBody(e.getMessage());
} catch (Exception e) {
System.err.println ("ERROR: Unexpected exception caught.");
response.setDocumentBody(e.getMessage());
}
return response;
}
}
|
PHP
|
UTF-8
| 15,160 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
<?php
declare(strict_types=1);
namespace AllenJB\Mailer\Tests;
use AllenJB\Mailer\Email;
use PHPUnit\Framework\TestCase;
class EmailTest extends TestCase
{
public function constructClassToTest(): Email
{
return new Email();
}
public function testSubject(): void
{
$email = $this->constructClassToTest();
$this->assertNull($email->subject());
$testValue = "Test Subject";
$email->setSubject($testValue);
$this->assertEquals($testValue, $email->subject());
}
public function testTextBody(): void
{
$email = $this->constructClassToTest();
$this->assertNull($email->bodyText());
$testValue = "Test Text Body\nWith Line\nReturns";
$email->setTextBody($testValue);
$this->assertEquals($testValue, $email->bodyText());
$appendValue = "Additional\nBody\nText";
$email->appendTextBody($appendValue);
$this->assertEquals($testValue . $appendValue, $email->bodyText());
}
public function testHtmlBody(): void
{
$email = $this->constructClassToTest();
$this->assertNull($email->bodyHtml());
$testValue = "<html lang='en'><body><p>Test \n<br />Body</p></body></html>";
$email->setHtmlBody($testValue);
$this->assertEquals($testValue, $email->bodyHtml());
}
public function testReturnPath(): void
{
$email = $this->constructClassToTest();
$this->assertNull($email->returnPath());
$testEmail = "return-path@example.com";
$email->setReturnPath($testEmail);
$this->assertEquals($testEmail, $email->returnPath()->email());
}
public function testReplyTo(): void
{
$email = $this->constructClassToTest();
$this->assertNull($email->from());
$this->assertNull($email->replyTo());
$this->assertNull($email->sender());
$this->assertNull($email->returnPath());
$testEmail = "reply-to@example.com";
$email->setReplyTo($testEmail);
$this->assertEquals($testEmail, $email->replyTo()->email());
$this->assertNull($email->replyTo()->displayName());
$email = $this->constructClassToTest();
$testDisplayName = "Reply To Name";
$email->setReplyTo($testEmail, $testDisplayName);
$this->assertEquals($testEmail, $email->replyTo()->email());
$this->assertEquals($testDisplayName, $email->replyTo()->displayName());
// Reply-To should not affect From or Sender for non-internal mails
$this->assertNull($email->from());
$this->assertNull($email->sender());
$this->assertNull($email->returnPath());
}
public function testSender(): void
{
$email = $this->constructClassToTest();
$this->assertNull($email->from());
$this->assertNull($email->replyTo());
$this->assertNull($email->sender());
$this->assertNull($email->returnPath());
$testEmail = "sender@example.com";
$email->setSender($testEmail);
$this->assertEquals($testEmail, $email->sender()->email());
$this->assertNull($email->sender()->displayName());
$email = $this->constructClassToTest();
$testDisplayName = "Sender Name";
$email->setSender($testEmail, $testDisplayName);
$this->assertEquals($testEmail, $email->sender()->email());
$this->assertEquals($testDisplayName, $email->sender()->displayName());
// Sender should not affect From or Reply-To for non-internal mails
$this->assertNull($email->from());
$this->assertNull($email->replyTo());
$this->assertNull($email->returnPath());
}
public function testFrom(): void
{
$email = $this->constructClassToTest();
$this->assertNull($email->from());
$this->assertNull($email->replyTo());
$this->assertNull($email->sender());
$this->assertNull($email->returnPath());
$testEmail = "from@example.com";
$email->setFrom($testEmail);
$this->assertEquals($testEmail, $email->from()->email());
$this->assertNull($email->from()->displayName());
$email = $this->constructClassToTest();
$testDisplayName = "From Name";
$email->setFrom($testEmail, $testDisplayName);
$this->assertEquals($testEmail, $email->from()->email());
$this->assertEquals($testDisplayName, $email->from()->displayName());
// From should not affect Reply-To or Sender for non-internal mails
$this->assertNull($email->replyTo());
$this->assertNull($email->sender());
$this->assertNull($email->returnPath());
}
public function testTo(): void
{
$email = $this->constructClassToTest();
$this->assertEquals([], $email->to());
$testEmail1 = "to1@example.com";
$email->addTo($testEmail1);
$recipients = $email->to();
$this->assertCount(1, $recipients);
$this->assertEquals($testEmail1, $recipients[0]->email());
$this->assertNull($recipients[0]->displayName());
$testEmail2 = "to2@example.com";
$testName2 = "Second Recipient";
$email->addTo($testEmail2, $testName2);
$recipients = $email->to();
$this->assertCount(2, $recipients);
$this->assertEquals($testEmail1, $recipients[0]->email());
$this->assertNull($recipients[0]->displayName());
$this->assertEquals($testEmail2, $recipients[1]->email());
$this->assertEquals($testName2, $recipients[1]->displayName());
$multiRecipients = [
"to3@example.com",
"to4@example.com" => "Fourth Recipient",
];
$email->addRecipientsTo($multiRecipients);
$recipients = $email->to();
$this->assertCount(4, $recipients);
$this->assertEquals($testEmail1, $recipients[0]->email());
$this->assertNull($recipients[0]->displayName());
$this->assertEquals($testEmail2, $recipients[1]->email());
$this->assertEquals($testName2, $recipients[1]->displayName());
$this->assertEquals($multiRecipients[0], $recipients[2]->email());
$this->assertNull($recipients[2]->displayName());
$this->assertEquals("to4@example.com", $recipients[3]->email());
$this->assertEquals("Fourth Recipient", $recipients[3]->displayName());
}
public function testCc(): void
{
$email = $this->constructClassToTest();
$this->assertEquals([], $email->cc());
$testEmail1 = "cc1@example.com";
$email->addCc($testEmail1);
$recipients = $email->cc();
$this->assertCount(1, $recipients);
$this->assertEquals($testEmail1, $recipients[0]->email());
$this->assertNull($recipients[0]->displayName());
$testEmail2 = "cc2@example.com";
$testName2 = "Second Recipient";
$email->addCc($testEmail2, $testName2);
$recipients = $email->cc();
$this->assertCount(2, $recipients);
$this->assertEquals($testEmail1, $recipients[0]->email());
$this->assertNull($recipients[0]->displayName());
$this->assertEquals($testEmail2, $recipients[1]->email());
$this->assertEquals($testName2, $recipients[1]->displayName());
$multiRecipients = [
"cc3@example.com",
"cc4@example.com" => "Fourth Recipient",
];
$email->addRecipientsCc($multiRecipients);
$recipients = $email->cc();
$this->assertCount(4, $recipients);
$this->assertEquals($testEmail1, $recipients[0]->email());
$this->assertNull($recipients[0]->displayName());
$this->assertEquals($testEmail2, $recipients[1]->email());
$this->assertEquals($testName2, $recipients[1]->displayName());
$this->assertEquals($multiRecipients[0], $recipients[2]->email());
$this->assertNull($recipients[2]->displayName());
$this->assertEquals("cc4@example.com", $recipients[3]->email());
$this->assertEquals("Fourth Recipient", $recipients[3]->displayName());
}
public function testBcc(): void
{
$email = $this->constructClassToTest();
$this->assertEquals([], $email->bcc());
$testEmail1 = "bcc1@example.com";
$email->addBcc($testEmail1);
$recipients = $email->bcc();
$this->assertCount(1, $recipients);
$this->assertEquals($testEmail1, $recipients[0]->email());
$this->assertNull($recipients[0]->displayName());
$testEmail2 = "bcc2@example.com";
$testName2 = "Second Recipient";
$email->addBcc($testEmail2, $testName2);
$recipients = $email->bcc();
$this->assertCount(2, $recipients);
$this->assertEquals($testEmail1, $recipients[0]->email());
$this->assertNull($recipients[0]->displayName());
$this->assertEquals($testEmail2, $recipients[1]->email());
$this->assertEquals($testName2, $recipients[1]->displayName());
$multiRecipients = [
"bcc3@example.com",
"bcc4@example.com" => "Fourth Recipient",
];
$email->addRecipientsBcc($multiRecipients);
$recipients = $email->bcc();
$this->assertCount(4, $recipients);
$this->assertEquals($testEmail1, $recipients[0]->email());
$this->assertNull($recipients[0]->displayName());
$this->assertEquals($testEmail2, $recipients[1]->email());
$this->assertEquals($testName2, $recipients[1]->displayName());
$this->assertEquals($multiRecipients[0], $recipients[2]->email());
$this->assertNull($recipients[2]->displayName());
$this->assertEquals("bcc4@example.com", $recipients[3]->email());
$this->assertEquals("Fourth Recipient", $recipients[3]->displayName());
// Verify that no BCC recipients leak into other recipient fields
$this->assertEquals([], $email->cc());
$this->assertEquals([], $email->to());
}
public function testReferences(): void
{
$email = $this->constructClassToTest();
$this->assertNull($email->inReplyTo());
$this->assertEquals([], $email->references());
$inReplyToId = "reply-to@test.id";
$email->setInReplyTo($inReplyToId);
$this->assertEquals($inReplyToId, $email->inReplyTo());
$refs = $email->references();
$this->assertCount(1, $refs);
$this->assertEquals($inReplyToId, $refs[0]);
$addRef1 = "additional1@test.id";
$email->addReference($addRef1);
$this->assertEquals($inReplyToId, $email->inReplyTo());
$refs = $email->references();
$this->assertCount(2, $refs);
$this->assertEquals($inReplyToId, $refs[0]);
$this->assertEquals($addRef1, $refs[1]);
$addRefs = ["additional2@test.id", "additional3@test.id"];
$email->addReference($addRefs);
$this->assertEquals($inReplyToId, $email->inReplyTo());
$refs = $email->references();
$this->assertCount(4, $refs);
$this->assertEquals($inReplyToId, $refs[0]);
$this->assertEquals($addRef1, $refs[1]);
$this->assertEquals($addRefs[0], $refs[2]);
$this->assertEquals($addRefs[1], $refs[3]);
}
public function testAttachments(): void
{
$email = $this->constructClassToTest();
$this->assertEquals([], $email->attachments());
$email->addAttachmentData("testAttachDataFileName", "text/plain", "testAttachData");
$email->addAttachmentData("testAttachDataFileName2", "text/plain", "testAttachData2", "inline");
$email->addAttachment("testAttachDataFile", "text/plain", "/test/AttachDataFile/Path");
$email->addAttachment("testAttachDataFile2.gif", "image/gif", "/test/AttachDataFile/Path2.gif", "inline");
$attachments = $email->attachments();
$this->assertCount(4, $attachments);
$this->assertEquals("data", $attachments[0]["type"]);
$this->assertEquals("testAttachDataFileName", $attachments[0]["filename"]);
$this->assertEquals("text/plain", $attachments[0]["contentType"]);
$this->assertEquals("testAttachData", $attachments[0]["data"]);
$this->assertEquals("attachment", $attachments[0]["disposition"]);
$this->assertEquals("data", $attachments[1]["type"]);
$this->assertEquals("testAttachDataFileName2", $attachments[1]["filename"]);
$this->assertEquals("text/plain", $attachments[1]["contentType"]);
$this->assertEquals("testAttachData2", $attachments[1]["data"]);
$this->assertEquals("inline", $attachments[1]["disposition"]);
$this->assertEquals("file", $attachments[2]["type"]);
$this->assertEquals("testAttachDataFile", $attachments[2]["filename"]);
$this->assertEquals("text/plain", $attachments[2]["contentType"]);
$this->assertEquals("/test/AttachDataFile/Path", $attachments[2]["path"]);
$this->assertEquals("attachment", $attachments[2]["disposition"]);
$this->assertEquals("file", $attachments[3]["type"]);
$this->assertEquals("testAttachDataFile2.gif", $attachments[3]["filename"]);
$this->assertEquals("image/gif", $attachments[3]["contentType"]);
$this->assertEquals("/test/AttachDataFile/Path2.gif", $attachments[3]["path"]);
$this->assertEquals("inline", $attachments[3]["disposition"]);
}
public function testAdditionalHeaders(): void
{
$email = $this->constructClassToTest();
$this->assertEquals([], $email->additionalHeaders());
$email->addHeader("Test-Header", "Test header value");
$headers = $email->additionalHeaders();
$this->assertCount(1, $headers);
$this->assertArrayHasKey("Test-Header", $headers);
$this->assertCount(1, $headers["Test-Header"]);
$this->assertEquals("Test header value", $headers["Test-Header"][0]);
$email->addHeader("Test-Header", "Test header new value");
$headers = $email->additionalHeaders();
$this->assertCount(1, $headers);
$this->assertArrayHasKey("Test-Header", $headers);
$this->assertCount(1, $headers["Test-Header"]);
$this->assertEquals("Test header new value", $headers["Test-Header"][0]);
$email->addHeader("Test-Header", "Test header additional value", false);
$headers = $email->additionalHeaders();
$this->assertCount(1, $headers);
$this->assertArrayHasKey("Test-Header", $headers);
$this->assertCount(2, $headers["Test-Header"]);
$this->assertEquals("Test header new value", $headers["Test-Header"][0]);
$this->assertEquals("Test header additional value", $headers["Test-Header"][1]);
$email->addHeader("Another-Header", "Another Header Value", false);
$headers = $email->additionalHeaders();
$this->assertCount(2, $headers);
$this->assertArrayHasKey("Test-Header", $headers);
$this->assertCount(2, $headers["Test-Header"]);
$this->assertEquals("Test header new value", $headers["Test-Header"][0]);
$this->assertEquals("Test header additional value", $headers["Test-Header"][1]);
$this->assertArrayHasKey("Another-Header", $headers);
$this->assertCount(1, $headers["Another-Header"]);
$this->assertEquals("Another Header Value", $headers["Another-Header"][0]);
}
}
|
Markdown
|
UTF-8
| 1,521 | 3.625 | 4 |
[] |
no_license
|
# Kruskal
## Descripción:
Este algoritmo se utiliza para encontrar el árbol de expansión mínima de una gráfica, la forma en la que resuelve el problema es *Greedy*.
* Input: Una gráfica **G** representada como lista de adyacencia.
* Output: Las aristas pertenecientes al árbol de expansión mínima.
* Tiempo de ejecución: O(ElgV)
## Código utilizado:
### Funciones de apoyo:
Estas funciones son fundamentales para la ejecución del algoritmo. Se utilizan para identificar si se crea un ciclo o no durante la ejecución del algoritmo principal.
```python
def make_set(x: Dict):
x['pointer'] = x
x['rank'] = 0
def union(x: Dict, y: Dict):
link(find_set(x), find_set(y))
def find_set(x: Dict):
pointer = x['pointer']
if pointer is not x:
pointer = find_set(pointer)
return pointer
def link(x: Dict, y: Dict):
if x['rank'] > y['rank']:
y['pointer'] = x
else:
x['pointer'] = y
if x['rank'] == y['rank']:
y['rank'] += 1
```
### Función **Kruskal**
```python
def kruskal(graph: Dict):
sol = []
edges = []
for node in graph:
make_set(graph[node])
for vecino in graph[node]['vecinos']:
edges.append({'u': node, 'v': vecino, 'w': graph[node]['vecinos'][vecino]})
merge_sort_dict(edges, key='w')
for edge in edges:
u = graph[edge['u']]
v = graph[edge['v']]
if find_set(u) is not find_set(v):
sol.append(edge)
union(u, v)
return sol
```
|
JavaScript
|
UTF-8
| 691 | 2.609375 | 3 |
[] |
no_license
|
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "menu") {
x.className += " responsive";
} else {
x.className = "menu";
}
}
function save(){
var cbArr = [];
var c = document.getElementsByClassName("cb");
var i;
for (i = 0; i < c.length; i++) {
cbArr.push(c[i].checked);
}
localStorage.setItem("cb", JSON.stringify(cbArr));
}
function load(){
var c = document.getElementsByClassName("cb");
var cbArr = [];
cbArr= JSON.parse(localStorage.getItem("cb"));
var i;
for (i = 0; i < cbArr.length; i++) {
item = cbArr[i];
c[i].checked = cbArr[i];
}
}
function wis(){
localStorage.clear()
}
|
Go
|
UTF-8
| 1,548 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
package conf
import (
"os"
"time"
"github.com/Depado/conftags"
"github.com/pkg/errors"
yaml "gopkg.in/yaml.v3"
)
// C is the main exported conf
var C Conf
// Conf is a configuration struct intended to be filled from a yaml file and/or
// sane defaults
type Conf struct {
Server Server `yaml:"server"`
Logger Logger `yaml:"logger"`
GithubOAuthToken string `yaml:"github_oauth_token"`
RServiceInterval string `yaml:"service_interval" default:"10m"`
RRepoInterval string `yaml:"repo_interval" default:"10m"`
ServiceInterval time.Duration
RepoInterval time.Duration
Services []Service `yaml:"services"`
}
// Parse parses the tags and configures the logger associated
func (c *Conf) Parse() error {
var err error
if err = conftags.Parse(&c.Server); err != nil {
return err
}
if err = conftags.Parse(c); err != nil {
return err
}
c.Logger.Configure()
if c.ServiceInterval, err = time.ParseDuration(c.RServiceInterval); err != nil {
return errors.Wrapf(err, "configuration error: couldn't parse 'service_interval' (%s)", c.RServiceInterval)
}
if c.RepoInterval, err = time.ParseDuration(c.RRepoInterval); err != nil {
return errors.Wrapf(err, "configuration error: couldn't parse 'repo_interval' (%s)", c.RRepoInterval)
}
return nil
}
// Load loads the configuration file into C
func Load(fp string) error {
var err error
var c []byte
if c, err = os.ReadFile(fp); err != nil {
return err
}
if err = yaml.Unmarshal(c, &C); err != nil {
return err
}
return C.Parse()
}
|
Java
|
UTF-8
| 3,907 | 2.25 | 2 |
[] |
no_license
|
package com.example.parth.logindemo;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.View;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Login_email extends MainActivity{
FirebaseAuth mAuth;
boolean LoginResult, RegisterResult, ForgotPasswordResult, EmailVerification;
public Login_email(){
mAuth = FirebaseAuth.getInstance();
LoginResult = false;
RegisterResult = false;
ForgotPasswordResult = false;
EmailVerification = false;
}
//Login method
public boolean methodLogin(String email, String password){
if(isEmailValid(email)){
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
LoginResult = true;
}
});
return LoginResult;
}else
return false;
}
public boolean isEmailValid(String email)
{
String regExpn =
"^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
+"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+"[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+"[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+"([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(regExpn,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches())
return true;
else
return false;
}
//Register method
public boolean methodRegister(String email, String password){
if(isEmailValid(email)){
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
RegisterResult = true;
sendVerificationEmail();
}
});
return RegisterResult;
}else
return false;
}
public boolean methodForgotPassword(String email){
if(isEmailValid(email)){
mAuth.sendPasswordResetEmail(email)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
ForgotPasswordResult = true;
} else {
ForgotPasswordResult = false;
}
}
});
return ForgotPasswordResult;
}else
return false;
}
private boolean sendVerificationEmail(){
FirebaseUser user = mAuth.getCurrentUser();
user.sendEmailVerification()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
EmailVerification = true;
}
});
return EmailVerification;
}
}
|
Java
|
UTF-8
| 614 | 3.015625 | 3 |
[] |
no_license
|
package com.sda.javagdy4.designpatterns.abstractfactory.zad1;
public class AppleMac extends AbstractPC {
private AppleMac(String computerName, ComputerBrand computerBrand, int cpuPowder, Double gpuPowder, boolean isOverclocked) {
super(computerName, computerBrand, cpuPowder, gpuPowder, isOverclocked);
}
public static AbstractPC createMacProRetina15() {
return new AppleMac("MacProRetina15", ComputerBrand.APPLE, 90, 0.99, false);
}
public static AbstractPC createMacProRetina20() {
return new AppleMac("MacProRetina20", ComputerBrand.APPLE, 92, 0.99, false);
}
}
|
JavaScript
|
UTF-8
| 475 | 3.640625 | 4 |
[] |
no_license
|
const numbers = document.querySelectorAll("[id^='num']");
numbers.forEach((numbers) => {
numbers.addEventListener('click', (e) => {
console.log(numbers.id);
});
});
function addition(numA, numB) {
return numA + numB;
}
function subtraction(numA, numB) {
return numA - numB;
}
function divide(numA, numB) {
return numA / numB;
}
function multiply(numA, numB) {
return numA * numB;
}
function operate(operator, numA, numB) {
return operator(numA, numB);
}
|
Markdown
|
UTF-8
| 12,183 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
# OpenAnafi
## Présentation
Open Anafi est une refonte de l’application existante sur Business Object, Anafi.
Cette application a pour but la génération de rapports financiers sur des collectivités publiques.
Elle s’appuie notamment sur la base DGFIP.
La base DGFIP est une base contenant tous les comptes ordonnés par exercice des collectivités publiques de France.
Mais, elle ne s’arrête pas là, elle a pour but à terme de proposer les fonctionnalités suivantes :
* Requêtage assisté de la base DGFIP
* Création assistée de trame métier (création de formule pour les nouveaux indicateurs)
## Découplement Back & Front
Le projet a été séparé en deux parties distincts:
* La première étant le projet actuelle, c'est le back-end de l'application: [ici](https://github.com/Cour-des-comptes/open-anafi-backend)
* La deuxième étant disponible au lien suivant, c'est le front-end de l'application: [ici](https://github.com/Cour-des-comptes/open-anafi-frontend)
## Architecture
Un serveur faisant tourner l’application Open Anafi est composé de 6 services distincts :
* **Angular** : partie du code servi par le serveur étant destiné à être exécuté par le navigateur internet du client.
* **Django** : partie du code étant exécuté sur le directement serveur.
* **Base de données PostgreSQL**
* **Rabbitmq** : gestion de queue intergicielle, il permet de faire passer des messages entre Django et Celery via le protocole AMQP
* **Celery** : il vient exécuter le code python de façon asynchrone et a accède aux mêmes bases de données et contexte que le code exécuté sur par le serveur Django
* **Apache** : le front et le back (respectivement Angular et Django) sont servies par le serveur apache.

### RabbitMQ
RabbitMQ fonctionne comme un service sur la machine. Il utilise une authentification avec un utilisateur et un mot de passe pour protéger l’envoi et la lecture des messages. De plus, les messages sont liés à un Vhost, ainsi plusieurs Vhost peuvent être utilisés simultanément.
### Celery
Celery fonctionne comme un processus démonisé par le système. On peut donc l’utiliser via l’interface ‘systemctl’. Il permet notamment d’exécuter du code python de façon asynchrone.
### Front et Back
La différence entre le front et le back se fait grâce à l’url que l’on utilise pour contacter la machine. Le serveur Apache donnera accès au Front ou au Back en fonction de celle-ci.
## Description du projet:
Le projet est rangé de la façon suivante :
* ccomptes/
Ce dossier comporte les configurations du projet, avec notamment toutes les options pour l’utilisation de celery et des différents module django. De plus, il comporte la liste des urls utilitées.
* open_anafi/
Ce dossier comporte la plus grande partie du code.
* open_anafi/lib/
Contient tout le code qui peut être utilisé par plusieurs service et permet de le ranger en fonction de son action. Les différentes librairies sont développées sous la forme de classes contenant des méthodes statiques.
* open_anafi/lib/ply/
Ce dossier contient une bonne partie du code utilisé pour le parsing des formules.
* open_anafi/task.py
Ce fichier en particulier contient le code qui sera exécuté par le worker Celery.
* open_anafi/views/
Ce dossier contient les différentes actions qui sont directement exécutées après les liens de l’API. Elles sont découpées par rapports aux différents modèles.
* open_anafi/models.py
Ce dossier contient la définition du modèle de donnée de la base applicative.
* open_anafi/serializers/
Ce dossier contient tous les serializers des modèles, en fonction des différents besoins de l’API. Pour rappel, le serializer transforme l’objet Json en objet Python en fonction de règles préalablement fournies.
## Développement avec docker
Prérequis : Installer docker et docker-compose
### Remplir le /opt/local_config.ini
Le fichier de configuration doit par défaut situé dans le dossier /opt/. Cette valeur peut-être modifiée dans le
fichier ccomptes/settings.py ligne 17. Il faudra ensuite reprendre le fichier local_config.ini.sample, le renommer
puis le completer.
### Construire et lancer l'image docker
Ouvrir un terminal dans le dossier /backend et lancer la commande 'docker-compose up'
Les modifications du code sont automatiquement prise en compte par le serveur Django.
Cependant Celery n'est pas relancé automatiquement. Pour prendre en compte les modifications du code utilisé par Celery ( i.e. tasks.py et les fonctions appelées par ce fichier ), il est nécessaire d'arreter le container (Ctrl +C) ainsi que de le relancer via la même commande 'docker-compose up'.
## Déploiement sur un serveur CentOs
### Préparation
Mise à jour yum :
```bash
sudo yum -y update
```
Installer outils de compilation:
```bash
sudo yum groupinstall "Development Tools"
```
Installer Python 3 :
```bash
sudo yum -y install https://centos7.iuscommunity.org/ius-release.rpm
sudo yum -y install python36u
sudo yum -y install python36u-devel
sudo yum -y install python36u-pip
sudo yum -y install graphviz
sudo python3.6 -m pip install --upgrade pip
```
### Création utilisateur deploy et du répertoire de déploiement
```bash
sudo adduser deploy
sudo passwd deploy
```
### Installation des dépendances python
Il est recommandé de créer un environnement virtuel dans le repertoire "/opt" :
```bash
pip3.6 install virtualenv
python3.6 -m venv ./venv
```
Installer Apache :
```bash
sudo yum -y install http
sudo yum -y install httpd-devel
```
Installer mod-wsgi:
```bash
sudo yum -y install wget
wget https://github.com/GrahamDumpleton/mod_wsgi/archive/4.6.4.tar.gz
tar xvfz 4.6.4.tar.gz
./configure --with-python=/usr/bin/python3.6
make
make install
make clean
```
Redémarrer Apache:
```bash
systemctl restart httpd
```
Configurer Apache:
```bash
cd /etc/httpd/conf.d/
touch backend.conf
```
backend.conf :
ATTENTION: Remplacer les valeurs génériques par les valeurs du serveur (SERVERNAME )
```bash
LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so
<VirtualHost *:80>
AllowEncodedSlashes NoDecode
ServerName SERVERNAME
Alias "/graphs" GRAPH_FOLDER
WSGIPassAuthorization On
WSGIScriptAlias / /opt/backend/ccomptes/wsgi.py
WSGIDaemonProcess ccomptes python-home=/opt/venv python-path=/opt/backend
WSGIProcessGroup ccomptes
<DirectoryMatch GRAPH_FOLDER>
Require all granted
</DirectoryMatch>
<Directory /opt/backend/ccomptes/>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
ErrorLog /var/log/httpd/backend_api_error.log
CustomLog /var/log/httpd/backend_api_access.log combined
LogLevel debug
</VirtualHost>
```
### Génération de clé de deploiement
Générer une clé ssh avec l'utilisateur "deploy"
```bash
su deploy
ssh-keygen
```
Ajouter cette clé au projet GITLAB (clés de deploiements) et à JENKINS
### Donner les droits pour redémarrer apache à l'utilisateur deploy
ligne 92 (fichier sudoers)
```bash
vim /etc/sudoers
deploy ALL=NOPASSWD: /sbin/service httpd restart,/etc/init.d/httpd restart,/usr/sbin/apache2ctl restart
```
### Donner les droits pour redémarrer celery à l'utilisateur deploy
```bash
sudo visudo
```
deploy ALL=NOPASSWD: /sbin/service celery restart,/etc/systemd/system restart
### Import initial du projet
ATTENTION: Remplacer les valeurs génériques par les valeurs du serveur (BRANCH)
```bash
su deploy
cd /opt
git clone -b BRANCH git@gitlabjf.ccomptes.fr:CommunautesJF/OpenAnafi/backend.git
```
### Créer le dossier templates
Créer le dossier templates et lui donner des droits pour tous
```bash
mkdir /opt/backend/openanafi/templates
chmod 777 /opt/backend/openanafi/templates
```
### Charger l'environnement virtuel et installer les dépendances (en sudo) :
```bash
source ./venv/bin/activate
pip install pip --upgrade
cd /opt/backend
pip install -r requirements.txt
```
### Installer le broker Rabbitmq pour la mise en place de celery et du traitement asynchrone des réquètes
#### Prérequis Installation du repo Erlang
In /etc/yum.repos.d/rabbitmq_erlang.repo
```bash
vi /etc/yum.repos.d/rabbitmq_erlang.repo
[rabbitmq_erlang]
name=rabbitmq_erlang
baseurl=https://packagecloud.io/rabbitmq/erlang/el/7/$basearch
repo_gpgcheck=1
gpgcheck=0
enabled=1
gpgkey=https://packagecloud.io/rabbitmq/erlang/gpgkey
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
metadata_expire=300
[rabbitmq_erlang-source]
name=rabbitmq_erlang-source
baseurl=https://packagecloud.io/rabbitmq/erlang/el/7/SRPMS
repo_gpgcheck=1
gpgcheck=0
enabled=1
gpgkey=https://packagecloud.io/rabbitmq/erlang/gpgkey
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
metadata_expire=300
yum -y install erlang
```
#### Installation du repo rabbitmq-server pour CentOS
```bash
curl -s https://packagecloud.io/install/repositories/rabbitmq/rabbitmq-server/script.rpm.sh | bash
yum -y install rabbitmq-server
systemctl start rabbitmq-server
systemctl enable rabbitmq-server
```
#### Configuration:
```bash
rabbitmqctl add_user myuser mypassword
rabbitmqctl add_vhost myvhost
rabbitmqctl set_user_tags myuser mytag
rabbitmqctl set_permissions -p myvhost myuser ".*" ".*" ".*"
```
#### Exemple:
```bash
rabbitmqctl add_user rabbitanafi Choose_your_passwd
rabbitmqctl add_vhost rabbitanafivhost
rabbitmqctl set_user_tags rabbitanafi rbanafi
rabbitmqctl set_permissions -p rabbitanafivhost rabbitanafi ".*" ".*" ".*"
```
#### Installation module celery :
```bash
cd /opt
source ./venv/bin/activate
python3.6 -m pip install celery
```
#### Installation de celery:
Ajouter dans le répertoire /etc/systemd/system/ le fichier celery.service avec le contenu suivant:
```bash
[Unit]
Description=Celery Service
After=network.target
[Service]
Type=forking
WorkingDirectory=/opt/backend/
ExecStart=/opt/venv/bin/celery multi start worker1\
-A ccomptes -l debug -c 5\
--pidfile=/var/run/celery.pid\
--logfile=/var/log/oa-celery.log
ExecStop=/opt/venv/bin/celery multi stopwait worker1 \
--pidfile=/var/run/celery.pid
ExecReload=/opt/venv/bin/celery multi restart worker1\
-A ccomptes -l debug -c 5\
--pidfile=/var/run/celery.pid\
--logfile=/var/log/oa-celery.log
[Install]
WantedBy=multi-user.target
```
Pour que le system prenne en compte ce nouveau service taper la commande :
```bash
systemctl daemon-reload
```
Si aucune erreur n'a été retournée, vous pouvez maintenant démarrer le service celery :
```bash
systemctl start celery
```
Les logs du processus celery se trouve dans le fichier /var/log/oa-celery.log
Redémarrer httpd.
## Remplir le /opt/local_config.ini
Le fichier de configuration doit par défaut situé dans le dossier /opt/. Cette valeur peut-être modifiée dans le
fichier ccomptes/settings.py ligne 17. Il faudra ensuite reprendre le fichier local_config.ini.sample, le renommer
puis le completer.
## Créer une base de test du flux CCI
Dans le dossier ./dump_cci, il faut executer les fichiers SQL 01_CCI_DGFIP_DDL.sql puis tous les fichiers
contenus dans le dossier 02_CCI_DGFIP_SQL_Donnees_config. Ensuite, vous pouvez importer les dernière données présentes dans
les fichiers collectivite.csv et execution_2010.csv grace aux commandes suivantes:
```bash
COPY execution_2010 FROM 'execution_2010.csv';
COPY collectivite FROM 'collectivite.csv';
```
## Intéraction avec l'API en python
Le script contenu dans le dossier script contient un exemple permettant de communiquer avec le Back End sans passer par
l'interface graphique. Il permet notamment de lancer plusieurs analyses en même temps.
## Ajout d'une nouvelle Trame.
Pour l'ajout d'une nouvelle trame, vous pouvez vous référer au fichier Trame M14 dans le dossiers docs/.
Il contient des exemples de formule utilisable dans le langage défini dans l'application. Dans le dump_bdd/
vous trouverez un modèles et un paramètrage d'une trame avec les formules des indicateurs.
|
C#
|
UTF-8
| 2,149 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace SharpGLTF.Memory
{
struct EncodedArrayEnumerator<T> : IEnumerator<T>
{
#region lifecycle
public EncodedArrayEnumerator(IReadOnlyList<T> accessor)
{
this._Accessor = accessor;
this._Count = accessor.Count;
this._Index = -1;
}
public void Dispose()
{
}
#endregion
#region data
private readonly IReadOnlyList<T> _Accessor;
private readonly int _Count;
private int _Index;
#endregion
#region API
public T Current => _Accessor[_Index];
object IEnumerator.Current => _Accessor[_Index];
public bool MoveNext()
{
++_Index;
return _Index < _Count;
}
public void Reset()
{
_Index = -1;
}
#endregion
}
static class EncodedArrayUtils
{
public static void _CopyTo(this IEnumerable<Int32> src, IList<UInt32> dst, int dstOffset = 0)
{
using (var ptr = src.GetEnumerator())
{
while (dstOffset < dst.Count && ptr.MoveNext())
{
dst[dstOffset++] = (UInt32)ptr.Current;
}
}
}
public static void _CopyTo<T>(this IEnumerable<T> src, IList<T> dst, int dstOffset = 0)
{
using (var ptr = src.GetEnumerator())
{
while (dstOffset < dst.Count && ptr.MoveNext())
{
dst[dstOffset++] = ptr.Current;
}
}
}
public static int _FirstIndexOf<T>(this IReadOnlyList<T> src, T value)
{
var comparer = EqualityComparer<T>.Default;
var c = src.Count;
for (int i = 0; i < c; ++i)
{
if (comparer.Equals(src[i], value)) return i;
}
return -1;
}
}
}
|
C#
|
UTF-8
| 2,146 | 3.015625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
namespace Squick
{
//TODO
public class Sprite
{
// Référence vers la classe du jeu
private Game e_game;
protected Vector2 _position;
protected Texture2D _texture;
protected Vector2 _speed;
protected bool _active;
// Position à l'écran du Sprite
public Vector2 Position{
get { return _position; }
set { _position = value; }
}
// Texture du Sprite
public Texture2D Texture{
get { return _texture; }
set { _texture = value; }
}
// Vitesse
public Vector2 Speed{
get { return _speed; }
set { _speed = value; }
}
// Largeur de l'image
public int Width{
get { return _texture.Width; }
}
// Hauteur de l'image
public int Height{
get { return _texture.Height; }
}
// Définie si le sprite est actif
public bool Active{
get { return _active; }
set { _active = value; }
}
// Objet Game
public Game Game{
get { return e_game; }
}
// ContentManager pour charger les ressources
public ContentManager Content{
get { return e_game.Content; }
}
#region Constructeurs
public Sprite(Game game) { }
public Sprite(Game game, Vector2 position) : this(game) { }
#endregion
// --- Schéma classique du pattern GameState
public virtual void Initialize() { }
public virtual void LoadContent(string textureName) { }
public virtual void UnloadContent() { }
public virtual void Update(GameTime gameTime) { }
public void Draw(SpriteBatch spriteBatch)
{
if (_active)
spriteBatch.Draw(_texture, _position, Color.White);
}
}
}
|
PHP
|
UTF-8
| 3,897 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
<?php
App::uses('AppHelper', 'View/Helper');
/**
* Ftp Helper
*
* @package cakeftp
* @author Kyle Robinson Young <kyle at dontkry.com>
* @copyright 2011 Kyle Robinson Young
*/
class FtpHelper extends AppHelper {
public $helpers = array('Html', 'Form');
/**
* listFiles
* Prints list of files
*
* @param array $data
* @return string
*/
public function listFiles($data = null) {
$data = array_merge(array(
'files' => array(),
'parent' => '',
), (array)$data);
$out = '';
if (!empty($data['parent'])) {
$parent = $this->Html->link(__d('cakeftp', 'Up Folder'), array(
'action' => 'index', $data['parent'],
));
} else {
$parent = ' ';
}
$out .= $this->Html->tableHeaders(array(
$parent,
__d('cakeftp', 'Last Modified'),
__d('cakeftp', 'Size'),
__d('cakeftp', 'Permissions'),
' ',
));
$cells = array();
if (!empty($data['files'])) {
foreach ($data['files'] as $file) {
extract($file['Ftp']);
if ($is_link == '1') {
$safe = substr($filename, strpos($filename, '-> ') + 3);
} else {
$safe = $path . $filename;
}
$safe = urlencode(base64_encode($safe));
if ($is_dir == '1' || $is_link) {
$filename = $this->Html->link($filename, array(
'action' => 'index', $safe,
));
}
if ($is_dir != '1' && $is_link != '1') {
$actions = $this->Html->link(__d('cakeftp', 'Download'), array(
'action' => 'download', $safe,
));
$actions .= $this->Html->link(__d('cakeftp', 'Delete'), array(
'action' => 'delete', $safe,
), array(), __d('cakeftp', 'Are you sure you wish to delete that file?'));
} else {
$actions = '';
}
$cells[] = array(
$filename,
$mtime,
$size,
$chmod,
array($actions, array('class' => 'actions', 'align' => 'right')),
);
}
}
$out .= $this->Html->tableCells($cells);
$out = $this->Html->tag('table', $out, array(
'cellpadding' => 0,
'cellspacing' => 0,
'width' => '100%',
'border' => 0,
));
return $this->output($out);
}
/**
* uploadForm
* Prints an upload form
*
* @param array $data
* @return string
*/
public function uploadForm($data = null) {
$data = array_merge(array(
'form' => array(
'enctype' => 'multipart/form-data',
'url' => array(
'action' => 'upload',
),
),
'path' => '.',
), (array)$data);
$out = '';
$out .= $this->Form->create('File', $data['form']);
$out .= $this->Form->hidden('path', array('value' => $data['path']));
$out .= $this->Form->input('file', array(
'type' => 'file',
'label' => __d('cakeftp', 'Upload File'),
));
$out .= $this->Form->end(__d('cakeftp', 'Upload'));
return $this->output($out);
}
/**
* loginForm
* Prints a login form
*
* @param array $data
* @return string
* @deprecated Write your own, this will be removed soon.
*/
public function loginForm($data = null) {
$data = array_merge(array(
'form' => array(
'url' => array(
'plugin' => 'ftp',
'controller' => 'client',
'action' => 'index',
),
),
'defaultHost' => 'example.com',
'defaultUsername' => 'user',
'defaultPassword' => '',
'defaultPath' => '.',
'defaultType' => 'ftp',
), (array)$data);
$out = '';
$out .= $this->Form->create('Ftp', $data['form']);
$out .= $this->Form->input('host', array('default' => $data['defaultHost']));
$out .= $this->Form->input('username', array('default' => $data['defaultUsername']));
$out .= $this->Form->input('password', array('default' => $data['defaultPassword']));
$out .= $this->Form->input('path', array('default' => $data['defaultPath']));
$out .= $this->Form->input('type', array(
'options' => array('ftp' => 'ftp', 'ssh' => 'ssh'),
'default' => $data['defaultType'],
));
$out .= $this->Form->input('port');
$out .= $this->Form->end(__d('cakeftp', 'Connect'));
return $this->output($out);
}
}
|
C
|
UTF-8
| 2,671 | 2.765625 | 3 |
[] |
no_license
|
// Maxwell's Underground Mudlib
// Greveck's Triangular Arm Shield
inherit "/std/armour";
string left_side;
void create() {
::create();
set_name("steel shield");
set("id", ({ "shield","steel shield","left-arm shield" }) );
set("short", "a cresent steel left-arm shield");
left_desc = ("This shield is made from pounded steel. The "
"outer edge of the shield is rounded into a cresent shape, with a row "
"of steel razor sharp spikes for impaling into an enemy.\nThe inside "
"curve of the shield is jagged, almost as if it was designed to be "
"joined with another piece\n");
full_desc = ("The shield is made from pounded steel. The round"
"outer edge of the shield has a row of razor sharp spikes for "
"impaling into an ememy.\nThe shield looks like it can be sperated "
"into two pieces.\n")
set_long(left_side);
set_weight(150);
set("value", 1);
set_type("shield");
set_limbs( ({ "left arm"}) );
set_ac(15);
set_ac(150,"impaling");
set_ac(15,"cutting");
set_ac(15,"crushing");
set_wear("You slide you arm through the steel arm clamp, locking "
"the shield securely on." );
set_remove("You undo the shield clamp and pull your arm out.");
set_material("Dwarven Steel");
set_property("shield_status","seperated");
}
init() {
::init();
add_action("join_shield","join");
add_action("seperate_shield","seperate");
}
int join_shield(string str){
if(str == "shield"){
if( (this_object()->query_property("side")) == "left side")
if(!present("right arm-shield")){
write("You can't join the shield, you don't have the right-arm "
"shield!")
return 1;
}
write("You push the two plates together and lock the clamp. The "
"shield is now a complete circle.");
return 1;
}
if( (this_object()->query_property("side")) == "right side")
if(!present("left arm-shield")){
write("You can't join the shield, you don't have the left-arm "
"shield!")
return 1;
}
}
}
}
int seperate_shield(string str){
if(str == "shield"){
if( (this_object()->query_property("shield_status")) == "seperated"){
write("The shield is already seperated!");
return 1;
}
write("You unlock the clamp and pull the shield apart into two "
"seperate arm shields.");
this_object()->set_property("shield_status","seperated");
return 1;
}
}
}
|
Python
|
UTF-8
| 921 | 2.78125 | 3 |
[] |
no_license
|
import pandas as pd
import seaborn as sns
cm = sns.light_palette("green", as_cmap=True)
avg_sen = pd.read_csv("avg_sen.csv")
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import colors
def background_gradient(s, m=None, M=None, cmap='RdYlGn', low=-1, high=1):
if m is None:
m = s.min().min()
if M is None:
M = s.max().max()
rng = M - m
norm = colors.Normalize(m ,M)
normed = s.apply(lambda x: norm(x.values))
cm = plt.cm.get_cmap(cmap)
c = normed.applymap(lambda x: colors.rgb2hex(cm(x)))
c.to_csv("colours.csv", index=False)
ret = c.applymap(lambda x: 'background-color: %s' % x)
return ret
avg_sen.style.apply(background_gradient, axis=None)
colours = pd.read_csv("colours.csv")
colours = colours.rename(columns={'Average Sentiment': 'hex_colour'})
avg_sen['hex_colour'] = colours
avg_sen.to_csv("sentiment_colours.csv", index=False)
|
Markdown
|
UTF-8
| 1,297 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
#csv4cpp [](https://travis-ci.org/astronomerdamo/csv4cpp)
C++ CSV Data File Parser
##Requirements
* C++ compiler [Note: only tested with gcc - see .travis.yml]
##Introduction
I wrote this function after becoming frustrated with the level of difficulty required to read in a tabled data file for use in C++ command line programs. This csv parser uses only standard (STL) C++ libraries
##Installation
```
git clone https://github.com/astronomerdamo/csv4cpp.git
```
##Usage
Feel free to copy only the csv parser function, or compile and test at will. If you choose to copy only the parser make note of the included libraries.
To compile,
```
g++ readcsv.cpp -o readcsv
```
To run using the provided data file example,
```
./readcsv data.csv
```
with output,
0.2 1.2 0.4
0.4 1.3 0.3
0.6 1.8 0.4
0.8 2.4 0.2
Or more generically,
```
./readcsv path_to/data.csv
```
__Note:__
* CSV parser is not built to support comments in data file (it's on my ToDo).
* The data file must have a constant number of columns.
* Every value in the data file should have a numeric value.
* The column delimiter must a single consistent character, a single space between values is ok.
|
C#
|
UTF-8
| 6,600 | 3.53125 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleCalculator
{
class CCalculator
{
/// <summary>expression of the calculation </summary>
private string displayStr = string.Empty;
/// <summary>input of the calculation </summary>
private string resultStr = "0";
public string ResultStr
{
get { return resultStr; }
set { resultStr = value; }
}
/// <summary>
/// operation "+-*/"
/// </summary>
private char opr;
public char Opr
{
get { return opr; }
set { opr = value; }
}
/// <summary>
/// result of the calculation
/// </summary>
private double result;
public double Result
{
get { return result; }
set { result = value; }
}
private double num1;
private double num2;
/// <summary>
/// to judge it's leftarg or rightarg
/// </summary>
private bool first;
/// <summary>
/// cancel once input
/// </summary>
/// <returns>original input</returns>
public string Back()
{
if (resultStr.Length > 0)
{
resultStr = resultStr.Remove(resultStr.Length - 1);//remove the last character of the input string
}
else
{
resultStr = "0";
}
return resultStr;
}
/// <summary>
/// clear all display state of the calculator
/// </summary>
/// <returns>diaplay text</returns>
public string Clear()
{
displayStr = string.Empty;
return displayStr;
}
/// <summary>
/// clear all result state of the calculator
/// </summary>
/// <returns>result text</returns>
public string RClear()
{
result = 0;
resultStr = "0";
return resultStr;
}
#region arithmetic operation
/// <summary>
/// To perform the arithmetic operation of addition.
/// </summary>
/// <param name="leftArg">left addend</param>
/// <param name="rightArg">right addend</param>
/// <returns></returns>
public double Add(double leftArg, double rightArg)
{
return leftArg + rightArg;
}
/// <summary>
/// To perform the arithmetic operation of subtraction.
/// </summary>
/// <param name="leftArg">minuend</param>
/// <param name="rightArg">subtrahend</param>
/// <returns></returns>
public double Subtract(double leftArg, double rightArg)
{
return leftArg - rightArg;
}
/// <summary>
/// To perform the arithmetic operation of multiplication
/// </summary>
/// <param name="leftArg">left multiplier</param>
/// <param name="rightArg">right multiplier</param>
/// <returns></returns>
public double Multiply(double leftArg, double rightArg)
{
return leftArg * rightArg;
}
/// <summary>
/// To perform the arithmetic operation of divisiton.
/// </summary>
/// <param name="leftArg">dividend</param>
/// <param name="rightArg">divisor</param>
/// <returns></returns>
public double Divide(double leftArg, double rightArg)
{
if (Math.Abs(rightArg) < 10e-9)
throw new DivideByZeroException(("Error: Division by zero was performed!"));
return leftArg / rightArg;
}
#endregion
/// <summary>
/// calculate the result of the expression On Normal Mode
/// </summary>
/// <returns></returns>
public string Calc()
{
NumChange();
switch (opr)
{
case '+':
result = Add(num1 , num2);
break;
case '-':
result = Subtract(num1 , num2);
break;
case '*':
result = Multiply(num1 , num2);
break;
case '/':
try
{
result = Divide(num1 , num2);
}
catch (DivideByZeroException ex)//DivideByZeroException may occur
{
resultStr = "divisor can't be 0";
return resultStr;
}
break;
}
resultStr = result.ToString();
return resultStr;
}
/// <summary>
/// set the operator of the expression
/// </summary>
/// <param name="btnopr">+ or - or * or /</param>
/// <returns></returns>
public string SetOperatorByLetter(string btnopr)
{
switch (btnopr)
{
case "+":
this.opr = '+';
break;
case "-":
this.opr = '-';
break;
case "*":
this.opr = '*';
break;
case "/":
this.opr = '/';
break;
}
NumChange();
return opr.ToString();
}
/// <summary>
/// change the right or left number
/// </summary>
public void NumChange()
{
if (!first)
{
num1 = this.result;
}
else
{
num2 = this.result;
}
first = !first;
}
/// <summary>
/// the number of the numberkey
/// </summary>
/// <param name="num">the number of the presskey</param>
/// <returns></returns>
public string NumberKey(string num)
{
if (resultStr.Equals("0"))
{
resultStr = num;
}
else
{
resultStr += num;
}
return resultStr;
}
/// <summary>
/// judge whether "." is used or not
/// </summary>
/// <returns>index of the "."</returns>
public int DotUsed()
{
return resultStr.IndexOf(".");
}
}
}
|
Swift
|
UTF-8
| 1,132 | 3.203125 | 3 |
[] |
no_license
|
import Foundation
public struct GetConfigValue {
var caseSensitive: Bool = false
var filePath: String
var setting: String
public init(caseSensitive: Bool = false, filePath: String, setting: String) {
self.caseSensitive = caseSensitive
self.filePath = filePath
self.setting = setting
}
public func run() throws -> String {
let url = URL(fileURLWithPath: filePath)
let fileContents = try FileReader.readFileContents(from: url)
var output: String?
fileContents.enumerateLines(invoking: { [self] text, stop in
if self.caseSensitive {
guard text.lowercased().starts(with: self.setting) else { return }
} else {
guard text.starts(with: self.setting) else { return }
}
output = text
.split(separator: "=")
.map { String($0) }
.last?
.trimmingCharacters(in: .whitespaces)
})
guard let echo = output else {
throw XCConfigError.settingNotFound
}
return echo
}
}
|
Java
|
UTF-8
| 754 | 1.96875 | 2 |
[] |
no_license
|
package com.lingda.gamble.operation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class NavigationOperationTest {
@Autowired
private LoginOperation loginOperation;
@Autowired
private NavigationOperation navigationOperation;
@Test
public void shouldNavigate() throws InterruptedException {
WebDriver driver = BrowserDriver.getDriver();
loginOperation.doLogin(driver);
navigationOperation.doNavigate(driver);
}
}
|
Python
|
UTF-8
| 1,608 | 3.140625 | 3 |
[
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# This file is part of scorevideo_lib: A library for working with scorevideo
# Use of this file is governed by the license in LICENSE.txt.
"""Test the utilities in :py:mod:`scorevideo_lib.base_utils`
"""
from hypothesis import given, example
from hypothesis.strategies import text, lists
from scorevideo_lib.base_utils import equiv_partition
# pragma pylint: disable=missing-docstring
def test_equiv_partition_simple():
nums = [str(i) for i in [1, 1, 5, 6, 3, 8, 8, 5, 7, 3, 5, 4, 7, 8]]
nums_orig = nums.copy()
partitions = equiv_partition(nums, lambda x, y: x == y)
exp = [['1', '1'], ['5', '5', '5'], ['6'], ['3', '3'], ['8', '8', '8'],
['7', '7'], ['4']]
assert partitions == exp
assert nums == nums_orig
def str_equiv(x, y):
if not x or not y:
return not x and not y
return x[0] == y[0]
# For how to get lists of strings: https://stackoverflow.com/q/43282267
@given(lists(text()))
@example(['', '0', '/'])
def test_equiv_partition_text(lst):
orig = lst.copy()
partitions = equiv_partition(lst, str_equiv)
# Check that elements of a given partition are equivalent
for part in partitions:
for x in part:
for y in part:
assert str_equiv(x, y)
# Check that elements of distinct partitions are not equivalent
for p_1 in partitions:
for p_2 in partitions:
if p_1 != p_2:
for x in p_1:
for y in p_2:
assert not str_equiv(x, y)
# Check that equiv_partition doesn't modify the list
assert orig == lst
|
C++
|
UHC
| 1,854 | 3.359375 | 3 |
[] |
no_license
|
#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;
struct info {
int x, y, p, q;
};
int n;
info coord[100001];
void Input()
{
cin >> n;
for (int i = 0; i < n; ++i)
{
int x, y;
cin >> x >> y;
coord[i].x = x;
coord[i].y = y;
coord[i].p = 1;
coord[i].q = 0;
}
}
// yǥ, xǥ
bool compare(const info& a, const info& b)
{
if (1LL * a.q * b.p != 1LL * a.p * b.q)
return 1LL * a.q * b.p < 1LL * a.p * b.q;
if (a.y != b.y) return a.y < b.y;
return a.x < b.x;
}
long long ccw(const info& f, const info& s, const info& n)
{
return 1LL * (f.x * s.y + s.x * n.y + n.x * f.y - s.x * f.y - n.x * s.y - f.x * n.y);
}
void Solve()
{
// 1. ´. ( yǥ )
sort(coord, coord + n, compare);
for (int i = 1; i < n; ++i)
{
coord[i].p = coord[i].x - coord[0].x;
coord[i].q = coord[i].y - coord[0].y;
}
// 2. Ͽ ٸ ݽð ( )
sort(coord + 1, coord + n, compare);
stack<int> st;
// 3. ÿ ù° ι° شϴ
st.push(0);
st.push(1);
int next = 2;
// 4. ÿ next ccw ؼ > 0 Ȯ(ȸ ϴ)
while (next < n)
{
while (st.size() >= 2)
{
int first, second;
second = st.top();
st.pop();
first = st.top();
// 5. pop ߴ second ٽ ÿ ְ next stack
// 6. < 0̸ (ȸ) popߴ second ְ ٽ
if (ccw(coord[first], coord[second], coord[next]) > 0)
{
st.push(second);
break;
}
}
st.push(next++);
}
cout << st.size();
}
int main(void)
{
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
Input();
Solve();
}
|
Java
|
UTF-8
| 3,007 | 2.390625 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package edu.harvard.iq.dataverse.authorization.providers.oauth2;
import com.nimbusds.jwt.JWT;
import com.nimbusds.oauth2.sdk.id.Subject;
import com.nimbusds.openid.connect.sdk.claims.UserInfo;
import com.nimbusds.openid.connect.sdk.validators.IDTokenValidator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.lang.reflect.Field;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class OIDCValidatorTest {
private OIDCValidator validator;
private JWT token = Mockito.mock(JWT.class);
@BeforeEach
void setUp() {
validator = new OIDCValidator();
}
// -------------------- TESTS --------------------
@Test
@DisplayName("Validation of ID token should fail if inner validator is uninitialized")
void validateIDToken__uninitializedValidator() throws OAuth2Exception {
// when & then
assertThatThrownBy(() -> validator.validateIDToken(token))
.isInstanceOf(OAuth2Exception.class);
}
@Test
@DisplayName("Validation of ID token should use internal validator's validation method")
void validateIDToken() throws Exception {
// given
IDTokenValidator internalValidator = setAndGetInternalMockValidator();
// when
validator.validateIDToken(token);
// then
Mockito.verify(internalValidator, Mockito.only()).validate(token, null);
}
@Test
@DisplayName("Validation of UserInfo should not fail when subjects from ID token and user info endpoint are equal")
void validateUserInfoSubject() throws OAuth2Exception {
// given
String subjectValue = "subject";
UserInfo userInfo = new UserInfo(new Subject(subjectValue));
Subject subjectFromIdToken = new Subject(subjectValue);
// when & then
validator.validateUserInfoSubject(userInfo, subjectFromIdToken);
}
@Test
@DisplayName("Validation of UserInfo should fail when subjects from ID token and user info endpoint are not equal")
void validateUserInfoSubject__differingSubjects() throws OAuth2Exception {
// given
UserInfo userInfo = new UserInfo(new Subject("subject1"));
Subject subjectFromIdToken = new Subject("subject2");
// when & then
assertThatThrownBy(() -> validator.validateUserInfoSubject(userInfo, subjectFromIdToken))
.isInstanceOf(OAuth2Exception.class);
}
// -------------------- PRIVATE --------------------
private IDTokenValidator setAndGetInternalMockValidator() throws Exception {
IDTokenValidator mockValidator = Mockito.mock(IDTokenValidator.class);
Field validatorField = OIDCValidator.class.getDeclaredField("validator");
validatorField.setAccessible(true);
validatorField.set(validator, mockValidator);
validatorField.setAccessible(false);
return mockValidator;
}
}
|
C++
|
UTF-8
| 611 | 2.578125 | 3 |
[] |
no_license
|
#include "World.h"
#include <time.h> /* time */
World::World()
{
gravity = new PuntoVector3D(0, GRAVITY, 0, 1);
srand(time(NULL));
}
World::~World()
{
delete gravity;
}
//NO SE USA
PuntoVector3D* World::getRandomPoint(GLfloat magnitud) {
GLfloat pi = getRandomNum(0.0f, PI);
// De 0 a 180 grados en radianes
GLfloat theta = acos(getRandomNum(-1, 1)); // sin (theta * pi)
PuntoVector3D *v = new PuntoVector3D(sin(theta)*cos(pi), sin(theta)*sin(pi), cos(theta), 1);
PuntoVector3D *aux = new PuntoVector3D(magnitud, magnitud, magnitud, 1);
v->productoEscalar(aux);
delete aux;
return v;
}
|
Java
|
UTF-8
| 2,063 | 3.53125 | 4 |
[] |
no_license
|
package FacebookQuestions;
import java.util.*;
public class QueueRemovals {
public static class Position{
int val, idx;
public Position(int idx, int val){
this.idx = idx;
this.val = val;
}
}
public static void main(String args[]) {
int n_1 = 6;
int x_1 = 5;
int[] arr_1 = {1, 2, 2, 3, 4, 5};
int[] expected_1 = {5, 6, 4, 1, 2 };
int[] output_1 = findPositions(arr_1, x_1);
Arrays.stream(output_1).forEach(value -> System.out.print(value + " "));
int n_2 = 13;
int x_2 = 4;
int[] arr_2 = {2, 4, 2, 4, 3, 1, 2, 2, 3, 4, 3, 4, 4};
int[] expected_2 = {2, 5, 10, 13};
int[] output_2 = findPositions(arr_2, x_2);
System.out.println("NEXT RES: ");
Arrays.stream(output_2).forEach(value -> System.out.print(value + " "));
}
private static int[] findPositions(int[] arr, int x) {
int[] output = new int[x];
Queue<Position> queue = new LinkedList<>();
for(int idx = 0; idx < arr.length; idx++){
queue.add(new Position(idx + 1, arr[idx]));
}
List<Position> poppedElements;
for(int idx = 0; idx < x; idx++){
poppedElements = new ArrayList<>();
int maxVal = Integer.MIN_VALUE;
int maxIdx = -1;
for(int j = 0; j < x && !queue.isEmpty(); j++){
Position currPosition = queue.poll();
poppedElements.add(currPosition);
if(currPosition.val > maxVal){
maxVal = currPosition.val;
maxIdx = currPosition.idx;
}
}
output[idx] = maxIdx;
for(Position popped : poppedElements){
if(popped.idx != maxIdx){
queue.add(new Position(popped.idx, (popped.val == 0) ? 0 : popped.val - 1));
}
}
}
return output;
}
}
|
Java
|
ISO-8859-1
| 226,913 | 1.546875 | 2 |
[] |
no_license
|
package com.gvs.crm.model.impl;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import com.gvs.crm.model.AgendaMovimentacao;
import com.gvs.crm.model.AnulacaoInstrumento;
import com.gvs.crm.model.Apolice;
import com.gvs.crm.model.ApoliceHome;
import com.gvs.crm.model.Aseguradora;
import com.gvs.crm.model.AspectosLegais;
import com.gvs.crm.model.AuxiliarSeguro;
import com.gvs.crm.model.ClassificacaoContas;
import com.gvs.crm.model.CodigoInstrumento;
import com.gvs.crm.model.CodigoInstrumentoHome;
import com.gvs.crm.model.Conta;
import com.gvs.crm.model.Corretora;
import com.gvs.crm.model.DadosCoaseguro;
import com.gvs.crm.model.DadosPrevisao;
import com.gvs.crm.model.DadosReaseguro;
import com.gvs.crm.model.DadosReaseguroHome;
import com.gvs.crm.model.Emissor;
import com.gvs.crm.model.EmissorHome;
import com.gvs.crm.model.Entidade;
import com.gvs.crm.model.EntidadeHome;
import com.gvs.crm.model.Evento;
import com.gvs.crm.model.FaturaSinistro;
import com.gvs.crm.model.Localidade;
import com.gvs.crm.model.LocalidadeHome;
import com.gvs.crm.model.MfAlertaTrempana;
import com.gvs.crm.model.Morosidade;
import com.gvs.crm.model.MovimentacaoFinanceiraConta;
import com.gvs.crm.model.Notificacao;
import com.gvs.crm.model.Parametro;
import com.gvs.crm.model.Plano;
import com.gvs.crm.model.PlanoHome;
import com.gvs.crm.model.Qualificacao;
import com.gvs.crm.model.QualificacaoHome;
import com.gvs.crm.model.Qualificadora;
import com.gvs.crm.model.QualificadoraHome;
import com.gvs.crm.model.RatioPermanente;
import com.gvs.crm.model.RatioTresAnos;
import com.gvs.crm.model.RatioUmAno;
import com.gvs.crm.model.Reaseguradora;
import com.gvs.crm.model.Refinacao;
import com.gvs.crm.model.RegistroAnulacao;
import com.gvs.crm.model.RegistroCobranca;
import com.gvs.crm.model.RegistroGastos;
import com.gvs.crm.model.Sinistro;
import com.gvs.crm.model.SinistroHome;
import com.gvs.crm.model.Suplemento;
import com.gvs.crm.model.Usuario;
import com.gvs.crm.model.UsuarioHome;
import com.gvs.crm.model.Uteis;
import infra.sql.SQLQuery;
import infra.sql.SQLRow;
import infra.sql.SQLUpdate;
public class AgendaMovimentacaoImpl extends EventoImpl implements
AgendaMovimentacao {
private int movimentoMes;
private int movimentoAno;
public void atualizarDataPrevistaConclusao(Date dataPrevistaConclusao) throws Exception
{
super.atualizarDataPrevistaConclusao(dataPrevistaConclusao);
}
public void atualizarDataPrevistaInicio(Date dataPrevistaInicio) throws Exception
{
super.atualizarDataPrevistaInicio(dataPrevistaInicio);
}
public void atualizarValidacao(String mod) throws Exception
{
SQLUpdate update = this.getModelManager().createSQLUpdate("crm","update agenda_movimentacao set validacao = ? where id = ?");
update.addString(mod);
update.addLong(this.obterId());
update.execute();
}
public String obterValidacao() throws Exception
{
SQLQuery query = this.getModelManager().createSQLQuery("crm","select validacao from agenda_movimentacao where id = ?");
query.addLong(this.obterId());
return query.executeAndGetFirstRow().getString("validacao");
}
public String obterIcone() throws Exception {
return "calendar.gif";
}
public void atribuirMesMovimento(int mes) throws Exception {
this.movimentoMes = mes;
}
public void atribuirAnoMovimento(int ano) throws Exception {
this.movimentoAno = ano;
}
public int obterMesMovimento() throws Exception
{
if (this.movimentoMes == 0)
{
SQLQuery query = this.getModelManager().createSQLQuery("crm","select movimento_mes from agenda_movimentacao where id=?");
query.addLong(this.obterId());
this.movimentoMes = query.executeAndGetFirstRow().getInt("movimento_mes");
}
return this.movimentoMes;
}
public int obterAnoMovimento() throws Exception
{
if (this.movimentoAno == 0)
{
SQLQuery query = this.getModelManager().createSQLQuery("crm","select movimento_ano from agenda_movimentacao where id=?");
query.addLong(this.obterId());
this.movimentoAno = query.executeAndGetFirstRow().getInt("movimento_ano");
}
return this.movimentoAno;
}
public boolean existeAgendaNoPeriodo(int mes, int ano, Entidade asseguradora, String tipo) throws Exception
{
boolean existe = false;
SQLQuery query = this.getModelManager().createSQLQuery("crm", "select movimento_mes, movimento_ano from agenda_movimentacao,evento where evento.id=agenda_movimentacao.id and origem=? and movimento_mes=? and movimento_ano=? and tipo=? and validacao=?");
query.addLong(asseguradora.obterId());
query.addInt(mes);
query.addInt(ano);
query.addString(tipo);
query.addString("Total");
SQLRow[] rows = query.execute();
if (rows.length > 0)
existe = true;
return existe;
}
public void incluir() throws Exception
{
super.incluir();
SQLUpdate insert = this.getModelManager().createSQLUpdate("insert into agenda_movimentacao (id, movimento_mes, movimento_ano) values (?,?,?)");
insert.addLong(this.obterId());
insert.addInt(this.obterMesMovimento());
insert.addInt(this.obterAnoMovimento());
insert.execute();
}
public void enviarBcp(String comentario) throws Exception
{
this.concluir(comentario);
for (Iterator i = this.obterInferiores().iterator(); i.hasNext();)
((Evento) i.next()).concluir(null);
}
public boolean permiteEnviarBcp() throws Exception {
boolean permite = false;
for (Iterator i = this.obterInferiores().iterator(); i.hasNext();) {
Evento e = (Evento) i.next();
if (e instanceof Notificacao) {
Notificacao notificacao = (Notificacao) e;
if (notificacao.obterTipo().equals(
"Notificacin de Recebimento"))
permite = true;
}
}
return permite;
}
public boolean permiteValidar() throws Exception {
boolean permite = true;
SQLQuery query = this
.getModelManager()
.createSQLQuery(
"crm",
"SELECT movimentacao_financeira_conta.data_prevista FROM evento,movimentacao_financeira_conta where origem=? and evento.id=movimentacao_financeira_conta.id group by movimentacao_financeira_conta.data_prevista");
query.addLong(this.obterOrigem().obterId());
SQLRow[] rows = query.execute();
for (int i = 0; i < rows.length; i++) {
Date data = new Date(rows[i].getLong("data_prevista"));
String mesEvento = new SimpleDateFormat("MM").format(data);
String anoEvento = new SimpleDateFormat("yyyy").format(data);
if (this.obterMesMovimento() == Integer.parseInt(mesEvento)
&& this.obterAnoMovimento() == Integer.parseInt(anoEvento))
return false;
}
return permite;
}
private String nomeArquivo;
private EntidadeHome home;
private Parametro parametro;
public Collection<String> validaArquivo(String nomeArquivo) throws Exception
{
home = (EntidadeHome) this.getModelManager().getHome("EntidadeHome");
parametro = (Parametro) home.obterEntidadePorApelido("parametros");
Collection<String> linhas = new ArrayList<>();
this.nomeArquivo = nomeArquivo;
File file = new File("" + "c:/Aseguradoras/Archivos/" + nomeArquivo+ ".txt");
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
String str = null;
if (file.exists())
{
while((str = in.readLine())!=null)
linhas.add(str);
in.close();
return this.validadorArquivo(linhas);
}
else
{
in.close();
throw new Exception("Erro: 26 - El Archivo " + nomeArquivo + ".txt no fue encontrado");
}
}
private Collection<String> erros = new ArrayList<>();
private Collection<ClassificacaoContas> classificacaoContasTotalizadas = new ArrayList<ClassificacaoContas>();
/////////////////// MTODO PRA VALIDAR O ARQUIVO CONTABIL
// ////////////////////////////////////////
private Collection<String> validadorArquivo(Collection<String> linhas) throws Exception
{
FileWriter file = new FileWriter("c:/tmp/LogContabil.txt");
//DecimalFormat formataValor = new DecimalFormat("");
int contador = 1;
int sequencial = 1;
EntidadeHome entidadeHome = (EntidadeHome) this.getModelManager().getHome("EntidadeHome");
UsuarioHome usuarioHome = (UsuarioHome) this.getModelManager().getHome("UsuarioHome");
CodigoInstrumentoHome codigoHome = (CodigoInstrumentoHome) this.getModelManager().getHome("CodigoInstrumentoHome");
EmissorHome emissorHome = (EmissorHome) this.getModelManager().getHome("EmissorHome");
QualificadoraHome qualificadoraHome = (QualificadoraHome) this.getModelManager().getHome("QualificadoraHome");
QualificacaoHome qualificacaoHome = (QualificacaoHome) this.getModelManager().getHome("QualificacaoHome");
LocalidadeHome localidadeHome = (LocalidadeHome) this.getModelManager().getHome("LocalidadeHome");
Uteis uteis = new Uteis();
Usuario responsavel = null;
Map<Integer,Integer> tipoRegistro = new TreeMap<>();
int numeroRegistros = 0;
boolean erro = false;
try
{
MovimentacaoFinanceiraConta mf;
MfAlertaTrempana mfAlertaTemprana;
Entidade entidade;
Conta conta;
Date dataInicio;
ClassificacaoContas cConta;
CodigoInstrumento codigoInstrumento;
Emissor emissor;
Qualificadora qualificadora;
Qualificacao qualificacao;
Localidade localidade;
//int mes,ano;
for (String linha : linhas)
{
System.out.println(linha);
//System.out.println("Contador:" + contador);
file.write("Contador: " + contador + " ;Linha: " + linha + "\r\n");
if (Integer.parseInt(linha.substring(5, 7)) != 1
&& Integer.parseInt(linha.substring(5, 7)) != 2
&& Integer.parseInt(linha.substring(5, 7)) != 3
&& Integer.parseInt(linha.substring(5, 7)) != 9)
erros.add("Linea = " + contador
+ " - Erro: xx - Tipo de registro: "
+ linha.substring(5, 7) + " incorrecto");
if (Integer.parseInt(linha.substring(5, 7)) == 1)
{
if (!tipoRegistro.containsKey(new Integer(linha.substring(5, 7))))
tipoRegistro.put(new Integer(linha.substring(5, 7)),new Integer(linha.substring(5, 7)));
else
erros.add("Linea = "+ contador + " - Erro: 07 - Existe ms de un registro tipo 01.");
}
if (Integer.parseInt(linha.substring(5, 7)) == 2)
{
if (!tipoRegistro.containsKey(new Integer(linha.substring(5, 7))))
tipoRegistro.put(new Integer(linha.substring(5, 7)),new Integer(linha.substring(5, 7)));
}
else if (Integer.parseInt(linha.substring(5, 7)) == 3)
{
if (!tipoRegistro.containsKey(new Integer(linha.substring(5, 7))))
tipoRegistro.put(new Integer(linha.substring(5, 7)),new Integer(linha.substring(5, 7)));
}
else if (Integer.parseInt(linha.substring(5, 7)) == 4)
{
if (!tipoRegistro.containsKey(new Integer(linha.substring(5, 7))))
tipoRegistro.put(new Integer(linha.substring(5, 7)),new Integer(linha.substring(5, 7)));
}
else if (Integer.parseInt(linha.substring(5, 7)) == 9)
{
if (!tipoRegistro.containsKey(new Integer(linha.substring(5, 7))))
tipoRegistro.put(new Integer(linha.substring(5, 7)),new Integer(linha.substring(5, 7)));
}
if (contador == linhas.size())
{ /* Final de arquivo *//*
* Rergistro
* 9
*/
if (linha.length() != 9)
{
erros.add("Linea = " + contador + " - Erro: 04 - Tamao de registro invlido.");
break;
}
else
{
/* Registro 9 */
String str01 = linha.substring(0, 5); // 05 Nmero
// Secuencial
sequencial = Integer.parseInt(str01);
if (contador != numeroRegistros)
erros.add("Linea = "+ contador + " - Erro: 09 - Nmero de registros informado no esta coincidiendo con el nmero de registros enviados.");
if (sequencial != contador)
erros.add("Linea = "+ contador + " - Erro 02 - La secuencia de la numeracin del archivo no esta en el orden secuencial y creciente");
if (!tipoRegistro.containsKey(new Integer(2)))
erros.add("Linea = " + contador + " - Erro: 17 - Falta registro tipo 02.");
if (!tipoRegistro.containsKey(new Integer(3)))
erros.add("Linea = " + contador + " - Erro: 18 - Falta registro tipo 03.");
/*if (!tipoRegistro.containsKey(new Integer(4)))
erros.add("Linea = " + contador + " - Erro: 18 - Falta registro tipo 04.");*/
if (!tipoRegistro.containsKey(new Integer(9)))
erros.add("Linea = " + contador + " - Erro: 21 - Falta registro tipo 09.");
}
}
else if (contador == 1)
{/* Comeco de arquivo *//* Rergistro 1 */
if (Integer.parseInt(linha.substring(5, 7)) != 1)
erros.add("Linea = "+ contador + " - Erro: 11 - El registro tipo 01 debe ser el primer registro del archivo.");
else
{
/* Rergistro 1 */
if (linha.length() != 46)
{
erros.add("Linea = "+ contador + " - Erro: 04 - El tamao del registro es diferente del especificado en el formato del registro.");
break;
}
String str01 = linha.substring(0, 5); // 05 Numero
// Secuencial
if (str01.length() != 5)
erros.add("Linha = "+ contador + " Coluna 0~5 - Erro: 04 - Tamanho de registro invlido.");
sequencial = Integer.parseInt(str01);
if (sequencial != contador)
erros.add("Linea = "+ contador + " - Erro 02 - La secuencia de la numeracin del archivo no esta en el orden secuencial y creciente");
String str02 = linha.substring(5, 7); // 02 Identifica el
// registro
if (str02.length() != 2)
erros.add("Linea = "+ contador + " Coluna 5~7 - Erro: 04 - Tamao de registro invlido.");
String str03 = linha.substring(7, 10); // 3 Identifica la
// Aseguradora
if (str03.length() != 3)
erros.add("Linea = "+ contador + " Coluna 7~18 - Erro: 04 - Tamanho de registro invlido.");
seguradora = (Entidade) entidadeHome.obterEntidadePorSigla(str03);
if (seguradora == null)
erros.add("Linea = " + contador+ " - Erro: 08 - Aseguradora " + str03.trim()+ " inexistente.");
else if (this.obterOrigem() != seguradora)
erros.add("Linha = " + contador + " - Erro: 25 - El aseguradora "+ str03.trim()
+ " no es el misma de la agenda.");
String str04 = linha.substring(10, 20); // 10 identifica el
// Usuario
if (str04.length() != 10)
erros.add("Linea = "+ contador+ " Coluna 18~29 - Erro: 04 - Tamao de registro invlido.");
responsavel = (Usuario) usuarioHome.obterUsuarioPorChave(str04.trim());
if (responsavel == null)
erros.add("Linea = " + contador+ " - Erro: 10 - Usuario " + str04.trim()+ " inexistente.");
String str05 = linha.substring(20, 24); // 04 Fecha de
// generacin del
// archivo
if (str05.length() != 4)
erros.add("Linea = "+ contador+ " Coluna 29~33 - Erro: 04 - Tama de registro invlido.");
String str06 = linha.substring(24, 26); // 02 Fecha de
// generacin del
// archivo
if (str06.length() != 2)
erros.add("Linea = "+ contador + " Coluna 33~35 - Erro: 04 - Tamao de registro invlido.");
String str07 = linha.substring(26, 28); // 02 Fecha de
// generacin del
// archivo
if (str07.length() != 2)
erros.add("Linea = "+ contador+ " Coluna 35~37 - Erro: 04 - Tamao de registro invlido.");
String str08 = linha.substring(28, 32); // 04 Ao / Mes del
// Movimiento
if (str08.length() != 4)
erros.add("Linea = "+ contador + " Coluna 37~41 - Erro: 04 - Tamao de registro invlido.");
ano = str08;
String str09 = linha.substring(32, 34); // 02 Mes del
// Movimiento
if (str09.length() != 2)
erros.add("Linea = "+ contador+ " Coluna 41~43 - Erro: 04 - Tamao de registro invlido.");
mes = str09;
if (Integer.parseInt(str09) != this.obterMesMovimento() || Integer.parseInt(str08) != this.obterAnoMovimento())
erros.add("Linea = "+ contador + " - Erro: 23 - Mes/Ao del movimento de la agenda, es diferente del Mes/Ao del Archivo");
String str10 = linha.substring(34, 44); // 10 Nmero total
// de registros
if (str10.length() != 10)
erros.add("Linea = "+ contador + " Coluna 43~53 - Erro: 04 - Tamao de registro invlido.");
numeroRegistros = Integer.parseInt(str10);
}
}
else if (Integer.parseInt(linha.substring(5, 7)) == 2)
{ /* Corpo *//*
* Rergistro
* 2 e
* 3
*/
if (Integer.parseInt(linha.substring(5, 7)) == 2)
if (linha.length() != 142)
{
erros.add("Linea = " + contador+ " - Erro: 04 - Tamao de registro invlido.");
break;
}
/* Rergistro 2 */
mf = (MovimentacaoFinanceiraConta) this.getModelManager().getEntity("MovimentacaoFinanceiraConta");
String str01 = linha.substring(0, 5); // 05 Nmero secuencial
if (str01.length() != 5)
erros.add("Linea = "+ contador+ " Coluna 0~5 - Erro: 04 - Tamao de registro invlido.");
sequencial = Integer.parseInt(str01);
if (sequencial != contador)
erros.add("Linea = " + contador+ " - Erro: 02 - La secuencia de la numeracin del archivo no esta en el orden secuencial y creciente");
String str02 = linha.substring(5, 7); // 02 Identifica el
// registro
if (str02.length() != 2)
erros.add("Linea = "+ contador+ " Coluna 5~7 - Erro: 04 - Tamao de registro invlido.");
String str03 = linha.substring(7, 17); // 10 Cuenta contable
if (str03.length() != 10)
erros.add("Linea = "+ contador+ " Coluna 7~17 - Erro: 04 - Tamao de registro invlido.");
String strNivel = linha.substring(7, 9);
entidade = (Entidade) entidadeHome.obterEntidadePorApelido(str03);
conta = null;
if (entidade instanceof Conta)
conta = (Conta) entidade;
if (conta == null)
erros.add("Linea = " + contador + " - Erro: 14 - Cuenta "+ str03.trim() + " inexistente o invlida.");
else if (!conta.obterAtivo())
erros.add("Linea = " + contador + " - Erro: 19 - Cuenta "+ str03.trim() + " no esta activa.");
String str04 = linha.substring(17, 27); // 10
if (str04.length() != 10)
erros.add("Linea = "+ contador + " Coluna 17~27 - Erro: 04 - Tamao de registro invlido.");
String str05 = linha.substring(27, 49); // 22 Total del
// movimiento de dbito
if (str05.length() != 22)
erros.add("Linea = "+ contador+ " Coluna 27~49 - Erro: 04 - Tamao de registro invlido.");
String str06 = linha.substring(49, 71); // 22 Total del
// movimiento de crdito
if (str06.length() != 22)
erros.add("Linea = "+ contador+ " Coluna 49~71 - Erro: 04 - Tamao de registro invlido.");
String str07 = linha.substring(71, 72); // 01 Estado del saldo
// anterior
if (str07.length() != 1)
erros.add("Linea = "+ contador+ " Coluna 71~72 - Erro: 04 - Tamao de registro invlido.");
String str08 = linha.substring(72, 94); // 22 Saldo del mes
// anterior
if (str08.length() != 22)
erros.add("Linea = "+ contador+ " Coluna 72~94 - Erro: 04 - Tamao de registro invlido.");
String str09 = linha.substring(94, 95); // 01 Estado del saldo
// actual
if (str09.length() != 1)
erros.add("Linea = "+ contador+ " Coluna 94~95 - Erro: 04 - Tamao de registro invlido.");
String str10 = linha.substring(95, 117); // 22 Saldo actual
if (str10.length() != 22)
erros.add("Linea = "+ contador + " Coluna 95~117 - Erro: 04 - Tamao de registro invlido.");
String str11 = linha.substring(117, 118); // 01 Estado del total
// de moneda
// extranjera
if (str11.length() != 1)
erros.add("Linea = "+ contador+ " Coluna 117~118 - Erro: 04 - Tamao de registro invlido.");
String str12 = linha.substring(118, 140); // 22 Total de moneda
// extranjera
if (str12.length() != 22)
erros.add("Linea = "+ contador + " Coluna 118~140 - Erro: 04 - Tamao de registro invlido.");
if (conta != null)
{
mf.atribuirOrigem(seguradora);
mf.atribuirResponsavel(responsavel);
dataInicio = new SimpleDateFormat("dd/MM/yyyy").parse("01/" + mes + "/" + ano);
mf.atribuirDataPrevista(dataInicio);
mf.atribuirConta(conta);
if (strNivel.equals("01") || strNivel.equals("05") || strNivel.equals("06"))
{
if (str07.equals("D"))
mf.atribuirSaldoAnterior(new BigDecimal(str08));
else
mf.atribuirSaldoAnterior(new BigDecimal(str08).multiply(new BigDecimal("-1")));
}
else if (strNivel.equals("02") || strNivel.equals("03") || strNivel.equals("04") || strNivel.equals("07"))
{
if (str07.equals("D"))
mf.atribuirSaldoAnterior(new BigDecimal(str08).multiply(new BigDecimal("-1")));
else
mf.atribuirSaldoAnterior(new BigDecimal(str08));
}
mf.atribuirDebito(new BigDecimal(str05));
mf.atribuirCredito(new BigDecimal(str06));
if (strNivel.equals("01") || strNivel.equals("05") || strNivel.equals("06"))
{
if (str09.equals("D"))
mf.atribuirSaldoAtual(new BigDecimal(str10));
else
mf.atribuirSaldoAtual(new BigDecimal(str10).multiply(new BigDecimal("-1")));
//System.out.println(conta.obterApelido() + " Saldo atual: " + str10);
}
else if (strNivel.equals("02") || strNivel.equals("03") || strNivel.equals("04") || strNivel.equals("07"))
{
if (str09.equals("D"))
mf.atribuirSaldoAtual(new BigDecimal(str10).multiply(new BigDecimal("-1")));
else
mf.atribuirSaldoAtual(new BigDecimal(str10));
//System.out.println(conta.obterApelido() + " Saldo atual: " + str10);
}
if (strNivel.equals("01") || strNivel.equals("05") || strNivel.equals("06"))
{
if (str11.equals("D"))
mf.atribuirSaldoEstrangeiro(new BigDecimal(str12));
else
mf.atribuirSaldoEstrangeiro(new BigDecimal(str12).multiply(new BigDecimal("-1")));
}
else if (strNivel.equals("02") || strNivel.equals("03")|| strNivel.equals("04") || strNivel.equals("07"))
{
if (str11.equals("D"))
mf.atribuirSaldoEstrangeiro(new BigDecimal(str12).multiply(new BigDecimal("-1")));
else
mf.atribuirSaldoEstrangeiro(new BigDecimal(str12));
}
mf.atribuirTitulo("Movimiento da Cuenta "+ conta.obterCodigo());
this.movimentacaoes.add(mf);
if (this.saldoAtualContaTotalizado.containsKey(conta.obterCodigo()))
erros.add("Linea = "+ contador+ " - Erro: 06 - Existe duplicidad del registro " + conta.obterCodigo());
else
{
this.contas.add(conta);
//BigDecimal saldoAtual = new BigDecimal(new Double(mf.obterSaldoAtual()).toString()).setScale(30);
BigDecimal saldoAtual = mf.obterSaldoAtual();
BigDecimal saldoAnterior = mf.obterSaldoAnterior();
BigDecimal credito = mf.obterCredito();
BigDecimal debito = mf.obterDebito();
BigDecimal saldoMoedaEstrangeira = mf.obterSaldoEstrangeiro();
/*if(conta.obterApelido().equals("0605010101") || conta.obterApelido().equals("0701010101") || conta.obterApelido().equals("0701010110") || conta.obterApelido().equals("0701010111") || conta.obterApelido().equals("0701010203"))
{
DecimalFormat formatador = new DecimalFormat();
//formatador.applyPattern("#,##0.00");
System.out.println("-------- " + conta.obterApelido() + " -------");
System.out.println("str10 " + str10);
System.out.println("saldoAtual " + saldoAtual.toPlainString());
System.out.println("saldoAnterior " + formataValor.format(saldoAnterior));
System.out.println("credito " + formataValor.format(credito));
System.out.println("debito " + formataValor.format(debito));
}*/
this.saldoAtualContaTotalizado.put(conta.obterCodigo(),saldoAtual);
this.saldoAnteriorContaTotalizado.put(conta.obterCodigo(), saldoAnterior);
this.creditoContaTotalizado.put(conta.obterCodigo(),credito);
this.debitoContaTotalizado.put(conta.obterCodigo(),debito);
this.saldoMoedaEstrangeiraContaTotalizado.put(conta.obterCodigo(), saldoMoedaEstrangeira);
}
for (Entidade e : conta.obterSuperiores())
{
if (e instanceof ClassificacaoContas)
{
ClassificacaoContas cContas2 = (ClassificacaoContas) e;
if (this.saldoAtualClassificacaoContasTotalizado.containsKey(cContas2.obterCodigo()))
{
BigDecimal valor = new BigDecimal(this.saldoAtualClassificacaoContasTotalizado.get(cContas2.obterCodigo()).toString());
//BigDecimal valor2 = valor.add(new BigDecimal(new Double(mf.obterSaldoAtual()).toString()));
BigDecimal valor2 = valor.add(mf.obterSaldoAtual());
/*if(cContas2.obterApelido().equals("0605010000"))
{
System.out.println(formataValor.format(valor) + " + Saldo atual " + mf.obterConta().obterApelido() + " " + formataValor.format(mf.obterSaldoAtual()));
}*/
this.saldoAtualClassificacaoContasTotalizado.remove(cContas2.obterCodigo());
this.saldoAtualClassificacaoContasTotalizado.put(cContas2.obterCodigo(),valor2);
}
else
{
/*if(cContas2.obterApelido().equals("0605010000"))
{
System.out.println("Saldo atual " + mf.obterConta().obterApelido() + " " + formataValor.format(mf.obterSaldoAtual()));
}*/
//BigDecimal novoValor = new BigDecimal(new Double(mf.obterSaldoAtual()).toString());
BigDecimal novoValor = mf.obterSaldoAtual();
this.saldoAtualClassificacaoContasTotalizado.put(cContas2.obterCodigo(),novoValor);
}
if (this.saldoAnteriorClassificacaoContasTotalizado.containsKey(cContas2.obterCodigo()))
{
BigDecimal valor = new BigDecimal(this.saldoAnteriorClassificacaoContasTotalizado.get(cContas2.obterCodigo()).toString());
BigDecimal valor2 = valor.add(mf.obterSaldoAnterior());
this.saldoAnteriorClassificacaoContasTotalizado.remove(cContas2.obterCodigo());
this.saldoAnteriorClassificacaoContasTotalizado.put(cContas2.obterCodigo(), valor2);
}
else
{
BigDecimal novoValor = mf.obterSaldoAnterior();
this.saldoAnteriorClassificacaoContasTotalizado.put(cContas2.obterCodigo(),novoValor);
}
if (this.saldoMoedaEstrangeiraClassificacaoContasTotalizado.containsKey(cContas2.obterCodigo()))
{
BigDecimal valor = new BigDecimal(this.saldoMoedaEstrangeiraClassificacaoContasTotalizado.get(cContas2.obterCodigo()).toString());
BigDecimal valor2 = valor.add(mf.obterSaldoEstrangeiro());
this.saldoMoedaEstrangeiraClassificacaoContasTotalizado.remove(cContas2.obterCodigo());
this.saldoMoedaEstrangeiraClassificacaoContasTotalizado.put(cContas2.obterCodigo(), valor2);
}
else
{
BigDecimal novoValor = mf.obterSaldoEstrangeiro();
this.saldoMoedaEstrangeiraClassificacaoContasTotalizado.put(cContas2.obterCodigo(), novoValor);
}
if (this.creditoClassificacaoContasTotalizado.containsKey(cContas2.obterCodigo()))
{
BigDecimal valor = new BigDecimal(this.creditoClassificacaoContasTotalizado.get(cContas2.obterCodigo()).toString());
BigDecimal valor2 = valor.add(mf.obterCredito());
this.creditoClassificacaoContasTotalizado.remove(cContas2.obterCodigo());
this.creditoClassificacaoContasTotalizado.put(cContas2.obterCodigo(), valor2);
//System.out.println(cContas2.obterCodigo() + " Credito: " + valor2);
}
else
{
BigDecimal novoValor = mf.obterCredito();
this.creditoClassificacaoContasTotalizado.put(cContas2.obterCodigo(), novoValor);
//System.out.println(cContas2.obterCodigo() + " Credito: " + novoValor);
}
if (this.debitoClassificacaoContasTotalizado.containsKey(cContas2.obterCodigo()))
{
BigDecimal valor = new BigDecimal(this.debitoClassificacaoContasTotalizado.get(cContas2.obterCodigo()).toString());
BigDecimal valor2 = valor.add(mf.obterDebito());
this.debitoClassificacaoContasTotalizado.remove(cContas2.obterCodigo());
this.debitoClassificacaoContasTotalizado.put(cContas2.obterCodigo(), valor2);
}
else
{
BigDecimal novoValor = mf.obterDebito();
this.debitoClassificacaoContasTotalizado.put(cContas2.obterCodigo(), novoValor);
}
if (!this.classificacaoContasTotalizadas.contains(cContas2) && !cContas2.obterCodigo().equals("0000000000"))
this.classificacaoContasTotalizadas.add(cContas2);
}
}
}
}
else if (Integer.parseInt(linha.substring(5, 7)) == 3)
{
if (linha.length() != 52)
{
erros.add("Linea = " + contador+ " - Erro: 04 - Tamao de registro invlido.");
break;
}
/* Rergistro 3 */
String str01 = linha.substring(0, 5); // 05 Nmero secuencial
if (str01.length() != 5)
erros.add("Linea = "+ contador+ " Coluna 0~5 - Erro: 04 - Tamao de registro invlido.");
sequencial = Integer.parseInt(str01);
if (sequencial != contador)
erros.add("Linea = " + contador+ " - Erro: 02 Nmero sequencial invalido.");
String str02 = linha.substring(5, 7); // 02 Identifica el
// registro
if (str02.length() != 2)
erros.add("Linea = "+ contador+ " Coluna 5~7 - Erro: 04 - Tamao de registro invlido.");
String str03 = linha.substring(7, 17); // 10 Cuenta contable
if (str03.length() != 10)
erros.add("Linea = "+ contador+ " Coluna 7~17 - Erro: 04 - Tamao de registro invalido.");
String strNivel = linha.substring(7, 9);
cConta = null;
entidade = (Entidade) entidadeHome.obterEntidadePorApelido(str03);
if (entidade instanceof ClassificacaoContas)
cConta = (ClassificacaoContas) entidade;
if (cConta == null)
erros.add("Linea = " + contador + " - Erro: 14 - "+ str03.trim()+ " no es una clasificacin de cuenta.");
String str04 = linha.substring(17, 27); // 10
if (str04.length() != 10)
erros.add("Linea = "+ contador+ " Coluna 17~27 - Erro: 04 - Tamao de registro invlido.");
String str05 = linha.substring(27, 28); // 01 Estado del total
// del nivel
if (str05.length() != 1)
erros.add("Linea = "+ contador+ " Coluna 27~28 - Erro: 04 - Tamao de registro invlido.");
String str06 = linha.substring(28, 50); // 22 Total del nivel
if (str06.length() != 22)
erros.add("Linea = "+ contador+ " Coluna 28~50 - Erro: 04 - Tamao de registro invlido.");
if (cConta != null)
{
if (!this.classificacaoContas.contains(cConta))
{
this.classificacaoContas.add(cConta);
//if(cConta.obterApelido().equals("0605010000"))
//System.out.println("");
if (!this.saldoAtualClassificacaoContasTotalizado.containsKey(cConta.obterCodigo()))
erros.add("Linea = "+ contador+ " - Erro: 24 - Cuenta " + cConta.obterCodigo()+ " totalizada no posee registro de asiento del tipo 02");
else
{
double valorTotalizadoMemoria = Double.parseDouble(this.saldoAtualClassificacaoContasTotalizado.get(cConta.obterCodigo()).toString());
double valorTotalizadoArquivo = Double.parseDouble(str06);
if (strNivel.equals("01") || strNivel.equals("05")|| strNivel.equals("06"))
{
if (str05.equals("C"))
valorTotalizadoArquivo = valorTotalizadoArquivo * -1;
}
else if (strNivel.equals("02")
|| strNivel.equals("03")
|| strNivel.equals("04")
|| strNivel.equals("07")) {
if (str05.equals("D"))
valorTotalizadoArquivo = valorTotalizadoArquivo * -1;
}
if (valorTotalizadoMemoria != valorTotalizadoArquivo)
{
erros.add("Linea = "+ contador+ " - Erro: 20 - Sumatoria del saldo de la cuenta: "+ cConta.obterCodigo()+ " esta incorrecta.");
/*System.out.println("Classif.: " + cConta.obterCodigo());
System.out.println("valorTotalizadoMemoria: "+ formataValor.format(valorTotalizadoMemoria));
System.out.println("valorTotalizadoArquivo: "+ formataValor.format(valorTotalizadoArquivo));
System.out.println("valorTotalizadoArquivo: "+ str06);
System.out.println("----------------------: ");*/
}
}
} else
erros.add("Linea = " + contador+ " - Erro: 21 - Cuenta "+ cConta.obterCodigo() + " esta em duplicidad");
}
}
else if (Integer.parseInt(linha.substring(5, 7)) == 4)
{
if (linha.length() != 137)
{
erros.add("Linea = " + contador+ " - Erro: 04 - Tamao de registro invlido.");
break;
}
codigoInstrumento = null;
emissor = null;
qualificadora = null;
qualificacao = null;
localidade = null;
String codAtivoStr = linha.substring(7,8);
String codInstrumentoStr = linha.substring(8,11);
String dataExtincaoStr = linha.substring(11,19);
String emissorStr = linha.substring(19,23);
String qualificadoraStr = linha.substring(23,25);
String qualificacaoStr = linha.substring(25,27);
String valorStr = linha.substring(27,49);
String porcentagemAcoesStr = linha.substring(49,56);
String mercadoStr = linha.substring(56,60);
String patrimonioStr = linha.substring(60,82);
String numeroFincaStr = linha.substring(82,91);
String localidadeStr = linha.substring(91,94);
String contaCorrenteStr = linha.substring(94,109);
String restringidoStr = linha.substring(109,110);
String valorRepresentativoStr = linha.substring(110,132);
String tipoInversaoStr = linha.substring(132,135);
int codAtivo = 0,codInstrumento = 0, codEmissor = 0, codQualificadora = 0, codQualificacao = 0, numeroFinca = 0, codLocalidade = 0, tipoInversao = 0;
Date dataExtincao = null;
BigDecimal valor = new BigDecimal(0);
BigDecimal porcentagemAcoes = new BigDecimal(0);
BigDecimal patrimonio = new BigDecimal(0);
BigDecimal valorRepresentativo = new BigDecimal(0);
if(uteis.eNumero(codAtivoStr))
{
codAtivo = Integer.valueOf(codAtivoStr);
if(codAtivo!=1 && codAtivo!=2)
erros.add("Linea = " + contador+ " - Error: 352 - Cdigo del activo diferente de 1 y 2. Informacin del archivo = " + codAtivoStr);
}
else
erros.add("Linea = " + contador+ " - Error: 351 - Cdigo del activo no es numrico. Informacin del archivo = " + codAtivoStr);
if(uteis.eNumero(codInstrumentoStr))
{
codInstrumento = Integer.valueOf(codInstrumentoStr);
codigoInstrumento = codigoHome.obterCodigoInstrumento(codInstrumento);
if(codigoInstrumento == null)
erros.add("Linea = " + contador+ " - Error: 370 - Cdigo del Instrumento "+codInstrumentoStr +" no fue encontrado");
}
else
erros.add("Linea = " + contador+ " - Error: 353 - Cdigo del Instrumento no es numrico. Informacin del archivo = " + codInstrumentoStr);
if((codInstrumento >= 1 && codInstrumento <= 3) || codInstrumento == 5)
{
if(uteis.eDataContabil(dataExtincaoStr))
{
String data = dataExtincaoStr.substring(6,8)+"/"+dataExtincaoStr.substring(4,6)+"/"+dataExtincaoStr.substring(0,4);
dataExtincao = new SimpleDateFormat("dd/MM/yyyy").parse(data);
}
else
erros.add("Linea = " + contador+ " - Error: 354 - Fecha de extincin o de maturacin no es una fecha. Informacin del archivo = " + dataExtincaoStr);
}
if((codInstrumento >= 1 && codInstrumento <= 12) || codInstrumento == 18)
{
if(uteis.eNumero(emissorStr))
{
codEmissor = Integer.valueOf(emissorStr);
emissor = emissorHome.obterEmissor(codEmissor);
if(emissor == null)
erros.add("Linea = " + contador+ " - Error: 371 - Cdigo del Emisor "+emissorStr +" no fue encontrado");
}
else
erros.add("Linea = " + contador+ " - Error: 355 - Cdigo del Emisor no es numrico. Informacin del archivo = " + emissorStr);
}
if(codInstrumento == 3 || codInstrumento == 5 || codInstrumento == 7 || codInstrumento == 9 || codInstrumento == 11)
{
if(uteis.eNumero(qualificadoraStr))
{
codQualificadora = Integer.valueOf(qualificadoraStr);
qualificadora = qualificadoraHome.obterQualificadora(codQualificadora);
if(qualificadora == null)
erros.add("Linea = " + contador+ " - Error: 372 - Cdigo de la Calificadora "+qualificadoraStr +" no fue encontrado");
}
else
erros.add("Linea = " + contador+ " - Error: 356 - Cdigo de la Calificadora no es numrico. Informacin del archivo = " + qualificadoraStr);
if(uteis.eNumero(qualificacaoStr))
{
codQualificacao = Integer.valueOf(qualificacaoStr);
qualificacao = qualificacaoHome.obterQualificacao(codQualificacao);
if(qualificacao == null)
erros.add("Linea = " + contador+ " - Error: 373 - Cdigo de la Calificacin "+qualificacaoStr +" no fue encontrado");
}
else
erros.add("Linea = " + contador+ " - Error: 357 - Cdigo de la Calificacin no es numrico. Informacin del archivo = " + qualificacaoStr);
}
if(uteis.eNumero(valorStr))
valor = new BigDecimal(valorStr);
else
erros.add("Linea = " + contador+ " - Error: 358 - Valor no es numrico. Informacin del archivo = " + valorStr);
if(codInstrumento >= 8 && codInstrumento <= 10)
{
if(uteis.eNumero(porcentagemAcoesStr))
porcentagemAcoes = new BigDecimal(porcentagemAcoesStr);
else
erros.add("Linea = " + contador+ " - Error: 359 - Porcentaje de las acciones no es numrico. Informacin del archivo = " + porcentagemAcoesStr);
}
if(codInstrumento == 9 || codInstrumento == 11)
{
if(!mercadoStr.toLowerCase().equals("i") && !mercadoStr.toLowerCase().equals("m") && !mercadoStr.toLowerCase().equals("p") && !mercadoStr.toLowerCase().equals("s"))
erros.add("Linea = " + contador+ " - Error: 360 - Mercado diferente de I, M, P, S. Informacin del archivo = " + mercadoStr);
}
else
{
if(!mercadoStr.equals(""))
erros.add("Linea = " + contador+ " - Error: 361 - Mercado debe estar en blanco. Informacin del archivo = " + mercadoStr);
}
if(codInstrumento == 4 || codInstrumento == 6)
{
if(uteis.eNumero(patrimonioStr))
patrimonio = new BigDecimal(patrimonioStr);
else
erros.add("Linea = " + contador+ " - Error: 362 - Patrimonio no es numrico. Informacin del archivo = " + patrimonioStr);
}
if(codInstrumento == 16 || codInstrumento == 17)
{
if(uteis.eNumero(numeroFincaStr))
numeroFinca = Integer.valueOf(numeroFincaStr);
else
erros.add("Linea = " + contador+ " - Error: 363 - Nmero de Finca no es numrico. Informacin del archivo = " + numeroFincaStr);
if(uteis.eNumero(localidadeStr))
{
codLocalidade = Integer.valueOf(localidadeStr);
localidade = localidadeHome.obterLocalidade(codLocalidade);
if(localidade == null)
erros.add("Linea = " + contador+ " - Error: 374 - Localidad "+localidadeStr +" no fue encontrada");
}
else
erros.add("Linea = " + contador+ " - Error: 364 - Localidad no es numrico. Informacin del archivo = " + localidadeStr);
if(contaCorrenteStr.equals(""))
erros.add("Linea = " + contador+ " - Error: 365 - Cuenta Corriente Catastral es obligatoria");
if(!restringidoStr.toLowerCase().equals("a") && !restringidoStr.toLowerCase().equals("c") && !restringidoStr.toLowerCase().equals("i") && !restringidoStr.toLowerCase().equals("u") && !restringidoStr.toLowerCase().equals("v") && !restringidoStr.toLowerCase().equals("n"))
erros.add("Linea = " + contador+ " - Error: 366 - Restringido o no de acuerdo al Artculo 6 diferente de A, C, I, U, V, N. Informacin del archivo = " + restringidoStr);
if(uteis.eNumero(valorRepresentativoStr))
valorRepresentativo = new BigDecimal(valorRepresentativoStr);
else
erros.add("Linea = " + contador+ " - Error: 367 - Valor Representativo no es numrico. Informacin del archivo = " + valorRepresentativoStr);
}
else
{
if(!contaCorrenteStr.equals(""))
erros.add("Linea = " + contador+ " - Error: 368 - Cuenta Corriente Catastral debe estar en blanco. Informacin del archivo = " + contaCorrenteStr);
if(!restringidoStr.equals(""))
erros.add("Linea = " + contador+ " - Error: 369 - Restringido o no de acuerdo al Artculo 6 debe estar en blanco. Informacin del archivo = " + restringidoStr);
}
if(codInstrumento == 18)
{
if(uteis.eNumero(tipoInversaoStr))
tipoInversao = Integer.valueOf(tipoInversaoStr);
else
erros.add("Linea = " + contador+ " - Error: 375 - Tipo de Inversin no es numrico. Informacin del archivo = " + tipoInversaoStr);
}
else
{
if(!tipoInversaoStr.equals(""))
erros.add("Linea = " + contador+ " - Error: 376 - Tipo de Inversin debe estar en blanco. Informacin del archivo = " + tipoInversaoStr);
}
if(erros.size() == 0)
{
mfAlertaTemprana = (MfAlertaTrempana) this.getModelManager().getEntity("MfAlertaTrempana");
mfAlertaTemprana.atribuirAno(Integer.valueOf(ano));
mfAlertaTemprana.atribuirMes(Integer.valueOf(mes));
mfAlertaTemprana.atribuirCodigoAtivo(codAtivo);
mfAlertaTemprana.atribuirCodigoInstrumento(codigoInstrumento);
mfAlertaTemprana.atribuirContaCorrente(contaCorrenteStr);
mfAlertaTemprana.atribuirDataExtincao(dataExtincao);
mfAlertaTemprana.atribuirEmissor(emissor);
mfAlertaTemprana.atribuirLocalidade(localidade);
mfAlertaTemprana.atribuirMercado(mercadoStr);
mfAlertaTemprana.atribuirNumeroFinca(numeroFinca);
mfAlertaTemprana.atribuirPatrimonio(patrimonio);
mfAlertaTemprana.atribuirPorcentagemAcoes(porcentagemAcoes);
mfAlertaTemprana.atribuirQualificacao(qualificacao);
mfAlertaTemprana.atribuirQualificadora(qualificadora);
mfAlertaTemprana.atribuirRestringido(restringidoStr);
mfAlertaTemprana.atribuirTipoInversao(tipoInversao);
mfAlertaTemprana.atribuirValor(valor);
mfAlertaTemprana.atribuirValorRepresentativo(valorRepresentativo);
movimentacaoesAlertaTemprana.add(mfAlertaTemprana);
}
}
contador++;
}
for (ClassificacaoContas cContas : this.classificacaoContasTotalizadas)
{
if (!this.classificacaoContas.contains(cContas))
erros.add("Erro: 22 - La Cuenta " + cContas.obterCodigo()+ " no fue totalizada");
}
//Collection totContasNivel3 = new ArrayList();
Collection<String> validaTotContasNivel3 = new ArrayList<>();
validaTotContasNivel3 = this.validarTotatizadorContasNivel3(saldoAtualContaTotalizado.values());
erros = validaTotContasNivel3;
if (erros.size() == 0)
this.compararContas();
file.write("Comparou as contas \r\n");
if (erros.size() == 0)
{
if (this.obterMesMovimento() != 7)
{
this.compararSaldoAtualComAnterior();
file.write("Comparou Saldo atual com anterior \r\n");
}
}
if (erros.size() == 0)
{
this.gravarMovimentacaoes();
file.write("Gravou Movimentaes \r\n");
this.copiarArquivo();
file.write("Copiou os arquivos \r\n");
}
}
catch (Exception e)
{
System.out.println(e.toString());
erros.add(e.toString() + " - Linea: " + contador);
file.write(e.toString() + "\r\n");
file.close();
erro = true;
}
if(!erro)
file.close();
return erros;
}
/////////////////// FIM DO MTODO PRA VALIDAR O ARQUIVO CONTABIL
// ////////////////////////////////////////
private void copiarArquivo() throws Exception
{
InputStream is = null;
OutputStream os = null;
byte[] buffer;
boolean success = true;
try {
//is = new FileInputStream("" + "/Aseguradoras/Archivos/" +
// this.nomeArquivo + ".txt");
is = new FileInputStream("" + "C:/Aseguradoras/Archivos/"
+ this.nomeArquivo + ".txt");
//os = new FileOutputStream("" + "/Aseguradoras/Backup/" +
// this.nomeArquivo + "_Backup.txt" );
os = new FileOutputStream("" + "C:/Aseguradoras/Backup/"
+ this.nomeArquivo + "_Backup.txt");
buffer = new byte[is.available()];
is.read(buffer);
os.write(buffer);
} catch (IOException e) {
success = false;
} catch (OutOfMemoryError e) {
success = false;
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
File arquivo = new File("C:/Aseguradoras/Archivos/" + this.nomeArquivo
+ ".txt");
//File arquivo = new File("/Aseguradoras/Archivos/" + this.nomeArquivo
// + ".txt");
arquivo.delete();
System.out.println("arquivo.delete(): " + arquivo.delete());
}
private void compararContas() throws Exception
{
DecimalFormat formatador = new DecimalFormat();
formatador.applyPattern("#,##0.00");
BigDecimal saldoAtual,saldoAnterior,credito,debito,saldoMoedaEstrangeira,tot;
for (Conta conta : this.contas)
{
saldoAtual = this.saldoAtualContaTotalizado.get(conta.obterCodigo());
saldoAnterior = this.saldoAnteriorContaTotalizado.get(conta.obterCodigo());
credito = this.creditoContaTotalizado.get(conta.obterCodigo());
debito = this.debitoContaTotalizado.get(conta.obterCodigo());
saldoMoedaEstrangeira = this.saldoMoedaEstrangeiraContaTotalizado.get(conta.obterCodigo());
if (conta.obterApelido().substring(0, 2).equals("01") || conta.obterApelido().substring(0, 2).equals("05") || conta.obterApelido().substring(0, 2).equals("06"))
{
//double tot = (saldoAnterior + debito) - credito;
tot = (saldoAnterior.add(debito)).subtract(credito);
tot.setScale(30);
if (saldoAtual.doubleValue() != tot.doubleValue())
{
erros.add("Erro: 348 - Cuenta " + conta.obterApelido() + " el saldo atual no cuadra");
System.out.println("1 - " +conta.obterApelido()+" saldoAtual " + saldoAtual + " tot " + tot);
}
}
else if (conta.obterApelido().substring(0, 2).equals("02") || conta.obterApelido().substring(0, 2).equals("03") || conta.obterApelido().substring(0, 2).equals("04") || conta.obterApelido().substring(0, 2).equals("07"))
{
//double tot = (saldoAnterior - debito) + credito;
tot = (saldoAnterior.subtract(debito)).add(credito);
if (saldoAtual.doubleValue() != tot.doubleValue())
{
erros.add("Erro: 348 - Cuenta " + conta.obterApelido()+ " el saldo atual no cuadra");
System.out.println("2 - " +conta.obterApelido()+" saldoAtual " + saldoAtual + " tot " + tot);
}
}
}
}
private void compararSaldoAtualComAnterior() throws Exception
{
ClassificacaoContas cContas1 = (ClassificacaoContas) home.obterEntidadePorApelido("0100000000");
ClassificacaoContas cContas2 = (ClassificacaoContas) home.obterEntidadePorApelido("0200000000");
ClassificacaoContas cContas3 = (ClassificacaoContas) home.obterEntidadePorApelido("0300000000");
ClassificacaoContas cContas4 = (ClassificacaoContas) home.obterEntidadePorApelido("0400000000");
ClassificacaoContas cContas5 = (ClassificacaoContas) home.obterEntidadePorApelido("0500000000");
ClassificacaoContas cContas6 = (ClassificacaoContas) home.obterEntidadePorApelido("0600000000");
ClassificacaoContas cContas7 = (ClassificacaoContas) home.obterEntidadePorApelido("0700000000");
Collection<ClassificacaoContas> contas = new ArrayList<>();
contas.add(cContas1);
contas.add(cContas2);
contas.add(cContas3);
contas.add(cContas4);
contas.add(cContas5);
contas.add(cContas6);
contas.add(cContas7);
int mesModificado = Integer.parseInt(mes);
int anoModificado = Integer.parseInt(ano);
if (mesModificado == 1)
{
mesModificado = 12;
anoModificado--;
}
else
mesModificado--;
String mesModificado2 = new Integer(mesModificado).toString();
if (mesModificado2.length() == 1)
mesModificado2 = "0" + mesModificado2;
String mesAnoModificao = mesModificado2 + new Integer(anoModificado).toString();
double saldoAnteriorMesAnterior,saldoAnteriorMesAtual;
for (ClassificacaoContas cContas : contas)
{
saldoAnteriorMesAnterior = cContas.obterTotalizacaoExistente(this.obterOrigem(), mesAnoModificao);
if (this.saldoAnteriorClassificacaoContasTotalizado.get(cContas.obterCodigo()) != null)
{
saldoAnteriorMesAtual = Double.parseDouble(this.saldoAnteriorClassificacaoContasTotalizado.get(cContas.obterCodigo()).toString());
if (saldoAnteriorMesAtual != saldoAnteriorMesAnterior)
{
System.out.println("saldoAnteriorMesAnterior: " + saldoAnteriorMesAnterior);
System.out.println("saldoAnteriorMesAtual: " + saldoAnteriorMesAtual);
erros.add("Erro: 350 - Saldo Acual de la Cuenta " + cContas.obterApelido() + " no se cuadra en Saldo Anterior");
}
}
if(cContas.obterApelido().equals("0100000000") || cContas.obterApelido().equals("0200000000"))
{
if(this.saldoAnteriorClassificacaoContasTotalizado.get(cContas.obterCodigo()) != null && this.saldoAtualClassificacaoContasTotalizado.get(cContas.obterCodigo())!=null)
{
double saldoAnterior = Double.parseDouble(this.saldoAnteriorClassificacaoContasTotalizado.get(cContas.obterCodigo()).toString());
double saldoAtual = Double.parseDouble(this.saldoAtualClassificacaoContasTotalizado.get(cContas.obterCodigo()).toString());
//if(saldoAtual == saldoAnterior)
//erros.add("Erro: 350 - Saldo Actual de la Cuenta " + cContas.obterApelido() + " s el mismo que el Saldo Anterior (en el archivo)");
}
}
}
}
private void gravarMovimentacaoes() throws Exception
{
for(MovimentacaoFinanceiraConta mf : this.movimentacaoes)
mf.incluir();
for(MfAlertaTrempana mf : this.movimentacaoesAlertaTemprana)
mf.incluir();
this.gravarTotalizacoes();
}
private void gravarTotalizacoes() throws Exception
{
BigDecimal saldoAtual,saldoAnterior,credito,debito,moedaEstrangeira,saldoMoedaEstrangeira;
for (ClassificacaoContas cContas : this.classificacaoContas)
{
saldoAtual = this.saldoAtualClassificacaoContasTotalizado.get(cContas.obterCodigo());
saldoAnterior = this.saldoAnteriorClassificacaoContasTotalizado.get(cContas.obterCodigo());
credito = this.creditoClassificacaoContasTotalizado.get(cContas.obterCodigo());
debito = this.debitoClassificacaoContasTotalizado.get(cContas.obterCodigo());
moedaEstrangeira = this.saldoMoedaEstrangeiraClassificacaoContasTotalizado.get(cContas.obterCodigo());
//System.out.println(cContas.obterApelido() + " CreditoCcontas: " + credito);
//System.out.println(cContas.obterApelido() + " DebitoCcontas: " + debito);
cContas.incluirRelatorio(mes + ano, saldoAtual.doubleValue(), debito.doubleValue(), credito.doubleValue(),saldoAnterior.doubleValue(), moedaEstrangeira.doubleValue(), seguradora);
}
for (Conta conta : this.contas)
{
saldoAtual = this.saldoAtualContaTotalizado.get(conta.obterCodigo());
saldoAnterior = this.saldoAnteriorContaTotalizado.get(conta.obterCodigo());
credito = this.creditoContaTotalizado.get(conta.obterCodigo());
debito = this.debitoContaTotalizado.get(conta.obterCodigo());
saldoMoedaEstrangeira = this.saldoMoedaEstrangeiraContaTotalizado.get(conta.obterCodigo());
//System.out.println(conta.obterApelido() + " CreditoCcontas: " + credito);
//System.out.println(conta.obterApelido() + " DebitoCcontas: " + debito);
conta.incluirRelatorio(mes + ano, saldoAtual.doubleValue(),saldoMoedaEstrangeira.doubleValue(), debito.doubleValue(), credito.doubleValue(), saldoAnterior.doubleValue(), seguradora);
}
}
private Collection<Conta> contas = new ArrayList<>();
private Collection<ClassificacaoContas> classificacaoContas = new ArrayList<>();
private Map<String, BigDecimal> saldoAtualContaTotalizado = new TreeMap<String, BigDecimal>();
private Map<String, BigDecimal> saldoAnteriorContaTotalizado = new TreeMap<String, BigDecimal>();
private Map<String, BigDecimal> saldoMoedaEstrangeiraContaTotalizado = new TreeMap<String, BigDecimal>();
private Map<String, BigDecimal> debitoContaTotalizado = new TreeMap<String, BigDecimal>();
private Map<String, BigDecimal> creditoContaTotalizado = new TreeMap<String, BigDecimal>();
private Map<String, BigDecimal> saldoAtualClassificacaoContasTotalizado = new TreeMap<String, BigDecimal>();
private Map<String, BigDecimal> saldoAnteriorClassificacaoContasTotalizado = new TreeMap<String, BigDecimal>();
private Map<String, BigDecimal> saldoMoedaEstrangeiraClassificacaoContasTotalizado = new TreeMap<String, BigDecimal>();
private Map<String, BigDecimal> debitoClassificacaoContasTotalizado = new TreeMap<String, BigDecimal>();
private Map<String, BigDecimal> creditoClassificacaoContasTotalizado = new TreeMap<String, BigDecimal>();
private Collection<MovimentacaoFinanceiraConta> movimentacaoes = new ArrayList<>();
private Collection<MfAlertaTrempana> movimentacaoesAlertaTemprana = new ArrayList<>();
private Entidade seguradora;
private String ano;
private String mes;
/*
* File f = new File("/tmp/teste.txt"); FileOutputStream fo = new
* FileOutputStream(f);
*/
//System.getProperty("line.separator");
/*
* String caminhoArquivo = getServletContext().getRealPath("/WEB-INF") +
* System.getProperty("file.separator") + nomeArq;
*
* FileWriter writer = new FileWriter(caminhoArquivo, true); PrintWriter
* arqLog = new PrintWriter(writer, true);
*
* SimpleDateFormat formataData = new SimpleDateFormat();
* formataData.applyPattern("dd/MM/yyyy 's' HH:mm:ss"); String
* dataHoraAtuais = formataData.format(new
* Date(System.currentTimeMillis()));
*
* BufferedWrite bw = new BufferedWriter(new
* FileWriter("/home/use/arquivo.txt")); depois eh so chamar o bw.writer("")
* passando uma string se o array for de string,faz um lao percorrendo todo
* o array e sai escrevendo no buffer,depois chama bw.flush() para fechar o
* buffer
*
* arqLog.println("email: " + email + " Data/Hora: " + dataHoraAtuais);
*
* arqLog.close(); writer.close();
*/
private Collection<String> validarTotatizadorContasNivel3(Collection<BigDecimal> contasTotalizadas) throws Exception
{
//EntidadeHome entidadeHome = (EntidadeHome) this.getModelManager().getHome("EntidadeHome");
//UsuarioHome usuarioHome = (UsuarioHome) this.getModelManager().getHome("UsuarioHome");
//FileWriter w = new FileWriter("c:/tmp/ConsParam.txt");
try
{
ClassificacaoContas cContas;
Entidade entidade;
for (Parametro.Consistencia consistencia : parametro.obterConsistencias())
{
//w.write(consistencia.obterSequencial() + "\r\n");
if (consistencia.obterOperando1().substring(0, 1).equals("c"))
{
if (home.obterEntidadePorApelido(consistencia.obterOperando1().substring(1,consistencia.obterOperando1().length())) != null)
{
entidade = (Entidade) home.obterEntidadePorApelido(consistencia.obterOperando1().substring(1,consistencia.obterOperando1().length()));
if (entidade instanceof ClassificacaoContas)
{
cContas = (ClassificacaoContas) entidade;
/*if(cContas.obterApelido().equals("0305000000"))
System.out.println("");*/
if (this.saldoAtualClassificacaoContasTotalizado.containsKey(cContas.obterCodigo()))
this.analisaOperador(cContas, consistencia, consistencia.obterOperando1(), consistencia.obterOperador(), consistencia.obterOperando2());
}
}
}
else if (consistencia.obterOperando1().equals("A"))
{
entidade = (Entidade) home.obterEntidadePorApelido(consistencia.obterOperando2().substring(1,consistencia.obterOperando2().length()));
if (entidade instanceof ClassificacaoContas)
{
cContas = (ClassificacaoContas) entidade;
if (this.saldoAtualClassificacaoContasTotalizado.containsKey(cContas.obterCodigo()))
this.analisaOperador(cContas, consistencia, consistencia.obterOperando1(), consistencia.obterOperador(), consistencia.obterOperando2());
}
else
this.analisaOperador(null, consistencia, consistencia.obterOperando1(), consistencia.obterOperador(),consistencia.obterOperando2());
}
else if (consistencia.obterOperando1().equals("B"))
{
entidade = (Entidade) home.obterEntidadePorApelido(consistencia.obterOperando2().substring(1,consistencia.obterOperando2().length()));
if (entidade instanceof ClassificacaoContas)
{
cContas = (ClassificacaoContas) entidade;
if (this.saldoAtualClassificacaoContasTotalizado.containsKey(cContas.obterCodigo()))
this.analisaOperador(cContas, consistencia,consistencia.obterOperando1(), consistencia.obterOperador(), consistencia.obterOperando2());
}
else
this.analisaOperador(null, consistencia, consistencia.obterOperando1(), consistencia.obterOperador(),consistencia.obterOperando2());
}
}
//w.close();
}
catch (Exception e)
{
erros.add(e.toString() + " - Error Interno: (validarTotatizadorContasNivel3)\r\n");
//w.write(e.toString() + "\r\n");
//w.close();
}
return erros;
}
private BigDecimal A = new BigDecimal("0.00");
private BigDecimal B = new BigDecimal("0.00");
private Collection analisaOperador(ClassificacaoContas cContas,Parametro.Consistencia consistencia, String operando1,String operador, String operando2) throws Exception
{
if (operador.equals("=="))
this.verificarConsistencias(cContas, consistencia, operando1, 1,operando2);
else if (operador.equals(">="))
this.verificarConsistencias(cContas, consistencia, operando1, 2,operando2);
else if (operador.equals(">"))
this.verificarConsistencias(cContas, consistencia, operando1, 3,operando2);
else if (operador.equals("<="))
this.verificarConsistencias(cContas, consistencia, operando1, 4,operando2);
else if (operador.equals("<"))
this.verificarConsistencias(cContas, consistencia, operando1, 5,operando2);
else if (operador.equals("<>"))
this.verificarConsistencias(cContas, consistencia, operando1, 6,operando2);
else if (operador.equals("="))
this.verificarConsistencias(cContas, consistencia, operando1, 7,operando2);
else if (operador.equals("+"))
this.verificarConsistencias(cContas, consistencia, operando1, 8,operando2);
else
erros.add("Operador Invlido");
return erros;
}
private Collection verificarConsistencias(ClassificacaoContas cContas,Parametro.Consistencia consistencia, String operando1,int operador, String operando2) throws Exception
{
BigDecimal totalizacao = new BigDecimal("0.00");
BigDecimal operando2Double = new BigDecimal("0.00");
switch (operador)
{
case 1:
{
if ((operando1.equals("A") && operando2.equals("B")) || (operando1.equals("B") && operando2.equals("A")))
{
if (this.A.doubleValue() == this.B.doubleValue())
{
}
else
{
System.out.println("A: " + this.A);
System.out.println("B: " + this.B);
erros.add(consistencia.obterMensagem());
}
}
else
{
if(cContas.obterApelido().equals("0305000000"))
System.out.println("");
totalizacao = this.saldoAtualClassificacaoContasTotalizado.get(cContas.obterCodigo());
operando2Double = new BigDecimal(operando2);
if (totalizacao.doubleValue() == operando2Double.doubleValue())
{
}
else
{
System.out.println(cContas.obterApelido() + " - totalizacao: " + totalizacao);
System.out.println("operando2: " + operando2);
erros.add(consistencia.obterMensagem());
}
}
//System.out.println("1 " + cContas.obterApelido() + ": " + totalizacao);
break;
}
case 2: {
if ((operando1.equals("A") && operando2.equals("B")) || operando1.equals("B") && operando2.equals("A"))
{
if (this.A.doubleValue() >= this.B.doubleValue())
{
}
else
erros.add(consistencia.obterMensagem());
}
else
{
if (operando1.equals("A"))
{
if (this.A.doubleValue() >= 0)
{
}
else
erros.add(consistencia.obterMensagem());
}
else if (operando1.equals("B"))
{
if (this.B.doubleValue() >= 0)
{
}
else
erros.add(consistencia.obterMensagem());
}
else
{
totalizacao = this.saldoAtualClassificacaoContasTotalizado.get(cContas.obterCodigo());
if (!operando2.equals("A"))
operando2Double = new BigDecimal(operando2);
else if (this.A.doubleValue() > 0)
operando2Double = this.A;
if(totalizacao.doubleValue() >= operando2Double.doubleValue())
{
}
else
erros.add(consistencia.obterMensagem());
}
}
//System.out.println("2 " + cContas.obterApelido() + ": " + totalizacao);
break;
}
case 3: {
if ((operando1.equals("A") && operando2.equals("B")) || operando1.equals("B") && operando2.equals("A"))
{
if (this.A.doubleValue() > this.B.doubleValue())
{
}
else
erros.add(consistencia.obterMensagem());
}
else
{
if (operando1.equals("A"))
{
if (this.A.doubleValue() > 0)
{
}
else
erros.add(consistencia.obterMensagem());
}
else if (operando1.equals("B"))
{
if (this.B.doubleValue() > 0)
{
}
else
erros.add(consistencia.obterMensagem());
}
else
{
totalizacao = this.saldoAtualClassificacaoContasTotalizado.get(cContas.obterCodigo());
if (!operando2.equals("A"))
operando2Double = new BigDecimal(operando2);
else if (this.A.doubleValue() > 0)
operando2Double = this.A;
/*
* System.out.println("totalizacao: " + totalizacao);
* System.out.println("operando2Double: " +
* operando2Double);
*/
if (totalizacao.doubleValue() > operando2Double.doubleValue())
{
}
else
{
erros.add(consistencia.obterMensagem());
}
}
}
//System.out.println("3 " + cContas.obterApelido() + ": " + totalizacao);
break;
}
case 4: {
if ((operando1.equals("A") && operando2.equals("B")) || operando1.equals("B") && operando2.equals("A"))
{
if (this.A.doubleValue() <= this.B.doubleValue())
{
}
else
erros.add(consistencia.obterMensagem());
}
else
{
System.out.println("operando1: " + operando1);
if (operando1.equals("A"))
{
if (this.A.doubleValue() <= 0)
{
}
else
erros.add(consistencia.obterMensagem());
}
else if (operando1.equals("B"))
{
if (this.B.doubleValue() <= 0)
{
}
else
erros.add(consistencia.obterMensagem());
}
else
{
totalizacao = this.saldoAtualClassificacaoContasTotalizado.get(cContas.obterCodigo());
if (!operando2.equals("A"))
operando2Double = new BigDecimal(operando2);
else if (this.A.doubleValue() > 0)
operando2Double = this.A;
/*
* System.out.println("totalizacao: " + totalizacao);
* System.out.println("operando2Double: " +
* operando2Double);
*/
if (totalizacao.doubleValue() <= operando2Double.doubleValue())
{
}
else
{
erros.add(consistencia.obterMensagem());
}
}
}
//System.out.println("4 " + cContas.obterApelido() + ": " + totalizacao);
break;
}
case 5: {
if ((operando1.equals("A") && operando2.equals("B")) || operando1.equals("B") && operando2.equals("A"))
{
if (this.A.doubleValue() < this.B.doubleValue())
{
}
else
erros.add(consistencia.obterMensagem());
}
else
{
if (operando1.equals("A"))
{
if (this.A.doubleValue() < 0)
{
}
else
erros.add(consistencia.obterMensagem());
}
else if (operando1.equals("B"))
{
if (this.B.doubleValue() < 0)
{
}
else
erros.add(consistencia.obterMensagem());
}
else
{
totalizacao = this.saldoAtualClassificacaoContasTotalizado.get(cContas.obterCodigo());
if (!operando2.equals("A"))
operando2Double = new BigDecimal(operando2);
else if (this.A.doubleValue() > 0)
operando2Double = this.A;
if (totalizacao.doubleValue() < operando2Double.doubleValue())
{
}
else
{
erros.add(consistencia.obterMensagem());
}
}
}
//System.out.println("5 " + cContas.obterApelido() + ": " + totalizacao);
break;
}
case 6: {
if ((operando1.equals("A") && operando2.equals("B")) || operando1.equals("B") && operando2.equals("A"))
{
if (this.A.doubleValue() != this.B.doubleValue())
{
}
else
erros.add(consistencia.obterMensagem());
}
else
{
if (operando1.equals("A"))
{
if (this.A.doubleValue() != 0)
{
}
else
erros.add(consistencia.obterMensagem());
}
else if (operando1.equals("B"))
{
if (this.B.doubleValue() != 0)
{
}
else
erros.add(consistencia.obterMensagem());
}
else
{
totalizacao = this.saldoAtualClassificacaoContasTotalizado.get(cContas.obterCodigo());
operando2Double = new BigDecimal(operando2);
if (totalizacao.doubleValue() != operando2Double.doubleValue())
{
}
else
{
erros.add(consistencia.obterMensagem());
}
}
}
//System.out.println("6 " + cContas.obterApelido() + ": " + totalizacao);
break;
}
case 7: {
if (operando1.equals("A") && operando2.equals("B"))
this.A = this.B;
else if (operando1.equals("B") && operando2.equals("A"))
this.B = this.A;
else if (operando1.equals("A") && operando2.equals("0"))
this.A = new BigDecimal("0.00");
else if (operando1.equals("B") && operando2.equals("0"))
this.B = new BigDecimal("0.00");
break;
}
case 8: {
if (operando1.equals("A"))
this.A = this.A.add(this.saldoAtualClassificacaoContasTotalizado.get(cContas.obterCodigo()));
else if (operando1.equals("B"))
this.B = this.B.add(this.saldoAtualClassificacaoContasTotalizado.get(cContas.obterCodigo()));
break;
}
default: {
erros.add("Operador Invlido");
}
}
return erros;
}
public Collection verificarApolice(String nomeArquivo) throws Exception {
Collection linhas = new ArrayList();
String bufferAux = "";
File file = new File("" + "C:/Aseguradoras/Archivos/" + "A"
+ nomeArquivo + ".txt");
File file2 = new File("" + "C:/Aseguradoras/Archivos/" + "B"
+ nomeArquivo + ".txt");
//File file = new File( "" + "/Aseguradoras/Archivos/" + "A" +
// nomeArquivo + ".txt" );
//File file2 = new File( "" + "/Aseguradoras/Archivos/" + "B" +
// nomeArquivo + ".txt" );
if (file.exists()) {
FileInputStream inputStreamArquivo = new FileInputStream(""
+ "C:/Aseguradoras/Archivos/" + "A" + nomeArquivo + ".txt");
//FileInputStream inputStreamArquivo = new FileInputStream( "" +
// "/Aseguradoras/Archivos/" + "A"+ nomeArquivo + ".txt" );
DataInputStream inputStreamData = new DataInputStream(
inputStreamArquivo);
while ((bufferAux = inputStreamData.readLine()) != null) {
linhas.add(new String(bufferAux));
}
if (file2.exists()) {
Collection erros = new ArrayList();
erros = this.validarApolice(linhas);
linhas.clear();
FileInputStream inputStreamArquivo2 = new FileInputStream(""
+ "C:/Aseguradoras/Archivos/" + "B" + nomeArquivo
+ ".txt");
//FileInputStream inputStreamArquivo2 = new FileInputStream( ""
// + "/Aseguradoras/Archivos/" + "B"+ nomeArquivo + ".txt" );
DataInputStream inputStreamData2 = new DataInputStream(
inputStreamArquivo2);
while ((bufferAux = inputStreamData2.readLine()) != null) {
linhas.add(new String(bufferAux));
}
this.validarAsegurado(linhas);
System.out.println("Total de Erros: " + erros.size());
if (erros.size() == 0) {
this.nomeArquivo = "A" + nomeArquivo;
this.copiarArquivo();
this.nomeArquivo = "B" + nomeArquivo;
this.copiarArquivo();
}
return erros;
} else
throw new Exception("Error: 02 - El Archivo " + "B"
+ nomeArquivo
+ ".txt no fue encontrado (Datos del Asegurado)");
} else
throw new Exception("Error: 01 - El Archivo " + "A" + nomeArquivo
+ ".txt no fue encontrado");
}
private Map apolices = new TreeMap();
private Collection dadosPrevisoes = new ArrayList();
private Map dadosReaseguros = new TreeMap();
private Collection dadosCoaseguros = new ArrayList();
private Map sinistros = new TreeMap();
private Collection faturas = new ArrayList();
private Collection anulacoes = new ArrayList();
private Collection cobrancas = new ArrayList();
private Collection aspectos2 = new ArrayList();
private Collection suplementos = new ArrayList();
private Collection refinacoes = new ArrayList();
private Collection gastos2 = new ArrayList();
private Collection anulacoes2 = new ArrayList();
private Collection morosidades = new ArrayList();
private Collection ratiosPermanentes = new ArrayList();
private Collection ratiosUmAno = new ArrayList();
private Collection ratiosTresAnos = new ArrayList();
private Collection validarApolice(Collection linhas) throws Exception {
int numeroLinha = 1;
PlanoHome planoHome = (PlanoHome) this.getModelManager().getHome(
"PlanoHome");
ApoliceHome apoliceHome = (ApoliceHome) this.getModelManager().getHome(
"ApoliceHome");
DadosReaseguroHome dadosReaseguroHome = (DadosReaseguroHome) this
.getModelManager().getHome("DadosReaseguroHome");
SinistroHome sinistroHome = (SinistroHome) this.getModelManager()
.getHome("SinistroHome");
EntidadeHome entidadeHome = (EntidadeHome) this.getModelManager()
.getHome("EntidadeHome");
UsuarioHome usuarioHome = (UsuarioHome) this.getModelManager().getHome(
"UsuarioHome");
Aseguradora aseguradora = null;
Usuario usuario = null;
Date dataGeracao = null;
String tipoArquivo = null;
int numeroTotalRegistros = 0;
for (Iterator i = linhas.iterator(); i.hasNext();) {
String linha = (String) i.next();
if (Integer.parseInt(linha.substring(0, 5)) != numeroLinha)
erros.add("Error: 02 - Numero secuencial invalido - Linea: "
+ numeroLinha);
System.out.println("numeroLinha: " + numeroLinha);
// REGISTRO TIPO 1
if (Integer.parseInt(linha.substring(5, 7)) == 1) {
String sigla = linha.substring(7, 10);
aseguradora = (Aseguradora) entidadeHome
.obterEntidadePorSigla(sigla);
if (aseguradora == null)
erros.add("Error: 03 - Aseguradora " + sigla
+ " no fue encontrada - Linea: " + numeroLinha);
else {
if (!this.obterOrigem().equals(aseguradora))
erros.add("Error: 06 - Aseguradora " + sigla
+ " no es la misma de la agenda - Linea: "
+ numeroLinha);
}
String chaveUsuario = linha.substring(10, 19);
usuario = usuarioHome.obterUsuarioPorChave(chaveUsuario.trim());
if (usuario == null)
erros.add("Error: 04 - Usuario " + chaveUsuario.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
String anoGeracao = linha.substring(20, 24);
String mesGeracao = linha.substring(24, 26);
String diaGeracao = linha.substring(26, 28);
if (diaGeracao.startsWith(" ") || mesGeracao.startsWith(" ")
|| diaGeracao.startsWith(" "))
erros.add("Error: 92 - Fecha Emisin Invalida - Linea: "
+ numeroLinha);
else
dataGeracao = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaGeracao + "/" + mesGeracao + "/"
+ anoGeracao);
String anoReporte = linha.substring(28, 32);
String mesReporte = linha.substring(32, 34);
if (this.obterMesMovimento() != Integer.parseInt(mesReporte))
erros
.add("Error: 07 - Mes informado es diferente del mes de la agenda");
if (this.obterAnoMovimento() != Integer.parseInt(anoReporte))
erros
.add("Error: 08 - Ao informado es diferente del ao de la agenda");
numeroTotalRegistros = Integer
.parseInt(linha.substring(34, 44));
tipoArquivo = "";
if (linha.substring(44, 45).equals("|"))
tipoArquivo = "Instrumento de cobertura";
}
// REGISTRO TIPO 2
else if (Integer.parseInt(linha.substring(5, 7)) == 2) {
Apolice apolice = (Apolice) this.getModelManager().getEntity(
"Apolice");
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String numeroApolice = linha.substring(17, 27);
String tipoApolice = "";
if (linha.substring(27, 28).equals(""))
erros
.add("Error: 12 - Status del Instrumento es obligatorio - Linea: "
+ numeroLinha);
if (linha.substring(27, 28).equals("1"))
tipoApolice = "Nuevo";
else if (linha.substring(27, 28).equals("2"))
tipoApolice = "Renovado";
Apolice apoliceAnterior = null;
if (this.apolices != null)
apoliceAnterior = (Apolice) this.apolices.get(linha
.substring(28, 38));
if (apoliceAnterior == null)
apoliceAnterior = apoliceHome.obterApolice(linha.substring(
28, 38));
String statusApolice = "";
//System.out.println("statusApolice: " +
// linha.substring(38,39));
if (linha.substring(38, 39).equals(""))
erros
.add("Error: 13 - Tipo del Instrumento es obligatorio - Linea: "
+ numeroLinha);
if (linha.substring(38, 39).equals("1"))
statusApolice = "Pliza Individual";
else if (linha.substring(38, 39).equals("2"))
statusApolice = "Pliza Madre";
else if (linha.substring(38, 39).equals("3"))
statusApolice = "Certificado de Seguro Colectivo";
else if (linha.substring(38, 39).equals("4"))
statusApolice = "Certificado Provisorio";
else if (linha.substring(38, 39).equals("5"))
statusApolice = "Nota de Cobertura de Raseguro";
String apoliceSuperiorStr = linha.substring(39, 49);
Apolice apoliceSuperior = null;
if (this.apolices != null)
apoliceSuperior = (Apolice) this.apolices
.get(apoliceSuperiorStr);
if (apoliceSuperior == null)
apoliceSuperior = apoliceHome
.obterApolice(apoliceSuperiorStr);
String afetadorPorSinistro = "";
if (linha.substring(49, 50).equals("1"))
afetadorPorSinistro = "S";
else if (linha.substring(49, 50).equals("2"))
afetadorPorSinistro = "No";
if (afetadorPorSinistro.equals(""))
erros
.add("Error: 14 - Afectado por Sinistro es obligatorio - Linea: "
+ numeroLinha);
String apoliceFlutuante = "";
if (linha.substring(50, 51).equals("1"))
apoliceFlutuante = "S";
else if (linha.substring(50, 51).equals("2"))
apoliceFlutuante = "No";
if (apoliceFlutuante.equals(""))
erros
.add("Error: 15 - Pliza Flotante es obligatorio - Linea: "
+ numeroLinha);
String codigoPlano = linha.substring(51, 63);
Plano plano = null;
if (!codigoPlano.equals("RG-0001")) {
plano = planoHome.obterPlano(codigoPlano);
if (plano == null)
erros.add("Error: 85 - Numero del Plan " + codigoPlano
+ " no fue encontrado - Linea: " + numeroLinha);
}
String numeroFatura = linha.substring(63, 72);
if (numeroFatura.equals(""))
erros
.add("Error: 16 - Numero de la Factura es obligatorio - Linea: "
+ numeroLinha);
String modalidadeVenda = "";
if (linha.substring(72, 73).equals("1"))
modalidadeVenda = "Con Intermediario";
else if (linha.substring(72, 73).equals("2"))
modalidadeVenda = "Sin Intermediario";
if (modalidadeVenda.equals(""))
erros
.add("Error: 17 - Modalidad de Venta es obligatorio - Linea: "
+ numeroLinha);
String anoInicioVigencia = linha.substring(73, 77);
String mesInicioVigencia = linha.substring(77, 79);
String diaInicioVigencia = linha.substring(79, 81);
Date dataIncioVigencia = null;
if (diaInicioVigencia.startsWith(" ")
|| mesInicioVigencia.startsWith(" ")
|| anoInicioVigencia.startsWith(" "))
erros
.add("Error: 92 - Fecha Inicio Vigencia Invalida - Linea: "
+ numeroLinha);
else
dataIncioVigencia = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaInicioVigencia + "/" + mesInicioVigencia
+ "/" + anoInicioVigencia);
String anoFimVigencia = linha.substring(81, 85);
String mesFimVigencia = linha.substring(85, 87);
String diaFimVigencia = linha.substring(87, 89);
Date dataFimVigencia = null;
if (diaFimVigencia.startsWith(" ")
|| mesFimVigencia.startsWith(" ")
|| anoFimVigencia.startsWith(" "))
erros
.add("Error: 92 - Fecha Fin Vigencia Invalida - Linea: "
+ numeroLinha);
else
dataFimVigencia = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaFimVigencia + "/" + mesFimVigencia + "/"
+ anoFimVigencia);
String diasCobertura = linha.substring(89, 94);
if (diasCobertura.equals(""))
erros
.add("Error: 18 - Dias de cobertura es obligatorio - Linea: "
+ numeroLinha);
String anoEmissao = linha.substring(94, 98);
String mesEmissao = linha.substring(98, 100);
String diaEmissao = linha.substring(100, 102);
Date dataEmissao = null;
if (diaEmissao.startsWith(" ") || mesEmissao.startsWith(" ")
|| anoEmissao.startsWith(" "))
erros.add("Error: 92 - Fecha Emisin Invalida - Linea: "
+ numeroLinha);
else
dataEmissao = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaEmissao + "/" + mesEmissao + "/"
+ anoEmissao);
String capitalGuaraniStr = linha.substring(102, 124);
if (capitalGuaraniStr.equals(""))
erros
.add("Error: 19 - Capital en Riesgo en Guaranies es obligatorio - Linea: "
+ numeroLinha);
double capitalGuarani = Double.parseDouble(capitalGuaraniStr);
String tipoMoedaCapitalGuarani = this.obterTipoMoeda(linha
.substring(124, 126));
String capitalMeStr = linha.substring(126, 148);
double capitalMe = Double.parseDouble(capitalMeStr);
String primasSeguroStr = linha.substring(148, 170);
if (primasSeguroStr.equals(""))
erros
.add("Error: 20 - Prima en Guaranies es obligatorio - Linea: "
+ numeroLinha);
double primasSeguro = Double.parseDouble(primasSeguroStr);
String tipoMoedaPrimas = this.obterTipoMoeda(linha.substring(
170, 172));
String primasMeStr = linha.substring(172, 194);
double primasMe = Double.parseDouble(primasMeStr);
String principalGuaraniStr = linha.substring(194, 216);
double principalGuarani = Double
.parseDouble(principalGuaraniStr);
String tipoMoedaPrincipalGuarani = this.obterTipoMoeda(linha
.substring(216, 218));
String principalMeStr = linha.substring(218, 240);
double principalMe = Double.parseDouble(principalMeStr);
String incapacidadeGuaraniStr = linha.substring(240, 262);
double incapacidadeGuarani = Double
.parseDouble(incapacidadeGuaraniStr);
String tipoMoedaIncapacidadeGuarani = this.obterTipoMoeda(linha
.substring(262, 264));
String incapacidadeMeStr = linha.substring(264, 286);
double incapacidadeMe = Double.parseDouble(incapacidadeMeStr);
String enfermidadeGuaraniStr = linha.substring(286, 308);
double enfermidadeGuarani = Double
.parseDouble(enfermidadeGuaraniStr);
String tipoMoedaEnfermidade = this.obterTipoMoeda(linha
.substring(308, 310));
String enfermidadeMeStr = linha.substring(310, 332);
double enfermidadeMe = Double.parseDouble(enfermidadeMeStr);
String acidentesGuaraniStr = linha.substring(332, 354);
double acidentesGuarani = Double
.parseDouble(acidentesGuaraniStr);
String tipoMoedaAcidente = this.obterTipoMoeda(linha.substring(
354, 356));
String acidentesMeStr = linha.substring(356, 378);
double acidentesMe = Double.parseDouble(acidentesMeStr);
String outrosGuaraniStr = linha.substring(378, 400);
double outrosGuarani = Double.parseDouble(outrosGuaraniStr);
String tipoMoedaOutros = this.obterTipoMoeda(linha.substring(
400, 402));
String outrosMeStr = linha.substring(402, 424);
double outrosMe = Double.parseDouble(outrosMeStr);
String financimantoGsStr = linha.substring(424, 446);
if (financimantoGsStr.equals(""))
erros
.add("Error: 21 - Inters por Financiamiento en Gs es obligatorio - Linea: "
+ numeroLinha);
double financimantoGS = Double.parseDouble(financimantoGsStr);
String tipoMoedaFinanciamentoGS = this.obterTipoMoeda(linha
.substring(446, 448));
String financiamentoMeStr = linha.substring(448, 470);
double financiamentoMe = Double.parseDouble(financiamentoMeStr);
String premioGsStr = linha.substring(470, 492);
if (premioGsStr.equals(""))
erros
.add("Error: 22 - Premio en Gs es obligatorio - Linea: "
+ numeroLinha);
double premioGs = Double.parseDouble(premioGsStr);
String tipoMoedaPremio = this.obterTipoMoeda(linha.substring(
492, 494));
String premioMeStr = linha.substring(494, 516);
double premioMe = Double.parseDouble(premioMeStr);
String formaPagamento = "";
if (linha.substring(516, 517).equals("1"))
formaPagamento = "Al contado";
else if (linha.substring(516, 517).equals("2"))
formaPagamento = "Financiado";
if (formaPagamento.equals(""))
erros
.add("Error: 23 - Forma de Pago es obligatorio - Linea: "
+ numeroLinha);
String qtdeParcelas = linha.substring(517, 520);
String refinacao = "";
if (linha.substring(520, 521).equals("1"))
refinacao = "S";
else if (linha.substring(520, 521).equals("2"))
refinacao = "No";
String inscricaoAgente = linha.substring(521, 525);
Entidade agente = null;
if (!inscricaoAgente.equals("0000")) {
if (inscricaoAgente.substring(0, 1).equals("0"))
agente = entidadeHome
.obterEntidadePorInscricao(inscricaoAgente
.substring(1, inscricaoAgente.length()));
else
agente = entidadeHome
.obterEntidadePorInscricao(inscricaoAgente);
if (agente == null)
erros.add("Error: 09 - Agente con inscripcin "
+ inscricaoAgente.substring(1, inscricaoAgente
.length())
+ " no fue encontrado - Linea: " + numeroLinha);
}
String comissaoGsStr = linha.substring(525, 547);
double comissaoGs = Double.parseDouble(comissaoGsStr);
String tipoMoedaComissaoGs = this.obterTipoMoeda(linha
.substring(547, 549));
String comissaoMeStr = linha.substring(549, 571);
double comissaoMe = Double.parseDouble(comissaoMeStr);
String situacaoSeguro = "";
if (linha.substring(571, 572).equals("1"))
situacaoSeguro = "Vigente";
else if (linha.substring(571, 572).equals("2"))
situacaoSeguro = "No Vigente Pendiente";
else if (linha.substring(571, 572).equals("3"))
situacaoSeguro = "No Vigente";
Corretora corredor = null;
String inscricaoCorredor = linha.substring(572, 576);
if (!inscricaoCorredor.equals("0000")) {
if (inscricaoCorredor.substring(0, 1).equals("0"))
corredor = (Corretora) entidadeHome
.obterEntidadePorInscricao(inscricaoCorredor
.substring(1, inscricaoCorredor
.length()));
else
corredor = (Corretora) entidadeHome
.obterEntidadePorInscricao(inscricaoCorredor);
if (corredor == null)
erros.add("Error: 09 - Corredor con inscripcin "
+ inscricaoCorredor.substring(1,
inscricaoCorredor.length())
+ " no fue encontrado - Linea: " + numeroLinha);
}
double numeroEndoso = Double.parseDouble(linha.substring(576,
586));
double certificado = Double.parseDouble(linha.substring(586,
593));
double numeroEndosoAnterior = Double.parseDouble(linha
.substring(593, 603));
double certificadoAnterior = Double.parseDouble(linha
.substring(603, 610));
apolices.put(numeroApolice, apolice);
if (erros.size() == 0) {
EntidadeHome home = (EntidadeHome) this.getModelManager()
.getHome("EntidadeHome");
Entidade destino = home.obterEntidadePorApelido("bcp");
apolice.atribuirOrigem(aseguradora);
apolice.atribuirDestino(destino);
apolice.atribuirResponsavel(usuario);
apolice.atribuirTipo(tipoApolice);
apolice.atribuirTitulo("Instumento: " + numeroApolice);
if (apoliceSuperior != null) {
apolice.atribuirSuperior(apoliceSuperior);
//apoliceSuperior.atualizarSuperior(this);
} else
apolice.atribuirSuperior(this);
//apolice.incluir();
apolice.atribuirDataPrevistaInicio(dataIncioVigencia);
apolice.atribuirDataPrevistaConclusao(dataFimVigencia);
apolice.atribuirSecao(cContas);
apolice.atribuirNumeroApolice(numeroApolice);
apolice.atribuirStatusApolice(statusApolice);
//if(apoliceAnterior!=null)
apolice.atribuirApoliceAnterior(apoliceAnterior);
apolice.atribuirAfetadoPorSinistro(afetadorPorSinistro);
apolice.atribuirApoliceFlutuante(apoliceFlutuante);
apolice.atribuirPlano(plano);
apolice.atribuirNumeroFatura(numeroFatura);
apolice.atribuirModalidadeVenda(modalidadeVenda);
apolice.atribuirApoliceFlutuante(apoliceFlutuante);
apolice.atribuirDiasCobertura(Integer
.parseInt(diasCobertura));
apolice.atribuirDataEmissao(dataEmissao);
apolice.atribuirCapitalGs(capitalGuarani);
apolice
.atribuirTipoMoedaCapitalGuarani(tipoMoedaCapitalGuarani);
apolice.atribuirCapitalMe(capitalMe);
apolice.atribuirPrimaGs(primasSeguro);
apolice.atribuirTipoMoedaPrimaGs(tipoMoedaPrimas);
apolice.atribuirPrimaMe(primasMe);
apolice.atribuirPrincipalGs(principalGuarani);
apolice
.atribuirTipoMoedaPrincipalGs(tipoMoedaPrincipalGuarani);
apolice.atribuirPrincipalMe(principalMe);
apolice.atribuirIncapacidadeGs(incapacidadeGuarani);
apolice
.atribuirTipoMoedaIncapacidadeGs(tipoMoedaIncapacidadeGuarani);
apolice.atribuirIncapacidadeMe(incapacidadeMe);
apolice.atribuirEnfermidadeGs(enfermidadeGuarani);
apolice
.atribuirTipoMoedaEnfermidadeGs(tipoMoedaEnfermidade);
apolice.atribuirEnfermidadeMe(enfermidadeMe);
apolice.atribuirAcidentesGs(acidentesGuarani);
apolice.atribuirTipoMoedaAcidentesGs(tipoMoedaAcidente);
apolice.atribuirAcidentesMe(acidentesMe);
apolice.atribuirOutrosGs(outrosGuarani);
apolice.atribuirTipoMoedaOutrosGs(tipoMoedaOutros);
apolice.atribuirOutrosMe(outrosMe);
apolice.atribuirFinanciamentoGs(financimantoGS);
apolice
.atribuirTipoMoedaFinanciamentoGs(tipoMoedaFinanciamentoGS);
apolice.atribuirFinanciamentoMe(financiamentoMe);
apolice.atribuirPremiosGs(premioGs);
apolice.atribuirTipoMoedaPremiosGs(tipoMoedaPremio);
apolice.atribuirPremiosMe(premioMe);
apolice.atribuirFormaPagamento(formaPagamento);
apolice
.atribuirQtdeParcelas(Integer
.parseInt(qtdeParcelas));
apolice.atribuirRefinacao(refinacao);
apolice.atribuirPremiosGs(premioGs);
//if(agente!=null)
apolice.atribuirInscricaoAgente(agente);
apolice.atribuirComissaoGs(comissaoGs);
apolice.atribuirTipoMoedaComissaoGs(tipoMoedaComissaoGs);
apolice.atribuirComissaoMe(comissaoMe);
apolice.atribuirSituacaoSeguro(situacaoSeguro);
if (codigoPlano.equals("RG-0001"))
apolice.atribuirCodigoPlano(codigoPlano);
apolice.atribuirCorredor(corredor);
apolice.atribuirNumeroEndoso(numeroEndoso);
apolice.atribuirNumeroEndosoAnterior(numeroEndosoAnterior);
apolice.atribuirCertificado(certificado);
apolice.atribuirCertificadoAnterior(certificadoAnterior);
/*
* apolice.atualizarDataPrevistaInicio(dataIncioVigencia);
* apolice.atualizarDataPrevistaConclusao(dataFimVigencia);
* apolice.atualizarSecao(cContas);
* apolice.atualizarNumeroApolice(numeroApolice);
* apolice.atualizarStatusApolice(statusApolice);
* if(apoliceAnterior!=null)
* apolice.atualizarApoliceAnterior(apoliceAnterior);
* apolice.atualizarAfetadoPorSinistro(afetadorPorSinistro);
* apolice.atualizarApoliceFlutuante(apoliceFlutuante);
* apolice.atualizarPlano(plano);
* apolice.atualizarNumeroFatura(numeroFatura);
* apolice.atualizarModalidadeVenda(modalidadeVenda);
* apolice.atualizarApoliceFlutuante(apoliceFlutuante);
* apolice.atualizarDiasCobertura(Integer.parseInt(diasCobertura));
* apolice.atualizarDataEmissao(dataEmissao);
* apolice.atualizarCapitalGs(capitalGuarani);
* apolice.atualizarTipoMoedaCapitalGuarani(tipoMoedaCapitalGuarani);
* apolice.atualizarCapitalMe(capitalMe);
* apolice.atualizarPrimaGs(primasSeguro);
* apolice.atualizarTipoMoedaPrimaGs(tipoMoedaPrimas);
* apolice.atualizarPrimaMe(primasMe);
* apolice.atualizarPrincipalGs(principalGuarani);
* apolice.atualizarTipoMoedaPrincipalGs(tipoMoedaPrincipalGuarani);
* apolice.atualizarPrincipalMe(principalMe);
* apolice.atualizarIncapacidadeGs(incapacidadeGuarani);
* apolice.atualizarTipoMoedaIncapacidadeGs(tipoMoedaIncapacidadeGuarani);
* apolice.atualizarIncapacidadeMe(incapacidadeMe);
* apolice.atualizarEnfermidadeGs(enfermidadeGuarani);
* apolice.atualizarTipoMoedaEnfermidadeGs(tipoMoedaEnfermidade);
* apolice.atualizarEnfermidadeMe(enfermidadeMe);
* apolice.atualizarAcidentesGs(acidentesGuarani);
* apolice.atualizarTipoMoedaAcidentesGs(tipoMoedaAcidente);
* apolice.atualizarAcidentesMe(acidentesMe);
* apolice.atualizarOutrosGs(outrosGuarani);
* apolice.atualizarTipoMoedaOutrosGs(tipoMoedaOutros);
* apolice.atualizarOutrosMe(outrosMe);
* apolice.atualizarFinanciamentoGs(financimantoGS);
* apolice.atualizarTipoMoedaFinanciamentoGs(tipoMoedaFinanciamentoGS);
* apolice.atualizarFinanciamentoMe(financiamentoMe);
* apolice.atualizarPremiosGs(premioGs);
* apolice.atualizarTipoMoedaPremiosGs(tipoMoedaPremio);
* apolice.atualizarPremiosMe(premioMe);
* apolice.atualizarFormaPagamento(formaPagamento);
* apolice.atualizarQtdeParcelas(Integer.parseInt(qtdeParcelas));
* apolice.atualizarRefinacao(refinacao);
* apolice.atualizarPremiosGs(premioGs); if(agente!=null)
* apolice.atualizarInscricaoAgente(agente);
* apolice.atualizarComissaoGs(comissaoGs);
* apolice.atualizarTipoMoedaComissaoGs(tipoMoedaComissaoGs);
* apolice.atualizarComissaoMe(comissaoMe);
* apolice.atualizarSituacaoSeguro(situacaoSeguro);
*/
}
}
// REGISTRO TIPO 3
else if (Integer.parseInt(linha.substring(5, 7)) == 3) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String numeroInstrumento = linha.substring(17, 27);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
String anoCorte = linha.substring(27, 31);
String mesCorte = linha.substring(31, 33);
String diaCorte = linha.substring(33, 35);
Date dataCorte = null;
if (diaCorte.startsWith(" ") || mesCorte.startsWith(" ")
|| anoCorte.startsWith(" "))
erros.add("Error: 92 - Fecha del Corte Invalida - Linea: "
+ numeroLinha);
else
dataCorte = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaCorte + "/" + mesCorte + "/" + anoCorte);
String cursoStr = linha.substring(35, 57);
if (cursoStr.equals(""))
erros
.add("Error: 24 - Riesgo en Curso es obligatorio - Linea: "
+ numeroLinha);
double curso = Double.parseDouble(cursoStr);
String sinistroStr = linha.substring(57, 79);
double valorSinistro = Double.parseDouble(sinistroStr);
String reservasStr = linha.substring(79, 101);
double reservas = Double.parseDouble(reservasStr);
String fundoStr = linha.substring(101, 123);
double fundos = Double.parseDouble(fundoStr);
String premiosStr = linha.substring(123, 145);
double premios = Double.parseDouble(premiosStr);
String tipoInstrumento = "";
if (linha.substring(145, 146).equals("1"))
tipoInstrumento = "Pliza Individual";
else if (linha.substring(145, 146).equals("2"))
tipoInstrumento = "Pliza Madre";
else if (linha.substring(145, 146).equals("3"))
tipoInstrumento = "Certificado de Seguro Colectivo";
else if (linha.substring(145, 146).equals("4"))
tipoInstrumento = "Certificado Provisorio";
else if (linha.substring(145, 146).equals("5"))
tipoInstrumento = "Nota de Cobertura de Reaseguro";
if (tipoInstrumento.equals(""))
erros
.add("Error: 101 - Instrumento es obligatorio - Linea: "
+ numeroLinha);
double numeroEndoso = Double.parseDouble(linha.substring(146,
156));
double certificado = Double.parseDouble(linha.substring(156,
163));
if (erros.size() == 0) {
DadosPrevisao dadosPrevisao = (DadosPrevisao) this
.getModelManager().getEntity("DadosPrevisao");
dadosPrevisao.atribuirOrigem(apolice.obterOrigem());
dadosPrevisao.atribuirDestino(apolice.obterDestino());
dadosPrevisao.atribuirResponsavel(apolice
.obterResponsavel());
dadosPrevisao.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
dadosPrevisao.atribuirSuperior(apolice);
dadosPrevisao.atribuirDataCorte(dataCorte);
dadosPrevisao.atribuirCurso(curso);
dadosPrevisao.atribuirSinistroPendente(valorSinistro);
dadosPrevisao.atribuirReservasMatematicas(reservas);
dadosPrevisao.atribuirFundosAcumulados(fundos);
dadosPrevisao.atribuirPremios(premios);
dadosPrevisao.atribuirTipoInstrumento(tipoInstrumento);
dadosPrevisao.atribuirNumeroEndoso(numeroEndoso);
dadosPrevisao.atribuirCertificado(certificado);
dadosPrevisoes.add(dadosPrevisao);
}
}
// REGISTRO TIPO 4
else if (Integer.parseInt(linha.substring(5, 7)) == 4) {
DadosReaseguro dadosReaseguro = (DadosReaseguro) this
.getModelManager().getEntity("DadosReaseguro");
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String tipoInstrumento = "";
if (linha.substring(17, 18).equals("1"))
tipoInstrumento = "Pliza Individual";
else if (linha.substring(17, 18).equals("2"))
tipoInstrumento = "Pliza Madre";
else if (linha.substring(17, 18).equals("3"))
tipoInstrumento = "Certificado de Seguro Colectivo";
else if (linha.substring(17, 18).equals("4"))
tipoInstrumento = "Certificado Provisorio";
else if (linha.substring(17, 18).equals("5"))
tipoInstrumento = "Nota de Cobertura de Reaseguro";
if (tipoInstrumento.equals(""))
erros
.add("Error: 101 - Instrumento es obligatorio - Linea: "
+ numeroLinha);
String numeroInstrumento = linha.substring(18, 28);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
String valorEndosoStr = linha.substring(28, 38);
double valorEndoso = Double.parseDouble(valorEndosoStr);
String qtdeStr = linha.substring(38, 40);
if (qtdeStr.equals(""))
erros
.add("Error: 25 - Cantidad de Reaseguros es obligatoria - Linea: "
+ numeroLinha);
int qtde = Integer.parseInt(qtdeStr);
int ultimo = 0;
for (int w = 0; w < qtde; w++) {
if (ultimo == 0)
ultimo = 40;
String inscricaoReaseguradora1 = linha.substring(ultimo,
ultimo + 3);
//String inscricaoReaseguradora1 = linha.substring(29,32);
if (inscricaoReaseguradora1.equals(""))
erros
.add("Error: 25 - Numero de la Reaseguradora es obligatorio - Linea: "
+ numeroLinha);
Entidade reaseguradora = null;
if (!inscricaoReaseguradora1.equals("000")) {
reaseguradora = entidadeHome
.obterEntidadePorInscricao(inscricaoReaseguradora1);
if (reaseguradora == null)
erros
.add("Error: 10 - Inscripcin "
+ inscricaoReaseguradora1
+ " de la Reaseguradora no fue encontrada o esta No Activa - Linea: "
+ numeroLinha);
}
String tipoContratoReaseguro1 = "";
//linha.substring(32,33)
if (linha.substring(ultimo + 3, ultimo + 3 + 1).equals("1"))
tipoContratoReaseguro1 = "Cuota parte";
else if (linha.substring(ultimo + 3, ultimo + 3 + 1)
.equals("2"))
tipoContratoReaseguro1 = "Excedente";
else if (linha.substring(ultimo + 3, ultimo + 3 + 1)
.equals("3"))
tipoContratoReaseguro1 = "Exceso de prdida";
else if (linha.substring(ultimo + 3, ultimo + 3 + 1)
.equals("4"))
tipoContratoReaseguro1 = "Facultativo no Proporcional";
else if (linha.substring(ultimo + 3, ultimo + 3 + 1)
.equals("5"))
tipoContratoReaseguro1 = "Facultativo Proporcional";
else if (linha.substring(ultimo + 3, ultimo + 3 + 1)
.equals("6"))
tipoContratoReaseguro1 = "Limitacin de Siniestralidad";
if (tipoContratoReaseguro1.equals(""))
erros
.add("Error: 26 - Tipo de Contrato de Reaseguro es obligatorio - Linea: "
+ numeroLinha);
//String inscricaoCorredoraReaseguro1 =
// linha.substring(33,36);
String inscricaoCorredoraReaseguro1 = linha.substring(
ultimo + 3 + 1, ultimo + 3 + 1 + 3);
Entidade corretora = null;
if (!inscricaoCorredoraReaseguro1.equals("000")) {
corretora = entidadeHome
.obterEntidadePorInscricao(inscricaoCorredoraReaseguro1);
if (corretora == null)
erros
.add("Error: 11 - Inscripcin "
+ inscricaoCorredoraReaseguro1
+ " de la Corredora o Reaseguradora no fue encontrada o esta No Activa - Linea: "
+ numeroLinha);
}
String reaseguroGs1Str = linha.substring(
ultimo + 3 + 1 + 3, ultimo + 3 + 1 + 3 + 22);
double reaseguroGs1 = Double.parseDouble(reaseguroGs1Str);
String tipoMoedaReaseguroGs1 = this.obterTipoMoeda(linha
.substring(ultimo + 3 + 1 + 3 + 22, ultimo + 3 + 1
+ 3 + 22 + 2));
String reaseguroMe1Str = linha.substring(ultimo + 3 + 1 + 3
+ 22 + 2, ultimo + 3 + 1 + 3 + 22 + 2 + 22);
double reaseguroMe1 = Double.parseDouble(reaseguroMe1Str);
String primaReaseguro1GsStr = linha.substring(ultimo + 3
+ 1 + 3 + 22 + 2 + 22, ultimo + 3 + 1 + 3 + 22 + 2
+ 22 + 22);
double primaReaseguro1Gs = Double
.parseDouble(primaReaseguro1GsStr);
String tipoMoedaPrimaReaseguro1 = this.obterTipoMoeda(linha
.substring(ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22,
ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2));
String primaReaseguro1MeStr = linha.substring(ultimo + 3
+ 1 + 3 + 22 + 2 + 22 + 22 + 2, ultimo + 3 + 1 + 3
+ 22 + 2 + 22 + 22 + 2 + 22);
double primaReaseguro1Me = Double
.parseDouble(primaReaseguro1MeStr);
String comissaoReaseguro1GsStr = linha.substring(ultimo + 3
+ 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22, ultimo + 3 + 1
+ 3 + 22 + 2 + 22 + 22 + 2 + 22 + 22);
double comissaoReaseguro1Gs = Double
.parseDouble(comissaoReaseguro1GsStr);
String tipoMoedaComissaoReaseguro1 = this
.obterTipoMoeda(linha.substring(ultimo + 3 + 1 + 3
+ 22 + 2 + 22 + 22 + 2 + 22 + 22, ultimo
+ 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22
+ 22 + 2));
String comissaoReaseguro1MeStr = linha.substring(ultimo + 3
+ 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22 + 22 + 2,
ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22 + 22
+ 2 + 22);
double comissaoReaseguro1Me = Double
.parseDouble(comissaoReaseguro1MeStr);
String anoInicioVigencia = linha.substring(ultimo + 3 + 1
+ 3 + 22 + 2 + 22 + 22 + 2 + 22 + 22 + 2 + 22,
ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22 + 22
+ 2 + 22 + 4);
String mesInicioVigencia = linha.substring(ultimo + 3 + 1
+ 3 + 22 + 2 + 22 + 22 + 2 + 22 + 22 + 2 + 22 + 4,
ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22 + 22
+ 2 + 22 + 4 + 2);
String diaInicioVigencia = linha.substring(ultimo + 3 + 1
+ 3 + 22 + 2 + 22 + 22 + 2 + 22 + 22 + 2 + 22 + 4
+ 2, ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22
+ 22 + 2 + 22 + 4 + 2 + 2);
Date dataInicioVigencia = null;
if (diaInicioVigencia.startsWith(" ")
|| mesInicioVigencia.startsWith(" ")
|| anoInicioVigencia.startsWith(" "))
erros
.add("Error: 92 - Fecha Inico Vigencia Invalida - Linea: "
+ numeroLinha);
else
dataInicioVigencia = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaInicioVigencia + "/"
+ mesInicioVigencia + "/"
+ anoInicioVigencia);
String anoFimVigencia = linha.substring(ultimo + 3 + 1 + 3
+ 22 + 2 + 22 + 22 + 2 + 22 + 22 + 2 + 22 + 4 + 2
+ 2, ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22
+ 22 + 2 + 22 + 4 + 2 + 2 + 4);
String mesFimVigencia = linha.substring(ultimo + 3 + 1 + 3
+ 22 + 2 + 22 + 22 + 2 + 22 + 22 + 2 + 22 + 4 + 2
+ 2 + 4, ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2
+ 22 + 22 + 2 + 22 + 4 + 2 + 2 + 4 + 2);
String diaFimVigencia = linha.substring(ultimo + 3 + 1 + 3
+ 22 + 2 + 22 + 22 + 2 + 22 + 22 + 2 + 22 + 4 + 2
+ 2 + 4 + 2, ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22
+ 2 + 22 + 22 + 2 + 22 + 4 + 2 + 2 + 4 + 2 + 2);
Date dataFimVigencia = null;
if (diaFimVigencia.startsWith(" ")
|| mesFimVigencia.startsWith(" ")
|| anoFimVigencia.startsWith(" "))
erros
.add("Error: 92 - Fecha Fin Vigencia Invalida - Linea: "
+ numeroLinha);
else
dataFimVigencia = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaFimVigencia + "/" + mesFimVigencia
+ "/" + anoFimVigencia);
String situacaoReaseguro1 = "";
if (linha.substring(
ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22 + 22
+ 2 + 22 + 4 + 2 + 2 + 4 + 2 + 2,
ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22 + 22
+ 2 + 22 + 4 + 2 + 2 + 4 + 2 + 2 + 1)
.equals("1"))
situacaoReaseguro1 = "Vigente";
else if (linha.substring(
ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22 + 22
+ 2 + 22 + 4 + 2 + 2 + 4 + 2 + 2,
ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22 + 22
+ 2 + 22 + 4 + 2 + 2 + 4 + 2 + 2 + 1)
.equals("2"))
situacaoReaseguro1 = "No Vigente";
if (situacaoReaseguro1.equals(""))
erros
.add("Error: 27 - Situacon de Reaseguro es obligatorio - Linea: "
+ numeroLinha);
ultimo = ultimo + 3 + 1 + 3 + 22 + 2 + 22 + 22 + 2 + 22
+ 22 + 2 + 22 + 4 + 2 + 2 + 4 + 2 + 2 + 1;
if (reaseguradora != null)
dadosReaseguros.put(new Long(cContas.obterId()
+ apolice.obterNumeroApolice()
+ reaseguradora.obterId())
+ tipoContratoReaseguro1, dadosReaseguro);
else
dadosReaseguros.put(new Long(cContas.obterId()
+ apolice.obterNumeroApolice())
+ tipoContratoReaseguro1, dadosReaseguro);
if (erros.size() == 0) {
//dadosReaseguro.verificarDuplicidade(apolice, cContas,
// reaseguradora, tipoContratoReaseguro1);
dadosReaseguro.atribuirOrigem(apolice.obterOrigem());
dadosReaseguro.atribuirDestino(apolice.obterDestino());
dadosReaseguro.atribuirResponsavel(apolice
.obterResponsavel());
dadosReaseguro.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
dadosReaseguro.atribuirSuperior(apolice);
//dadosReaseguro.incluir();
dadosReaseguro.atribuirReaseguradora(reaseguradora);
dadosReaseguro
.atribuirTipoContrato(tipoContratoReaseguro1);
//if(corretora!=null)
dadosReaseguro.atribuirCorredora(corretora);
dadosReaseguro.atribuirCapitalGs(reaseguroGs1);
dadosReaseguro
.atribuirTipoMoedaCapitalGs(tipoMoedaReaseguroGs1);
dadosReaseguro.atribuirCapitalMe(reaseguroMe1);
dadosReaseguro.atribuirPrimaGs(primaReaseguro1Gs);
dadosReaseguro
.atribuirTipoMoedaPrimaGs(tipoMoedaPrimaReaseguro1);
dadosReaseguro.atribuirPrimaMe(primaReaseguro1Me);
dadosReaseguro.atribuirComissaoGs(comissaoReaseguro1Gs);
dadosReaseguro
.atribuirTipoMoedaComissaoGs(tipoMoedaComissaoReaseguro1);
dadosReaseguro.atribuirComissaoMe(comissaoReaseguro1Me);
dadosReaseguro
.atribuirDataPrevistaInicio(dataInicioVigencia);
dadosReaseguro
.atribuirDataPrevistaConclusao(dataFimVigencia);
dadosReaseguro.atribuirSituacao(situacaoReaseguro1);
dadosReaseguro.atribuirValorEndoso(valorEndoso);
dadosReaseguro.atribuirTipoInstrumento(tipoInstrumento);
}
/*
* else { if(apolice!=null) { apolice.excluir(); break; } }
*/
}
}
// REGISTRO TIPO 5
else if (Integer.parseInt(linha.substring(5, 7)) == 5) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String tipoInstrumento = "";
if (linha.substring(17, 18).equals("1"))
tipoInstrumento = "Pliza Individual";
else if (linha.substring(17, 18).equals("2"))
tipoInstrumento = "Pliza Madre";
else if (linha.substring(17, 18).equals("3"))
tipoInstrumento = "Certificado de Seguro Colectivo";
else if (linha.substring(17, 18).equals("4"))
tipoInstrumento = "Certificado Provisorio";
else if (linha.substring(17, 18).equals("5"))
tipoInstrumento = "Nota de Cobertura de Reaseguro";
if (tipoInstrumento.equals(""))
erros
.add("Error: 101 - Instrumento es obligatorio - Linea: "
+ numeroLinha);
String numeroInstrumento = linha.substring(18, 28);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
double numeroEndoso = Double.parseDouble(linha
.substring(28, 38));
double certificado = Double
.parseDouble(linha.substring(38, 45));
String grupo = linha.substring(45, 47);
String qtdeStr = linha.substring(47, 49);
if (qtdeStr.equals(""))
erros
.add("Error: 27 - Cantidad de Aseguradoras es obligatoria - Linea: "
+ numeroLinha);
int qtde = Integer.parseInt(qtdeStr);
int ultimo = 0;
for (int w = 0; w < qtde; w++) {
if (ultimo == 0)
ultimo = 49;
String inscricaoAseguradora = linha.substring(ultimo,
ultimo + 3);
if (inscricaoAseguradora.equals(""))
erros
.add("Error: 27 - Numero de la Aseguradora es obligatorio - Linea: "
+ numeroLinha);
Entidade aseguradora2 = null;
aseguradora2 = entidadeHome
.obterEntidadePorInscricao(inscricaoAseguradora);
if (aseguradora2 == null)
erros.add("Error: 74 - Aseguradora "
+ inscricaoAseguradora
+ " - no fue encontrada - Linea: "
+ numeroLinha);
String capitalGsStr = linha.substring(ultimo + 3,
ultimo + 3 + 22);
if (capitalGsStr.equals(""))
erros
.add("Error: 28 - Capital en Riesgo en Gs es obligatorio - Linea: "
+ numeroLinha);
double capitalGs = Double.parseDouble(capitalGsStr);
String tipoMoedaCapitalGs1 = this.obterTipoMoeda(linha
.substring(ultimo + 3 + 22, ultimo + 3 + 22 + 2));
String capitalMeStr = linha.substring(ultimo + 3 + 22 + 2,
ultimo + 3 + 22 + 2 + 22);
double capitalMe = Double.parseDouble(capitalMeStr);
String porcentagemCoaseguradoraStr = linha.substring(ultimo
+ 3 + 22 + 2 + 22, ultimo + 3 + 22 + 2 + 22 + 6);
if (porcentagemCoaseguradoraStr.equals(""))
erros
.add("Error: 29 - Porcentaje de participacin es obligatorio - Linea: "
+ numeroLinha);
double porcentagemCoaseguradora = Double
.parseDouble(porcentagemCoaseguradoraStr);
String primaGsStr = linha.substring(ultimo + 3 + 22 + 2
+ 22 + 6, ultimo + 3 + 22 + 2 + 22 + 3 + 22);
if (primaGsStr.equals(""))
erros
.add("Error: 30 - Prima en Gs es obligatoria - Linea: "
+ numeroLinha);
double primaGs = Double.parseDouble(primaGsStr);
String tipoMoedaPrimaGs = this.obterTipoMoeda(linha
.substring(ultimo + 3 + 22 + 2 + 22 + 3 + 22,
ultimo + 3 + 22 + 2 + 22 + 3 + 22 + 2));
String primaMeStr = linha.substring(ultimo + 3 + 22 + 2
+ 22 + 3 + 22 + 2, ultimo + 3 + 22 + 2 + 22 + 3
+ 22 + 2 + 22);
double primaMe = Double.parseDouble(primaMeStr);
ultimo = ultimo + 3 + 22 + 2 + 22 + 3 + 22 + 2 + 22;
if (erros.size() == 0) {
DadosCoaseguro dadosCoaseguro = (DadosCoaseguro) this
.getModelManager().getEntity("DadosCoaseguro");
//dadosCoaseguro.verificarDuplicidade(apolice, cContas,
// aseguradora2);
dadosCoaseguro.atribuirOrigem(apolice.obterOrigem());
dadosCoaseguro.atribuirDestino(apolice.obterDestino());
dadosCoaseguro.atribuirResponsavel(apolice
.obterResponsavel());
dadosCoaseguro.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
dadosCoaseguro.atribuirSuperior(apolice);
//dadosCoaseguro.incluir();
dadosCoaseguro.atribuirAseguradora(aseguradora2);
dadosCoaseguro.atribuirGrupo(grupo);
dadosCoaseguro.atribuirCapitalGs(capitalGs);
dadosCoaseguro
.atribuirTipoMoedaCapitalGs(tipoMoedaCapitalGs1);
dadosCoaseguro.atribuirCapitalMe(capitalMe);
dadosCoaseguro
.atribuirParticipacao(porcentagemCoaseguradora);
dadosCoaseguro.atribuirPrimaGs(primaGs);
dadosCoaseguro
.atribuirTipoMoedaPrimaGs(tipoMoedaPrimaGs);
dadosCoaseguro.atribuirPrimaMe(primaMe);
dadosCoaseguro.atribuirTipoInstrumento(tipoInstrumento);
dadosCoaseguro.atribuirNumeroEndoso(numeroEndoso);
dadosCoaseguro.atribuirCertificado(certificado);
dadosCoaseguros.add(dadosCoaseguro);
}
/*
* else { if(apolice!=null) { apolice.excluir(); break; } }
*/
}
}
// REGISTRO TIPO 6
else if (Integer.parseInt(linha.substring(5, 7)) == 6) {
Sinistro sinistro = (Sinistro) this.getModelManager()
.getEntity("Sinistro");
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String tipoInstrumento = "";
if (linha.substring(17, 18).equals("1"))
tipoInstrumento = "Pliza Individual";
else if (linha.substring(17, 18).equals("2"))
tipoInstrumento = "Pliza Madre";
else if (linha.substring(17, 18).equals("3"))
tipoInstrumento = "Certificado de Seguro Colectivo";
else if (linha.substring(17, 18).equals("4"))
tipoInstrumento = "Certificado Provisorio";
else if (linha.substring(17, 18).equals("5"))
tipoInstrumento = "Nota de Cobertura de Reaseguro";
if (tipoInstrumento.equals(""))
erros
.add("Error: 101 - Instrumento es obligatorio - Linea: "
+ numeroLinha);
String numeroInstrumento = linha.substring(18, 28);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
double numeroEndoso = Double.parseDouble(linha
.substring(28, 38));
double certificado = Double
.parseDouble(linha.substring(38, 45));
String qtdeStr = linha.substring(45, 47);
if (qtdeStr.equals(""))
erros
.add("Error: 31 - Cantidad de Siniestros es obligatoria - Linea: "
+ numeroLinha);
int qtde = Integer.parseInt(qtdeStr);
int ultimo = 0;
for (int w = 0; w < qtde; w++) {
if (ultimo == 0)
ultimo = 47;
String numeroSinistro = linha.substring(ultimo, ultimo + 6);
if (numeroSinistro.equals(""))
erros
.add("Error: 32 - Numero del Siniestro es obligatorio - Linea: "
+ numeroLinha);
String anoSinistro = linha.substring(ultimo + 6,
ultimo + 6 + 4);
String mesSinistro = linha.substring(ultimo + 6 + 4,
ultimo + 6 + 4 + 2);
String diaSinistro = linha.substring(ultimo + 6 + 4 + 2,
ultimo + 6 + 4 + 2 + 2);
Date dataSinistro = null;
if (diaSinistro.startsWith(" ")
|| mesSinistro.startsWith(" ")
|| anoSinistro.startsWith(" "))
erros
.add("Error: 92 - Fecha Sinistro Invalida - Linea: "
+ numeroLinha);
else
dataSinistro = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaSinistro + "/" + mesSinistro + "/"
+ anoSinistro);
String anoDenunciaSinistro = linha.substring(ultimo + 6 + 4
+ 2 + 2, ultimo + 6 + 4 + 2 + 2 + 4);
String mesDenunciaSinistro = linha.substring(ultimo + 6 + 4
+ 2 + 2 + 4, ultimo + 6 + 4 + 2 + 2 + 4 + 2);
String diaDenunciaSinistro = linha
.substring(ultimo + 6 + 4 + 2 + 2 + 4 + 2, ultimo
+ 6 + 4 + 2 + 2 + 4 + 2 + 2);
Date dataDenunciaSinistro = null;
if (diaDenunciaSinistro.startsWith(" ")
|| mesDenunciaSinistro.startsWith(" ")
|| anoDenunciaSinistro.startsWith(" "))
erros
.add("Error: 92 - Fecha Denuncia del Sinistro Invalida - Linea: "
+ numeroLinha);
else
dataDenunciaSinistro = new SimpleDateFormat(
"dd/MM/yyyy").parse(diaDenunciaSinistro + "/"
+ mesDenunciaSinistro + "/"
+ anoDenunciaSinistro);
String numeroLiquidador = linha.substring(ultimo + 6 + 4
+ 2 + 2 + 4 + 2 + 2, ultimo + 6 + 4 + 2 + 2 + 4 + 2
+ 2 + 3);
AuxiliarSeguro auxiliar = null;
auxiliar = (AuxiliarSeguro) entidadeHome
.obterEntidadePorInscricao(numeroLiquidador);
if (auxiliar == null)
erros
.add("Error: 84 - Auxiliar de Seguro con Inscripcin "
+ numeroLiquidador
+ " no fue encontrado - Linea: "
+ numeroLinha);
String montanteGsStr = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 4 + 2 + 2 + 3, ultimo + 6 + 4 + 2 + 2 + 4 + 2
+ 2 + 3 + 22);
if (montanteGsStr.equals(""))
erros
.add("Error: 33 - Monto estimado en Gs es obligatorio - Linea: "
+ numeroLinha);
double montanteGs = Double.parseDouble(montanteGsStr);
String tipoMoedaMontante = this.obterTipoMoeda(linha
.substring(ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3
+ 22, ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2
+ 3 + 22 + 2));
String montanteMeStr = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 4 + 2 + 2 + 3 + 22 + 2, ultimo + 6 + 4 + 2
+ 2 + 4 + 2 + 2 + 3 + 22 + 2 + 22);
double montanteMe = Double.parseDouble(montanteMeStr);
String situacaoSinistro = "";
if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22,
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22 + 1).equals("1"))
situacaoSinistro = "Pendiente de Liquidacin";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22,
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22 + 1).equals("2"))
situacaoSinistro = "Controvertido";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22,
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22 + 1).equals("3"))
situacaoSinistro = "Pendiente de Pago";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22,
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22 + 1).equals("4"))
situacaoSinistro = "Recharzado";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22,
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22 + 1).equals("5"))
situacaoSinistro = "Judicializado";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22,
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22 + 1).equals("6"))
situacaoSinistro = "Pagado";
if (situacaoSinistro.equals(""))
erros
.add("Error: 34 - Situacin del Siniestro es obligatoria - Linea: "
+ numeroLinha);
String anoFinalizacao = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 4 + 2 + 2 + 3 + 22 + 2 + 22 + 1, ultimo + 6
+ 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4);
String mesFinalizacao = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 4 + 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4, ultimo
+ 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2 + 22 + 1
+ 4 + 2);
String diaFinalizacao = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 4 + 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4 + 2,
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22 + 1 + 4 + 2 + 2);
Date dataFinalizacao = null;
if (diaFinalizacao.startsWith(" ")
|| mesFinalizacao.startsWith(" ")
|| anoFinalizacao.startsWith(" "))
erros
.add("Error: 92 - Fecha Finalizacin Invalida - Linea: "
+ numeroLinha);
else
dataFinalizacao = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaFinalizacao + "/" + mesFinalizacao
+ "/" + anoFinalizacao);
String anoRecupero = linha.substring(ultimo + 6 + 4 + 2 + 2
+ 4 + 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22 + 1 + 4 + 2 + 2 + 4);
String mesRecupero = linha.substring(ultimo + 6 + 4 + 2 + 2
+ 4 + 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4 + 2 + 2 + 4,
ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22 + 1 + 4 + 2 + 2 + 4 + 2);
String diaRecupero = linha.substring(ultimo + 6 + 4 + 2 + 2
+ 4 + 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4 + 2 + 2 + 4
+ 2, ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22
+ 2 + 22 + 1 + 4 + 2 + 2 + 4 + 2 + 2);
Date dataRecupero = null;
if (diaRecupero.startsWith(" ")
|| mesRecupero.startsWith(" ")
|| anoRecupero.startsWith(" "))
erros
.add("Error: 92 - Fecha Recupero Invalida - Linea: "
+ numeroLinha);
else
dataRecupero = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaRecupero + "/" + mesRecupero + "/"
+ anoRecupero);
String recuperoReaseguradoraStr = linha.substring(ultimo
+ 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2 + 22 + 1
+ 4 + 2 + 2 + 4 + 2 + 2, ultimo + 6 + 4 + 2 + 2 + 4
+ 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4 + 2 + 2 + 4 + 2
+ 2 + 22);
double recuperoReaseguradora = Double
.parseDouble(recuperoReaseguradoraStr);
String recuperoTerceiroStr = linha.substring(ultimo + 6 + 4
+ 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4 + 2
+ 2 + 4 + 2 + 2 + 22, ultimo + 6 + 4 + 2 + 2 + 4
+ 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4 + 2 + 2 + 4 + 2
+ 2 + 22 + 22);
double recuperoTerceiro = Double
.parseDouble(recuperoTerceiroStr);
String participacaoStr = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 4 + 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4 + 2 + 2
+ 4 + 2 + 2 + 22 + 22, ultimo + 6 + 4 + 2 + 2 + 4
+ 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4 + 2 + 2 + 4 + 2
+ 2 + 22 + 22 + 6);
double participacao = Double.parseDouble(participacaoStr);
String descricao = linha.substring(ultimo + 6 + 4 + 2 + 2
+ 4 + 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4 + 2 + 2 + 4
+ 2 + 2 + 22 + 22 + 6, ultimo + 6 + 4 + 2 + 2 + 4
+ 2 + 2 + 3 + 22 + 2 + 22 + 1 + 4 + 2 + 2 + 4 + 2
+ 2 + 22 + 22 + 2 + 120);
if (descricao.equals(""))
erros
.add("Error: 35 - Descripcin del Siniestro es obligatoria - Linea: "
+ numeroLinha);
ultimo = ultimo + 6 + 4 + 2 + 2 + 4 + 2 + 2 + 3 + 22 + 2
+ 22 + 1 + 4 + 2 + 2 + 4 + 2 + 2 + 22 + 22 + 2
+ 120;
sinistros.put(numeroSinistro, sinistro);
if (erros.size() == 0) {
sinistro.atribuirOrigem(apolice.obterOrigem());
sinistro.atribuirDestino(apolice.obterDestino());
sinistro
.atribuirResponsavel(apolice.obterResponsavel());
sinistro.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
sinistro.atribuirSuperior(apolice);
sinistro.atribuirNumero(numeroSinistro);
sinistro.atribuirDataSinistro(dataSinistro);
sinistro.atribuirDataDenuncia(dataDenunciaSinistro);
sinistro.atribuirAgente(auxiliar);
sinistro.atribuirMontanteGs(montanteGs);
sinistro.atribuirTipoMoedaMontanteGs(tipoMoedaMontante);
sinistro.atribuirMontanteMe(montanteMe);
sinistro.atribuirSituacao(situacaoSinistro);
sinistro.atribuirDataPagamento(dataFinalizacao);
sinistro.atribuirDataRecuperacao(dataRecupero);
sinistro
.atribuirValorRecuperacao(recuperoReaseguradora);
sinistro
.atribuirValorRecuperacaoTerceiro(recuperoTerceiro);
sinistro.atribuirParticipacao(participacao);
sinistro.atribuirTipoInstrumento(tipoInstrumento);
sinistro.atribuirNumeroEndoso(numeroEndoso);
sinistro.atribuirCertificado(certificado);
String descricao2 = "";
int cont = 1;
for (int j = 0; j < descricao.length();) {
String caracter = descricao.substring(j, cont);
if (j == 100) {
boolean entrou = false;
while (!caracter.equals(" ")) {
descricao2 += caracter;
j++;
cont++;
if (j == descricao.length())
break;
else
caracter = descricao.substring(j, cont);
entrou = true;
}
if (!entrou) {
j++;
cont++;
} else
descricao2 += "\n";
} else {
descricao2 += caracter;
cont++;
j++;
}
}
sinistro.atribuirDescricao(descricao2);
}
/*
* else { if(apolice!=null) { apolice.excluir(); break; } }
*/
}
}
// REGISTRO TIPO 7
else if (Integer.parseInt(linha.substring(5, 7)) == 7) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String tipoInstrumento = "";
if (linha.substring(17, 18).equals("1"))
tipoInstrumento = "Pliza Individual";
else if (linha.substring(17, 18).equals("2"))
tipoInstrumento = "Pliza Madre";
else if (linha.substring(17, 18).equals("3"))
tipoInstrumento = "Certificado de Seguro Colectivo";
else if (linha.substring(17, 18).equals("4"))
tipoInstrumento = "Certificado Provisorio";
else if (linha.substring(17, 18).equals("5"))
tipoInstrumento = "Nota de Cobertura de Reaseguro";
if (tipoInstrumento.equals(""))
erros
.add("Error: 101 - Instrumento es obligatorio - Linea: "
+ numeroLinha);
String numeroInstrumento = linha.substring(18, 28);
double numeroEndoso = Double.parseDouble(linha
.substring(28, 38));
double certificado = Double
.parseDouble(linha.substring(38, 45));
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
String qtdeStr = linha.substring(45, 47);
if (qtdeStr.equals(""))
erros
.add("Error: 36 - Cantidad de Facturas es obligatoria - Linea: "
+ numeroLinha);
int qtde = Integer.parseInt(qtdeStr);
int ultimo = 0;
for (int w = 0; w < qtde; w++) {
if (ultimo == 0)
ultimo = 47;
String numeroSinistro = linha.substring(ultimo, ultimo + 6);
if (numeroSinistro.equals(""))
erros
.add("Error: 37 - Numero del Siniestro es obligatorio - Linea: "
+ numeroLinha);
Sinistro sinistro = null;
if (this.sinistros != null)
sinistro = (Sinistro) this.sinistros
.get(numeroSinistro);
if (sinistro == null)
sinistro = sinistroHome.obterSinistro(numeroSinistro);
if (sinistro == null)
erros.add("Error: 74 - Siniestro "
+ numeroSinistro.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
String anoSinistro = linha.substring(ultimo + 6,
ultimo + 6 + 4);
String mesSinistro = linha.substring(ultimo + 6 + 4,
ultimo + 6 + 4 + 2);
String diaSinistro = linha.substring(ultimo + 6 + 4 + 2,
ultimo + 6 + 4 + 2 + 2);
Date dataSinistro = null;
if (diaSinistro.startsWith(" ")
|| mesSinistro.startsWith(" ")
|| anoSinistro.startsWith(" "))
erros
.add("Error: 92 - Fecha Sinistro Invalida - Linea: "
+ numeroLinha);
else
dataSinistro = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaSinistro + "/" + mesSinistro + "/"
+ anoSinistro);
String tipoDocumento = "";
if (linha.substring(ultimo + 6 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1).equals("1"))
tipoDocumento = "Factura Crdito";
else if (linha.substring(ultimo + 6 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1).equals("2"))
tipoDocumento = "Autofactura";
else if (linha.substring(ultimo + 6 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1).equals("3"))
tipoDocumento = "Boleta de Venta";
else if (linha.substring(ultimo + 6 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1).equals("4"))
tipoDocumento = "Nota de Crdito";
else if (linha.substring(ultimo + 6 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1).equals("5"))
tipoDocumento = "Nota de Dbito";
else if (linha.substring(ultimo + 6 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1).equals("6"))
tipoDocumento = "Recibo";
else if (linha.substring(ultimo + 6 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1).equals("7"))
tipoDocumento = "Factura al Contado";
else if (linha.substring(ultimo + 6 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1).equals("8"))
tipoDocumento = "Otros";
if (tipoDocumento.equals(""))
erros
.add("Error: 37 - Tipo del Documento Recibido es obligatorio - Linea: "
+ numeroLinha);
String numeroDocumento = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1, ultimo + 6 + 4 + 2 + 2 + 1 + 9);
if (numeroDocumento.equals(""))
erros
.add("Error: 38 - Numero del Documento del Proveedor es obligatorio - Linea: "
+ numeroLinha);
String numeroFatura = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 9, ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9);
String tipoDocumentoProvedor = "";
if (linha.substring(ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9,
ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9 + 1).equals("1"))
tipoDocumentoProvedor = "CI";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9,
ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9 + 1).equals("2"))
tipoDocumentoProvedor = "RUC";
if (tipoDocumentoProvedor.equals(""))
erros
.add("Error: 102 - Tipo del Documento del Proveedor es obligatorio - Linea: "
+ numeroLinha);
String rucProvedor = linha.substring(ultimo + 6 + 4 + 2 + 2
+ 1 + 9 + 9 + 1, ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9
+ 11);
if (rucProvedor.equals(""))
erros
.add("Error: 39 - Numero del RUC o CI del Proveedor es obligatorio - Linea: "
+ numeroLinha);
String nomeProvedor = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 9 + 9 + 11, ultimo + 6 + 4 + 2 + 2 + 1
+ 9 + 9 + 11 + 60);
if (nomeProvedor.equals(""))
erros
.add("Erro: 40 - Nombre del Proveedor es obligatorio - Linea: "
+ numeroLinha);
String anoDocumento = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 9 + 9 + 11 + 60, ultimo + 6 + 4 + 2 + 2
+ 1 + 9 + 9 + 11 + 60 + 4);
String mesDocumento = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 9 + 9 + 11 + 60 + 4, ultimo + 6 + 4 + 2
+ 2 + 1 + 9 + 9 + 11 + 60 + 4 + 2);
String diaDocumento = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 9 + 9 + 11 + 60 + 4 + 2, ultimo + 6 + 4
+ 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4 + 2 + 2);
Date dataDocumento = null;
if (diaDocumento.startsWith(" ")
|| mesDocumento.startsWith(" ")
|| anoDocumento.startsWith(" "))
erros
.add("Error: 92 - Fecha Documento Invalida - Linea: "
+ numeroLinha);
else
dataDocumento = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaDocumento + "/" + mesDocumento + "/"
+ anoDocumento);
String montanteDocumentoStr = linha.substring(ultimo + 6
+ 4 + 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4
+ 2 + 2 + 22);
if (montanteDocumentoStr.equals(""))
erros
.add("Error: 41 - Valor del Documento es obligatorio - Linea: "
+ numeroLinha);
double montanteDocumento = Double
.parseDouble(montanteDocumentoStr);
String anoPagamento = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 9 + 9 + 11 + 60 + 4 + 2 + 2 + 22, ultimo
+ 6 + 4 + 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4 + 2 + 2
+ 22 + 4);
String mesPagamento = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 9 + 9 + 11 + 60 + 4 + 2 + 2 + 22 + 4,
ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4
+ 2 + 2 + 22 + 4 + 2);
String diaPagamento = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 9 + 9 + 11 + 60 + 4 + 2 + 2 + 22 + 4 + 2,
ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4
+ 2 + 2 + 22 + 4 + 2 + 2);
Date dataPagamento = null;
if (diaPagamento.startsWith(" ")
|| mesPagamento.startsWith(" ")
|| anoPagamento.startsWith(" "))
erros
.add("Error: 92 - Fecha Pagamento Invalida - Linea: "
+ numeroLinha);
else
dataPagamento = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaPagamento + "/" + mesPagamento + "/"
+ anoPagamento);
String situacaoFatura = "";
if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4
+ 2 + 2 + 22 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4
+ 2 + 2 + 22 + 4 + 2 + 2 + 1).equals("1"))
situacaoFatura = "Pagada";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4
+ 2 + 2 + 22 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4
+ 2 + 2 + 22 + 4 + 2 + 2 + 1).equals("2"))
situacaoFatura = "Pendiente";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4
+ 2 + 2 + 22 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4
+ 2 + 2 + 22 + 4 + 2 + 2 + 1).equals("3"))
situacaoFatura = "Anulada";
if (situacaoFatura.equals(""))
erros
.add("Error: 42 - Situacin de la Factura es obligatoria - Linea: "
+ numeroLinha);
ultimo = ultimo + 6 + 4 + 2 + 2 + 1 + 9 + 9 + 11 + 60 + 4
+ 2 + 2 + 22 + 4 + 2 + 2 + 1;
if (erros.size() == 0) {
FaturaSinistro fatura = (FaturaSinistro) this
.getModelManager().getEntity("FaturaSinistro");
//fatura.verificarDuplicidade(sinistro, tipoDocumento,
// numeroDocumento, rucProvedor);
fatura.atribuirOrigem(sinistro.obterOrigem());
fatura.atribuirDestino(sinistro.obterDestino());
fatura.atribuirResponsavel(sinistro.obterResponsavel());
fatura.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
fatura.atribuirSuperior(sinistro);
//fatura.incluir();
fatura.atribuirDataSinistro(dataSinistro);
fatura.atribuirTipo(tipoDocumento);
fatura.atribuirNumeroDocumento(numeroDocumento);
fatura.atribuirNumeroFatura(numeroFatura);
fatura.atribuirRucProvedor(rucProvedor);
fatura.atribuirNomeProvedor(nomeProvedor);
fatura.atribuirDataDocumento(dataDocumento);
fatura.atribuirMontanteDocumento(montanteDocumento);
fatura.atribuirDataPagamento(dataPagamento);
fatura.atribuirSituacaoFatura(situacaoFatura);
fatura.atribuirTipoInstrumento(tipoInstrumento);
fatura.atribuirNumeroEndoso(numeroEndoso);
fatura.atribuirCertificado(certificado);
fatura
.atribuirTipoDocumentoProveedor(tipoDocumentoProvedor);
faturas.add(fatura);
}
/*
* else { if(apolice!=null) { apolice.excluir(); break; } }
*/
}
}
// REGISTRO TIPO 8
else if (Integer.parseInt(linha.substring(5, 7)) == 8) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String numeroInstrumento = linha.substring(17, 27);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
String anoAnulacao = linha.substring(27, 31);
String mesAnulacao = linha.substring(31, 33);
String diaAnulacao = linha.substring(33, 35);
Date dataAnulacao = null;
if (diaAnulacao.startsWith(" ") || mesAnulacao.startsWith(" ")
|| anoAnulacao.startsWith(" "))
erros.add("Error: 92 - Fecha Anulacin Invalida - Linea: "
+ numeroLinha);
else
dataAnulacao = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaAnulacao + "/" + mesAnulacao + "/"
+ anoAnulacao);
String tipoAnulacao = "";
if (linha.substring(35, 36).equals("1"))
tipoAnulacao = "Total";
else if (linha.substring(35, 36).equals("2"))
tipoAnulacao = "Parcial";
String capitalAnuladoGsStr = linha.substring(36, 58);
double capitalAnuladoGs = Double
.parseDouble(capitalAnuladoGsStr);
String tipoMoedaCapitalAnulado = this.obterTipoMoeda(linha
.substring(58, 60));
String capitalAnuladoMeStr = linha.substring(60, 82);
double capitalAnuladoMe = Double
.parseDouble(capitalAnuladoMeStr);
String solicitado = "";
if (linha.substring(82, 83).equals("1"))
solicitado = "Asegurado";
else if (linha.substring(82, 83).equals("2"))
solicitado = "Tomador";
else if (linha.substring(82, 83).equals("3"))
solicitado = "Compaia Aseguradora";
else if (linha.substring(82, 83).equals("4"))
solicitado = "Otros";
if (solicitado.equals(""))
erros
.add("Error: 43 - Solicitado Por es obligatorio - Linea: "
+ numeroLinha);
String diasCorridos = linha.substring(83, 88);
if (diasCorridos.equals(""))
erros
.add("Error: 44 - Dias Corridos es obligatorio - Linea: "
+ numeroLinha);
String primaAnuladaGsStr = linha.substring(88, 110);
if (primaAnuladaGsStr.equals(""))
erros
.add("Error: 45 - Prima Anulada en Gs es obligatoria - Linea: "
+ numeroLinha);
double primaAnuladaGs = Double.parseDouble(primaAnuladaGsStr);
String tipoMoedaPrimaAnuladaGs = this.obterTipoMoeda(linha
.substring(110, 112));
String primaAnuladaMeStr = linha.substring(112, 134);
if (primaAnuladaMeStr.equals(""))
erros
.add("Error: 46 - Prima Anulada en M/E es obligatoria - Linea: "
+ numeroLinha);
double primaAnuladaMe = Double.parseDouble(primaAnuladaMeStr);
String comissaoAnuladaGsStr = linha.substring(134, 156);
double comissaoAnuladaGs = Double
.parseDouble(comissaoAnuladaGsStr);
String tipoMoedaComissaoAnuladaGs = this.obterTipoMoeda(linha
.substring(156, 158));
String comissaoAnuladaMeStr = linha.substring(158, 180);
if (comissaoAnuladaMeStr.equals(""))
erros
.add("Error: 47 - Comisin Anulada en M/E es obligatoria - Linea: "
+ numeroLinha);
double comissaoAnuladaMe = Double
.parseDouble(comissaoAnuladaMeStr);
String comissaoRecuperarGsStr = linha.substring(180, 202);
double comissaoRecuperarGs = Double
.parseDouble(comissaoRecuperarGsStr);
String tipoMoedaComissaoRecuperarGs = this.obterTipoMoeda(linha
.substring(202, 204));
String comissaoRecuperarMeStr = linha.substring(204, 226);
double comissaoRecuperarMe = Double
.parseDouble(comissaoRecuperarMeStr);
String saldoAnuladoGsStr = linha.substring(226, 248);
if (saldoAnuladoGsStr.equals(""))
erros
.add("Error: 48 - Saldo Anulacin en Gs es obligatorio - Linea: "
+ numeroLinha);
double saldoAnuladoGs = Double.parseDouble(saldoAnuladoGsStr);
String tipoMoedaSaldoAnuladoGs = this.obterTipoMoeda(linha
.substring(248, 250));
String saldoAnuladoMeStr = linha.substring(250, 272);
if (saldoAnuladoMeStr.equals(""))
erros
.add("Error: 49 - Saldo Anulacin en M/E es obligatorio - Linea: "
+ numeroLinha);
double saldoAnuladoMe = Double.parseDouble(saldoAnuladoMeStr);
String destinoSaldoAnulacao = "";
if (linha.substring(272, 273).equals("1"))
destinoSaldoAnulacao = "Cuando el Saldo es Cero";
else if (linha.substring(272, 273).equals("2"))
destinoSaldoAnulacao = "A favor del Asegurado/Tomador";
else if (linha.substring(272, 273).equals("3"))
destinoSaldoAnulacao = "A favor de la Compaia";
String motivoAnulacao = linha.substring(273, 393);
String tipoInstrumento = "";
if (linha.substring(393, 394).equals("1"))
tipoInstrumento = "Pliza Individual";
else if (linha.substring(393, 394).equals("2"))
tipoInstrumento = "Pliza Madre";
else if (linha.substring(393, 394).equals("3"))
tipoInstrumento = "Certificado de Seguro Colectivo";
else if (linha.substring(393, 394).equals("4"))
tipoInstrumento = "Certificado Provisorio";
else if (linha.substring(393, 394).equals("5"))
tipoInstrumento = "Nota de Cobertura de Reaseguro";
if (tipoInstrumento.equals(""))
erros
.add("Error: 101 - Instrumento es obligatorio - Linea: "
+ numeroLinha);
double numeroEndoso = Double.parseDouble(linha.substring(394,
404));
double certificado = Double.parseDouble(linha.substring(404,
411));
if (erros.size() == 0) {
AnulacaoInstrumento anulacao = (AnulacaoInstrumento) this
.getModelManager().getEntity("AnulacaoInstrumento");
anulacao.atribuirOrigem(apolice.obterOrigem());
anulacao.atribuirDestino(apolice.obterDestino());
anulacao.atribuirResponsavel(apolice.obterResponsavel());
anulacao.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
anulacao.atribuirSuperior(apolice);
anulacao.atribuirDataAnulacao(dataAnulacao);
anulacao.atribuirTipo(tipoAnulacao);
anulacao.atribuirCapitalGs(capitalAnuladoGs);
anulacao
.atribuirTipoMoedaCapitalGs(tipoMoedaCapitalAnulado);
anulacao.atribuirCapitalMe(capitalAnuladoMe);
anulacao.atribuirSolicitadoPor(solicitado);
anulacao.atribuirDiasCorridos(Integer
.parseInt(diasCorridos));
anulacao.atribuirPrimaGs(primaAnuladaGs);
anulacao.atribuirTipoMoedaPrimaGs(tipoMoedaPrimaAnuladaGs);
anulacao.atribuirPrimaMe(primaAnuladaMe);
anulacao.atribuirComissaoGs(comissaoAnuladaGs);
anulacao
.atribuirTipoMoedaComissaoGs(tipoMoedaComissaoAnuladaGs);
anulacao.atribuirComissaoMe(comissaoAnuladaMe);
anulacao.atribuirComissaoRecuperarGs(comissaoRecuperarGs);
anulacao
.atribuirTipoMoedaComissaoRecuperarGs(tipoMoedaComissaoRecuperarGs);
anulacao.atribuirComissaoRecuperarMe(comissaoRecuperarMe);
anulacao.atribuirSaldoAnulacaoGs(saldoAnuladoGs);
anulacao
.atribuirTipoMoedaSaldoAnulacaoGs(tipoMoedaSaldoAnuladoGs);
anulacao.atribuirSaldoAnulacaoMe(saldoAnuladoMe);
anulacao.atribuirDestinoSaldoAnulacao(destinoSaldoAnulacao);
anulacao.atribuirTipoInstrumento(tipoInstrumento);
anulacao.atribuirNumeroEndoso(numeroEndoso);
anulacao.atribuirCertificado(certificado);
apolice.atualizarDataEncerramento(dataAnulacao);
apolice.atualizarSituacaoSeguro("No Vigente");
String motivoAnulacao2 = "";
int cont = 1;
for (int j = 0; j < motivoAnulacao.length();) {
String caracter = motivoAnulacao.substring(j, cont);
if (j == 100) {
boolean entrou = false;
while (!caracter.equals(" ")) {
motivoAnulacao2 += caracter;
j++;
cont++;
if (j == motivoAnulacao.length())
break;
else
caracter = motivoAnulacao
.substring(j, cont);
entrou = true;
}
if (!entrou) {
j++;
cont++;
} else
motivoAnulacao2 += "\n";
} else {
motivoAnulacao2 += caracter;
cont++;
j++;
}
}
anulacao.atribuirDescricao(motivoAnulacao2);
anulacoes.add(anulacao);
}
/*
* else { if(apolice!=null) { apolice.excluir(); break; } }
*/
}
// REGISTRO TIPO 9
else if (Integer.parseInt(linha.substring(5, 7)) == 9) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String tipoInstrumento = "";
if (linha.substring(17, 18).equals("1"))
tipoInstrumento = "Pliza Individual";
else if (linha.substring(17, 18).equals("2"))
tipoInstrumento = "Pliza Madre";
else if (linha.substring(17, 18).equals("3"))
tipoInstrumento = "Certificado de Seguro Colectivo";
else if (linha.substring(17, 18).equals("4"))
tipoInstrumento = "Certificado Provisorio";
else if (linha.substring(17, 18).equals("5"))
tipoInstrumento = "Nota de Cobertura de Reaseguro";
if (tipoInstrumento.equals(""))
erros
.add("Error: 101 - Instrumento es obligatorio - Linea: "
+ numeroLinha);
String numeroInstrumento = linha.substring(18, 28);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
double numeroEndoso = Double.parseDouble(linha
.substring(28, 38));
double certificado = Double
.parseDouble(linha.substring(38, 45));
String qtdeStr = linha.substring(45, 47);
if (qtdeStr.equals(""))
erros
.add("Error: 50 - Cantidad de Cobranzas es obligatoria - Linea: "
+ numeroLinha);
int qtde = Integer.parseInt(qtdeStr);
int ultimo = 0;
for (int w = 0; w < qtde; w++) {
if (ultimo == 0)
ultimo = 47;
String anoCobranca = linha.substring(ultimo, ultimo + 4);
String mesCobranca = linha.substring(ultimo + 4,
ultimo + 4 + 2);
String diaCobranca = linha.substring(ultimo + 4 + 2,
ultimo + 4 + 2 + 2);
Date dataCobranca = null;
if (diaCobranca.startsWith(" ")
|| mesCobranca.startsWith(" ")
|| anoCobranca.startsWith(" "))
erros
.add("Error: 92 - Fecha Cobranza Invalida - Linea: "
+ numeroLinha);
else
dataCobranca = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaCobranca + "/" + mesCobranca + "/"
+ anoCobranca);
String anoVencimentoCobranca = linha.substring(
ultimo + 4 + 2 + 2, ultimo + 4 + 2 + 2 + 4);
String mesVencimentoCobranca = linha.substring(ultimo + 4
+ 2 + 2 + 4, ultimo + 4 + 2 + 2 + 4 + 2);
String diaVencimentoCobranca = linha.substring(ultimo + 4
+ 2 + 2 + 4 + 2, ultimo + 4 + 2 + 2 + 4 + 2 + 2);
Date dataVencimentoCobranca = null;
if (diaVencimentoCobranca.startsWith(" ")
|| mesVencimentoCobranca.startsWith(" ")
|| anoVencimentoCobranca.startsWith(" "))
erros
.add("Error: 92 - Fecha Vencimiento Cobranza Invalida - Linea: "
+ numeroLinha);
else
dataVencimentoCobranca = new SimpleDateFormat(
"dd/MM/yyyy").parse(diaVencimentoCobranca + "/"
+ mesVencimentoCobranca + "/"
+ anoVencimentoCobranca);
String cotaCobranca = linha.substring(ultimo + 4 + 2 + 2
+ 4 + 2 + 2, ultimo + 4 + 2 + 2 + 4 + 2 + 2 + 2);
if (cotaCobranca.equals(""))
erros
.add("Error: 51 - Numero de la Cuota de la Cobranza es obligatorio - Linea: "
+ numeroLinha);
String valorCobrancaGsStr = linha.substring(ultimo + 4 + 2
+ 2 + 4 + 2 + 2 + 2, ultimo + 4 + 2 + 2 + 4 + 2 + 2
+ 2 + 22);
if (valorCobrancaGsStr.equals(""))
erros
.add("Error: 52 - Valor en Gs de la Cobranza es obligatorio - Linea: "
+ numeroLinha);
double valorCobrancaGs = Double
.parseDouble(valorCobrancaGsStr);
String tipoMoedaCobrancaGs = this
.obterTipoMoeda(linha.substring(ultimo + 4 + 2 + 2
+ 4 + 2 + 2 + 2 + 22, ultimo + 4 + 2 + 2
+ 4 + 2 + 2 + 2 + 22 + 2));
String valorCobrancaMeStr = linha.substring(ultimo + 4 + 2
+ 2 + 4 + 2 + 2 + 2 + 22 + 2, ultimo + 4 + 2 + 2
+ 4 + 2 + 2 + 2 + 22 + 2 + 22);
double valorCobrancaMe = Double
.parseDouble(valorCobrancaMeStr);
String valorInteresCobrancaStr = linha.substring(ultimo + 4
+ 2 + 2 + 4 + 2 + 2 + 2 + 22 + 2 + 22, ultimo + 4
+ 2 + 2 + 4 + 2 + 2 + 2 + 22 + 2 + 22 + 22);
double valorInteresCobranca = Double
.parseDouble(valorInteresCobrancaStr);
ultimo = ultimo + 4 + 2 + 2 + 4 + 2 + 2 + 2 + 22 + 2 + 22
+ 22;
if (erros.size() == 0) {
RegistroCobranca cobranca = (RegistroCobranca) this
.getModelManager()
.getEntity("RegistroCobranca");
//cobranca.verificarDuplicidade(apolice, cContas,
// dataCobranca, Integer.parseInt(cotaCobranca));
cobranca.atribuirOrigem(apolice.obterOrigem());
cobranca.atribuirDestino(apolice.obterDestino());
cobranca
.atribuirResponsavel(apolice.obterResponsavel());
cobranca.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
cobranca.atribuirSuperior(apolice);
//cobranca.incluir();
cobranca.atribuirDataCobranca(dataCobranca);
cobranca.atribuirDataVencimento(dataVencimentoCobranca);
cobranca.atribuirNumeroParcela(Integer
.parseInt(cotaCobranca));
cobranca.atribuirValorCobrancaGs(valorCobrancaGs);
cobranca
.atribuirTipoMoedaValorCobrancaGs(tipoMoedaCobrancaGs);
cobranca.atribuirValorCobrancaMe(valorCobrancaMe);
cobranca.atribuirValorInteres(valorInteresCobranca);
cobranca.atribuirTipoInstrumento(tipoInstrumento);
cobranca.atribuirNumeroEndoso(numeroEndoso);
cobranca.atribuirCertificado(certificado);
cobrancas.add(cobranca);
}
/*
* else { if(apolice!=null) { apolice.excluir(); break; } }
*/
}
}
// REGISTRO TIPO 10
else if (Integer.parseInt(linha.substring(5, 7)) == 10) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String numeroInstrumento = linha.substring(17, 27);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
String numeroOrdem = linha.substring(27, 33);
if (numeroOrdem.equals(""))
erros
.add("Error: 53 - Numero de Orden es obligatorio - Linea: "
+ numeroLinha);
String anoNotificacao = linha.substring(33, 37);
String mesNotificacao = linha.substring(37, 39);
String diaNotificacao = linha.substring(39, 41);
Date dataNotificacao = null;
if (diaNotificacao.startsWith(" ")
|| mesNotificacao.startsWith(" ")
|| anoNotificacao.startsWith(" "))
erros
.add("Error: 92 - Fecha Notificacin Invalida - Linea: "
+ numeroLinha);
else
dataNotificacao = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaNotificacao + "/" + mesNotificacao + "/"
+ anoNotificacao);
String assuntoQuestionado = linha.substring(41, 161);
if (assuntoQuestionado.equals(""))
erros
.add("Error: 54 - Asunto Cuestionado es obligatorio - Linea: "
+ numeroLinha);
String demandante = linha.substring(161, 201);
if (demandante.equals(""))
erros
.add("Error: 55 - Actor o Demandante es obligatorio - Linea: "
+ numeroLinha);
String demandado = linha.substring(201, 241);
if (demandado.equals(""))
erros.add("Error: 56 - Demandado es obligatorio - Linea: "
+ numeroLinha);
String julgado = linha.substring(241, 243);
if (julgado.equals(""))
erros.add("Error: 57 - Juzgado es obligatorio - Linea: "
+ numeroLinha);
String turno = linha.substring(243, 245);
if (turno.equals(""))
erros.add("Error: 58 - Turno es obligatorio - Linea: "
+ numeroLinha);
String juiz = linha.substring(245, 285);
if (juiz.equals(""))
erros.add("Error: 59 - Juez es obligatorio - Linea: "
+ numeroLinha);
String numeroSecretaria = linha.substring(285, 287);
if (numeroSecretaria.equals(""))
erros
.add("Error: 60 - Numero de la Secretaria es obligatorio - Linea: "
+ numeroLinha);
String advogado = linha.substring(287, 327);
if (advogado.equals(""))
erros
.add("Error: 61 - Abogado que esta a cargo del caso es obligatorio - Linea: "
+ numeroLinha);
String circunscricao = linha.substring(327, 329);
if (circunscricao.equals(""))
erros
.add("Error: 62 - Circunscripcin es obligatoria - Linea: "
+ numeroLinha);
String forum = linha.substring(329, 331);
if (forum.equals(""))
erros.add("Error: 63 - Fuero es obligatorio - Linea: "
+ numeroLinha);
String anoDemanda = linha.substring(331, 335);
String mesDemanda = linha.substring(335, 337);
String diaDemanda = linha.substring(337, 339);
Date dataDemanda = null;
if (diaDemanda.startsWith(" ") || mesDemanda.startsWith(" ")
|| anoDemanda.startsWith(" "))
erros.add("Error: 92 - Fecha Demanda Invalida - Linea: "
+ numeroLinha);
else
dataDemanda = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaDemanda + "/" + mesDemanda + "/"
+ anoDemanda);
String montanteDemandandoStr = linha.substring(339, 361);
if (montanteDemandandoStr.equals(""))
erros
.add("Error: 64 - Valor demandado es obligatorio - Linea: "
+ numeroLinha);
double montanteDemandando = Double
.parseDouble(montanteDemandandoStr);
String montanteSentencaStr = linha.substring(361, 383);
double montanteSentenca = Double
.parseDouble(montanteSentencaStr);
String anoCancelamento = linha.substring(383, 387);
String mesCancelamento = linha.substring(387, 389);
String diaCancelamento = linha.substring(389, 391);
Date dataCancelamento = null;
if (diaCancelamento.startsWith(" ")
|| mesCancelamento.startsWith(" ")
|| anoCancelamento.startsWith(" "))
erros
.add("Error: 92 - Fecha Cancelacin Invalida - Linea: "
+ numeroLinha);
else
dataCancelamento = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaCancelamento + "/" + mesCancelamento
+ "/" + anoCancelamento);
String caraterDemanda = "";
if (linha.substring(391, 392).equals("1"))
caraterDemanda = "La propria Compaia";
else if (linha.substring(391, 392).equals("2"))
caraterDemanda = "Citada en garantia";
if (caraterDemanda.equals(""))
erros
.add("Error: 65 - Carcter de la demanda es obligatorio - Linea: "
+ numeroLinha);
String responsabilidadeMaximaStr = linha.substring(392, 414);
double responsabilidadeMaxima = Double
.parseDouble(responsabilidadeMaximaStr);
String provisaoSinistroStr = linha.substring(414, 436);
double provisaoSinistro = Double
.parseDouble(provisaoSinistroStr);
String objetoCausa = linha.substring(436, 686);
if (objetoCausa.equals(""))
erros
.add("Error: 66 - Objeto de la Causa es obligatorio - Linea: "
+ numeroLinha);
String observacoes = linha.substring(686, 936);
String tipoInstrumento = "";
if (linha.substring(936, 937).equals("1"))
tipoInstrumento = "Pliza Individual";
else if (linha.substring(936, 937).equals("2"))
tipoInstrumento = "Pliza Madre";
else if (linha.substring(936, 937).equals("3"))
tipoInstrumento = "Certificado de Seguro Colectivo";
else if (linha.substring(936, 937).equals("4"))
tipoInstrumento = "Certificado Provisorio";
else if (linha.substring(936, 937).equals("5"))
tipoInstrumento = "Nota de Cobertura de Reaseguro";
if (tipoInstrumento.equals(""))
erros
.add("Error: 101 - Instrumento es obligatorio - Linea: "
+ numeroLinha);
double numeroEndoso = Double.parseDouble(linha.substring(937,
947));
double certificado = Double.parseDouble(linha.substring(947,
954));
if (erros.size() == 0) {
AspectosLegais aspectos = (AspectosLegais) this
.getModelManager().getEntity("AspectosLegais");
//aspectos.verificarDuplicidade(apolice, cContas,
// numeroOrdem);
aspectos.atribuirOrigem(apolice.obterOrigem());
aspectos.atribuirDestino(apolice.obterDestino());
aspectos.atribuirResponsavel(apolice.obterResponsavel());
aspectos.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
aspectos.atribuirSuperior(apolice);
//aspectos.incluir();
aspectos.atribuirNumeroOrdem(numeroOrdem);
aspectos.atribuirDataNotificacao(dataNotificacao);
aspectos.atribuirAssunto(assuntoQuestionado);
aspectos.atribuirDemandante(demandante);
aspectos.atribuirDemandado(demandado);
aspectos.atribuirJulgado(julgado);
aspectos.atribuirTurno(turno);
aspectos.atribuirJuiz(juiz);
aspectos.atribuirSecretaria(numeroSecretaria);
aspectos.atribuirAdvogado(advogado);
aspectos.atribuirCircunscricao(circunscricao);
aspectos.atribuirForum(forum);
aspectos.atribuirDataDemanda(dataDemanda);
aspectos.atribuirMontanteDemandado(montanteDemandando);
aspectos.atribuirMontanteSentenca(montanteSentenca);
aspectos.atribuirDataCancelamento(dataCancelamento);
aspectos.atribuirTipo(caraterDemanda);
aspectos
.atribuirResponsabilidadeMaxima(responsabilidadeMaxima);
aspectos.atribuirSinistroPendente(provisaoSinistro);
aspectos.atribuirTipoInstrumento(tipoInstrumento);
aspectos.atribuirNumeroEndoso(numeroEndoso);
aspectos.atribuirCertificado(certificado);
String objetoCausa2 = "";
int cont = 1;
for (int j = 0; j < objetoCausa.length();) {
String caracter = objetoCausa.substring(j, cont);
if (j == 100 || j == 200) {
boolean entrou = false;
while (!caracter.equals(" ")) {
objetoCausa2 += caracter;
j++;
cont++;
if (j == objetoCausa.length())
break;
else
caracter = objetoCausa.substring(j, cont);
entrou = true;
}
if (!entrou) {
j++;
cont++;
} else
objetoCausa2 += "\n";
} else {
objetoCausa2 += caracter;
cont++;
j++;
}
}
//System.out.println("Objeto de la Causa: " +
// objetoCausa2);
aspectos.atribuirObjetoCausa(objetoCausa2);
cont = 1;
String observacoes2 = "";
for (int j = 0; j < observacoes.length();) {
String caracter = observacoes.substring(j, cont);
if (j == 100 || j == 200) {
boolean entrou = false;
while (!caracter.equals(" ")) {
observacoes2 += caracter;
j++;
cont++;
if (j == observacoes.length())
break;
else
caracter = observacoes.substring(j, cont);
entrou = true;
}
if (!entrou) {
j++;
cont++;
} else
observacoes2 += "\n";
} else {
observacoes2 += caracter;
cont++;
j++;
}
}
//System.out.println("Obs: " + observacoes2);
aspectos.atribuirDescricao(observacoes2);
aspectos2.add(aspectos);
}
/*
* else { if(apolice!=null) { apolice.excluir(); break; } }
*/
}
// REGISTRO TIPO 11
else if (Integer.parseInt(linha.substring(5, 7)) == 11) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String tipoInstrumento = "";
if (linha.substring(17, 18).equals("1"))
tipoInstrumento = "Pliza Individual";
else if (linha.substring(17, 18).equals("2"))
tipoInstrumento = "Pliza Madre";
else if (linha.substring(17, 18).equals("3"))
tipoInstrumento = "Certificado de Seguro Colectivo";
else if (linha.substring(17, 18).equals("4"))
tipoInstrumento = "Certificado Provisorio";
else if (linha.substring(17, 18).equals("5"))
tipoInstrumento = "Nota de Cobertura de Reaseguro";
if (tipoInstrumento.equals(""))
erros
.add("Error: 101 - Instrumento es obligatorio - Linea: "
+ numeroLinha);
String numeroInstrumento = linha.substring(18, 28);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
double numeroEndoso2 = Double.parseDouble(linha.substring(28,
38));
double certificado2 = Double.parseDouble(linha
.substring(38, 45));
String qtdeStr = linha.substring(45, 47);
if (qtdeStr.equals(""))
erros
.add("Error: 67 - Cantidad de Endosos es obligatoria - Linea: "
+ numeroLinha);
int qtde = Integer.parseInt(qtdeStr);
int ultimo = 0;
for (int w = 0; w < qtde; w++) {
if (ultimo == 0)
ultimo = 47;
String numeroEndoso = linha.substring(ultimo, ultimo + 10);
if (numeroEndoso.equals(""))
erros
.add("Error: 68 - Numero del Endoso es obligatorio - Linea: "
+ numeroLinha);
String anoEmissao = linha.substring(ultimo + 10,
ultimo + 10 + 4);
String mesEmissao = linha.substring(ultimo + 10 + 4,
ultimo + 10 + 4 + 2);
String diaEmissao = linha.substring(ultimo + 10 + 4 + 2,
ultimo + 10 + 4 + 2 + 2);
Date dataEmissao = null;
if (diaEmissao.startsWith(" ")
|| mesEmissao.startsWith(" ")
|| anoEmissao.startsWith(" "))
erros
.add("Error: 92 - Fecha Emisin Invalida - Linea: "
+ numeroLinha);
else
dataEmissao = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaEmissao + "/" + mesEmissao + "/"
+ anoEmissao);
String anoVigenciaInicial = linha.substring(ultimo + 10 + 4
+ 2 + 2, ultimo + 10 + 4 + 2 + 2 + 4);
String mesVigenciaInicial = linha.substring(ultimo + 10 + 4
+ 2 + 2 + 4, ultimo + 10 + 4 + 2 + 2 + 4 + 2);
String diaVigenciaInicial = linha.substring(ultimo + 10 + 4
+ 2 + 2 + 4 + 2, ultimo + 10 + 4 + 2 + 2 + 4 + 2
+ 2);
Date dataVigenciaInicial = null;
if (diaVigenciaInicial.startsWith(" ")
|| mesVigenciaInicial.startsWith(" ")
|| anoVigenciaInicial.startsWith(" "))
erros
.add("Error: 92 - Fecha Inicio Vigencia Invalida - Linea: "
+ numeroLinha);
else
dataVigenciaInicial = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaVigenciaInicial + "/"
+ mesVigenciaInicial + "/"
+ anoVigenciaInicial);
String anoVigenciaVencimento = linha.substring(ultimo + 10
+ 4 + 2 + 2 + 4 + 2 + 2, ultimo + 10 + 4 + 2 + 2
+ 4 + 2 + 2 + 4);
String mesVigenciaVencimento = linha.substring(ultimo + 10
+ 4 + 2 + 2 + 4 + 2 + 2 + 4, ultimo + 10 + 4 + 2
+ 2 + 4 + 2 + 2 + 4 + 2);
String diaVigenciaVencimento = linha.substring(ultimo + 10
+ 4 + 2 + 2 + 4 + 2 + 2 + 4 + 2, ultimo + 10 + 4
+ 2 + 2 + 4 + 2 + 2 + 4 + 2 + 2);
Date dataVigenciaVencimento = null;
if (diaVigenciaVencimento.startsWith(" ")
|| mesVigenciaVencimento.startsWith(" ")
|| anoVigenciaVencimento.startsWith(" "))
erros
.add("Error: 92 - Fecha Fin Vigencia Invalida - Linea: "
+ numeroLinha);
else
dataVigenciaVencimento = new SimpleDateFormat(
"dd/MM/yyyy").parse(diaVigenciaVencimento + "/"
+ mesVigenciaVencimento + "/"
+ anoVigenciaVencimento);
String razaoEmissao = linha.substring(ultimo + 10 + 4 + 2
+ 2 + 4 + 2 + 2 + 4 + 2 + 2, ultimo + 10 + 4 + 2
+ 2 + 4 + 2 + 2 + 4 + 2 + 2 + 120);
if (razaoEmissao.equals(""))
erros
.add("Error: 69 - Razn o causa es obligatoria - Linea: "
+ numeroLinha);
String primaGsStr = linha.substring(ultimo + 10 + 4 + 2 + 2
+ 4 + 2 + 2 + 4 + 2 + 2 + 120, ultimo + 10 + 4 + 2
+ 2 + 4 + 2 + 2 + 4 + 2 + 2 + 120 + 22);
if (primaGsStr.equals(""))
erros
.add("Error: 70 - Prima en Gs del Endoso es obligatoria - Linea: "
+ numeroLinha);
double primaGs = Double.parseDouble(primaGsStr);
String tipoMoedaPrimaGs = this.obterTipoMoeda(linha
.substring(ultimo + 10 + 4 + 2 + 2 + 4 + 2 + 2 + 4
+ 2 + 2 + 120 + 22, ultimo + 10 + 4 + 2 + 2
+ 4 + 2 + 2 + 4 + 2 + 2 + 120 + 22 + 2));
String primaMeStr = linha.substring(ultimo + 10 + 4 + 2 + 2
+ 4 + 2 + 2 + 4 + 2 + 2 + 120 + 22 + 2, ultimo + 10
+ 4 + 2 + 2 + 4 + 2 + 2 + 4 + 2 + 2 + 120 + 22 + 2
+ 22);
double primaMe = Double.parseDouble(primaMeStr);
ultimo = ultimo + 10 + 4 + 2 + 2 + 4 + 2 + 2 + 4 + 2 + 2
+ 120 + 22 + 2 + 22;
if (erros.size() == 0) {
Suplemento suplemento = (Suplemento) this
.getModelManager().getEntity("Suplemento");
suplemento.atribuirOrigem(apolice.obterOrigem());
suplemento.atribuirDestino(apolice.obterDestino());
suplemento.atribuirResponsavel(apolice
.obterResponsavel());
suplemento.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
suplemento.atribuirSuperior(apolice);
suplemento.atribuirNumero(numeroEndoso);
suplemento.atribuirDataEmissao(dataEmissao);
suplemento
.atribuirDataPrevistaInicio(dataVigenciaInicial);
suplemento
.atribuirDataPrevistaConclusao(dataVigenciaVencimento);
suplemento.atribuirPrimaGs(primaGs);
suplemento.atribuirTipoMoedaPrimaGs(tipoMoedaPrimaGs);
suplemento.atribuirPrimaMe(primaMe);
suplemento.atribuirTipoInstrumento(tipoInstrumento);
suplemento.atribuirNumeroEndoso(numeroEndoso2);
suplemento.atribuirCertificado(certificado2);
String razaoEmissao2 = "";
int cont = 1;
for (int j = 0; j < razaoEmissao.length();) {
String caracter = razaoEmissao.substring(j, cont);
if (j == 100) {
boolean entrou = false;
while (!caracter.equals(" ")) {
razaoEmissao2 += caracter;
j++;
cont++;
if (j == razaoEmissao.length())
break;
else
caracter = razaoEmissao.substring(j,
cont);
entrou = true;
}
if (!entrou) {
j++;
cont++;
} else
razaoEmissao2 += "\n";
} else {
razaoEmissao2 += caracter;
cont++;
j++;
}
}
suplemento.atribuirRazao(razaoEmissao2);
suplementos.add(suplemento);
}
/*
* else { if(apolice!=null) { apolice.excluir(); break; } }
*/
}
}
// REGISTRO TIPO 12
else if (Integer.parseInt(linha.substring(5, 7)) == 12) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String numeroInstrumento = linha.substring(17, 27);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
String anoFinalizacao = linha.substring(27, 31);
String mesFinalizacao = linha.substring(31, 33);
String diaFinalizacao = linha.substring(33, 35);
Date dataFinalizacao = null;
if (diaFinalizacao.startsWith(" ")
|| mesFinalizacao.startsWith(" ")
|| anoFinalizacao.startsWith(" "))
erros
.add("Error: 92 - Fecha Finalizacin Invalida - Linea: "
+ numeroLinha);
else
dataFinalizacao = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaFinalizacao + "/" + mesFinalizacao + "/"
+ anoFinalizacao);
String tipoInstrumento = "";
if (linha.substring(35, 36).equals("1"))
tipoInstrumento = "Pliza Individual";
else if (linha.substring(35, 36).equals("2"))
tipoInstrumento = "Pliza Madre";
else if (linha.substring(35, 36).equals("3"))
tipoInstrumento = "Certificado de Seguro Colectivo";
else if (linha.substring(35, 36).equals("4"))
tipoInstrumento = "Certificado Provisorio";
else if (linha.substring(35, 36).equals("5"))
tipoInstrumento = "Nota de Cobertura de Reaseguro";
if (tipoInstrumento.equals(""))
erros
.add("Error: 101 - Instrumento es obligatorio - Linea: "
+ numeroLinha);
double numeroEndoso = Double.parseDouble(linha
.substring(36, 46));
double certificado = Double
.parseDouble(linha.substring(46, 53));
if (erros.size() == 0) {
//apolice.excluirFinalizacao();
//apolice.adicionarFinalizacao(dataFinalizacao);
apolice.atualizarDataEncerramento(dataFinalizacao);
apolice.atualizarSituacaoSeguro("No Vigente");
}
/*
* else { apolice.excluir(); break; }
*/
}
// REGISTRO TIPO 13
else if (Integer.parseInt(linha.substring(5, 7)) == 13) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String numeroInstrumento = linha.substring(17, 27);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
String anoInicioVigencia = linha.substring(27, 31);
String mesInicioVigencia = linha.substring(31, 33);
String diaInicioVigencia = linha.substring(33, 35);
Date dataInicioVigencia = null;
if (diaInicioVigencia.startsWith(" ")
|| mesInicioVigencia.startsWith(" ")
|| anoInicioVigencia.startsWith(" "))
erros
.add("Error: 92 - Fecha Inicio Vigencia Invalida - Linea: "
+ numeroLinha);
else
dataInicioVigencia = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaInicioVigencia + "/" + mesInicioVigencia
+ "/" + anoInicioVigencia);
String anoFimVigencia = linha.substring(35, 39);
String mesFimVigencia = linha.substring(39, 41);
String diaFimVigencia = linha.substring(41, 43);
Date dataFimVigencia = null;
if (diaFimVigencia.startsWith(" ")
|| mesFimVigencia.startsWith(" ")
|| anoFimVigencia.startsWith(" "))
erros.add("Error: 92 - Fecha Fin Invalida - Linea: "
+ numeroLinha);
else
dataFimVigencia = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaFimVigencia + "/" + mesFimVigencia + "/"
+ anoFimVigencia);
String financiamentoGsStr = linha.substring(43, 65);
if (financiamentoGsStr.equals(""))
erros
.add("Error: 71 - Inters por Financiamento en Gs es obligatorio - Linea: "
+ numeroLinha);
double financiamentoGs = Double.parseDouble(financiamentoGsStr);
String tipoMoedaFinanciamentoGs = this.obterTipoMoeda(linha
.substring(65, 67));
String financiamentoMeStr = linha.substring(67, 89);
double financiamentoMe = Double.parseDouble(financiamentoMeStr);
String qtde = linha.substring(89, 92);
if (qtde.equals(""))
erros
.add("Error: 72 - Cantidad de Cuotas de la Refinanciacin es obligatoria - Linea: "
+ numeroLinha);
String tipoInstrumento = "";
if (linha.substring(92, 93).equals("1"))
tipoInstrumento = "Pliza Individual";
else if (linha.substring(92, 93).equals("2"))
tipoInstrumento = "Pliza Madre";
else if (linha.substring(92, 93).equals("3"))
tipoInstrumento = "Certificado de Seguro Colectivo";
else if (linha.substring(92, 93).equals("4"))
tipoInstrumento = "Certificado Provisorio";
else if (linha.substring(92, 93).equals("5"))
tipoInstrumento = "Nota de Cobertura de Reaseguro";
if (tipoInstrumento.equals(""))
erros
.add("Error: 101 - Instrumento es obligatorio - Linea: "
+ numeroLinha);
double numeroEndoso = Double.parseDouble(linha.substring(93,
103));
double certificado = Double.parseDouble(linha.substring(103,
110));
if (erros.size() == 0) {
Refinacao refinacao = (Refinacao) this.getModelManager()
.getEntity("Refinacao");
refinacao.atribuirOrigem(apolice.obterOrigem());
refinacao.atribuirDestino(apolice.obterDestino());
refinacao.atribuirResponsavel(apolice.obterResponsavel());
refinacao.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
refinacao.atribuirSuperior(apolice);
refinacao.atribuirDataPrevistaInicio(dataInicioVigencia);
refinacao.atribuirDataPrevistaConclusao(dataFimVigencia);
refinacao.atribuirFinanciamentoGs(financiamentoGs);
refinacao
.atribuirTipoMoedaFinanciamentoGs(tipoMoedaFinanciamentoGs);
refinacao.atribuirFinanciamentoMe(financiamentoMe);
refinacao.atribuirQtdeParcelas(Integer.parseInt(qtde));
refinacao.atribuirTipoInstrumento(tipoInstrumento);
refinacao.atribuirNumeroEndoso(numeroEndoso);
refinacao.atribuirCertificado(certificado);
refinacoes.add(refinacao);
}
/*
* else { if(apolice!=null) { apolice.excluir(); break; } }
*/
}
// REGISTRO TIPO 14
else if (Integer.parseInt(linha.substring(5, 7)) == 14) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String tipoInstrumento = "";
if (linha.substring(17, 18).equals("1"))
tipoInstrumento = "Pliza Individual";
else if (linha.substring(17, 18).equals("2"))
tipoInstrumento = "Pliza Madre";
else if (linha.substring(17, 18).equals("3"))
tipoInstrumento = "Certificado de Seguro Colectivo";
else if (linha.substring(17, 18).equals("4"))
tipoInstrumento = "Certificado Provisorio";
else if (linha.substring(17, 18).equals("5"))
tipoInstrumento = "Nota de Cobertura de Reaseguro";
if (tipoInstrumento.equals(""))
erros
.add("Error: 101 - Instrumento es obligatorio - Linea: "
+ numeroLinha);
String numeroInstrumento = linha.substring(18, 28);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
double numeroEndoso = Double.parseDouble(linha
.substring(28, 38));
double certificado = Double
.parseDouble(linha.substring(38, 45));
String qtdeStr = linha.substring(45, 47);
int qtde = Integer.parseInt(qtdeStr);
int ultimo = 0;
for (int w = 0; w < qtde; w++) {
if (ultimo == 0)
ultimo = 47;
String numeroSinistro = linha.substring(ultimo, ultimo + 6);
Sinistro sinistro = null;
if (this.sinistros != null)
sinistro = (Sinistro) this.sinistros
.get(numeroSinistro);
if (sinistro == null)
erros.add("Error: 74 - Siniestro "
+ numeroSinistro.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
if (numeroSinistro.equals(""))
erros
.add("Error: 37 - Numero del Siniestro es obligatorio - Linea: "
+ numeroLinha);
String anoSinistro = linha.substring(ultimo + 6,
ultimo + 6 + 4);
String mesSinistro = linha.substring(ultimo + 6 + 4,
ultimo + 6 + 4 + 2);
String diaSinistro = linha.substring(ultimo + 6 + 4 + 2,
ultimo + 6 + 4 + 2 + 2);
Date dataSinistro = null;
if (diaSinistro.startsWith(" ")
|| mesSinistro.startsWith(" ")
|| anoSinistro.startsWith(" "))
erros
.add("Error: 92 - Fecha Sinistro Invalida - Linea: "
+ numeroLinha);
else
dataSinistro = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaSinistro + "/" + mesSinistro + "/"
+ anoSinistro);
String tipoPagamento = "";
if (linha.substring(ultimo + 6 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1).equals("1"))
tipoPagamento = "Liquidador";
else if (linha.substring(ultimo + 6 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1).equals("2"))
tipoPagamento = "Asegurado";
else if (linha.substring(ultimo + 6 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1).equals("3"))
tipoPagamento = "Tercero";
else if (linha.substring(ultimo + 6 + 4 + 2 + 2,
ultimo + 6 + 4 + 2 + 2 + 1).equals("4"))
tipoPagamento = "Otros";
String numeroLiquidador = linha.substring(ultimo + 6 + 4
+ 2 + 2 + 1, ultimo + 6 + 4 + 2 + 2 + 1 + 3);
AuxiliarSeguro auxiliar = null;
auxiliar = (AuxiliarSeguro) entidadeHome
.obterEntidadePorInscricao(numeroLiquidador);
if (auxiliar == null)
erros
.add("Error: 84 - Auxiliar de Seguro con Inscripcin "
+ numeroLiquidador
+ " no fue encontrado - Linea: "
+ numeroLinha);
String nomeTerceiro = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 3, ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60);
String abonadoGsStr = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 3 + 60, ultimo + 6 + 4 + 2 + 2 + 1 + 3
+ 60 + 22);
double abonadoGs = Double.parseDouble(abonadoGsStr);
String tipoMoedaAbonoGs = this.obterTipoMoeda(linha
.substring(
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22,
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22
+ 2));
String abonadoMeStr = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 3 + 60 + 22 + 2, ultimo + 6 + 4 + 2 + 2
+ 1 + 3 + 60 + 22 + 2 + 22);
double abonadoMe = Double.parseDouble(abonadoMeStr);
String anoPagamento = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 3 + 60 + 22 + 2 + 22, ultimo + 6 + 4 + 2
+ 2 + 1 + 3 + 60 + 22 + 2 + 22 + 4);
String mesPagamento = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 3 + 60 + 22 + 2 + 22 + 4, ultimo + 6 + 4
+ 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22 + 4 + 2);
String diaPagamento = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 3 + 60 + 22 + 2 + 22 + 4 + 2, ultimo + 6
+ 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22 + 4 + 2 + 2);
Date dataPagamento = null;
if (diaPagamento.startsWith(" ")
|| mesPagamento.startsWith(" ")
|| anoPagamento.startsWith(" "))
erros
.add("Error: 92 - Fecha Pagamento Invalida - Linea: "
+ numeroLinha);
else
dataPagamento = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaPagamento + "/" + mesPagamento + "/"
+ anoPagamento);
String numeroCheque = linha.substring(ultimo + 6 + 4 + 2
+ 2 + 1 + 3 + 60 + 22 + 2 + 22 + 4 + 2 + 2, ultimo
+ 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22 + 4 + 2
+ 2 + 10);
String bancoStr = linha.substring(ultimo + 6 + 4 + 2 + 2
+ 1 + 3 + 60 + 22 + 2 + 22 + 4 + 2 + 2 + 10, ultimo
+ 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22 + 4 + 2
+ 2 + 10 + 10);
Conta banco = null;
banco = (Conta) entidadeHome
.obterEntidadePorApelido(bancoStr);
if (banco == null)
erros.add("Error: 88 - Banco " + bancoStr
+ " no fue encontrado - Linea: " + numeroLinha);
String situacaoSinistro = "";
if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10,
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10 + 1).equals("1"))
situacaoSinistro = "Pendiente de Liquidacin";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10,
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10 + 1).equals("2"))
situacaoSinistro = "Controvertido";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10,
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10 + 1).equals("3"))
situacaoSinistro = "Pendiente de Pago";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10,
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10 + 1).equals("4"))
situacaoSinistro = "Rechazado";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10,
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10 + 1).equals("5"))
situacaoSinistro = "Judicializado";
String situacaoPagamento = "";
if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10 + 1,
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10 + 1 + 1).equals("1"))
situacaoPagamento = "Normal";
else if (linha.substring(
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10 + 1,
ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10 + 1 + 1).equals("2"))
situacaoPagamento = "Anulado";
ultimo = ultimo + 6 + 4 + 2 + 2 + 1 + 3 + 60 + 22 + 2 + 22
+ 4 + 2 + 2 + 10 + 10 + 1 + 1;
if (erros.size() == 0) {
RegistroGastos gastos = (RegistroGastos) this
.getModelManager().getEntity("RegistroGastos");
gastos.atribuirOrigem(sinistro.obterOrigem());
gastos.atribuirDestino(sinistro.obterDestino());
gastos.atribuirResponsavel(sinistro.obterResponsavel());
gastos.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
gastos.atribuirSuperior(sinistro);
gastos.atribuirDataSinistro(dataSinistro);
gastos.atribuirTipo(tipoPagamento);
gastos.atribuirAuxiliarSeguro(auxiliar);
gastos.atribuirNomeTerceiro(nomeTerceiro);
gastos.atribuirAbonoGs(abonadoGs);
gastos.atribuirTipoMoedaAbonoGs(tipoMoedaAbonoGs);
gastos.atribuirAbonoMe(abonadoMe);
gastos.atribuirDataPagamento(dataPagamento);
gastos.atribuirNumeroCheque(numeroCheque);
gastos.atribuirBanco(banco);
gastos.atribuirSituacaoSinistro(situacaoSinistro);
gastos.atribuirSituacaoPagamento(situacaoPagamento);
gastos.atribuirTipoInstrumento(tipoInstrumento);
gastos.atribuirNumeroEndoso(numeroEndoso);
gastos.atribuirCertificado(certificado);
gastos2.add(gastos);
}
/*
* else { if(apolice!=null) { apolice.excluir(); break; } }
*/
}
}
// REGISTRO TIPO 15
else if (Integer.parseInt(linha.substring(5, 7)) == 15) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String numeroInstrumento = linha.substring(17, 27);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
String inscricaoReaseguradora = linha.substring(27, 30);
Reaseguradora reaseguradora = null;
reaseguradora = (Reaseguradora) entidadeHome
.obterEntidadePorInscricao(inscricaoReaseguradora);
if (reaseguradora == null)
erros.add("Error: 10 - Inscripcin de la Reaseguradora "
+ inscricaoReaseguradora
+ " no fue encontrada o esta No Activa - Linea: "
+ numeroLinha);
String tipoContrato = "";
if (linha.substring(30, 31).equals("1"))
tipoContrato = "Cuota parte";
else if (linha.substring(30, 31).equals("2"))
tipoContrato = "Excedente";
else if (linha.substring(30, 31).equals("3"))
tipoContrato = "Exceso de prdida";
else if (linha.substring(30, 31).equals("4"))
tipoContrato = "Facultativo no Proporcional";
else if (linha.substring(30, 31).equals("5"))
tipoContrato = "Facultativo Proporcional";
else if (linha.substring(30, 31).equals("6"))
tipoContrato = "Limitacin de Siniestralidad";
String anoAnulacao = linha.substring(31, 35);
String mesAnulacao = linha.substring(35, 37);
String diaAnulacao = linha.substring(37, 39);
Date dataAnulacao = null;
if (diaAnulacao.startsWith(" ") || mesAnulacao.startsWith(" ")
|| anoAnulacao.startsWith(" "))
erros.add("Error: 92 - Fecha Anulacin Invalida - Linea: "
+ numeroLinha);
else
dataAnulacao = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaAnulacao + "/" + mesAnulacao + "/"
+ anoAnulacao);
String tipoAnulacao = "";
if (linha.substring(39, 40).equals("1"))
tipoAnulacao = "Total";
else if (linha.substring(39, 40).equals("2"))
tipoAnulacao = "Parcial";
String capitalAnuladoGsStr = linha.substring(40, 62);
double capitalAnuladoGs = Double
.parseDouble(capitalAnuladoGsStr);
String tipoMoedaCapitalAnuladoGs = this.obterTipoMoeda(linha
.substring(62, 64));
String capitalAnuladoMeStr = linha.substring(64, 86);
double capitalAnuladoMe = Double
.parseDouble(capitalAnuladoMeStr);
String diaCorridos = linha.substring(86, 91);
String primaAnuladaGsStr = linha.substring(91, 113);
double primaAnuladaGs = Double.parseDouble(primaAnuladaGsStr);
String tipoMoedaPrimaAnuladaGs = this.obterTipoMoeda(linha
.substring(113, 115));
String primaAnuladaMeStr = linha.substring(115, 137);
double primaAnuladaMe = Double.parseDouble(primaAnuladaMeStr);
String comissaoAnuladaGsStr = linha.substring(137, 159);
double comissaoAnuladaGs = Double
.parseDouble(comissaoAnuladaGsStr);
String tipoMoedaComissaoAnuladaGs = this.obterTipoMoeda(linha
.substring(159, 161));
String comissaoAnuladaMeStr = linha.substring(161, 183);
double comissaoAnuladaMe = Double
.parseDouble(comissaoAnuladaMeStr);
String motivoAnulacao = linha.substring(183, 303);
DadosReaseguro dadosReaseguro = null;
if (this.dadosReaseguros != null) {
if (reaseguradora != null)
dadosReaseguro = (DadosReaseguro) this.dadosReaseguros
.get(new Long(cContas.obterId()
+ apolice.obterNumeroApolice()
+ reaseguradora.obterId())
+ tipoContrato);
else
dadosReaseguro = (DadosReaseguro) this.dadosReaseguros
.get(new Long(cContas.obterId()
+ apolice.obterNumeroApolice())
+ tipoContrato);
}
if (dadosReaseguro == null)
dadosReaseguro = dadosReaseguroHome.obterDadosReaseguro(
cContas, apolice, reaseguradora, tipoContrato);
if (dadosReaseguro == null)
erros.add("Error: 83 - Reaseguradora "
+ inscricaoReaseguradora
+ " no fue encontrada o esta No Activa - Linea: "
+ numeroLinha);
if (erros.size() == 0) {
RegistroAnulacao anulacao = (RegistroAnulacao) this
.getModelManager().getEntity("RegistroAnulacao");
anulacao.verificarDuplicidade(apolice, cContas,
reaseguradora, tipoContrato);
anulacao.atribuirOrigem(dadosReaseguro.obterOrigem());
anulacao.atribuirDestino(dadosReaseguro.obterDestino());
anulacao.atribuirResponsavel(dadosReaseguro
.obterResponsavel());
anulacao.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
anulacao.atribuirSuperior(dadosReaseguro);
dadosReaseguro.atribuirSituacao("No Vigente");
//anulacao.incluir();
anulacao.atribuirReaeguradora(reaseguradora);
anulacao.atribuirTipoContrato(tipoContrato);
anulacao.atribuirDataAnulacao(dataAnulacao);
anulacao.atribuirTipo(tipoAnulacao);
anulacao.atribuirCapitalGs(capitalAnuladoGs);
anulacao
.atribuirTipoMoedaCapitalGs(tipoMoedaCapitalAnuladoGs);
anulacao.atribuirCapitalMe(capitalAnuladoMe);
anulacao
.atribuirDiasCorridos(Integer.parseInt(diaCorridos));
anulacao.atribuirPrimaGs(primaAnuladaGs);
anulacao.atribuirTipoMoedaPrimaGs(tipoMoedaPrimaAnuladaGs);
anulacao.atribuirPrimaMe(primaAnuladaMe);
anulacao.atribuirComissaoGs(comissaoAnuladaGs);
anulacao
.atribuirTipoMoedaComissaoGs(tipoMoedaComissaoAnuladaGs);
int cont = 1;
String motivoAnulacao2 = "";
for (int j = 0; j < motivoAnulacao.length();) {
String caracter = motivoAnulacao.substring(j, cont);
if (j == 100 || j == 200) {
boolean entrou = false;
while (!caracter.equals(" ")) {
motivoAnulacao2 += caracter;
j++;
cont++;
if (j == motivoAnulacao.length())
break;
else
caracter = motivoAnulacao
.substring(j, cont);
entrou = true;
}
if (!entrou) {
j++;
cont++;
} else
motivoAnulacao2 += "\n";
} else {
motivoAnulacao2 += caracter;
cont++;
j++;
}
}
anulacao.atribuirDescricao(motivoAnulacao2);
anulacoes2.add(anulacao);
}
/*
* else { if(apolice!=null) { apolice.excluir(); break; } }
*/
}
// REGISTRO TIPO 16
else if (Integer.parseInt(linha.substring(5, 7)) == 16) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros.add("Error: 05 - Cuenta " + apelidoCconta.trim()
+ " no fue encontrada - Linea: " + numeroLinha);
String numeroInstrumento = linha.substring(17, 27);
Apolice apolice = null;
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado - Linea: " + numeroLinha);
String anoCorte = linha.substring(27, 31);
String mesCorte = linha.substring(31, 33);
String diaCorte = linha.substring(33, 35);
Date dataCorte = null;
if (diaCorte.startsWith(" ") || mesCorte.startsWith(" ")
|| anoCorte.startsWith(" "))
erros.add("Error: 92 - Fecha Corte Invalida - Linea: "
+ numeroLinha);
else
dataCorte = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaCorte + "/" + mesCorte + "/" + anoCorte);
String numeroParcela = linha.substring(35, 37);
String anoVencimento = linha.substring(37, 41);
String mesVencimento = linha.substring(41, 43);
String diaVencimento = linha.substring(43, 45);
Date dataVencimento = null;
if (diaVencimento.startsWith(" ")
|| mesVencimento.startsWith(" ")
|| anoVencimento.startsWith(" "))
erros
.add("Error: 92 - Fecha Vencimiento Invalida - Linea: "
+ numeroLinha);
else
dataVencimento = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaVencimento + "/" + mesVencimento + "/"
+ anoVencimento);
String diaAtraso = linha.substring(45, 48);
String valorGsStr = linha.substring(48, 70);
double valorGs = Double.parseDouble(valorGsStr);
String tipoMoeda = this.obterTipoMoeda(linha.substring(70, 72));
String valorMeStr = linha.substring(72, 94);
double valorMe = Double.parseDouble(valorMeStr);
if (erros.size() == 0) {
Morosidade morosidade = (Morosidade) this.getModelManager()
.getEntity("Morosidade");
morosidade.atribuirOrigem(apolice.obterOrigem());
morosidade.atribuirDestino(apolice.obterDestino());
morosidade.atribuirResponsavel(apolice.obterResponsavel());
morosidade.atribuirTitulo("Datos do Instrumento: "
+ numeroInstrumento);
morosidade.atribuirSuperior(apolice);
//morosidade.incluir();
morosidade.atribuirDataCorte(dataCorte);
morosidade.atribuirNumeroParcela(Integer
.parseInt(numeroParcela));
morosidade.atribuirDataVencimento(dataVencimento);
morosidade.atribuirDiasAtraso(Integer.parseInt(diaAtraso));
morosidade.atribuirValorGs(valorGs);
morosidade.atribuirTipoMoedaValorGs(tipoMoeda);
morosidade.atribuirValorMe(valorMe);
morosidades.add(morosidade);
}
/*
* else { if(apolice!=null) { apolice.excluir(); break; } }
*/
}
//REGISTRO TIPO 18
else if (Integer.parseInt(linha.substring(5, 7)) == 18) {
String ativoCorrenteStr = linha.substring(7, 29);
double ativoCorrente = Double.parseDouble(ativoCorrenteStr);
String passivoCorrenteStr = linha.substring(29, 51);
double passivoCorrente = Double.parseDouble(passivoCorrenteStr);
String inversaoStr = linha.substring(51, 73);
double inversao = Double.parseDouble(inversaoStr);
String deudasStr = linha.substring(73, 95);
double deudas = Double.parseDouble(deudasStr);
String usoStr = linha.substring(95, 117);
double uso = Double.parseDouble(usoStr);
String vendaStr = linha.substring(117, 139);
double venda = Double.parseDouble(vendaStr);
String leasingStr = linha.substring(139, 161);
double leasing = Double.parseDouble(leasingStr);
String resultadoStr = linha.substring(161, 183);
double resultado = Double.parseDouble(resultadoStr);
EntidadeHome home = (EntidadeHome) this.getModelManager()
.getHome("EntidadeHome");
RatioPermanente ratio = (RatioPermanente) this
.getModelManager().getEntity("RatioPermanente");
Entidade bcp = home.obterEntidadePorApelido("bcp");
ratio.atribuirOrigem(aseguradora);
ratio.atribuirDestino(bcp);
ratio.atribuirResponsavel(this.obterUsuarioAtual());
ratio.atribuirTitulo("Ratio Financeiro - Permanente");
ratio.atribuirDataPrevistaInicio(dataGeracao);
//ratio.incluir();
ratio.atribuirAtivoCorrente(ativoCorrente);
ratio.atribuirPassivoCorrente(passivoCorrente);
ratio.atribuirInversao(inversao);
ratio.atribuirDeudas(deudas);
ratio.atribuirUso(uso);
ratio.atribuirVenda(venda);
ratio.atribuirLeasing(leasing);
ratio.atribuirResultados(resultado);
ratiosPermanentes.add(ratio);
/*
* for(Iterator k =
* aseguradora.obterEventosComoOrigem().iterator() ; k.hasNext() ; ) {
* Evento e = (Evento) k.next();
*
* if(e instanceof RatioPermanente)
* if(e.obterId()!=ratio.obterId())
* if(e.obterFase().obterCodigo().equals(Evento.EVENTO_PENDENTE))
* e.atualizarFase(Evento.EVENTO_CONCLUIDO); }
*/
}
// REGISTRO TIPO 19
else if (Integer.parseInt(linha.substring(5, 7)) == 19) {
String primasDiretasStr = linha.substring(7, 29);
double primasDiretas = Double.parseDouble(primasDiretasStr);
String primasAceitasStr = linha.substring(29, 51);
double primasAceitas = Double.parseDouble(primasAceitasStr);
String primasCedidasStr = linha.substring(51, 73);
double primasCedidas = Double.parseDouble(primasCedidasStr);
String anulacaoPrimasDiretasStr = linha.substring(73, 95);
double anulacaoPrimasDiretas = Double
.parseDouble(anulacaoPrimasDiretasStr);
String anulacaoPrimasAtivasStr = linha.substring(95, 117);
double anulacaoPrimasAtivas = Double
.parseDouble(anulacaoPrimasAtivasStr);
String anulacaoPrimasCedidasStr = linha.substring(117, 139);
double anulacaoPrimasCedidas = Double
.parseDouble(anulacaoPrimasCedidasStr);
EntidadeHome home = (EntidadeHome) this.getModelManager()
.getHome("EntidadeHome");
RatioUmAno ratio = (RatioUmAno) this.getModelManager()
.getEntity("RatioUmAno");
Entidade bcp = home.obterEntidadePorApelido("bcp");
ratio.atribuirOrigem(aseguradora);
ratio.atribuirDestino(bcp);
ratio.atribuirResponsavel(this.obterUsuarioAtual());
ratio.atribuirTitulo("Ratio Financeiro - Un Ao");
ratio.atribuirDataPrevistaInicio(dataGeracao);
//ratio.incluir();
ratio.atribuirPrimasDiretas(primasDiretas);
ratio.atribuirPrimasAceitas(primasAceitas);
ratio.atribuirPrimasCedidas(primasCedidas);
ratio.atribuirAnulacaoPrimasDiretas(anulacaoPrimasDiretas);
ratio.atribuirAnulacaoPrimasAtivas(anulacaoPrimasAtivas);
ratio.atribuirAnulacaoPrimasCedidas(anulacaoPrimasCedidas);
ratiosUmAno.add(ratio);
/*
* for(Iterator k =
* aseguradora.obterEventosComoOrigem().iterator() ; k.hasNext() ; ) {
* Evento e = (Evento) k.next();
*
* if(e instanceof RatioUmAno) if(e.obterId()!=ratio.obterId())
* if(e.obterFase().obterCodigo().equals(Evento.EVENTO_PENDENTE))
* e.atualizarFase(Evento.EVENTO_CONCLUIDO); }
*/
}
// REGISTRO TIPO 20
else if (Integer.parseInt(linha.substring(5, 7)) == 20) {
String sinistrosPagosStr = linha.substring(7, 29);
double sinistrosPagos = Double.parseDouble(sinistrosPagosStr);
String gastosSinistroStr = linha.substring(29, 51);
double gastosSinistro = Double.parseDouble(gastosSinistroStr);
String sinistrosRecuperadosStr = linha.substring(51, 73);
double sinistrosRecuperados = Double
.parseDouble(sinistrosRecuperadosStr);
String gastosRecupeadosStr = linha.substring(73, 95);
double gastosRecupeados = Double
.parseDouble(gastosRecupeadosStr);
String recuperoSinistroStr = linha.substring(95, 117);
double recuperoSinistro = Double
.parseDouble(recuperoSinistroStr);
String provisoesStr = linha.substring(117, 139);
double provisoes = Double.parseDouble(provisoesStr);
EntidadeHome home = (EntidadeHome) this.getModelManager()
.getHome("EntidadeHome");
RatioTresAnos ratio = (RatioTresAnos) this.getModelManager()
.getEntity("RatioTresAnos");
Entidade bcp = home.obterEntidadePorApelido("bcp");
ratio.atribuirOrigem(aseguradora);
ratio.atribuirDestino(bcp);
ratio.atribuirResponsavel(this.obterUsuarioAtual());
ratio.atribuirTitulo("Ratio Financeiro - Tres Ao");
ratio.atribuirDataPrevistaInicio(dataGeracao);
//ratio.incluir();
ratio.atribuirSinistrosPagos(sinistrosPagos);
ratio.atribuirGastosSinistros(gastosSinistro);
ratio.atribuirSinistrosRecuperados(sinistrosRecuperados);
ratio.atribuirGastosRecuperados(gastosRecupeados);
ratio.atribuirRecuperoSinistros(recuperoSinistro);
ratio.atribuirProvisoes(provisoes);
ratiosTresAnos.add(ratio);
}
// REGISTRO TIPO 99
else if (Integer.parseInt(linha.substring(5, 7)) == 99) {
if (numeroLinha != numeroTotalRegistros)
erros.add("Error: 86 - Numero total de registros ("
+ numeroLinha + ") no es el mismo del archivo ("
+ numeroTotalRegistros + ") - Linea: "
+ numeroLinha);
}
numeroLinha++;
}
return erros;
}
private void gravarEventosDaApolice() throws Exception {
//System.out.println("Apolices: " + this.apolices.size());
System.out.println("Gravando Eventos......: ");
for (Iterator i = this.apolices.values().iterator(); i.hasNext();) {
Apolice apolice = (Apolice) i.next();
apolice.incluir();
}
System.out.println("Gravou Apolice......: ");
for (Iterator i = this.dadosPrevisoes.iterator(); i.hasNext();) {
DadosPrevisao dados = (DadosPrevisao) i.next();
Apolice apolice = (Apolice) dados.obterSuperior();
dados.verificarDuplicidade(apolice, apolice.obterSecao(), dados
.obterDataCorte(), dados.obterNumeroEndoso());
dados.incluir();
}
System.out.println("Gravou Dados Previso......: ");
for (Iterator i = this.dadosReaseguros.values().iterator(); i.hasNext();) {
DadosReaseguro dados = (DadosReaseguro) i.next();
Apolice apolice = (Apolice) dados.obterSuperior();
if (dados.obterReaseguradora() != null)
dados.verificarDuplicidade(apolice, apolice.obterSecao(), dados
.obterReaseguradora(), dados.obterTipoContrato(), dados
.obterValorEndoso());
dados.incluir();
}
System.out.println("Gravou Dados Reaseguro......: ");
for (Iterator i = this.dadosCoaseguros.iterator(); i.hasNext();) {
DadosCoaseguro dados = (DadosCoaseguro) i.next();
Apolice apolice = (Apolice) dados.obterSuperior();
dados.verificarDuplicidade(apolice, apolice.obterSecao(), dados
.obterAseguradora(), dados.obterNumeroEndoso());
dados.incluir();
}
System.out.println("Gravou Dados Coaseguro......: ");
for (Iterator i = this.sinistros.values().iterator(); i.hasNext();) {
Sinistro sinistro = (Sinistro) i.next();
Apolice apolice = (Apolice) sinistro.obterSuperior();
sinistro.verificarDuplicidade(apolice, apolice.obterSecao(),
sinistro.obterNumero(), sinistro.obterNumeroEndoso());
sinistro.incluir();
}
System.out.println("Gravou Sinistro......: ");
for (Iterator i = this.faturas.iterator(); i.hasNext();) {
FaturaSinistro fatura = (FaturaSinistro) i.next();
Sinistro sinistro = (Sinistro) fatura.obterSuperior();
//fatura.verificarDuplicidade(sinistro, fatura.obterTipo(), fatura
//.obterNumeroDocumento(), fatura.obterRucProvedor(), fatura
//.obterNumeroEndoso(), fatura.obterDataPagamento());
fatura.incluir();
}
System.out.println("Gravou Faturas Sinistro......: ");
for (Iterator i = this.anulacoes.iterator(); i.hasNext();) {
AnulacaoInstrumento anulacao = (AnulacaoInstrumento) i.next();
Apolice apolice = (Apolice) anulacao.obterSuperior();
anulacao.verificarDuplicidade(apolice, apolice.obterSecao(),
anulacao.obterDataAnulacao(), anulacao.obterNumeroEndoso());
anulacao.incluir();
}
System.out.println("Gravou Anulaes......: ");
for (Iterator i = this.cobrancas.iterator(); i.hasNext();) {
RegistroCobranca cobranca = (RegistroCobranca) i.next();
Apolice apolice = (Apolice) cobranca.obterSuperior();
cobranca
.verificarDuplicidade(apolice, apolice.obterSecao(),
cobranca.obterDataCobranca(), cobranca
.obterNumeroParcela(), cobranca
.obterNumeroEndoso());
cobranca.incluir();
}
System.out.println("Gravou Cobrana......: ");
for (Iterator i = this.aspectos2.iterator(); i.hasNext();) {
AspectosLegais aspectos = (AspectosLegais) i.next();
Apolice apolice = (Apolice) aspectos.obterSuperior();
aspectos.verificarDuplicidade(apolice, apolice.obterSecao(),
aspectos.obterNumeroOrdem(), aspectos.obterNumeroEndoso());
aspectos.incluir();
}
System.out.println("Gravou Aspectos Legais......: ");
for (Iterator i = this.suplementos.iterator(); i.hasNext();) {
Suplemento suplemento = (Suplemento) i.next();
Apolice apolice = (Apolice) suplemento.obterSuperior();
suplemento.verificarDuplicidade(apolice, apolice.obterSecao(),
suplemento.obterNumero());
suplemento.incluir();
}
System.out.println("Gravou Suplementos......: ");
for (Iterator i = this.refinacoes.iterator(); i.hasNext();) {
Refinacao refinacao = (Refinacao) i.next();
Apolice apolice = (Apolice) refinacao.obterSuperior();
refinacao.verificarDuplicidade(apolice, apolice.obterSecao(),
refinacao.obterNumeroEndoso());
refinacao.incluir();
}
System.out.println("Gravou Refinanciacin......: ");
for (Iterator i = this.gastos2.iterator(); i.hasNext();) {
RegistroGastos gastos = (RegistroGastos) i.next();
Sinistro sinistro = (Sinistro) gastos.obterSuperior();
//gastos.verificarDuplicidade(sinistro, gastos.obterDataSinistro(),
// gastos.obterNumeroEndoso());
gastos.incluir();
}
System.out.println("Gravou Registros de Gastos......: ");
for (Iterator i = this.anulacoes2.iterator(); i.hasNext();) {
RegistroAnulacao anulacao = (RegistroAnulacao) i.next();
anulacao.incluir();
}
System.out.println("Gravou Anulaes 2......: ");
for (Iterator i = this.morosidades.iterator(); i.hasNext();) {
Morosidade morosidade = (Morosidade) i.next();
morosidade.incluir();
}
System.out.println("Gravou Morosidade......: ");
for (Iterator i = this.ratiosPermanentes.iterator(); i.hasNext();) {
RatioPermanente ratios = (RatioPermanente) i.next();
for (Iterator k = ratios.obterOrigem().obterEventosComoOrigem()
.iterator(); k.hasNext();) {
Evento e = (Evento) k.next();
if (e instanceof RatioTresAnos)
if (e.obterFase().obterCodigo().equals(
Evento.EVENTO_PENDENTE))
e.atualizarFase(Evento.EVENTO_CONCLUIDO);
}
ratios.incluir();
}
System.out.println("Gravou Ratios Permanentes......: ");
for (Iterator i = this.ratiosUmAno.iterator(); i.hasNext();) {
RatioUmAno ratios = (RatioUmAno) i.next();
for (Iterator k = ratios.obterOrigem().obterEventosComoOrigem()
.iterator(); k.hasNext();) {
Evento e = (Evento) k.next();
if (e instanceof RatioTresAnos)
if (e.obterFase().obterCodigo().equals(
Evento.EVENTO_PENDENTE))
e.atualizarFase(Evento.EVENTO_CONCLUIDO);
}
ratios.incluir();
}
System.out.println("Gravou Ratios 1 Ano......: ");
for (Iterator i = this.ratiosTresAnos.iterator(); i.hasNext();) {
RatioTresAnos ratios = (RatioTresAnos) i.next();
for (Iterator k = ratios.obterOrigem().obterEventosComoOrigem()
.iterator(); k.hasNext();) {
Evento e = (Evento) k.next();
if (e instanceof RatioTresAnos)
if (e.obterFase().obterCodigo().equals(
Evento.EVENTO_PENDENTE))
e.atualizarFase(Evento.EVENTO_CONCLUIDO);
}
ratios.incluir();
}
System.out.println("Gravou Ratios 3 Anos......: ");
}
private Collection validarAsegurado(Collection linhas) throws Exception {
int numeroLinha = 1;
ApoliceHome apoliceHome = (ApoliceHome) this.getModelManager().getHome(
"ApoliceHome");
EntidadeHome entidadeHome = (EntidadeHome) this.getModelManager()
.getHome("EntidadeHome");
UsuarioHome usuarioHome = (UsuarioHome) this.getModelManager().getHome(
"UsuarioHome");
Apolice apolice = null;
Aseguradora aseguradora = null;
Usuario usuario = null;
Date dataGeracao = null;
String tipoArquivo = null;
int numeroTotalRegistros = 0;
for (Iterator i = linhas.iterator(); i.hasNext();) {
String linha = (String) i.next();
if (Integer.parseInt(linha.substring(0, 5)) != numeroLinha)
erros
.add("Error: 02 - Numero secuencial invalido (Archivo Datos del Asegurado) - Linea: "
+ numeroLinha);
System.out.println("numeroLinhaB: " + numeroLinha);
// REGISTRO TIPO 1
if (Integer.parseInt(linha.substring(5, 7)) == 1) {
String sigla = linha.substring(7, 10);
aseguradora = (Aseguradora) entidadeHome
.obterEntidadePorSigla(sigla);
if (aseguradora == null)
erros
.add("Error: 03 - Aseguradora "
+ sigla
+ " no fue encontrada (Archivo Datos del Asegurado) - Linea: "
+ numeroLinha);
else {
if (!this.obterOrigem().equals(aseguradora))
erros
.add("Error: 06 - Aseguradora "
+ sigla
+ " no es la misma de la agenda (Archivo Datos del Asegurado) - Linea: "
+ numeroLinha);
}
String chaveUsuario = linha.substring(10, 19);
usuario = usuarioHome.obterUsuarioPorChave(chaveUsuario.trim());
if (usuario == null)
erros
.add("Error: 04 - Usuario "
+ chaveUsuario.trim()
+ " no fue encontrado (Archivo Datos del Asegurado) - Linea: "
+ numeroLinha);
String anoGeracao = linha.substring(20, 24);
String mesGeracao = linha.substring(24, 26);
String diaGeracao = linha.substring(26, 28);
if (diaGeracao.startsWith(" ") || mesGeracao.startsWith(" ")
|| anoGeracao.startsWith(" "))
erros.add("Error: 92 - Fecha Emisin Invalida - Linea: "
+ numeroLinha);
else
dataGeracao = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaGeracao + "/" + mesGeracao + "/"
+ anoGeracao);
String anoReporte = linha.substring(28, 32);
String mesReporte = linha.substring(32, 34);
if (this.obterMesMovimento() != Integer.parseInt(mesReporte))
erros
.add("Error: 07 - Mes informado es diferente del mes de la agenda (Archivo Datos del Asegurado)");
if (this.obterAnoMovimento() != Integer.parseInt(anoReporte))
erros
.add("Error: 08 - Ao informado es diferente del ao de la agenda (Archivo Datos del Asegurado)");
numeroTotalRegistros = Integer
.parseInt(linha.substring(34, 44));
tipoArquivo = "";
if (!linha.substring(44, 45).toLowerCase().equals("n"))
erros.add("Error: 82 - Tipo de Archivo Invalido - Linea: "
+ numeroLinha);
}
// REGISTRO TIPO 17
else if (Integer.parseInt(linha.substring(5, 7)) == 17) {
String apelidoCconta = linha.substring(7, 17);
ClassificacaoContas cContas = null;
cContas = (ClassificacaoContas) entidadeHome
.obterEntidadePorApelido(apelidoCconta.trim());
if (cContas == null)
erros
.add("Error: 05 - Cuenta "
+ apelidoCconta.trim()
+ " no fue encontrada (Archivo Datos del Asegurado) - Linea: "
+ numeroLinha);
String numeroInstrumento = linha.substring(17, 27);
if (this.apolices != null)
apolice = (Apolice) this.apolices.get(numeroInstrumento);
if (apolice == null)
apolice = apoliceHome.obterApolice(numeroInstrumento);
if (apolice == null)
erros
.add("Error: 73 - Instumento "
+ numeroInstrumento.trim()
+ " no fue encontrado (Archivo Datos del Asegurado) - Linea: "
+ numeroLinha);
String nomeAsegurado = linha.substring(27, 87);
String tipoPessoa = "";
if (linha.substring(87, 88).equals("1"))
tipoPessoa = "Persona Fisica";
else if (linha.substring(87, 88).equals("2"))
tipoPessoa = "Persona Juridica";
String tipoIdentificacao = "";
if (linha.substring(88, 89).equals("1"))
tipoIdentificacao = "Cdula de Identidad Paraguaya";
else if (linha.substring(88, 89).equals("2"))
tipoIdentificacao = "Cdula de Identidad Extranjera";
else if (linha.substring(88, 89).equals("3"))
tipoIdentificacao = "Passaporte";
else if (linha.substring(88, 89).equals("4"))
tipoIdentificacao = "RUC";
else if (linha.substring(88, 89).equals("5"))
tipoIdentificacao = "Otro";
String numeroIdentificacao = linha.substring(89, 104);
String anoNascimento = linha.substring(104, 108);
String mesNascimento = linha.substring(108, 110);
String diaNascimento = linha.substring(110, 112);
Date dataNascimento = null;
if (diaNascimento.startsWith(" ")
|| mesNascimento.startsWith(" ")
|| anoNascimento.startsWith(" ")) {
if (cContas.obterApelido().startsWith("04010120")
&& tipoPessoa.equals("Persona Fisica"))
erros
.add("Error: 92 - Fecha de Nacimiento invalida - Linea: "
+ numeroLinha);
else {
}
} else
dataNascimento = new SimpleDateFormat("dd/MM/yyyy")
.parse(diaNascimento + "/" + mesNascimento + "/"
+ anoNascimento);
String tomadorSeguro = linha.substring(112, 172);
if (erros.size() == 0) {
apolice.atribuirNomeAsegurado(nomeAsegurado);
apolice.atribuirTipoPessoa(tipoPessoa);
apolice.atribuirTipoIdentificacao(tipoIdentificacao);
apolice.atribuirNumeroIdentificacao(numeroIdentificacao);
apolice.atribuirDataNascimento(dataNascimento);
apolice.atribuirNomeTomador(tomadorSeguro);
}
}
numeroLinha++;
}
if (erros.size() == 0)
this.gravarEventosDaApolice();
return erros;
}
private String obterTipoMoeda(String cod) throws Exception {
String moeda = "";
if (cod.equals("01"))
moeda = "Guaran";
else if (cod.equals("02"))
moeda = "Dlar USA";
else if (cod.equals("03"))
moeda = "Euro";
else if (cod.equals("04"))
moeda = "Real";
else if (cod.equals("05"))
moeda = "Peso Arg";
else if (cod.equals("06"))
moeda = "Peso Uru";
else if (cod.equals("07"))
moeda = "Yen";
return moeda;
}
public boolean permiteAtualizar() throws Exception
{
EntidadeHome home = (EntidadeHome) this.getModelManager().getHome("EntidadeHome");
Entidade informatica = home.obterEntidadePorApelido("informatica");
if(this.obterId() > 0)
{
if(this.obterFase().obterCodigo().equals(Evento.EVENTO_CONCLUIDO))
return super.permiteAtualizar();
else
{
if(informatica!=null)
{
if(this.obterUsuarioAtual().obterSuperiores().contains(informatica) || this.obterUsuarioAtual().obterId() == 1)
return true;
else
return false;
}
else
return super.permiteAtualizar();
}
}
else
return true;
}
public void atualizarQtdeA(int total) throws Exception
{
SQLUpdate update = this.getModelManager().createSQLUpdate("crm","update agenda_movimentacao set qtdeA = ? where id = ?");
update.addInt(total);
update.addLong(this.obterId());
update.execute();
}
public void atualizarQtdeB(int total) throws Exception
{
SQLUpdate update = this.getModelManager().createSQLUpdate("crm","update agenda_movimentacao set qtdeB = ? where id = ?");
update.addInt(total);
update.addLong(this.obterId());
update.execute();
}
public int obterQtdeRegistrosA() throws Exception
{
int qtde = 0;
SQLQuery query = this.getModelManager().createSQLQuery("crm","select qtdeA from agenda_movimentacao where id = ?");
query.addLong(this.obterId());
qtde = query.executeAndGetFirstRow().getInt("qtdeA");
if(qtde == 0)
{
//String[] mesAnoArray = ultimaAgendaStr.split("/");
//String mesAno = mesAnoArray[1] + mesAnoArray[0];
String mesAno = "";
mesAno+= this.obterAnoMovimento();
if(new Integer(this.obterMesMovimento()).toString().length() == 1)
mesAno += "0" + this.obterMesMovimento();
else
mesAno += this.obterMesMovimento();
String sigla = this.obterOrigem().obterSigla();
File file = new File("C:/Aseguradoras/Archivos/A" + sigla + mesAno + ".txt");
if(file.exists())
{
Scanner scan = new Scanner(file);
String linha = scan.nextLine();
//qtde = Integer.parseInt(linha.substring(34, 44));
qtde = Integer.parseInt(linha.substring(36, 46));
this.atualizarQtdeA(qtde);
}
}
return qtde;
}
public int obterQtdeRegistrosB() throws Exception
{
int qtde = 0;
SQLQuery query = this.getModelManager().createSQLQuery("crm","select qtdeB from agenda_movimentacao where id = ?");
query.addLong(this.obterId());
qtde = query.executeAndGetFirstRow().getInt("qtdeB");
if(qtde == 0)
{
String mesAno = "";
mesAno+= this.obterAnoMovimento();
if(new Integer(this.obterMesMovimento()).toString().length() == 1)
mesAno += "0" + this.obterMesMovimento();
else
mesAno += this.obterMesMovimento();
String sigla = this.obterOrigem().obterSigla();
File file = new File("C:/Aseguradoras/Archivos/B" + sigla + mesAno + ".txt");
if(file.exists())
{
Scanner scan = new Scanner(file);
String linha = scan.nextLine();
//qtde = Integer.parseInt(linha.substring(34, 44));
qtde = Integer.parseInt(linha.substring(36, 46));
this.atualizarQtdeB(qtde);
}
}
return qtde;
}
public Date obterDataModificacaoArquivo() throws Exception
{
Date data = null;
String mesAno = "";
mesAno+= this.obterAnoMovimento();
if(new Integer(this.obterMesMovimento()).toString().length() == 1)
mesAno += "0" + this.obterMesMovimento();
else
mesAno += this.obterMesMovimento();
String sigla = this.obterOrigem().obterSigla();
File file = new File("C:/Aseguradoras/Archivos/A" + sigla + mesAno + ".txt");
if(file.exists())
{
long dataLong = file.lastModified();
if(dataLong > 0)
data = new Date(dataLong);
}
return data;
}
public void atualizarEspecial(String especial) throws Exception
{
SQLUpdate update = this.getModelManager().createSQLUpdate("crm","update agenda_movimentacao set especial = ? where id = ?");
update.addString(especial);
update.addLong(this.obterId());
update.execute();
}
public String obterEspecial() throws Exception
{
SQLQuery query = this.getModelManager().createSQLQuery("crm","select especial from agenda_movimentacao where id = ?");
query.addLong(this.obterId());
return query.executeAndGetFirstRow().getString("especial");
}
public boolean eEspecial() throws Exception
{
if(this.obterEspecial().equals("Sim"))
return true;
else
return false;
}
public void atualizarInscricaoEspecial(String especial) throws Exception
{
SQLUpdate update = this.getModelManager().createSQLUpdate("crm","update agenda_movimentacao set inscricao_especial = ? where id = ?");
update.addString(especial);
update.addLong(this.obterId());
update.execute();
}
public void atualizarSuplementosEspecial(String especial) throws Exception
{
SQLUpdate update = this.getModelManager().createSQLUpdate("crm","update agenda_movimentacao set suplemento_especial = ? where id = ?");
update.addString(especial);
update.addLong(this.obterId());
update.execute();
}
public void atualizarCapitalEspecial(String especial) throws Exception
{
SQLUpdate update = this.getModelManager().createSQLUpdate("crm","update agenda_movimentacao set capital_especial = ? where id = ?");
update.addString(especial);
update.addLong(this.obterId());
update.execute();
}
public void atualizarDataEspecial(String especial) throws Exception
{
SQLUpdate update = this.getModelManager().createSQLUpdate("crm","update agenda_movimentacao set fecha_especial = ? where id = ?");
update.addString(especial);
update.addLong(this.obterId());
update.execute();
}
public void atualizarDocumentoEspecial(String especial) throws Exception
{
SQLUpdate update = this.getModelManager().createSQLUpdate("crm","update agenda_movimentacao set documento_especial = ? where id = ?");
update.addString(especial);
update.addLong(this.obterId());
update.execute();
}
public void atualizarApAnteriorEspecial(String especial) throws Exception
{
SQLUpdate update = this.getModelManager().createSQLUpdate("crm","update agenda_movimentacao set ap_anterior_especial = ? where id = ?");
update.addString(especial);
update.addLong(this.obterId());
update.execute();
}
public void atualizarEndosoApolice(String especial) throws Exception
{
SQLUpdate update = this.getModelManager().createSQLUpdate("crm","update agenda_movimentacao set endoso_apolice = ? where id = ?");
update.addString(especial);
update.addLong(this.obterId());
update.execute();
}
public String obterInscricaoEspecial() throws Exception
{
SQLQuery query = this.getModelManager().createSQLQuery("crm","select inscricao_especial from agenda_movimentacao where id = ?");
query.addLong(this.obterId());
return query.executeAndGetFirstRow().getString("inscricao_especial");
}
public String obterSuplementoEspecial() throws Exception
{
SQLQuery query = this.getModelManager().createSQLQuery("crm","select suplemento_especial from agenda_movimentacao where id = ?");
query.addLong(this.obterId());
return query.executeAndGetFirstRow().getString("suplemento_especial");
}
public String obterCapitalEspecial() throws Exception
{
SQLQuery query = this.getModelManager().createSQLQuery("crm","select capital_especial from agenda_movimentacao where id = ?");
query.addLong(this.obterId());
return query.executeAndGetFirstRow().getString("capital_especial");
}
public String obterDataEspecial() throws Exception
{
SQLQuery query = this.getModelManager().createSQLQuery("crm","select fecha_especial from agenda_movimentacao where id = ?");
query.addLong(this.obterId());
return query.executeAndGetFirstRow().getString("fecha_especial");
}
public String obterDocumentoEspecial() throws Exception
{
SQLQuery query = this.getModelManager().createSQLQuery("crm","select documento_especial from agenda_movimentacao where id = ?");
query.addLong(this.obterId());
return query.executeAndGetFirstRow().getString("documento_especial");
}
public String obterApAnteriorEspecial() throws Exception
{
SQLQuery query = this.getModelManager().createSQLQuery("crm","select ap_anterior_especial from agenda_movimentacao where id = ?");
query.addLong(this.obterId());
return query.executeAndGetFirstRow().getString("ap_anterior_especial");
}
public String obterEndosoApolice() throws Exception
{
SQLQuery query = this.getModelManager().createSQLQuery("crm","select endoso_apolice from agenda_movimentacao where id = ?");
query.addLong(this.obterId());
return query.executeAndGetFirstRow().getString("endoso_apolice");
}
public void atualizaUltimaAgenda(String tipo) throws Exception
{
long asegId = this.obterOrigem().obterId();
int mes = this.obterMesMovimento();
int ano = this.obterAnoMovimento();
long agendaId = this.obterId();
SQLQuery query = this.getModelManager().createSQLQuery("crm","select count(*) as qtde from ultima_agenda where aseguradora_id = ? and mes > ? and ano > ? and tipo = ?");
query.addLong(asegId);
query.addInt(mes);
query.addInt(ano);
query.addString(tipo);
int qtde = query.executeAndGetFirstRow().getInt("qtde");
if(qtde == 0)
{
query = this.getModelManager().createSQLQuery("crm","select count(*) as qtde from ultima_agenda where aseguradora_id = ? and tipo = ?");
query.addLong(this.obterOrigem().obterId());
query.addString(tipo);
qtde = query.executeAndGetFirstRow().getInt("qtde");
if(qtde == 0)
{
SQLUpdate insert = this.getModelManager().createSQLUpdate("crm","insert into ultima_agenda(aseguradora_id, agenda_id, mes, ano, tipo) values(?,?,?,?,?)");
insert.addLong(asegId);
insert.addLong(agendaId);
insert.addInt(mes);
insert.addInt(ano);
insert.addString(tipo);
insert.execute();
}
else
{
SQLUpdate update = this.getModelManager().createSQLUpdate("crm","update ultima_agenda set agenda_id = ?, mes = ?, ano = ? where aseguradora_id = ? and tipo = ?");
update.addLong(agendaId);
update.addInt(mes);
update.addInt(ano);
update.addLong(asegId);
update.addString(tipo);
update.execute();
}
}
}
}
|
Python
|
UTF-8
| 560 | 2.5625 | 3 |
[] |
no_license
|
import search_data
import pymysql
def locker_name(locker_name) :
# Open database connection
db = pymysql.connect("localhost","pi","1234","serverlocker" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql_select_name = "select Name_Locker from locker_name where DLK_Name_Locker = '%s' " %(locker_name)
cursor.execute(sql_select_name)
select_Locker = cursor.fetchone()
return select_Locker[0]
db.close()
#res = search_data.location_name(1)
res = locker_name(1)
print(res)
|
C++
|
UTF-8
| 801 | 2.75 | 3 |
[] |
no_license
|
// If n=6, then the pattern should be like this :
// 666666
// 655556
// 654456
// 654456
// 655556
// 666666
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int num=n;
int size=n;
int arr[n][n]={0};
for(int i=0;i<n;i++){
int a=i,b=i;
while(b<size){
arr[a][b]=num;
b++;
}
b--;
while(a<size){
arr[a][b]=num;
a++;
}
a--;
while(b>=i){
arr[a][b]=num;
b--;
}
b++;
while(a>=i){
arr[a][b]=num;
a--;
}
num--;
size--;
}
for(int i=0;i<n;i++,cout<<endl){
for(int j=0;j<n;j++){
cout<<arr[i][j];
}
}
return 0;
}
|
Java
|
UTF-8
| 2,449 | 2.59375 | 3 |
[] |
no_license
|
package search.model;
import com.google.common.base.MoreObjects;
import java.time.LocalDateTime;
import java.util.Objects;
public class UserClickEvent {
private String id;
private String sessionId;
private String country;
private String browser;
private String url;
private LocalDateTime date;
public UserClickEvent() {
}
public UserClickEvent(String id, String sessionId, String country,
String browser, String url, LocalDateTime date) {
this.id = id;
this.sessionId = sessionId;
this.country = country;
this.browser = browser;
this.url = url;
this.date = date;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getBrowser() {
return browser;
}
public void setBrowser(String browserName) {
this.browser = browserName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public LocalDateTime getDate() {
return date;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("sessionId", sessionId)
.add("country", country)
.add("browser", browser)
.add("url", url)
.add("date", date)
.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserClickEvent that = (UserClickEvent) o;
return Objects.equals(sessionId, that.sessionId) &&
Objects.equals(country, that.country) &&
browser == that.browser &&
Objects.equals(url, that.url) &&
Objects.equals(date, that.date);
}
@Override
public int hashCode() {
return Objects.hash(sessionId, country, browser, url, date);
}
}
|
Python
|
UTF-8
| 13,127 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
# Copyright (C) 2015 Richard Klees <richard.klees@rwth-aachen.de>
from .core import StreamProcessor, Stop, MayResume, Exhausted, subprocess
from .types import Type
###############################################################################
#
# Some classes that simplify the usage of StreamProcessor
#
###############################################################################
class Producer(StreamProcessor):
"""
A producer is the source for a stream, that is, it produces new data for
the downstream without an upstream and creates no result.
"""
def __init__(self, type_init, type_out):
super(Producer, self).__init__(type_init, (), (), type_out)
def step(self, env, stream):
return self.produce(env, stream.send)
def produce(self, env, send):
"""
Generate new data to be send downstream.
The data must have the type declared with type_out.
"""
raise NotImplementedError("Producer::produce: implement "
"me for class %s!" % type(self))
class Consumer(StreamProcessor):
"""
A consumer is the sink for a stream, that is it consumes data from upstream
without producing new values. It also returns a result.
"""
def __init__(self, type_init, type_result, type_in):
super(Consumer, self).__init__(type_init, type_result, type_in, ())
def step(self, env, stream):
return self.consume(env, stream.await, stream.result)
def consume(self, env, await, result):
"""
Consume data from upstream.
Consume must be able to process values with types according to type_in.
Could return a result.
"""
raise NotImplementedError("Consumer::consume: implement "
"me for class %s!" % type(self))
class Pipe(StreamProcessor):
"""
A pipe is an element between a source and a sink, that is it consumes data
from upstream an produces new data for downstream. It does not produce a
result.
"""
def __init__(self, type_init, type_in, type_out):
super(Pipe, self).__init__(type_init, (), type_in, type_out)
def step(self, env, stream):
return self.transform(env, stream.await, stream.send)
def transform(self, env, await, send):
"""
Take data from upstream and generate data for downstream. Must adhere to
the types from type_in and type_out.
"""
raise NotImplementedError("Pipe::transform: implement "
"me for class %s!" % type(self))
###############################################################################
#
# Some processors to perform simple and common tasks.
#
###############################################################################
class _NoValue(object):
"""
None could be some value, so we need something else to mark a non value.
"""
pass
class ConstProducer(Producer):
"""
A const producer sends a custom value downstream infinitely.
The value to be produced could either be given to the constructor
or set via setup.
"""
def __init__(self, value = _NoValue, value_type = _NoValue, amount = _NoValue):
"""
Either pass a value for the const value to be produced or
a type of the value if the value should be set via setup.
"""
if value is _NoValue and value_type is _NoValue:
raise TypeError("Either pass value or value_type.")
self.value = value
self.amount = amount
if value is not _NoValue:
super(ConstProducer, self).__init__((), type(value))
else:
super(ConstProducer, self).__init__(value_type, value_type)
def setup(self, params, result):
super(ConstProducer, self).setup(params, result)
if self.value is not _NoValue:
return [self.value, 0]
return [params[0], 0]
def produce(self, env, send):
if self.amount != _NoValue:
if env[1] == self.amount:
return Stop
env[1] += 1
send(env[0])
return MayResume
def const(value = _NoValue, value_type = _NoValue, amount = _NoValue):
"""
A const producer sends a custom value downstream infinitely.
The value to be produced could either be given to the constructor
or set via setup.
"""
return ConstProducer(value, value_type, amount)
class ListProducer(Producer):
"""
The ListProducerroducer sends the values from a list downstream.
The list could either be given to the constructor or setup.
"""
def __init__(self, vlist = _NoValue, item_type = _NoValue):
"""
Pass a list of values as vlist or the type of items the list should
contain, if the list of values should be given to setup.
Throws, when vlist contains values of different types.
Makes a copy of the supplied list.
"""
if vlist is _NoValue and item_type is _NoValue:
raise TypeError("Either pass value or item_type.")
if vlist is _NoValue:
self.vlist = vlist
self.item_type = Type.get(item_type)
super(ListProducer, self).__init__([item_type], item_type)
else:
if len(vlist) == 0:
raise ValueError("vlist is empty list.")
item_type = Type.infer(vlist[0])
if not Type.get([item_type]).contains(vlist):
raise TypeError("Expected list with items of type '%s'only." % item_type)
self.vlist = list(vlist)
super(ListProducer, self).__init__((), item_type)
def setup(self, params, result):
super(ListProducer, self).setup(params, result)
if self.vlist is not _NoValue:
vlist = self.vlist
else:
vlist = list(params[0])
return { "index" : 0, "list" : vlist, "len" : len(vlist) }
def produce(self, env, send):
# Take special care of empty lists, since our downstream
# could not possibly know were already out of values.
if env["len"] == 0 and env["index"] == 0:
env["index"] += 1
return Stop
if env["index"] >= env["len"]:
raise Exhausted
send(env["list"][env["index"]])
env["index"] += 1
if env["index"] == env["len"]:
return Stop
return MayResume
def from_list(vlist = _NoValue, item_type = _NoValue):
"""
A producer that sends the values from a list downstream.
The list could either be given to the constructor or on initialisation.
"""
return ListProducer(vlist, item_type)
class ListConsumer(Consumer):
"""
Puts consumed values to a list.
Either appends to the list given in the constructor or creates a fresh list
in setup.
"""
def __init__(self, append_to = None, max_amount = None):
tvar = Type.get()
self.append_to = append_to
self.max_amount = max_amount
if append_to is None:
super(ListConsumer, self).__init__((), [tvar], tvar)
else:
super(ListConsumer, self).__init__((), (), tvar)
def setup(self, params, result):
super(ListConsumer, self).setup(params, result)
if self.append_to is None:
assert self.type_result() != ()
res = []
result(res)
return res
return None
def consume(self, env, await, result):
if self.append_to is None:
env.append(await())
result(env)
if self.max_amount is not None and len(env) >= self.max_amount:
return Stop
return MayResume
if self.max_amount is not None and len(self.append_to) >= self.max_amount:
return Stop
self.append_to.append(await())
return MayResume
def to_list(append_to = None, max_amount = None):
"""
Put consumed values to a list.
Appends to an exisiting list if append_to is used. Creates a fresh
list and returns in as result otherwise.
"""
return ListConsumer(append_to, max_amount)
class LambdaPipe(Pipe):
"""
A pipe that processes each piece of data with a lambda.
"""
def __init__(self, type_in, type_out, _lambda):
super(LambdaPipe, self).__init__((), type_in, type_out)
self._lambda = _lambda
def transform(self, env, await, send):
self._lambda(await, send)
return MayResume
def pipe(type_in, type_out, _lambda = None):
"""
Decorate a function to become a pipe that works via await and send and
resumes infinitely.
"""
if _lambda is None:
def decorator(fun):
return LambdaPipe(type_in, type_out, fun)
return decorator
return LambdaPipe(type_in, type_out, _lambda)
def transformation(type_in, type_out, _lambda = None):
"""
Decorate a function to be a pipe.
"""
if _lambda is None:
def decorator(fun):
l = lambda await, send: send(fun(await()))
return LambdaPipe(type_in, type_out, l)
return decorator
return LambdaPipe(type_in, type_out, _lambda)
class FilterPipe(Pipe):
"""
A pipe that only lets data pass that matches a predicate.
"""
max_tries_per_step = 10
def __init__(self, type_init, type_io):
super(FilterPipe, self).__init__(type_init, type_io, type_io)
def transform(self, env, await, send):
for _ in range(0, self.max_tries_per_step):
val = await()
if self.predicate(env, val):
send(val)
return MayResume
return MayResume
def predicate(self, env, val):
"""
Check whether the value is ok. Return bool.
"""
raise NotImplementedError("FilterPipe::predicate: implement "
"me for class %s!" % type(self))
class LambdaFilterPipe(FilterPipe):
"""
A filter whos predicate is a lambda.
"""
def __init__(self, type_io, _lambda):
super(LambdaFilterPipe, self).__init__((), type_io)
self._lambda = _lambda
def predicate(self, env, val):
return self._lambda(val)
def pass_if(type_io, _lambda = None):
"""
Decorate a predicate and get a pipe that only lets values
through when the predicate matches.
"""
if _lambda is None:
def decorator(fun):
return LambdaFilterPipe(type_io, fun)
return decorator
return LambdaFilterPipe(type_io, _lambda)
def tee():
"""
Distributes an input over to a tuple: a -> (a,a).
"""
_any = Type.get()
@transformation(_any, (_any, _any))
def tee(v):
return v,v
return tee
def nop():
"""
Does nothing with the data: a -> a
"""
_any = Type.get()
@transformation(_any, _any)
def nop(v):
return v
return nop
def maps(a_pipe):
"""
Maps a pipe over lists from upstream and sends the resulting list
downstream: maps(a -> b) is of type [a] -> [b].
The pipe is initialized once per list and produces one result per list,
which are collected in a result list.
"""
if a_pipe.type_in() == () or a_pipe.type_out() == ():
raise TypeError("Expected pipe as argument.")
tinit = a_pipe.type_init()
tin = a_pipe.type_in()
# Subprocess takes inits from upstream and sends
# results downstream.
mapper = subprocess( from_list(item_type = tin) >>
a_pipe >>
to_list())
# If pipe has an init type that means we have to provide
# it it with a value, which itself should be given as init
# value but is constant over all subprocesses of maps.
# As the pipe comes second in the subprocess this is were
# the init value needs to go too.
if a_pipe.type_init() != ():
mapper = nop() * const(value_type = tinit) >> mapper
# Same for result, but in this case the result of the pipe
# comes first.
if a_pipe.type_result() != ():
mapper = mapper >> to_list() * nop()
return mapper
# Maybe to be reused for generator style producers
#
#class EnvAndGen(object):
# def __init__(self, env, gen):
# self.env = env
# self.gen = gen
#
# def step(self, env, await, send):
# if not isinstance(env, EnvAndGen):
# env = EnvAndGen(env, self.produce(env))
#
# send(next(env.gen))
# return MayResume(())
#
#
# ... and consumers
# def step(self, env, await, send):
# def _upstream():
# while True:
# val = await()
# yield val
#
# return self.consume(env, _upstream())
#
# ... and pipes
# def step(self, env, await, send):
# if not isinstance(env, EnvAndGen):
# def _upstream():
# while True:
# val = await()
# yield val
#
# env = EnvAndGen(env, self.transform(env, _upstream()))
#
# send(next(env.gen))
# return MayResume(())
|
Python
|
UTF-8
| 1,608 | 3.578125 | 4 |
[] |
no_license
|
from functools import partial
class Bowling:
def __init__(self):
pass
def frame_to_score(frame, first_bonus_points=0, second_bonus_points=0):
if len(frame) == 1:
# strike
if frame == "X":
score = 10
if len(frame == 2):
# both misses
if frame[0] == "-" and frame[1] == "-":
score = 0
# first numeric pins, second miss
if frame[0].isdigit() and frame[1] == "-":
score = int(frame[0])
# two numeric pins
if frame[0].isdigit() and frame[1].isdigit():
score = int(frame[0]) + int(frame[1])
# first numeric pins, second spare
if frame[0].isdigit() and frame[1] == "/":
score = 10
return score + first_bonus_points() + second_bonus_points()
def frame_to_partially_apply_indexes(frame):
if frame.contains("X"):
return 2 # next 2 frames partially apply
if frame.contains("/"):
return 1 # next 1 frame partially apply
def solve(self, input) -> int:
tokens = input.split(' ')
score_frame_partials = []
partial_applications = {} # maps index to how many next frames to apply
for idx, token in enumerate(tokens):
score_frame_partials.append(partial(frame_to_score, token))
partially_apply_frames = frame_to_partially_apply_indexes(token)
if partially_apply_frames != None:
partial_applications[idx] = partially_apply_frames
return -1
|
Python
|
UTF-8
| 194 | 4.09375 | 4 |
[] |
no_license
|
#check if number is positve, negative or zero
num=int(input("enter number: "))
if num >= 1:
print("positive number")
elif num < 0:
print("negative number")
else:
print("zero")
|
Java
|
UTF-8
| 15,311 | 1.84375 | 2 |
[] |
no_license
|
/**
* Copyright (C) 2011 Morgan Humes <morgan@lanaddict.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
package net.milkbowl.vault;
import java.util.Collection;
import java.util.logging.Logger;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.plugins.Economy_3co;
import net.milkbowl.vault.economy.plugins.Economy_BOSE6;
import net.milkbowl.vault.economy.plugins.Economy_BOSE7;
import net.milkbowl.vault.economy.plugins.Economy_Essentials;
import net.milkbowl.vault.economy.plugins.Economy_MultiCurrency;
import net.milkbowl.vault.economy.plugins.Economy_iConomy4;
import net.milkbowl.vault.economy.plugins.Economy_iConomy5;
import net.milkbowl.vault.economy.plugins.Economy_iConomy6;
import net.milkbowl.vault.permission.Permission;
import net.milkbowl.vault.permission.plugins.Permission_GroupManager;
import net.milkbowl.vault.permission.plugins.Permission_Permissions2;
import net.milkbowl.vault.permission.plugins.Permission_Permissions3;
import net.milkbowl.vault.permission.plugins.Permission_PermissionsBukkit;
import net.milkbowl.vault.permission.plugins.Permission_PermissionsEx;
import net.milkbowl.vault.permission.plugins.Permission_SuperPerms;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;
public class Vault extends JavaPlugin {
private static final Logger log = Logger.getLogger("Minecraft");
@Override
public void onDisable() {
// Remove all Service Registrations
getServer().getServicesManager().unregisterAll(this);
log.info(String.format("[%s] Disabled Version %s", getDescription().getName(), getDescription().getVersion()));
}
@Override
public void onEnable() {
// Load Vault Addons
loadEconomy();
loadPermission();
getCommand("vault-info").setExecutor(this);
getCommand("vault-reload").setExecutor(this);
log.info(String.format("[%s] Enabled Version %s", getDescription().getName(), getDescription().getVersion()));
}
/**
* Attempts to load Economy Addons
*/
private void loadEconomy() {
// Try to load MultiCurrency
if (packageExists(new String[] { "me.ashtheking.currency.Currency", "me.ashtheking.currency.CurrencyList" })) {
Economy econ = new Economy_MultiCurrency(this);
getServer().getServicesManager().register(net.milkbowl.vault.economy.Economy.class, econ, this, ServicePriority.Normal);
log.info(String.format("[%s][Economy] MultiCurrency found: %s", getDescription().getName(), econ.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Economy] MultiCurrency not found.", getDescription().getName()));
}
// Try to load 3co
if (packageExists(new String[] { "me.ic3d.eco.ECO" })) {
Economy econ = new Economy_3co(this);
getServer().getServicesManager().register(net.milkbowl.vault.economy.Economy.class, econ, this, ServicePriority.Normal);
log.info(String.format("[%s][Economy] 3co found: %s", getDescription().getName(), econ.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Economy] 3co not found.", getDescription().getName()));
}
// Try to load BOSEconomy
if (packageExists(new String[] { "cosine.boseconomy.BOSEconomy", "cosine.boseconomy.CommandManager" })) {
Economy bose6 = new Economy_BOSE6(this);
getServer().getServicesManager().register(net.milkbowl.vault.economy.Economy.class, bose6, this, ServicePriority.Normal);
log.info(String.format("[%s][Economy] BOSEconomy6 found: %s", getDescription().getName(), bose6.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Economy] BOSEconomy6 not found.", getDescription().getName()));
}
// Try to load BOSEconomy
if (packageExists(new String[] { "cosine.boseconomy.BOSEconomy", "cosine.boseconomy.CommandHandler" })) {
Economy bose7 = new Economy_BOSE7(this);
getServer().getServicesManager().register(net.milkbowl.vault.economy.Economy.class, bose7, this, ServicePriority.Normal);
log.info(String.format("[%s][Economy] BOSEconomy7 found: %s", getDescription().getName(), bose7.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Economy] BOSEconomy7 not found.", getDescription().getName()));
}
// Try to load Essentials Economy
if (packageExists(new String[] { "com.earth2me.essentials.api.Economy", "com.earth2me.essentials.api.NoLoanPermittedException", "com.earth2me.essentials.api.UserDoesNotExistException" })) {
Economy essentials = new Economy_Essentials(this);
getServer().getServicesManager().register(net.milkbowl.vault.economy.Economy.class, essentials, this, ServicePriority.Low);
log.info(String.format("[%s][Economy] Essentials Economy found: %s", getDescription().getName(), essentials.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Economy] Essentials Economy not found.", getDescription().getName()));
}
// Try to load iConomy 4
if (packageExists(new String[] { "com.nijiko.coelho.iConomy.iConomy", "com.nijiko.coelho.iConomy.system.Account" })) {
Economy icon4 = new Economy_iConomy4(this);
getServer().getServicesManager().register(net.milkbowl.vault.economy.Economy.class, icon4, this, ServicePriority.High);
log.info(String.format("[%s][Economy] iConomy 4 found: ", getDescription().getName(), icon4.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Economy] iConomy 4 not found.", getDescription().getName()));
}
// Try to load iConomy 5
if (packageExists(new String[] { "com.iConomy.iConomy", "com.iConomy.system.Account", "com.iConomy.system.Holdings" })) {
Economy icon5 = new Economy_iConomy5(this);
getServer().getServicesManager().register(net.milkbowl.vault.economy.Economy.class, icon5, this, ServicePriority.High);
log.info(String.format("[%s][Economy] iConomy 5 found: %s", getDescription().getName(), icon5.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Economy] iConomy 5 not found.", getDescription().getName()));
}
// Try to load iConomy 6
if (packageExists(new String[] { "com.iCo6.iConomy" })) {
Economy icon6 = new Economy_iConomy6(this);
getServer().getServicesManager().register(net.milkbowl.vault.economy.Economy.class, icon6, this, ServicePriority.High);
log.info(String.format("[%s][Economy] iConomy 6 found: %s", getDescription().getName(), icon6.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Economy] iConomy 6 not found.", getDescription().getName()));
}
}
/**
* Attempts to load Permission Addons
*/
private void loadPermission() {
// Try to load PermissionsEx
if (packageExists(new String[] { "ru.tehkode.permissions.bukkit.PermissionsEx" })) {
Permission ePerms = new Permission_PermissionsEx(this);
getServer().getServicesManager().register(net.milkbowl.vault.permission.Permission.class, ePerms, this, ServicePriority.Highest);
log.info(String.format("[%s][Permission] PermissionsEx found: %s", getDescription().getName(), ePerms.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Permission] PermissionsEx not found.", getDescription().getName()));
}
//Try loading PermissionsBukkit
if (packageExists(new String[] {"com.platymuus.bukkit.permissions.PermissionsPlugin"} )) {
Permission pPerms = new Permission_PermissionsBukkit(this);
getServer().getServicesManager().register(net.milkbowl.vault.permission.Permission.class, pPerms, this, ServicePriority.Highest);
log.info(String.format("[%s][Permission] PermissionsBukkit found: %s", getDescription().getName(), pPerms.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Permission] PermissionsBukkit not found.", getDescription().getName()));
}
// Try to load GroupManager
if (packageExists(new String[] { "org.anjocaido.groupmanager.GroupManager" })) {
Permission gPerms = new Permission_GroupManager(this);
getServer().getServicesManager().register(net.milkbowl.vault.permission.Permission.class, gPerms, this, ServicePriority.High);
log.info(String.format("[%s][Permission] GroupManager found: %s", getDescription().getName(), gPerms.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Permission] GroupManager not found.", getDescription().getName()));
}
// Try to load Permissions 3 (Yeti)
if (packageExists(new String[] { "com.nijiko.permissions.ModularControl" })) {
Permission nPerms = new Permission_Permissions3(this);
getServer().getServicesManager().register(net.milkbowl.vault.permission.Permission.class, nPerms, this, ServicePriority.High);
log.info(String.format("[%s][Permission] Permissions 3 (Yeti) found: %s", getDescription().getName(), nPerms.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Permission] Permissions 3 (Yeti) not found.", getDescription().getName()));
}
// Try to load Permissions 2 (Phoenix)
if (packageExists(new String[] { "com.nijiko.permissions.Control" })) {
Permission oPerms = new Permission_Permissions2(this);
getServer().getServicesManager().register(net.milkbowl.vault.permission.Permission.class, oPerms, this, ServicePriority.Low);
log.info(String.format("[%s][Permission] Permissions 2 (Phoenix) found: %s", getDescription().getName(), oPerms.isEnabled() ? "Loaded" : "Waiting"));
} else {
log.info(String.format("[%s][Permission] Permissions 2 (Phoenix) not found.", getDescription().getName()));
}
Permission perms = new Permission_SuperPerms(this);
getServer().getServicesManager().register(net.milkbowl.vault.permission.Permission.class, perms, this, ServicePriority.Lowest);
log.info(String.format("[%s][Permission] SuperPermissions loaded as backup permission system.", getDescription().getName()));
}
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if (sender instanceof Player) {
// Check if Player
// If so, ignore command if player is not Op
Player p = (Player) sender;
if (!p.isOp()) {
return true;
}
} else if (!(sender instanceof ConsoleCommandSender)) {
// Check if NOT console
// Ignore it if not originated from Console!
return true;
}
if (command.getLabel().equals("vault-info")) {
// Get String of Registered Economy Services
String registeredEcons = null;
Collection<RegisteredServiceProvider<Economy>> econs = this.getServer().getServicesManager().getRegistrations(net.milkbowl.vault.economy.Economy.class);
for (RegisteredServiceProvider<Economy> econ : econs) {
Economy e = econ.getProvider();
if (registeredEcons == null) {
registeredEcons = e.getName();
} else {
registeredEcons += ", " + e.getName();
}
}
// Get String of Registered Permission Services
String registeredPerms = null;
Collection<RegisteredServiceProvider<Permission>> perms = this.getServer().getServicesManager().getRegistrations(net.milkbowl.vault.permission.Permission.class);
for (RegisteredServiceProvider<Permission> perm : perms) {
Permission p = perm.getProvider();
if (registeredPerms == null) {
registeredPerms = p.getName();
} else {
registeredPerms += ", " + p.getName();
}
}
// Get Economy & Permission primary Services
Economy econ = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class).getProvider();
Permission perm = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class).getProvider();
// Send user some info!
sender.sendMessage(String.format("[%s] Vault v%s Information", getDescription().getName(), getDescription().getVersion()));
sender.sendMessage(String.format("[%s] Economy: %s [%s]", getDescription().getName(), econ.getName(), registeredEcons));
sender.sendMessage(String.format("[%s] Permission: %s [%s]", getDescription().getName(), perm.getName(), registeredPerms));
return true;
} else {
// Show help
sender.sendMessage("Vault Commands:");
sender.sendMessage(" /vault-info - Displays information about Vault");
return true;
}
}
/**
* Determines if all packages in a String array are within the Classpath
* This is the best way to determine if a specific plugin exists and will be
* loaded. If the plugin package isn't loaded, we shouldn't bother waiting
* for it!
* @param packages String Array of package names to check
* @return Success or Failure
*/
private static boolean packageExists(String[] packages) {
try {
for (String pkg : packages) {
Class.forName(pkg);
}
return true;
} catch (Exception e) {
return false;
}
}
}
|
Python
|
UTF-8
| 976 | 3.296875 | 3 |
[] |
no_license
|
# zero.安装框架 pip install requests
import requests
import re
# first.确定URL(网址,统一资源定位符) URL是自己起的名字
url = 'http://www.doutula.com/photo/list/'
# second.请求(使用这个框架(requests),里面的get(网络请求方法,去网址(URL)里面拿数据)
text_string = requests.get(url).text
print(text_string)
# third.筛选数据(使用正则表达式)
image_urls = re.findall('data-original="(.*?)"', text_string) # data-original="(.*?)" ?为贪恋符号,语句可以筛选本URL中的全部特定内容
for image_url in image_urls:
image_name = image_url.split('/')[-1]
print(image_name)
# ['this.src='http:','','img.doutula.com','production','uploads','image','2019','06','07','20190607864141_oKJUcr.jpg']
# 下载内容
image = requests.get(image_url).content
# fourth.保存数据
with open('./Crawler_images/%s' % image_name, 'wb') as file:
file.write(image)
|
JavaScript
|
UTF-8
| 1,505 | 2.515625 | 3 |
[] |
no_license
|
import { Line, Html } from "@react-three/drei"
import styled from "styled-components"
const StyledNumAxis = styled.span`
/* display: none; */
opacity: 1;
font-family: "Roboto";
font-weight: 400;
font-size: ${(props) => (props.colored ? "1.2rem" : "1rem")};
color: ${(props) => (props.colored ? "#437ef1" : "white")};
`
const MyLine = (props) => {
return (
<Line name="axis" points={props.points} color="white" lineWidth={2} />
)
}
let nums = [-1, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1]
let multiFactor = 1
const Dots = () => {
return nums.map((item, index) => (
<>
<MyLine
points={[
[item * multiFactor, 0.025, 0],
[item * multiFactor, -0.025, 0],
]}
/>
{item ? (
<Html
center={true}
position={[item * multiFactor, -0.2, 0]}
distanceFactor={2}>
<StyledNumAxis>{item}</StyledNumAxis>
</Html>
) : null}
<MyLine
points={[
[0.025, item * multiFactor, 0],
[-0.025, item * multiFactor, 0],
]}
/>
{item ? (
<Html
center={true}
position={[-0.2, item * multiFactor, 0]}
distanceFactor={2}>
<StyledNumAxis>{item}</StyledNumAxis>
</Html>
) : null}
</>
))
}
const Axis = () => {
return (
<>
<Dots />
{/* <MyLine
points={[
[-2, 0.025, 0],
[-2, -0.025, 0],
]}
/> */}
<MyLine
points={[
[1, 0, 0],
[-1, 0, 0],
]}
/>
<MyLine
points={[
[0, 1, 0],
[0, -1, 0],
]}
/>
</>
)
}
export default Axis
|
PHP
|
UTF-8
| 459 | 3.046875 | 3 |
[] |
no_license
|
<?php
namespace App\Game\Models;
class Franchise extends GameModel
{
/** @var string */
private $name;
public static function parse(array $attributes): self
{
$franchise = new self();
$franchise->parseAttributes($attributes);
return $franchise;
}
public function getName()
{
return $this->name;
}
public function setName(string $name): void
{
$this->name = $name;
}
}
|
C#
|
UTF-8
| 1,209 | 3.125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using handlelisteApp.Context;
using handlelisteApp.Models;
using System.Linq;
namespace handlelisteApp.Data
{
public class ItemRepository : IItemRepository
{
private readonly ShoppingListContext _context;
public ItemRepository(ShoppingListContext context)
{
_context = context;
}
public void AddItem(Item item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
_context.Items.Add(item);
}
public void AddItems(List<Item> items)
{
_context.Items.AddRange(items);
}
public Item FindByItemName(string itemName)
{
return _context.Items.Where(i => i.ItemName == itemName).FirstOrDefault();
}
public void DeleteItem(Item item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
_context.Items.Remove(item);
}
public bool SaveChanges()
{
return _context.SaveChanges() > 0;
}
}
}
|
Java
|
UTF-8
| 184 | 2.359375 | 2 |
[] |
no_license
|
package br.com.exemplo.secao22;
public interface Teste {
int valor = 9;
public String menssagem();
default void meu_metodo() {
System.out.println("Default method...");
}
}
|
Java
|
UTF-8
| 685 | 3.84375 | 4 |
[] |
no_license
|
package CollectionAssignment;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//Write a Java program to reverse elements in a array list.
public class ReverseElementInArrayList {
public static void main(String[] args) {
// Create a list and add some colors to the list
List<String> list_Strings = new ArrayList<String>();
list_Strings.add("A");
list_Strings.add("B");
list_Strings.add("C");
list_Strings.add("D");
list_Strings.add("E");
System.out.println("List before reversing :\n" + list_Strings);
Collections.reverse(list_Strings);
System.out.println("List after reversing :\n" + list_Strings);
}
}
|
PHP
|
UTF-8
| 2,469 | 2.671875 | 3 |
[] |
no_license
|
<?php
namespace App\Http\Livewire;
use App\Models\Education;
use Carbon\Carbon;
use Livewire\Component;
use Livewire\WithPagination;
class Educations extends Component
{
use WithPagination;
public $rowID;
public $specialty;
public $university;
public $interval;
// Exist Ruses
protected $rules = [
'specialty' => 'required|max:50',
'university' => 'required|max:50',
'interval' => 'required|max:12',
];
//realtime validation
public function updated($propertyName)
{
$this->validateOnly($propertyName);
}
// to reset inputs
public function resetInputFields()
{
$this->specialty = '';
$this->university = '';
$this->interval = '';
}
// Education Add
public function educationAdd()
{
$this->validate();
Education::create(
[
'specialty' => $this->specialty,
'university' => $this->university,
'interval' => $this->interval,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]
);
$this->dispatchBrowserEvent('closeAddModal',['type' => 'success', 'title'=> 'Adding','message' => 'finished successfully']);
$this->resetInputFields();
}
// Education Remove
public function remove($id)
{
Education::destroy($id);
$this->resetPage();
}
public function read($id)
{
$this->rowID = $id;
$edu = Education::find($id);
$this->specialty = $edu->specialty;
$this->university = $edu->university;
$this->interval = $edu->interval;
}
public function educationUpdate()
{
Education::whereId($this->rowID)
->update([
'specialty' =>$this->specialty,
'university'=>$this->university,
'interval' =>$this->interval,
]);
$this->dispatchBrowserEvent('educationUpdate', ['type' => 'success', 'title'=> 'Updating','message' => 'finished successfully']);
$this->resetInputFields();
}
public function render()
{
return view('livewire.educations',[
'educations'=>Education::orderBy('id','desc')
->paginate(2)
->onEachSide(0)
]);
}
}
|
Java
|
UTF-8
| 9,266 | 1.664063 | 2 |
[] |
no_license
|
package Qlytics.Pages;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import QlyticsAutomation.Qlytics.AppLibrary;
public class SignUpPage {
WebDriver driver;
public static String firstNameInput = "xpath://input[@id='firstName']";
public static String lastNameInput = "xpath://input[@id='lastName']";
public static String emailInput = "xpath://input[@id='email']";
public static String passwordInput = "xpath://input[@id='password']";
public static String cnfPasswordInput = "xpath://input[@id='confirmPassword']";
public static String phoneNumberInput = "xpath://input[@id='phoneNumber']";
public static String companyNameInput = "xpath://input[@id='companyName']";
public static String jobTitleInput = "xpath://input[@id='jobTitle']";
public static String registerButton = "xpath://button[@class='ant-btn ant-btn-primary']";
public static String loginLink = "xpath://a[text()='Login']";
// Login page
public static String EmailAddressInput = "xpath://input[@placeholder='Email Address']";
public static String LoginpasswordInput = "xpath://input[@placeholder='Password']";
public static String LoginButton = "xpath://button[@class='ant-btn ant-btn-primary ant-btn-block']";
public static String signUpLink = "xpath://a[text()='Sign up']";
// Verification Message
public static String VerificationMessage = "xpath://span[text()='Verification e-mail sent.']";
// Logout
public static String profileButton = "xpath://ul[@class='action-menu ml-10 ant-menu ant-menu-root ant-menu-dark ant-menu-horizontal ng-star-inserted']";
public static String logoutButton = "xpath://*[contains(text(),'Logout')]";
// forgot password
public static String forgotLink = "xpath://a[text()='Forgot password']";
/// Data marketplace
public static String datamraketButton = "xpath://li[contains(text(),'Data Marketplace')]";
public static String dataBaseList = "xpath://div[div[p[text()='Datasets']]]//*[contains(text(),'More')]";
public static String selectDataSet = "xpath:(//div[div[p[text()='Datasets']]]//*[contains(text(),'More')])[Replace]";
public static String DataSetView = "xpath://div[div[h4[text()='ABOUT THIS DATABASE']]]//button[span[contains(text(),'VIEW')]]";
public static String verifyDatasetPage = "xpath://h5[contains(text(),'- Datasets')]";
public static String DataSetViewButton = "xpath://div[h5[contains(text(),'- Datasets')]]//button";
public static String DataSetSelectViewButton = "xpath:(//div[h5[contains(text(),'- Datasets')]]//button)[Replace]";
public static String dataRecordsLabel = "xpath://div[contains(text(),'Dataset records')]";
//TalentHub
public static String talentHuBButton = "xpath://li[contains(text(),'Talent Hub')]";
public static String SearchTextBox = "xpath://input[@placeholder='Machine learning...']";
public static String SearchButton = "xpath://button[@class='btn btn-primary ant-btn ant-btn-primary']";
public static String morebutton = "xpath://*[contains(text(),'More')]";
/// Resource
public static String projectButton = "xpath://li[contains(text(),'Projects')]";
public static String resourceButton = "xpath://div[span[span[text()='Resources']]]";
public static String computeText = "xpath://li[contains(text(),'Compute')]";
public static String createInstanceButton = "xpath://button[@class='ant-btn ant-btn-primary ng-star-inserted']";
public static String nameTextbox = "xpath://input[@placeholder='please enter a name']";
public static String Typedropdown = "xpath://div[nz-form-item//label[contains(text(),'Type *')]]//input";
public static String keypairAddButton = "xpath://button[@class='mt-40 ant-btn ant-btn-default ant-btn-circle ant-btn-icon-only']";
public static String createleynameButton = "xpath://input[@placeholder='please enter key pair name']";
public static String createButton = "xpath://div[@class='ant-drawer-body']//button";
public static String keypairdropdown = "xpath://div[nz-form-item//label[contains(text(),'Key Pair *')]]//input";
public static String qlytivsFunctionlaContainer = "xpath://div[nz-form-item//label[contains(text(),'Qlytics Functional Container *')]]//input";
public static String qlyticscontainerList = "xpath://ul[@class='ant-select-dropdown-menu ant-select-dropdown-menu-root ant-select-dropdown-menu-vertical']//li";
public static String qlyticscontainerListselect = "xpath:(//ul[@class='ant-select-dropdown-menu ant-select-dropdown-menu-root ant-select-dropdown-menu-vertical']//li)[Replace]";
public static String createButton2 = "xpath://div[div[@class='ant-col-24']]//button";
public static String ActionThreeDot = "xpath://button[@class='ant-dropdown-trigger ant-btn ant-btn-primary ant-btn-icon-only']";
public static String stopButton = "xpath://li[contains(text(),'Stop')]";
public static String typeSelect = "xpath://ul[@role='menu']//li[contains(text(),Replace)]";
public static String keySelect = "xpath://ul[@class='ant-select-dropdown-menu ant-select-dropdown-menu-root ant-select-dropdown-menu-vertical']//li[contains(text(),Replace)]";
public SignUpPage(WebDriver driver) {
super();
this.driver = driver;
}
public void registration(String firstName, String lastName, String email, String pass, String CnfPass,
String PhoneNo, String CompanyName, String jobTitle) {
AppLibrary.enterText(driver, firstNameInput, firstName);
AppLibrary.enterText(driver, lastNameInput, lastName);
AppLibrary.enterText(driver, emailInput, email);
AppLibrary.enterText(driver, passwordInput, pass);
AppLibrary.enterText(driver, cnfPasswordInput, CnfPass);
AppLibrary.enterText(driver, phoneNumberInput, PhoneNo);
AppLibrary.enterText(driver, companyNameInput, CompanyName);
AppLibrary.enterText(driver, jobTitleInput, jobTitle);
AppLibrary.clickElement(driver, registerButton);
}
public void Login(String emailaddess, String pass) {
AppLibrary.sleep(2000);
AppLibrary.enterText(driver, EmailAddressInput, emailaddess);
AppLibrary.enterText(driver, LoginpasswordInput, pass);
AppLibrary.clickElement(driver, LoginButton);
AppLibrary.sleep(3000);
}
public void Logout() {
AppLibrary.sleep(1000);
AppLibrary.mouseHover(driver, profileButton);
// AppLibrary.clickElement(driver, profileButton);
AppLibrary.clickElement(driver, logoutButton);
}
public void dataMarketPlaceSearch() {
AppLibrary.sleep(1000);
AppLibrary.clickElement(driver, datamraketButton);
AppLibrary.sleep(3000);
List<WebElement> listings = AppLibrary.findElements(driver, dataBaseList);
System.out.println(listings.size());
int size = listings.size();
//
// for (int i = 1; i < size; i++) {
int randnMumber = ThreadLocalRandom.current().nextInt(1, size);
AppLibrary.clickElement(driver, selectDataSet.replace("Replace",""+randnMumber+""));
AppLibrary.sleep(1000);
AppLibrary.clickElement(driver, DataSetView);
AppLibrary.sleep(2000);
AppLibrary.findElement(driver, verifyDatasetPage);
List<WebElement> listings2 = AppLibrary.findElements(driver,DataSetViewButton );
System.out.println(listings2.size());
int size2 = listings2.size();
int randnMumber2 = ThreadLocalRandom.current().nextInt(1, size2);
AppLibrary.sleep(1000);
AppLibrary.clickElement(driver, DataSetSelectViewButton.replace("Replace",""+randnMumber2+""));
AppLibrary.sleep(1000);
AppLibrary.findElement(driver, dataRecordsLabel );
// }
}
public void searchGlobalTalent(String text) {
AppLibrary.clickElement(driver, talentHuBButton);
AppLibrary.clickElement(driver, morebutton);
AppLibrary.enterText(driver, SearchTextBox, text);
AppLibrary.clickElement(driver, SearchButton);
}
public void CreateInstance(String name,String type) {
AppLibrary.clickElement(driver, projectButton);
AppLibrary.sleep(1000);
AppLibrary.clickElement(driver, resourceButton);
AppLibrary.clickElement(driver, computeText);
AppLibrary.sleep(2000);
AppLibrary.clickElement(driver, createInstanceButton);
AppLibrary.enterText(driver, nameTextbox, name);
AppLibrary.enterText(driver, Typedropdown,type );
AppLibrary.clickElement(driver, typeSelect.replace("Replace", type));
AppLibrary.clickElement(driver, keypairAddButton);
AppLibrary.enterText(driver, createleynameButton, name);
AppLibrary.clickElement(driver, createButton);
AppLibrary.enterText(driver, keypairdropdown,type );
AppLibrary.clickElement(driver, keySelect.replace("Replace", name));
AppLibrary.clickElement(driver, qlytivsFunctionlaContainer);
List<WebElement> listings = AppLibrary.findElements(driver,qlyticscontainerList );
System.out.println(listings.size());
int size = listings.size();
int randnMumber = ThreadLocalRandom.current().nextInt(1, size);
AppLibrary.sleep(1000);
AppLibrary.clickElement(driver, qlyticscontainerListselect.replace("Replace",""+randnMumber+""));
AppLibrary.clickElement(driver, createButton2);
AppLibrary.sleep(2000);
AppLibrary.clickElement(driver, ActionThreeDot);
AppLibrary.clickElement(driver, stopButton);
}
}
|
Markdown
|
UTF-8
| 2,040 | 2.703125 | 3 |
[] |
no_license
|
This is a mini-project that is part of my masters program at university of Birmingham. Preech is a sublime Text 2 plugin that adds speech based programming functionality to sublime in order to allow programmers to dictate their code. Preech uses CMU sphinx to perform Speech-To-text. The project is still in pre-alpha state and is not yet usable.
Check out a demo video: http://youtu.be/58OhMEKnHa0
Prerequisites
=============
- Java SE: Java SE 6 Development Kit or better. Go to http://java.sun.com, and select "J2SE" from popular downloads. Download JDK. It needs to be in your PATH variable so that typing "java" in a command line/terminal works.
- Sublime text 2 (http://www.sublimetext.com/2)
How to test it
=================
- download the entire master repository as a .Zip file by clicking on "zip" above.
- Unzip the file and rename the folder to "preech"
- Open your sublime text 2 editor
- Click on preferences > browse packages ...
- copy the folder "preech" (that you just unzipped) into the folder that shows up (the packages folder)
- restart sublime text 2
- click File , you should see the Preech menu there (http://i.imgur.com/piqj3.png)
Starting speech recognition
------------------------------
- it's best to have your command panel open when testing to see the recognized words and any other errors. you can open it by clicking CTRL + ` (that's not a colon it's the key above your TAB key on most keyboards)
- Start a new file. don't call it anything so that sublime's autocomplete doesn't interfere with the speech
- MAKE SURE THE CURSOR IS IN THE FILE , then click on file > Preech > Start Dictation
- A Java command prompt should show up. Just minimize it and selct the file again. Wait a little until the recognizer initializes, then start speaking. What you say should appear in the command panel.
Bugs
--------
There's a problem with "stop dictation". You can't do two consecutive speech dications in the same session. You have to restart sublime text 2 in between. and then start dictation again
|
Python
|
UTF-8
| 1,116 | 3.109375 | 3 |
[] |
no_license
|
"""
problem link : https://www.hackerrank.com/challenges/luck-balance/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=greedy-algorithms
"""
# !/bin/python3
import math
import os
import random
import re
import sys
# Complete the luckBalance function below.
def luckBalance(k, contests):
# 중요하지 않은 대회는 모두 진다
not_importants_sum = sum([c[0] for c in contests if c[1] == 0])
# 중요한 대회 : 제일 큰 k개는 지고, 나머지는 이겨야 한다.
importants = sorted([c for c in contests if c[1] == 1], key=lambda x: -x[0])
lose_sum = sum([c[0] for c in importants[:k]])
win_sum = sum([c[0] for c in importants[k:]])
return not_importants_sum + lose_sum - win_sum
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nk = input().split()
n = int(nk[0])
k = int(nk[1])
contests = []
for _ in range(n):
contests.append(list(map(int, input().rstrip().split())))
result = luckBalance(k, contests)
fptr.write(str(result) + '\n')
fptr.close()
|
SQL
|
UTF-8
| 4,878 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
-- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Mar 04, 2016 at 10:24 AM
-- Server version: 5.6.17
-- PHP Version: 5.5.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `lara`
--
-- --------------------------------------------------------
--
-- Table structure for table `books`
--
CREATE TABLE IF NOT EXISTS `books` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`cat_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`author` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`image` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10 ;
--
-- Dumping data for table `books`
--
INSERT INTO `books` (`id`, `created_at`, `updated_at`, `name`, `cat_id`, `author`, `image`) VALUES
(1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 'sdsdsd', '1', 'test', 'sdsdsd'),
(2, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 'sdsdsd', '2', 'sdsdsdA', 'sdsdsd'),
(3, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 'sdsdsd', '3', 'sdsdsd', 'sdsdsd'),
(5, '2016-02-19 04:45:44', '2016-02-19 04:47:56', 'ajeet', '', 'jaiswal', ''),
(8, '2016-02-19 05:35:26', '2016-02-19 05:35:26', 'ajeet', '', 'author', '');
-- --------------------------------------------------------
--
-- Table structure for table `migrations`
--
CREATE TABLE IF NOT EXISTS `migrations` (
`migration` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `migrations`
--
INSERT INTO `migrations` (`migration`, `batch`) VALUES
('2014_10_12_000000_create_users_table', 1),
('2014_10_12_100000_create_password_resets_table', 1),
('2016_02_11_073016_add_votes_to_users_table', 2),
('2016_02_18_115422_create_books_table', 3),
('2016_02_18_115425_create_books_table', 4);
-- --------------------------------------------------------
--
-- Table structure for table `password_resets`
--
CREATE TABLE IF NOT EXISTS `password_resets` (
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
KEY `password_resets_email_index` (`email`),
KEY `password_resets_token_index` (`token`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`type` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`vote` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=6 ;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `type`, `vote`, `name`, `email`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES
(1, 'R', NULL, 'test', 'a@gmail.com', 'pass@123', 'test', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(2, 'R', NULL, 'ajeet', 'jeet.super@gmail.com', '$2y$10$RDfQ02x1O4bQsbjAgHbNAOm85/j9mnuaBkgKukM5BpNP8FqMoOXoC', '2dxnHnTCd3jFC4Mw8UJ9BfLTSpSqjK0mnl7iAw2CRWe9f1lpPIKqh9Zw5h7s', '2016-02-11 04:21:17', '2016-02-11 04:22:04'),
(3, 'A', NULL, 'ajeet jaiswal', 'jeet.super1@gmail.com', '$2y$10$21.Fr6wogIUYKPkPVcSn7uNSTJVB1IPIUFDE851b9XFebgksJoHWS', 'pBcRVs6CsmmxZ9geyfQvGIQZB7Z56wXCNBetN9QQXFmWlErDzFfoIzMyhcfY', '2016-02-15 02:17:32', '2016-02-22 05:30:57'),
(4, '', NULL, 'ajeet85', 'jeet.super11@gmail.com', '$2y$10$MVXutSGPI2AmLcWG8dqfR.pQFn7imcVzDonKtmAwe53mecib4MkNK', 'iQo3DsSYR8p8UWEDuhWE0D2RTwGs7mCrVbRLLsrRrWxioHDnlqhY2FNqcY0V', '2016-02-22 04:32:10', '2016-02-22 05:40:32'),
(5, '', NULL, 'sds', 'aj@gmail.com', '$2y$10$nBzBt9y9Z3cbYfRF1BGeoucMH3XI0Y.4ZZhsvUl9N0N6/J3xsOuVC', 'nQciTGFkqOJT5OAe9VjMXmT54qK6wjUd15WTEudmgLairW15oWJ1P3FwMO3x', '2016-03-04 01:41:37', '2016-03-04 01:51:11');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java
|
UTF-8
| 162 | 2.34375 | 2 |
[
"MIT"
] |
permissive
|
package org.psjava.ds.numbersystrem;
public interface DivisableNumberSystem<T> extends MultipliableNumberSystem<T> {
T divide(T dividend, T divisor);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.