branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>sophialittlejohn/propulsion_bootcamp<file_sep>/python/week1/day1/day1.py
import re
import itertools
def is_string(string):
return isinstance(string, str)
print(is_string('hello')) # True
print(is_string(['hello'])) # False
print(is_string('this is a long sentence')) # True
print(is_string({'a': 2})) # False
def is_only_string(string):
return type(string) is str and \
" " in string and any(char.isdigit() for char in string)
print(is_only_string('11')) # False
print(is_only_string(['hello'])) # ? Please handle this case!! Should return False
print(is_only_string('this is a long sentence')) # False
print(is_only_string({'a': 2})) # # ? Please handle this case!! Should return False
print(is_only_string("1 2"))
def is_alphanumeric(string):
return is_string(string) and re.match("[0-9a-zA-z]", string) and re.match("[0-9]+", string)
print(is_alphanumeric('11')) # True
print(is_alphanumeric(['hello'])) # False
print(is_alphanumeric('this is a long sentence')) # False
print(is_alphanumeric({'a': 2})) # False
print(is_alphanumeric("this is string....!!!")) # False
def is_array_or_tuple(string):
if isinstance(string, list) or isinstance(string, tuple):
return "is_array_or_tuple is true"
else:
return "is_array_or_tuple is false"
print(is_array_or_tuple('hello')) # False
print(is_array_or_tuple(['hello'])) # True
print(is_array_or_tuple([2, {}, 10])) # True
print(is_array_or_tuple({'a': 2})) # False
print(is_array_or_tuple((1, 2))) #
print(is_array_or_tuple(set()))
def are_same_type(some_input):
first = type(some_input[0])
for element in some_input[1:]:
if not isinstance(element, first):
return False
return True
def are_same_type_alt(some_input):
iseq = iter(some_input)
first = type(next(iseq))
return all((type(x) is first) for x in iseq)
print(are_same_type_alt(['hello', 'world', 'long sentence'])) # True
print(are_same_type_alt([1, 2, 9, 10])) # True
print(are_same_type_alt([1, 2, 9, 10, "hello"])) # False
print(are_same_type([['hello'], 'hello', ['bye']])) # False
print(are_same_type([['hello'], [1, 2, 3], [{'a': 2}]])) # True
print(are_same_type([['hello'], set('hello')])) # False
def longest_string(s1, s2):
if type(s1) is not str or type(s2) is not str:
return False
# testing that inputs are strings containing lowercase a-z
if not re.match("[a-z]", s1) and not re.match("[a-z]", s2):
return False
else:
empty = []
S = s1+s2
for element in S:
if element not in empty:
empty.append(element)
empty = sorted(empty)
empty = ''.join(empty)
return empty
a = 'xyaabbbccccdefww'
b = 'xxxxyyyyabklmopq'
x = 'abcdefghijklmnopqrstuvwxyz'
y = 12
print(longest_string(a, b)) # abcdefklmopqwxy
print(longest_string(a, x)) # abcdefghijklmnopqrstuvwxyz
print(longest_string(a, y)) # False
def convert(number):
string = str(number)
new_list = []
for element in string:
new_list.append(element)
return sorted(new_list, reverse=True)
print(convert(429563)) # [9, 6, 5, 4, 3, 2]
print(convert(324)) # [4, 3, 2]
def count_repetition(some_list):
dictionary = {}
for element in some_list:
if element not in dictionary:
dictionary[element] = 1
else:
dictionary[element] += 1
return dictionary
print(count_repetition(['kerouac', 'fante', 'fante', 'buk', 'hemingway', 'hornby', 'kerouac', 'buk', 'fante']))
# {'kerouac': 2, 'fante': 3, 'buk': 2, 'hemingway': 1, 'hornby': 1}
def is_caught(string):
c = string.find("C") + 1
m = string.find("m")
return len(string[c:m]) < 3
print(is_caught('C.....m')) # False
print(is_caught('C..m')) # True
print(is_caught('..C..m')) # True
print(is_caught('...C...m')) # False
print(is_caught('C.m')) # True
def split_the_bill(group):
value_sum = 0
# compute the average
for key, value in group.items():
value_sum += value
avg = value_sum / len(group)
# determine the difference from what was actually paid
for key, value in group.items():
group[key] = avg - value
return group
group = {
'Amy': 20,
'Bill': 15,
'Chris': 10
}
print(split_the_bill(group)) # { 'Amy': -5, 'Bill': 0, 'Chris': 5 }
def exp_recursive(b, n):
if n == 0:
return 1
if n >= 1:
return b * exp_recursive(b, n - 1)
print(exp_recursive(5, 3)) # 125
print(exp_recursive(2, 4)) # 16
print(exp_recursive(5, 1)) # 5
print(exp_recursive(6, 0)) # 1
def zero_sum(arr):
# making sure input is a list of numbers
if not (are_same_type(arr) and isinstance(arr[0], int)):
return False
list_of_pos = []
for i in range(len(arr)):
# start second loop at i so you don't repeat the i's you've already been through
# also to prevent repetition
for j in range(i, len(arr)):
if arr[i] + arr[j] == 0:
index = [i, j]
list_of_pos.append(index)
# with list comprehension
# [[i,j] for i in range(len(arr)) for j in range(i, len(arr)) if arr[i] + arr[j] == 0]
if len(list_of_pos) >= 1:
return list_of_pos[:]
print(zero_sum([1, 5, 0, -5, 3, -1])) # [[0, 5], [1, 3], [2, 2]]
print(zero_sum([1, -1])) # [[0, 1]]
print(zero_sum([0, 4, 3, 5])) # [[0, 0]]
def count_upper_lower():
sentence = str(input("Sentence to evaluate: "))
upper_count = 0
lower_count = 0
for i in sentence:
if i.isupper():
upper_count += 1
if i.islower():
lower_count += 1
return "UPPER CASE {} LOWER CASE {}".format(upper_count, lower_count)
# print(count_upper_lower())
def new_dict(dict_input):
new = current = {}
for name in dict_input:
current[name] = {}
current = current[name]
return new
print(new_dict([1, 2, 3, 4, 5])) # {1: {2: {3: {4: {5: {}}}}}}
def banking():
amount = 0
while True:
deposit = input("deposit: ")
if not deposit:
break
else:
deposit = int(deposit)
amount += deposit
while True:
withdraw = input("withdraw: ")
if not withdraw:
break
else:
withdraw = int(withdraw)
amount += withdraw
return amount
# print(banking())
def print_dictionary():
newer_dict = {}
for i in range(1, 21):
newer_dict[i] = i**2
print(newer_dict[i])
# print_dictionary()
def permute(some_list):
return list(itertools.permutations(some_list, 3))
print(permute([1, 2, 3])) # [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [1, 2, 3]]
def perms(nums):
result_perms = [[]]
for n in nums:
new_perms = []
for perm in result_perms:
for i in range(len(perm) + 1):
new_perms.append(perm[:i] + [n] + perm[i:])
result_perms = new_perms
return result_perms
print(perms([1, 2, 3]))
def zero_nine(num):
num = num % 10
if num == 1:
word = 'one'
return word
if num == 2:
word = 'two'
return word
if num == 3:
word = 'three'
return word
if num == 4:
word = 'four'
return word
if num == 5:
word = 'five'
return word
if num == 6:
word = 'six'
return word
if num == 7:
word = 'seven'
return word
if num == 8:
word = 'eight'
return word
if num == 9:
word = 'nine'
return word
if num == 0:
word = 'zero'
return word
else:
word = ''
return word
def teens(num):
if num == 11:
word = 'eleven'
return word
if num == 12:
word = 'twelve'
return word
if num == 13:
word = 'thirteen'
return word
if num == 14:
word = 'fourteen'
return word
if num == 15:
word = 'fifteen'
return word
if num == 16:
word = 'sixteen'
return word
if num == 17:
word = 'seventeen'
return word
if num == 18:
word = 'eighteen'
return word
if num == 19:
word = 'nineteen'
return word
def twenties(num):
num = num - (num % 10)
if num == 10:
word = 'ten'
return word
if num == 20:
word = 'twenty'
return word
if num == 30:
word = 'thirty'
return word
if num == 40:
word = 'fourty'
return word
else:
word = ''
return word
def write_number(num):
if num < 10:
return zero_nine(num)
if num > 10 and num < 20:
return teens(num)
if num > 19 and num < 50:
return twenties(num) + zero_nine(num)
#
# print(write_number(11)) # "eleven"
# print(write_number(2)) # "two"
# print(write_number(32)) # "thirty-two"
# print(write_number(10))
# print(write_number(44))
<file_sep>/python/week1/day3/classes_examples.py
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine(self):
return "The " + self.brand + "'s engine just started"
def stop_engine(self):
return "The " + self.brand + "'s engine stopped"
def makes_noise(self):
return self.brand + "'s " + self.model + " makes a lot of noise"
def makes_no_noise(self):
return "A " + self.brand + " does not make any noise"
audi = Car('Audi', 'A3')
bmw = Car('BMW', '325')
print(audi.start_engine())
print(audi.brand)
print(bmw.start_engine())
print(bmw.makes_noise())
class Circle:
# this is a class attribute
PI = 3.1415
def __init__(self, rad):
self.rad = rad
def area(self):
return Circle.PI * self.rad * self.rad
print(Circle.PI) # 3.1415
new_circle = Circle(10)
second_circle = Circle(10)
print(new_circle.PI) # 3.1415
print(new_circle.area()) # 314.150
# this only changes the instance of the class attribute
new_circle.PI = 7
print(new_circle.PI)
print(second_circle.PI)
# this changes the class attribute
Circle.PI = 5
print(Circle.PI)
print(new_circle.area())
class Students:
names = []
def __init__(self, name):
self.name = name
self.names.append(name)
ilya = Students('Ilya')
sophia = Students('Sophia')
print(Students.names) # ['Ilya', 'Sophia']
print(sophia.names) # ['Ilya', 'Sophia']
print(ilya.names) # ['Ilya', 'Sophia']
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine(self):
return "The " + self.brand + "'s engine just started"
def stop_engine(self):
return "The " + self.brand + "'s engine stopped"
def make_noise(self):
return self.brand + "'s " + self.model + " makes a lot of noise"
# inheritance with additional attributes, thats what the super() keyword is for
class Battery:
def __init__(self):
self.battery = 60
self.range = None
def battery_size(self):
return "This car has {} kWh battery".format(self.battery)
def get_range(self):
if self.battery == 60:
self.range = 240
elif self.battery == 85:
self.range = 270
return 'This car can go {} km in full charge.'.format(str(self.range))
class ElectroCar(Car):
def __init__(self, brand, model):
super().__init__(brand, model)
self.battery = Battery()
tesla = ElectroCar('Tesla', 'Roadster')
tesla2 = ElectroCar('Tesla', 'Roadster')
print(tesla.battery.get_range()) # This car can go 240 km in full charge.
# magic methods
class Words:
def __init__(self):
self.words = []
def add(self, word):
self.words.append(word)
# this allows us to invoke the method without having to use the instantiation
# here the len method alone would work on just words see first print method
def __len__(self):
return len(self.words)
words = Words()
print(len(words)) # 0
words.add("Hello")
words.add("World")
print(len(words)) # 2
# try except
while 1:
try:
first_number = int(input("First number: "))
second_number = int(input("Second number: "))
answer = first_number / second_number
except ValueError:
print("Please use only numbers")
except ZeroDivisionError:
print("No zeros please")
else:
# we got the correct input - print answer, and exit the while 1 loop
print(answer)
break
<file_sep>/prep_work/prime_nums.py
def prime_number(n):
if n == 1:
return False
if n == 2:
return True
if n > 2:
for i in range(2, n):
if n % i == 0:
return False
else:
return True
print(prime_number(20))
print(prime_number(13))
print(prime_number(1))
print(prime_number(2))
<file_sep>/python/week1/day2/shopping_list.py
# 7 shopping list
def help_menu():
print("""
Press 'h' for help menu
Press 's' to show the item in your list
Press 'a' to add a new item to the list
Press 'r' to remove an item from the list
Press 'q' to quit
""")
def show_items():
if len(shop_list) == 0:
print("Shopping list is empty")
else:
for i,j in enumerate(shop_list):
print("{0}: {1}".format(i+1, j))
def add_items(item):
if not item:
print("No item entered")
else:
place = input("What place do you want to add {} to? > ".format(item))
if isinstance(place, int):
shop_list.insert(item, place)
else:
shop_list.append(item)
def remove_items(item):
if item in shop_list:
shop_list.remove(item)
else:
print("{} not in shopping list".format(item))
if __name__ == "__main__":
shop_list = []
while True:
var = input("What do you want to do? > ")
if var == 'h':
help_menu()
elif var == 's':
show_items()
elif var == 'a':
add_items(input("What would you like to add? > "))
elif var == 'r':
remove_items(input("What would you like to remove? > "))
elif var == 'q':
quit()
else:
print("Invalid input")<file_sep>/prep_work/seq_of_zeros.py
def get_size_of_longest_sequence_of_zeros(args):
binary = bin(args)[2:]
lengths = []
i = 0
counter = 0
while i < len(binary):
if int(binary[i]) == 0:
counter += 1
else:
lengths.append(counter)
counter = 0
i += 1
lengths.append(counter)
lengths = sorted(lengths)
return lengths[-1]
print(get_size_of_longest_sequence_of_zeros(7)) # binary representation: 111 - 0
print(get_size_of_longest_sequence_of_zeros(8)) # binary representation: 1000 - 3
print(get_size_of_longest_sequence_of_zeros(457)) # binary representation: 111001001 - longest 2
print(get_size_of_longest_sequence_of_zeros(40)) # binary representation: 101000 - longest 3
print(get_size_of_longest_sequence_of_zeros(12546)) # binary representation: 11000100000010 - longest 6
<file_sep>/prep_work/no_duplicates.py
def unique_array(args):
unique = []
for i in args:
if i not in unique:
unique.append(i)
return unique
print(unique_array([0, 3, -2, 4, 3, 2])) # [0, 3, -2, 4, 2]
print(unique_array([10, 22, 10, 20, 11, 22])) # [10, 22, 20, 11]
<file_sep>/python/week1/day2/day2.py
# 1.1 even numbers
print(list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])))
# 1.2 square elements
print(list(map(lambda x: x*x, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])))
# 1.3 square even numbers
print(list(map(lambda x: x*x, filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))))
# 1.4 find certain numbers
def find_numbers_exp(min, max):
new_list = []
for i in range(min, max):
if i % 7 == 0 and i % 5 != 0:
new_list.append(i)
return new_list
print(find_numbers_exp(10, 50))
minimum = 10
maximum = 50
print(list(filter(lambda x: x % 7 == 0 and x % 5 != 0, [x for x in range(minimum, maximum)])))
# 2 Webstore
orders = [
{
'id': 'order_001',
'item': 'Introduction to Python',
'quantity': 1,
'price_per_item': 32
},
{
'id': 'order_002',
'item': 'Advanced Python',
'quantity': 3,
'price_per_item': 40
},
{
'id': 'order_003',
'item': 'Python web frameworks',
'quantity': 2,
'price_per_item': 51
}
]
def total(el):
total_price = el['quantity'] * el['price_per_item']
if total_price < 100:
total_price += 10
return total_price
def compute_total(order):
# new_list = []
# for el in order:
# total = (el['quantity'] * el['price_per_item'])
# if total < 100:
# total += 10
# new_list.append((el['id'], total))
# return new_list
return list(map(lambda el: (el['id'], total(el)), order))
print(compute_total(orders))
# 3 input and range
def input_range(n):
new_dict = {}
for i in range(1, n+1):
new_dict[i] = i*i
return new_dict
print(input_range(10))
# 4 list comprehension
li1 = range(1, 21)
print([i*i for i in li1 if i > 15])
# 5 print style
li2 = range(1, 11)
print([i for i in li2 if i % 2 == 0])
def sep_list(li):
for i in li:
if i % 2 == 0:
print(i, end='')
else:
print('_', end='')
# li3 = range(1, 11)
# sep_list(li3)
# 6 BMI calc
def bmi_calc():
weight = float(input("Your weight in KG: >"))
height = int(input("Your height in CM: >"))
bmi = weight / ((height/100)**2)
if bmi < 18.5:
return 'Your BMI is {}, you are underweight'.format(bmi)
elif 18.5 <= bmi <= 25.0:
return "Your BMI is {}, you are normal weight".format(bmi)
else:
return 'Your BMI is {}, you are overweight'.format(bmi)
print(bmi_calc())
# 7 shopping list --> separate file
# 8 number game --> separate file
# 9 hangman --> separate file
<file_sep>/python/week1/day2/hangman.py
import random
import re
def rand_word():
word = random.choice(my_list)
return word
def user_input():
guess = input("Write your letter: ")
if not re.match('[a-z]$', guess):
print("Invalid data type")
user_input()
else:
return guess
def underscores(words):
for i in range(len(words)):
print("_ ", end='')
print('\n')
user_inp = user_input()
if user_inp in words:
print("YES")
else:
underscores(words)
if __name__ == '__main__':
f = open('hangman_words.txt')
# creating a list from the txt file and then choosing a random word from list
my_list = []
for line in f:
my_list.append(line)
words = rand_word()
underscores(words)
# print(user_input())
<file_sep>/prep_work/pentagonal_nums.py
def get_pentagonal_number(n):
i = 1
while i < n+1:
p = (3*(i**2) - i) / 2
print(int(p))
i += 1
get_pentagonal_number(50)
# formula: https://en.wikipedia.org/wiki/Pentagonal_number
<file_sep>/prep_work/second_smallest.py
def find_second_smallest(args):
args = sorted(args)
return args[1]
print(find_second_smallest([0, 3, -2, 4, 3, 2])) #0
print(find_second_smallest([10, 22, 10, 20, 11, 22])) #10<file_sep>/python/week1/day3/inheritance/house.py
from python.week1.day3.inheritance.shapes import *
class House:
def __init__(self):
self._walls = []
self._holes = []
def register_wall(self, shape):
self._walls.append(shape)
def register_hole(self, shape):
self._holes.append(shape)
def get_wall_area(self):
return sum(map(lambda w: w.get_area(), self._walls)) - \
sum(map(lambda h: h.get_area(), self._holes))
def draw(self, screen, fcolor, bcolor, scale):
for w in self._walls:
w.draw(screen, fcolor, scale)
for h in self._holes:
h.draw(screen, bcolor, scale)
def create_house():
base_wall = Rectangle(2, 1.5, 4, 3)
roof_wall = Triangle(2, 4, 4, 2)
door = Rectangle(2, 1.5, 4, 3)
window1 = Rectangle(2, 1.5, 4, 3)
window2 = Circle(2, 1, 0.75)
my_house = House()
my_house.register_wall(base_wall)
my_house.register_wall(roof_wall)
my_house.register_hole(door)
my_house.register_hole(window1)
my_house.register_hole(window2)
return my_house.get_wall_area()
<file_sep>/prep_work/js_exercises.js
// 1 Reverse
function reverse(string) {
var reversed = "";
for (i = string.length-1; i >= 0; i--) {
reversed += string[i];
}
return reversed;
}
console.log(reverse("abcd"));
// 2 Factorial
function factorial(n) {
if (n === 0 ) {
return 1;
} else {
return n * factorial(n-1)
}
}
console.log(factorial(5));
// 3 Longest Word
function longest_word(sentence) {
var sen = sentence.split(" ");
sen.sort(function(a,b) {
return b.length - a.length
});
return sen[0];
}
console.log(longest_word('This is an amazing test'));
// 4 Sum Nums
function sum_nums(num) {
var sum = num;
for (var i = num-1; i >= 0; i--) {
sum += i;
}
return sum;
}
console.log(sum_nums(6));
// 5 Time Conversion
function time_conversion(minutes) {
var hours = String(Math.floor(minutes / 60));
var minutes = String(minutes % 60);
if (minutes.length < 2) {
minutes = "0" + minutes;
}
return hours + ":" + minutes;
}
console.log(time_conversion(155));
// 6 Count Vowels
function count_vowels(string) {
var vowels = "aeiou";
var counter = 0;
for (var i = 0; i < string.length; i++) {
for (var j = 0; j < vowels.length; j++) {
if (string[i] === vowels[j]) {
counter += 1;
}
}
}
return counter;
}
console.log(count_vowels('alphabet'));
console.log(count_vowels('aeiou'));
console.log(count_vowels('Sophia'));
// 7 Palindrome
function palindrome(string) {
if (reverse(string) === string) {
return true;
} else {
return false;
}
}
console.log(palindrome('abbba'));
console.log(palindrome('babbba'));
console.log(palindrome(''));
// 8 Most Letters
function nearby_az(string) {
for (var i = 0; i < string.length; i++) {
if (string[i] === "a" && (string[i+1]==="z" ||
string[i+2]==="z" || string[i+3]==="z")) {
return true;
} else {
return false;
}
}
}
console.log(nearby_az('abbbz'));
console.log(nearby_az('abz'));
console.log(nearby_az('abbz'));
// 9 Two Sum
function two_sum(nums) {
if (typeof(nums) !== "object") {
return null;
}
var positionList = [];
for (var i = 0; i <= nums.length-1; i++) {
for (var j = 0; j < nums.length-1; j++) {
if ((nums[i] + nums[j]) === 0) {
var index = [i, j];
if (!positionList[i] && !positionList[j]) {
positionList.push(index);
}
}
}
}
if (positionList.length >= 1) {
return positionList;
} else {
return null;
}
}
console.log(two_sum([1, 3, -1, 5]));
console.log(two_sum([1, 5, 3, -4]));
console.log(two_sum([1, 3, -1, 5, -3]));
console.log(two_sum(1));
// 10 Is Power of Two
function is_power_of_two(num) {
if (num === 1) {
return true;
}
for (var i = 0; i < num; i++) {
if (2**i === num) {
return true;
}
}
return false;
}
console.log(is_power_of_two(8));
console.log(is_power_of_two(24));
console.log(is_power_of_two(1));
console.log(is_power_of_two(2));
// 11 Repeat a string
function repeat_string_num_times(str, num) {
var repeated = "";
if (num <= 0) {
return repeated;
} else {
for (var i = 0; i < num; i ++) {
repeated = repeated + str;
}
}
return repeated;
}
console.log(repeat_string_num_times("abc", 3));
console.log(repeat_string_num_times("abc", -1));
// // 12 Sum All Numbers in a Range
function add_all(arr) {
var sum = 0;
for (var i = arr[0]; i<=arr[1]; i++) {
sum += i
}
return sum;
}
console.log(add_all([1, 4]));
console.log(add_all([5, 10]));
// 13 True or False
function is_it_true(args) {
if (args === true || args === false) {
return true;
} else {
return false;
}
}
console.log(is_it_true(true));
console.log(is_it_true("true"));
console.log(is_it_true(false));
// 14 Return Largest Number in Arrays
function largest_of_four(arr) {
var list = [];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
var temp = arr[i][j]
for (var k = 0; k < arr[i].length; k++) {
if (arr[i][k] > temp) {
var temp = arr[i][k];
}
}
}
list.push(temp);
}
return list;
}
console.log(largest_of_four([[13, 27, 18, 26], [4, 5, 1, 3],
[32, 35, 37, 39], [1000, 1001, 857, 1]]));
// [27,5,39,1001]
console.log(largest_of_four([[13, 27, 18, 85], [4, 5, 16, 3],
[50, 35, 37, 39], [1000, 1001, 857, 1005]]));
// 85 16 50 1005
// // 15 Does it start with Java
function starts_with_java(str) {
var bool = str.startsWith("Java");
return bool;
}
console.log(starts_with_java("JavaScript"));
console.log(starts_with_java("Java"));
console.log(starts_with_java("Python"));
<file_sep>/prep_work/bank.js
function Bank() {
this.customers = [];
}
Bank.prototype.addCustomer = function(customer) {
this.customers[customer] = 0;
}
Bank.prototype.printAccount = function(customer) {
console.log(customer + " account is " + this.customers[customer]);
}
Bank.prototype.deposit = function(customer, amount) {
this.customers[customer] += amount;
}
Bank.prototype.withdraw = function(customer, amount) {
if (this.customers[customer] > amount) {
this.customers[customer] -= amount;
} else {
return console.log("Insufficient funds available!");
}
}
Bank.prototype.printAllAccounts = function() {
var list = this.customers;
for (var i in list) {
console.log("Name: " + i + " - " + list[i] + ".- CHF");
}
}
var bank = new Bank();
// bank.addCustomer("Sheldor");
// bank.printAccount("Sheldor");
// bank.deposit("Sheldor", 10);
// bank.addCustomer("Raj");
// bank.printAccount("Raj");
// bank.deposit("Raj", 10);
// bank.printAccount("Raj");
// bank.printAccount("Sheldor");
// bank.addCustomer("Sophia");
// bank.deposit("Sophia", 20);
// bank.printAccount("Sophia");
// bank.withdraw("Sophia", 10);
// bank.printAccount("Sophia");
// bank.withdraw("Sophia", 20);
// bank.printAllAccounts();
bank.addCustomer("Glamma")
bank.printAccount("Glamma")
bank.deposit("Glamma", 100)
bank.printAccount("Glamma")
bank.withdraw("Glamma", 10)
bank.printAccount("Glamma")
bank.addCustomer("Pia")
bank.addCustomer("Daddy")
bank.printAllAccounts()
<file_sep>/python/week1/day3/inheritance/shapes.py
import math
import pygame
class Shape:
def __init__(self, x, y):
self.center = (x, y)
def get_area(self):
# because its not implemented in this class, just here for inheritance
raise NotImplementedError
# empty shape does not have an area -> return 0
def draw(self, screen, color, scale):
raise NotImplementedError
# right click, generate to see all the methods that can be overwritten
class Rectangle(Shape):
def __init__(self, x, y, width, height):
super().__init__(x, y)
# underscore is the naming convention that means that its a private var and shouldn't be touched
self._width = width
self._height = height
def get_area(self):
return self._width * self._height
def draw(self, screen, color, scale):
pygame.draw.rect(screen, color, int((self.center[0] - self._width/2))*scale,
int((self.center[1] - self._width/2))*scale, self._width*scale, self._height*scale)
class Triangle(Rectangle):
def __init__(self, x, y, width, height):
super().__init__(x, y, width, height)
def get_area(self):
return super().get_area() / 2
class Circle(Shape):
def __init__(self, x, y, radius):
super().__init__(x, y)
self._radius = radius
def get_area(self):
return self._radius**2 * math.pi
<file_sep>/python/week1/day3/books.py
class Book1:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return "{} by {}".format(self.title, self.author)
class Bookcase1:
def __init__(self, books):
self.books = self.create_books(books)
def create_books(self, books):
return [Book1(t, a) for t, a in books]
def __iter__(self):
for book in self.books:
yield str(book)
books = [
('title1', 'author1'),
('title2', 'author2'),
('title3', 'author3'),
]
new_bookcase = Bookcase1(books)
for book in new_bookcase:
print(book)
# class methods often help you create objects
# class methods are called on the object itself and the other methods are called on instances
# solutions published:
class Book:
def __init__(self, author, title):
self.title = title
self.author = author
def __str__(self):
return "{} by {}".format(self.title, self.author)
class Bookcase:
def __init__(self, books=[]):
self.books = books
def __iter__(self):
yield from self.books
@classmethod
# the book_list default is set to an empty list so that the code will still run if nothing is passed into the func
def create_books(cls, book_list=[]):
books = []
for title, author in book_list:
books.append(Book(title, author))
return cls(books)
# this is a cls method being called on the object bookcase, this helps us generate books for further use
the_books = Bookcase.create_books(
[("<NAME>", "The old man and the see"), ("<NAME>", "Beyond Good and Evil")])
for book in the_books:
print(book)
book2 = Bookcase.create_books()
<file_sep>/prep_work/player.py
class Player(object):
def __init__(self, name, tracks=[]):
self.name = name
self.tracks = tracks
self.current_track = 0
def add(self, track):
self.track = track
self.tracks.append(self.track)
def play(self):
print("Playing: {0} ({1}) by {2}".format(self.tracks[self.current_track].title,
self.tracks[self.current_track].album, self.tracks[self.current_track].artist))
def next(self):
if self.current_track < len(self.tracks) - 1:
self.current_track += 1
else:
print("Error: no more tracks to play!")
def previous(self):
if self.current_track > 0:
self.current_track -= 1
else:
print("Error: no more tracks to play!")
def select_track(self, num):
self.num = num
self.current_track = self.num
def print_track_info(self):
i = 0
while i < len(self.tracks):
print("Track {0}: {1} ({2}) by {3}".format(i+1,
self.tracks[i].title,
self.tracks[i].album,
self.tracks[i].artist))
i += 1
<file_sep>/prep_work/hello.py
def hello(*name):
if len(name) == 0:
print("Hello, Unknown!")
else:
print("Hello, {} !".format(name[0]))
hello("Sophia")
hello()
def hello_all(*names):
i = 0
if len(names) == 0:
print("Hello, Unknown!")
else:
while i < len(names):
print("Hello, {}!".format(names[i]))
i += 1
hello_all("Sally", "Markus")
hello_all()
<file_sep>/python/week1/day3/test_house.py
from python.week1.day3.inheritance.house import House
from python.week1.day3.inheritance.shapes import *
base_wall = Rectangle(2, 1.5, 4, 3)
roof_wall = Triangle(2, 4, 4, 2)
door = Rectangle(2, 1.5, 4, 3)
window1 = Rectangle(2, 1.5, 4, 3)
window2 = Circle(2, 1, 0.75)
my_house = House()
my_house.register_wall(base_wall)
my_house.register_wall(roof_wall)
my_house.register_hole(door)
my_house.register_hole(window1)
my_house.register_hole(window2)
print(my_house.get_wall_area())<file_sep>/prep_work/finding_digit.py
import functools
def find(number, count=0):
if number < 10 and count == 0:
return count
# source: https://stackoverflow.com/questions/21270320/turn-a-single-number-into-single-digits-python
nums = [int(d) for d in str(number)]
result = functools.reduce(lambda x, y: x * y, nums)
if result > 9:
return find(result, count+1)
else:
return count+1
print(find(57)) # 3
print(find(5923)) # 2
print(find(90)) # 1
print(find(7)) # 0
print(find(999)) # 4
<file_sep>/README.md
# Propulsion Bootcamp
This repo holds the exercises from week 1 at Propulsion. The rest of the exercises will follow shortly.
<file_sep>/python/week1/day4/test_game.py
import pygame
import sys
from python.week1.day3.inheritance.house import House, create_house
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("myGame")
red = pygame.Color(255, 0, 0)
white = pygame.Color(255, 255, 255)
screen.fill(red)
x = 0
fpsClocks = pygame.time.Clock()
my_house = create_house()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(red)
x += 1
if x > 500:
x = 0
my_house.draw(screen, red, white, 100)
# coordinate in top left are 0,0, bottom in this ex is 800,600
pygame.draw.rect(screen, white, (x, 200, 100, 50))
pygame.display.update()
fpsClocks.tick(60)
<file_sep>/python/week1/day3/water_molecule.py
class Quark:
def __init__(self, charge):
self.charge = charge
@property
def type(self):
if self.charge == (1/3):
return 'Up'
else:
return 'Down'
def print_symbol(self):
return "Symbol: {}".format(self.type[:1])
def print_info(self):
return "Type: {}; Charge: {}".format(self.type, self.charge)
class Nucleon:
def __init__(self, type):
self.type = type
def add_quarks(self):
if self.type == 'Proton':
self.proton = Quark(-1/3).charge + Quark(2/3).charge + Quark(2/3).charge
return self.proton
elif self.type == 'Neutron':
self.neutron = Quark(-1/3).charge + Quark(-1/3).charge + Quark(2/3).charge
return self.neutron
def print_info(self):
if self.add_quarks() == 1:
print("Symbol: {}".format(self.type[:1]))
print("The Proton contains 3 quarks - Proton with +{}e elementary charge".format(self.proton))
else:
print("Symbol: {}".format(self.type[:1]))
print("The Neutron contains 3 quarks - Neutron with +{}e elementary charge".format(self.neutron))
class Atom:
def __init__(self, name, position, charge):
self.name = name
self.atomic_num = self.find_num()
self.atomic_mass = self.find_mass()
self.position = position
self.charge = charge
def oxygen(self):
self.protons = Nucleon('Proton').add_quarks() * 8
self.neutrons = Nucleon('Neutron').add_quarks() * 8
self.oxy = [self.protons, self.neutrons]
return self.oxy
def hydrogen(self):
self.protons = Nucleon('Proton').add_quarks()
return self.protons
def find_num(self):
# num is sum(proton)
if self.name == 'oxygen':
return self.oxygen()[0] + self.oxygen()[1]
elif self.name == 'hydrogen':
return self.hydrogen()
def find_mass(self):
# mass is sum(proton) + sum(neutrons)
pass
def calc_charge(self):
# is the sum of the charges
pass
quark = Quark(1)
print(quark.print_symbol())
print(quark.print_info())
quark1 = Quark(-1)
print(quark1.print_symbol())
print(quark1.print_info())
nuc = Nucleon('Proton')
nuc.print_info()
nuc2 = Nucleon('Neutron')
nuc2.print_info()
water = Atom('oxygen', '1 1 1', -1)
print(water.find_num())
water = Atom('hydrogen', '1 1 1', -2)
print(water.find_num())
"""
Solutions:
class Quark:
def __init__(self, quark_type, charge):
self.quark_type = quark_type
self.charge = charge
def symbol(self):
return 'Symbol: {}'.format(self.quark_type[:1])
def __repr__(self):
return 'Type: {}; Charge: {}'.format(self.quark_type, self.charge)
# up = Quark('Up', 0.666)
# down = Quark('Down', -0.333)
# print(up)
# print(up.symbol())
# print(down)
# print(down.symbol())
# result
# Type: Up; Charge: 0.666
# Symbol: U
# Type: Down; Charge: -0.333
# Symbol: D
from quark import Quark
class Nucleon:
def __init__(self, nucleon_type, charge):
self.nucleon_type = nucleon_type
self.charge = charge
self.quark_list = []
def symbol(self):
return 'Symbol: {}'.format(self.nucleon_type[:1])
def add_quark(self, quark):
return self.quark_list.append(quark)
def __repr__(self):
nucleon = 'The {} contains {} quarks - '.format(self.nucleon_type, len(self.quark_list))
return nucleon + ' {} with +{}e elementary charge'.format(self.nucleon_type, int(round(self.charge)))
from quark import Quark
from nucleon import Nucleon
from atom import Atom
from atom import Atom
class Molecule:
def __init__(self, name='Generic'):
self.name = name
self.atom_list = []
def add_atom(self, atom):
self.atom_list.append(atom)
def __repr__(self):
count = 0
info = 'This is a molecule named {} and '.format(self.name)
info += 'it has {} atoms:'.format(len(self.atom_list))
atoms_info = ''
for atom in self.atom_list:
count += 1
atoms_info += '#' + str(count) + ' ' + str(atom) + '\n'
return info + '\nThe atoms are: \n' + atoms_info
water = Molecule('Water')
up_quark = Quark('Up', 0.666)
down_quark = Quark('Down', -0.333)
proton = Nucleon('Proton', (2 * up_quark.charge + down_quark.charge))
proton.add_quark(up_quark)
proton.add_quark(up_quark)
proton.add_quark(down_quark)
neutron = Nucleon('Neutron', 2 * down_quark.charge + up_quark.charge)
neutron.add_quark(up_quark)
neutron.add_quark(up_quark)
neutron.add_quark(down_quark)
oxygen = Atom('Oxygen', 8 * proton.charge, (8 * proton.charge + 8 * (neutron.charge + 1)), 1, 1, 1, -2)
hydrogen = Atom("Hydrogen", proton.charge, (proton.charge + neutron.charge), 2, 2, 2, 1)
water.add_atom(oxygen)
water.add_atom(hydrogen)
water.add_atom(hydrogen)
print(water)
from nucleon import Nucleon
from quark import Quark
class Atom:
def __init__(self, name, atomic_number, atomic_mass, x, y, z, charge):
self.name = name
self.atomic_number = atomic_number
self.atomic_mass = atomic_mass
self.position = (x, y, z)
self.charge = charge
def symbol(self):
return 'Symbol: {}'.format(self.name[:1])
def __repr__(self):
return "Name: {}\nDescription:\n".format(self.name) + \
"- Atomic number: {}\n".format(self.atomic_number) + \
"- Atomic mass: {}\n".format(self.atomic_mass) + \
"- Position: {} {} {}\n".format(self.position[0],
self.position[1],
self.position[2]) + \
"- Charge: {}".format(self.charge)
# up_quark = Quark('Up', 0.666)
# down_quark = Quark('Down', -0.333)
#
# proton = Nucleon('Proton', (2 * up_quark.charge + down_quark.charge))
# proton.add_quark(up_quark)
# proton.add_quark(up_quark)
# proton.add_quark(down_quark)
# # print(proton.symbol())
# # print(proton)
#
# neutron = Nucleon('Neutron', 2 * down_quark.charge + up_quark.charge)
# neutron.add_quark(up_quark)
# neutron.add_quark(up_quark)
# neutron.add_quark(down_quark)
# # print(neutron.symbol())
# # print(neutron)
#
# # atomic number of an atom is equal to the number of protons it has.
# # atomic mass of an atom can be found by adding the the number of protons with the numbers of neutrons
# # Oxygen has 8 protons and 8 neutrons
# # Oxygen charge is -2
#
# oxygen = Atom('Oxygen', 8 * proton.charge, (8 * proton.charge + 8 * (neutron.charge + 1)), 1, 1, 1, -2)
# print(oxygen.symbol())
# print(oxygen)
#
#
# Symbol: O
# Name: Oxygen
# Description:
# - Atomic number: 7.992000000000001
# - Atomic mass: 15.992
# - Position: 1 1 1
# - Charge: -2
# Symbol: H
# Name: Hydrogen
# Description:
# - Atomic number: 0.9990000000000001
# - Atomic mass: 0.9990000000000001
# - Position: 2 2 2
# - Charge: 1
#
# # Hydrogen has 1 proton and 0 neutrons
# # Hydrogen charge is +1
# hydrogen = Atom("Hydrogen", proton.charge, (proton.charge + neutron.charge), 2, 2, 2, 1)
# print(hydrogen.symbol())
# print(hydrogen)
"""
<file_sep>/python/week1/day4/snake_game/tester.py
some_list = []
i = 0
j = 0
x = 10
y = 40
while i < 10:
j = 0
i += 1
y += 10
while j < 10:
some_list.append((x, y))
x += 50
j += 1
print(some_list)
<file_sep>/prep_work/valid_pw.py
import re
# modified from: https://www.w3resource.com/python-exercises/python-conditional-exercise-15.php
def is_valid_password():
p = input("Input your password")
x = True
while x:
if not len(p) <= 10:
break
elif not re.search("[a-z]", p):
break
elif not re.search("[0-9]", p):
break
elif not re.search("[A-Z]", p):
break
elif re.search("\s", p):
break
else:
print("Valid Password")
x = False
break
if x:
print("Not a Valid Password")
is_valid_password()
<file_sep>/prep_work/test.js
function Person(age) {
this.age = age;
}
var oldPerson = new Person(85);
console.log(oldPerson.age);
var youngPerson = new Person(5);
console.log(youngPerson.age);
Person.prototype.speak = function(line) {
console.log("I am " + this.age + " years old.");
}
oldPerson.speak();
Person.prototype.gender = function(gender) {
this.gender = ("female" || "male");
console.log(this.gender);
}
oldPerson.gender("female");<file_sep>/prep_work/vowels.py
def count_of_vowels(args):
count = 0
for i in args:
if i == "a" or i == "e" or i == "i" or i == "o" or i == "u" or \
i == "A" or i == "E" or i == "I" or i == "O" or i == "U":
count += 1
return count
print(count_of_vowels("Propulsion Academy"))
<file_sep>/python/week1/day3/inheritance_paint.py
from math import pi
class Shape:
def __init__(self, x, y):
self.center = (x, y)
def get_area(self):
# empty shape does not have an area -> return 0
return 0
class Circle(Shape):
def __init__(self, x, y, radius):
super().__init__(x, y)
self.radius = radius
def get_area(self):
return pi * self.radius**2
class Triangle(Shape):
def __init__(self, x, y, height, width):
super().__init__(x, y)
self.height = height
self.width = width
def get_area(self):
return (self.height * self.width) / 2
class Rectangle(Triangle):
def get_area(self):
return self.height * self.width
circle = Circle(1, 2, 0.75)
triangle = Triangle(1, 2, 2, 4)
rectangle_big = Rectangle(1, 2, 3, 4)
rectangle_medium = Rectangle(1, 2, 1, 2)
rectangle_small = Rectangle(1, 2, 1, 1)
area_house = rectangle_big.get_area() + triangle.get_area() - rectangle_medium.get_area() - \
rectangle_small.get_area() - circle.get_area()
print(area_house)
<file_sep>/python/week1/day3/car.py
"""Create a class name Car, the __init__ method takes the color of the car,
the tank size and the number of laps in a race and the length of a lap.
Overload the class with a special method which will give the users the
opportunity to pass an many arguments as they like. Keep in mind the **kwargs,
for example, brand, model, HP etc."""
class Car:
def __init__(self, color, tank_size, laps, lap_length, **kwargs):
self.color = color
self.tank_size = tank_size
self.laps = laps
self.lap_length = lap_length
self.info = {}
for k, v in kwargs.items():
self.info[k] = v
def run_lap(self):
while self.laps > 0:
self.laps -= 1
self.tank_size -= 0.2
print("Fuel remaining: {}".format(round(self.tank_size, 2)))
self.check_pit_stop()
print("Race completed")
def check_pit_stop(self):
if self.tank_size <= 10:
print("Tank contain 10l or less. Please refill!")
try:
amount = int(input("How many liters? > "))
self.tank_size += amount
except ValueError:
print("Please use only numbers")
car = Car("red", 12, 20, "400m", extra='extras')
car.run_lap()
<file_sep>/prep_work/factorial.py
# def factorial(n):
# if n == 0:
# return 1
# else:
# return n * factorial(n-1)
#
#
# print(factorial(5))
def factorial_iter(n):
if n == 0:
return 1
else:
i = n
total = 1
while i > 1:
total = total * i
i -= 1
return total
print(factorial_iter(5))
print(factorial_iter(4))
print(factorial_iter(1))
print(factorial_iter(2))
<file_sep>/python/week1/day2/number_game.py
import random
def play():
counter = 1
rand_num = random.randint(1, 11)
print(rand_num)
print("'I am thinking of a number from 1-10. Can you find it? You have 5 tries.")
guess = input("Guess: > ")
if guess.isdigit():
while counter < 5:
if int(guess) != rand_num:
print("Wrong, try again! (try {} of 5)".format(counter+1))
guess = input("Guess: > ")
if guess.isdigit():
counter += 1
else:
print("Not a number, guess again!")
guess = input("Guess: > ")
elif int(guess) == rand_num:
print("Congrats, you guessed it in {} tries!".format(counter+1))
play_again()
if counter == 5:
print("You didn't guess it!")
play_again()
else:
print("Not a number, start over!")
play()
def play_again():
answer = input("Would you like to play again? ('y' or 'n')? > ")
if answer == 'y':
play()
elif answer == 'n':
quit()
else:
print("Invalid input")
play_again()
if __name__ == '__main__':
play()
<file_sep>/prep_work/weird_sort.py
import math
def sort_it(the_array):
i = 0
j = 0
rounded_list = []
even_list = []
odd_list = []
# to make sure the array are rounded
while i < len(the_array):
rounded_list.append((round(the_array[i])))
i += 1
while j < len(rounded_list):
if rounded_list[j] % 2 == 0:
even_list.append(rounded_list[j])
else:
odd_list.append(rounded_list[j])
j += 1
odd_list = sorted(odd_list)
even_list = sorted(even_list, reverse=True)
final_list = odd_list + even_list
return final_list
print(sort_it([1, 2, 3, 4, 5, 6, 7, 8, 9])) # [1,3,5,7,9,8,6,4,2]
print(sort_it([26.66, 24.01, 52.00, 2.10, 44.15, 1.02, 11.15]))
<file_sep>/prep_work/mid_char.py
import math
def get_middle_character(args):
if len(args) % 2 != 0:
middle = math.floor(len(args)/2)
return args[middle]
else:
left_mid = math.floor(len(args)/2 - 1)
right_mid = math.ceil(len(args)/2)
return args[left_mid] + args[right_mid]
print(get_middle_character("3500"))
print(get_middle_character("35100"))
print(get_middle_character("12345678"))<file_sep>/prep_work/fibonacci.py
def fibonacci(args):
if args <= 1:
return args
else:
return fibonacci(args - 1) + fibonacci(args - 2)
print(fibonacci(0)) # 0
print(fibonacci(1)) # 1
print(fibonacci(2)) # 1
print(fibonacci(3)) # 2
print(fibonacci(7)) # 13
print(fibonacci(12)) # 144
<file_sep>/python/week1/day5/bricks/bricks.py
import random
import os
import pygame
import sys
import time
pygame.init()
# colors
red = pygame.Color(244, 66, 66)
white = pygame.Color(234, 218, 197)
blue = pygame.Color(79, 58, 201)
# brick colors
c1 = pygame.Color(11, 32, 39)
c2 = pygame.Color(64, 121, 140)
c3 = pygame.Color(112, 169, 161)
c4 = pygame.Color(207, 215, 199)
c5 = pygame.Color(246, 241, 209)
list_of_color = [c3, c4]
# setting surface
width = 810
height = 500
radius = 10
surface = pygame.display.set_mode((width, height))
pygame.display.set_caption("bricks")
surface.fill(c4)
surface.convert()
paddle_w = 40
paddle_h = 10
def game_over():
pygame.font.init()
done = False
font = pygame.font.SysFont("comicsansms", 60)
text = font.render("Press Enter to play again", True, (255, 255, 255))
text2 = font.render("Press ESC to quit", True, (255, 255, 255))
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
time.sleep(1)
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
os.execl(sys.executable, sys.executable, *sys.argv)
surface.fill(white)
surface.blit(text,
(400 - text.get_width() // 2, 200 - text.get_height() // 2))
surface.blit(text2,
(400 - text2.get_width() // 2, 300 - text2.get_height() // 2))
pygame.display.flip()
class Ball:
def __init__(self):
# initial positions
self.x = width // 2
self.y = height // 2
# initial directions
self.dx = 5
self.dy = 5
def move_ball(self):
# updating position with direction
self.y += self.dy
self.x += self.dx
# check bounds
if self.x + self.dx < radius or self.x + self.dx > width - radius:
self.dx = -self.dx
if self.y + self.dy < radius:
self.dy = -self.dy
# if ball hits the bottom -> game over
if self.y + self.dy > height - radius:
print("GAME OVER!")
self.dy = 0
self.dx = 0
time.sleep(2)
game_over()
def draw_ball(self):
pygame.draw.circle(surface, (random.randint(0,255), random.randint(0,255), random.randint(0,255)), (self.x, self.y), radius)
class Paddle:
def __init__(self):
# setting paddle size
self.go_right = + 10
self.go_left = -10
self.paddle_dx = 10
self.paddle_x = width // 2
self.paddle_y = height - 30
def move_paddle(self):
# check bounds
if self.paddle_x + self.paddle_dx < 10:
self.paddle_x = 0
if self.paddle_x + self.paddle_dx > width - 40:
self.paddle_x = width - 40
# set key functionality
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.paddle_x += self.go_left
if event.key == pygame.K_RIGHT:
self.paddle_x += self.go_right
def draw_paddle(self):
self.paddle = (self.paddle_x, self.paddle_y, paddle_w, paddle_h)
pygame.draw.rect(surface, c2, self.paddle)
class Brick:
def __init__(self, brick_posx=0, brick_posy=0):
self.brick_w = 40
self.brick_h = 15
self.brick_posx = brick_posx
self.brick_posy = brick_posy
self.brick_color = red
self.brick = (self.brick_posx, self.brick_posy, self.brick_w, self.brick_h)
class Game:
def __init__(self):
pygame.font.init()
self.ball = Ball()
self.paddle = Paddle()
self.brick = Brick()
self.score = 0
# creating bricks
# i is number of rows, k is number of bricks across
tuple_of_bricks = []
i = 0
y = 0
while i < 7:
k = 0
y += 25
x = 10
i += 1
# k = 16 fills the width of the screen
while k < 16:
a_brick = Brick(brick_posx=x, brick_posy=y)
tuple_of_bricks.append(a_brick.brick)
x += 50
k += 1
# convert tuple to list for indexing
self.list_of_bricks = []
for j in tuple_of_bricks:
self.list_of_bricks.append(list(j))
# self.list_of_rects = []
# for j in self.list_of_bricks:
# self.list_of_rects.append((surface, random.choice(list_of_color), j))
def score_keeper(self):
# print score to surface
score = "Score: " + str(self.score)
myfont = pygame.font.SysFont("comicsansms", 25)
# render text
label = myfont.render(score, 1, c1)
surface.blit(label, (width-100, 5))
# check for brick and ball collision
def collision_brick_check(self):
for self.k in self.list_of_bricks:
# check for collision of ball with brick
if self.ball.x in range(self.k[0], self.k[0] + self.brick.brick_w) and \
self.ball.y == self.k[1] + 20 or self.ball.y == self.k[1] - 20:
self.ball.dy = -self.ball.dy
return self.k
def collision_paddle_check(self):
# check for collision of ball with paddle
if self.ball.x in range(self.paddle.paddle_x, self.paddle.paddle_x + paddle_w) and \
self.paddle.paddle_y == self.ball.y:
self.ball.dy = -self.ball.dy
def play(self):
self.ball.draw_ball()
self.ball.move_ball()
self.paddle.move_paddle()
self.paddle.draw_paddle()
Game.collision_paddle_check(self)
Game.score_keeper(self)
# drawing bricks
for i in self.list_of_bricks:
pygame.draw.rect(surface, c3, i)
# if ball and brick collide remove brick from list
if Game.collision_brick_check(self):
print("removed k: {}".format(self.k))
self.list_of_bricks.remove(self.k)
self.score += 1
print(self.score)
if len(self.list_of_bricks) == 0:
print("you won!")
game_over()
game = Game()
running = True
if __name__ == '__main__':
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
game.play()
pygame.display.update()
# frames per second
fspClocks = pygame.time.Clock()
fspClocks.tick(360)
pygame.display.update()
surface.fill(c4)
<file_sep>/python/week1/day4/snake_game/snake.py
import pygame
import sys
import random
def game_over():
print("Game over!")
ans = input("Play again? ('y' or 'n') >")
if ans == 'y':
return start()
else:
quit()
def start():
height = 300
width = 400
screen = pygame.display.set_mode((height, width))
pygame.display.set_caption("Snake Game")
pink = pygame.Color(255, 234, 249)
black = pygame.Color(0, 0, 0)
blue = pygame.Color(10, 48, 109)
screen.fill(pink)
num1 = random.randint(0, height)
num2 = random.randint(0, width)
direction = "right"
y = round(width / 2)
x = round(height / 2)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame .K_UP:
direction = 'up'
if event.key == pygame.K_DOWN:
direction = 'down'
if event.key == pygame.K_LEFT:
direction = 'left'
if event.key == pygame.K_RIGHT:
direction = 'right'
for i in snake_body:
pygame.draw.rect(screen, black, (i[0], i[1], 10, 10))
if direction == 'up':
y -= 1
if direction == 'down':
y += 1
if direction == 'left':
x -= 1
if direction == 'right':
x += 1
if y == 0 or y == width:
game_over()
if x == 0 or x == height:
game_over()
snake_body.insert(0, ([x, y]))
if (num1 in range(x - 5, x + 5) and num2 in range(y - 5, y + 5)) or (
num1 in range(y - 5, y + 5) and num2 in range(x - 5, x + 5)):
if direction == 'up':
snake_body.insert(-1, ([num1, num2+5]))
if direction == 'down':
snake_body.insert(-1, ([num1, num2-5]))
if direction == 'left':
snake_body.insert(-1, ([num1 + 5, num2]))
if direction == 'right':
snake_body.insert(-1, ([num1 - 5, num2]))
num1 = random.randint(0, 290)
num2 = random.randint(0, 390)
else:
snake_body.pop()
pygame.draw.rect(screen, blue, (num1, num2, 10, 10))
pygame.display.update()
screen.fill(pink)
if __name__ == '__main__':
pygame.init()
snake_body = [[100, 50], [90, 50], [80, 50]]
fspClocks = pygame.time.Clock()
fspClocks.tick(6)
start()
<file_sep>/prep_work/files_and_dirs.py
import os
def files_and_dirlist():
return os.listdir(path='.')
print(files_and_dirlist())<file_sep>/python/week1/day3/math_quiz.py
import random
import datetime
class Questions:
text = None
answer = None
class Add(Questions):
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
self.answer = arg1 + arg2
self.text = "{} + {} = ? ".format(arg1, arg2)
class Multiply(Questions):
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
self.answer = arg1 * arg2
self.text = "{} * {} = ? ".format(arg1, arg2)
class Subtract(Questions):
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
self.answer = arg1 - arg2
self.text = "{} - {} = ? ".format(arg1, arg2)
class TheQuiz:
question_list = [Add, Multiply, Subtract]
def __init__(self):
self.questions = [self.question_list[random.randint(0, 2)](random.randint(1, 10), random.randint(1, 10)) for i in range(16)]
def __iter__(self):
for q in self.questions:
yield q
def start(self):
"""Starts the timer"""
start = datetime.datetime.now()
return start
def stop(self, message="Total: "):
"""Stops the timer. Returns the time elapsed"""
stop = datetime.datetime.now()
return message + str(stop - self.start())
def start_quiz(self):
right_ans = 0
wrong_ans = 0
self.start()
for i in self.questions:
print(i.text)
try:
ans = int(input("Answer: > "))
except ValueError:
print("Not a number")
ans = None
if ans == i.answer:
right_ans += 1
else:
wrong_ans += 1
print(self.stop())
qu1 = TheQuiz()
qu1.start_quiz()
<file_sep>/prep_work/music_player.js
function Player() {
this.tracks = [];
this.currentTrack = 0;
};
function Track(artist, title, album) {
this.artist = artist;
this.title = title;
this.album = album;
}
Player.prototype.add = function(track) {
this.tracks.push(track);
}
Player.prototype.play = function() {
console.log("Playing: " + this.tracks[this.currentTrack].title +
" by " + this.tracks[this.currentTrack].artist);
}
Player.prototype.next = function() {
if (this.currentTrack < this.tracks.length-1) {
this.currentTrack += 1;
} else {
console.log("Error: no more tracks to play!");
}
}
Player.prototype.previous = function() {
if (this.currentTrack > 0) {
this.currentTrack -= 1;
} else {
console.log("Error: no more tracks to play!");
}
}
var player = new Player();
var driveTrack = new Track('Incubus', 'Drive', 'Make Yourself');
var laBambaTrack = new Track('<NAME>', 'La Bamba', 'La Bamba');
player.add(driveTrack);
player.play();
player.add(laBambaTrack);
player.next();
player.play();
player.next();
player.previous();
player.play();
player.previous();
player.previous();
|
6c47a070436f2c0ab669120330dd70e9a460b1d3
|
[
"JavaScript",
"Python",
"Markdown"
] | 38 |
Python
|
sophialittlejohn/propulsion_bootcamp
|
10c0744e5b3e59c69c59dafc49594cf51ac32b2a
|
b03a4526c46daa2ee9c261e49e06087ca1a25660
|
refs/heads/master
|
<repo_name>pranalini/django1<file_sep>/rango/models.py
from django.db import models
from rango.models import Category
# Create your models here.
class Category(models.Model):
names = models.CharField(max_length=128, unique=True) #what type
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
class Meta:
verbous_name_plural = 'Catagories'
def __str__(self): # For Python 2, use __unicode__ too
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __str__(self): # For Python 2, use __unicode__ too
return self.title
|
332f08b31cf73a9779d11d390791a94fee0a84ff
|
[
"Python"
] | 1 |
Python
|
pranalini/django1
|
90ba9c47b7c1aa2045bb744ab20607099e168d1a
|
af8c2b2946f8f7bc7200d987d6046dd646b4e19e
|
refs/heads/master
|
<repo_name>zukhra-dotcom/Bridge_Pattern_Zukhra_Umarova<file_sep>/src/com/company/Main.java
package com.company;
public class Main {
public static void main(String[] args) {
Discipline [] disciplines = {
new AdvancedJava(new SoftwareEngineer()),
new LinearAlgebra(new Cybersecurity())
};
for(Discipline discipline: disciplines){
discipline.studyDisciplines();
}
}
}
|
11a6c89066406833bd3c56b88adc3a753dd0b231
|
[
"Java"
] | 1 |
Java
|
zukhra-dotcom/Bridge_Pattern_Zukhra_Umarova
|
ac0e98052d77cd9c44d2d23837cc4f501ba01244
|
b6ea1225bd236268412b8b1909cdb7799410f1dc
|
refs/heads/master
|
<file_sep>package mx.tec.algebravectores
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.Spinner
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val arr= arrayOf(
doubleArrayOf( 1.0, 2.0, -1.0, 0.0),
doubleArrayOf( 2.0, 3.0, -1.0, 0.0),
doubleArrayOf(-2.0, 0.0, -3.0, 0.0)
)
val btnIniciar = findViewById<Button>(R.id.btnIniciar)
val spinnerK = findViewById<Spinner>(R.id.spinnerK)
val spinnerR = findViewById<Spinner>(R.id.spinnerR)
var datos1= arrayListOf("1", "2", "3", "4")
var datos3= arrayListOf("R2", "R3")
val adaptador1 = ArrayAdapter(this@MainActivity,
android.R.layout.simple_spinner_dropdown_item, datos1
)
val adaptador3 = ArrayAdapter(this@MainActivity,
android.R.layout.simple_spinner_dropdown_item, datos3
)
spinnerK.adapter = adaptador1
spinnerR.adapter = adaptador3
btnIniciar.setOnClickListener{
var seleccion1 = spinnerK.selectedItem.toString()
var seleccion3 = spinnerR.selectedItem.toString()
var r = ""
if(seleccion3.equals("R2")){
r="2"
}
if(seleccion3.equals("R3")){
r="3"
}
val i = Intent(this@MainActivity, MainActivity3::class.java)
i.putExtra("param1", seleccion1)
i.putExtra("param2", r)
startActivity(i)
}
}
}<file_sep>package mx.tec.algebravectores
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.widget.EditText
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
class MainActivity3 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main3)
setSupportActionBar(findViewById(R.id.toolbar))
//Matriz de ejemplo de como se guarda en memoria la matriz
val matriz = arrayOf(
doubleArrayOf( 1.0, 2.0, -1.0, -4.0, 0.0),
doubleArrayOf( 2.0, 3.0, -1.0, -11.0, 0.0),
doubleArrayOf(-2.0, 0.0, -3.0, 22.0, 0.0)
)
var k = intent.getStringExtra("param1").toString().toInt() //variable que guarda la cantidad de vectores a ingresar.
val r = intent.getStringExtra("param2").toString().toInt() //variable para tomar el valor de Rn
k+=1
val listaVectores = arrayListOf<EditText>() //lista de inputs
val listadoble = Array(r) { DoubleArray(k) } //matriz de vectores
val constraintLayout = findViewById(R.id.constraintLayout) as ConstraintLayout
val cont = 120F
var id = 0
var vv=0F
//Los siguientes for anidados son para generar los inputs para escribir los vectores.
for(item in 1..r) {
for (item1 in 1..k) {
val bot = EditText(this@MainActivity3)
bot.inputType = InputType.TYPE_CLASS_DATETIME+InputType.TYPE_NUMBER_FLAG_SIGNED + InputType.TYPE_NUMBER_FLAG_DECIMAL + InputType.TYPE_CLASS_NUMBER + InputType.TYPE_DATETIME_VARIATION_TIME
bot.layoutParams = ConstraintLayout.LayoutParams(
ConstraintLayout.LayoutParams.WRAP_CONTENT,
ConstraintLayout.LayoutParams.WRAP_CONTENT
)
bot.translationX = 40F + cont * (item1 + 1)
bot.translationY = 400F+vv
bot.layoutParams.width = 100
bot.id = id
Log.e("ID", bot.id.toString())
constraintLayout.addView(bot)
id+=1
listaVectores.add(bot)
}
vv+=100F
}
var resultado = ""
findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { view ->
if(k-1<=r) {
var tamanoMatriz = 0
//for para guardar en una matriz tipo de dato Double, los datos que se ingresaron en los inputs. Para posteriormente usar operaciones.
for (item in 0..r - 1) {
for (item1 in 0..k - 1) {
//Condición para aceptar las fracciones
if (listaVectores.get(tamanoMatriz).text.contains("/")) {
val opera = listaVectores.get(tamanoMatriz).text.split("/")
Log.e("OPERA", opera.toString())
Log.e("PRIMER OPERA", opera[0].toString())
Log.e("SEGUNDO OPERA", opera[1].toString())
var resultado = 0.00
resultado = opera[0].toString().toDouble() / opera[1].toString().toDouble()
resultado.toString().toDouble()
Log.e("Resultado", resultado.toString())
listadoble[item][item1] = resultado
} else {
listadoble[item][item1] = listaVectores.get(tamanoMatriz).text.toString().toDouble()
}
tamanoMatriz++
}
}
for (r in 0 until listadoble.size) {
for (c in 0 until listadoble[0].size) {
if (listadoble[r][c] == -0.0) listadoble[r][c] =
0.0 // get rid of negative zeros
print("${"% 6.2f".format(listadoble[r][c])} ")
}
println()
}
//Mandamos a llamar el metodo para reducir la matriz y le enviamos la matriz original
toReducedRowEchelonForm(listadoble)
for (r in 0 until listadoble.size) {
for (c in 0 until listadoble[0].size) {
if (listadoble[r][c] == -0.0) listadoble[r][c] =
0.0 // get rid of negative zeros
print("${"% 6.2f".format(listadoble[r][c])} ")
}
println()
}
var suma1 = 0.0
var suma2 = 0.0
for (i in 0 until listadoble.size) {
for (n in 0 until listadoble[0].size) {
suma1 = suma1 + listadoble[i][n]
}
}
for (i in 0 until listadoble[0].size - 1) {
suma2 = suma2 + listadoble[i][i]
}
Log.e("K", (k - 1).toString())
Log.e("Suma matriz", suma1.toString())
Log.e("Suma matriz", suma2.toString())
//Condición para determinar si es independiente
if (suma1 == k - 1.toDouble() && suma2 == k - 1.toDouble()) {
resultado = "Es linealmente independiente"
} else {
resultado = "Es linealmente dependiente"
}
}else{
resultado="Es linealmente dependiente porque el número de vectores es mayor a Rn"
}
//Funcionalidad para cuando le das click al botón para que te indique si tu matriz es linealmente independiente o independiente, y te regresa al inicio.
Snackbar.make(view, resultado, Snackbar.LENGTH_LONG)
.setAction("Back"){
val i = Intent(this@MainActivity3, MainActivity::class.java)
i.flags= Intent. FLAG_ACTIVITY_CLEAR_TASK or
Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(i)
}.show()
}
}
//Función que realizará las operaciones para llevar la matriz a la reducida.
private fun toReducedRowEchelonForm(arr:Array<DoubleArray>) {
var lead = 0
val rowCount = arr.size //toma el tamaño de las filas
val colCount = arr[0].size //toma el tamaño del primer vector que son las columnas
for (r in 0 until rowCount) { //desde 0 hasta cada fila recorre la matriz
if (colCount <= lead) return //se regresa si es menor igual a lead
var i = r //variable que lleva el control del for
while (arr[i][lead] == 0.0) {
i++
if (rowCount == i) {
i = r
lead++
if (colCount == lead) return
}
}
val temp = arr[i]
arr[i] = arr[r]
arr[r] = temp
//Multiplicación
if (arr[r][lead] != 0.0) {
val div = arr[r][lead]
for (j in 0 until colCount) arr[r][j] /= div
}
//División
for (k in 0 until rowCount) {
if (k != r) {
val mult = arr[k][lead]
for (j in 0 until colCount) arr[k][j] -= arr[r][j] * mult
}
}
lead++
}
}
}
<file_sep>package mx.tec.algebravectores
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.InputType.TYPE_CLASS_NUMBER
import android.util.Log
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
class MainActivity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
val btnReIniciar = findViewById<Button>(R.id.btnReIniciar)
btnReIniciar.setOnClickListener{
val i = Intent(this@MainActivity2, MainActivity::class.java)
i.flags= Intent. FLAG_ACTIVITY_CLEAR_TASK or
Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(i)
}
}
}
|
0adf81cc68d2fcb71a778a800d6e37878c90e3e4
|
[
"Kotlin"
] | 3 |
Kotlin
|
k-atara/AlgebraVectores
|
c5ccefbc41dc06c39deaae753187f3e984010164
|
8f19b321d8747e08bf956b81a3c9e650fa0b281e
|
refs/heads/master
|
<file_sep><h2>New <span class='muted'>Name</span></h2>
<br>
<?php echo render('name/_form'); ?>
<p><?php echo Html::anchor('name', 'Back'); ?></p>
<file_sep><h2>Viewing <span class='muted'>#<?php echo $name->id; ?></span></h2>
<p>
<strong>Name:</strong>
<?php echo $name->name; ?></p>
<?php echo Html::anchor('name/edit/'.$name->id, 'Edit'); ?> |
<?php echo Html::anchor('name', 'Back'); ?><file_sep><?php
class Controller_Name extends Controller_Template
{
public function action_index()
{
$data['names'] = Model_Name::find('all');
$this->template->title = "Names";
$this->template->content = View::forge('name/index', $data);
}
public function action_view($id = null)
{
is_null($id) and Response::redirect('name');
if ( ! $data['name'] = Model_Name::find($id))
{
Session::set_flash('error', 'Could not find name #'.$id);
Response::redirect('name');
}
$this->template->title = "Name";
$this->template->content = View::forge('name/view', $data);
}
public function action_create()
{
if (Input::method() == 'POST')
{
$val = Model_Name::validate('create');
if ($val->run())
{
$name = Model_Name::forge(array(
'name' => Input::post('name'),
));
if ($name and $name->save())
{
Session::set_flash('success', 'Added name #'.$name->id.'.');
Response::redirect('name');
}
else
{
Session::set_flash('error', 'Could not save name.');
}
}
else
{
Session::set_flash('error', $val->error());
}
}
$this->template->title = "Names";
$this->template->content = View::forge('name/create');
}
public function action_edit($id = null)
{
is_null($id) and Response::redirect('name');
if ( ! $name = Model_Name::find($id))
{
Session::set_flash('error', 'Could not find name #'.$id);
Response::redirect('name');
}
$val = Model_Name::validate('edit');
if ($val->run())
{
$name->name = Input::post('name');
if ($name->save())
{
Session::set_flash('success', 'Updated name #' . $id);
Response::redirect('name');
}
else
{
Session::set_flash('error', 'Could not update name #' . $id);
}
}
else
{
if (Input::method() == 'POST')
{
$name->name = $val->validated('name');
Session::set_flash('error', $val->error());
}
$this->template->set_global('name', $name, false);
}
$this->template->title = "Names";
$this->template->content = View::forge('name/edit');
}
public function action_delete($id = null)
{
is_null($id) and Response::redirect('name');
if ($name = Model_Name::find($id))
{
$name->delete();
Session::set_flash('success', 'Deleted name #'.$id);
}
else
{
Session::set_flash('error', 'Could not delete name #'.$id);
}
Response::redirect('name');
}
}
<file_sep><?php
// Bootstrap the framework DO NOT edit this
require COREPATH.'bootstrap.php';
Autoloader::add_classes(array(
// Add classes you want to override here
// Example: 'View' => APPPATH.'classes/view.php',
));
// Register the autoloader
Autoloader::register();
/**
* Your environment. Can be set to any of the following:
*
* Fuel::DEVELOPMENT
* Fuel::TEST
* Fuel::STAGING
* Fuel::PRODUCTION
*/
Fuel::$env = (isset($_SERVER['FUEL_ENV']) ? $_SERVER['FUEL_ENV'] : Fuel::DEVELOPMENT);
// Initialize the framework with the config file.
Fuel::init('config.php');
$cleardb = parse_url(getenv('CLEARDB_DATABASE_URL'));
Log::warning("Settings ClearDB...");
Config::load('db', 'db');
$dsn = sprintf("mysql:host=%s; dbname=%s; unix_socket=/var/run/mysqld/mysqld.sock", $cleardb['host'], substr($cleardb['path'], 1));
Log::warning("db.default.connection.dsn = ".$dsn);
Config::set('db.default.connection.dsn', $dsn);
Config::set('db.default.connection.username', $cleardb['user']);
Log::warning("db.default.connection.hostname = ".$cleardb['user']);
Config::set('db.default.connection.password', $cleardb['pass']);
Log::warning("db.default.connection.hostname = ".$cleardb['pass']);
Config::save('db', 'db');
Log::warning( print_r(Config::get('db'), true) );
<file_sep><h2>Viewing <span class='muted'>#<?php echo $HelloWorld->id; ?></span></h2>
<?php echo Html::anchor('helloworld/edit/'.$HelloWorld->id, 'Edit'); ?> |
<?php echo Html::anchor('helloworld', 'Back'); ?><file_sep><h2>Editing <span class='muted'>Name</span></h2>
<br>
<?php echo render('name/_form'); ?>
<p>
<?php echo Html::anchor('name/view/'.$name->id, 'View'); ?> |
<?php echo Html::anchor('name', 'Back'); ?></p>
<file_sep><?php
class Controller_HelloWorld extends Controller_Template
{
public function action_index()
{
$data['HelloWorlds'] = Model_HelloWorld::find('all');
$this->template->title = "HelloWorlds";
$this->template->content = View::forge('helloworld/index', $data);
}
public function action_view($id = null)
{
is_null($id) and Response::redirect('helloworld');
if ( ! $data['HelloWorld'] = Model_HelloWorld::find($id))
{
Session::set_flash('error', 'Could not find HelloWorld #'.$id);
Response::redirect('helloworld');
}
$this->template->title = "HelloWorld";
$this->template->content = View::forge('helloworld/view', $data);
}
public function action_create()
{
if (Input::method() == 'POST')
{
$val = Model_HelloWorld::validate('create');
if ($val->run())
{
$HelloWorld = Model_HelloWorld::forge(array(
));
if ($HelloWorld and $HelloWorld->save())
{
Session::set_flash('success', 'Added HelloWorld #'.$HelloWorld->id.'.');
Response::redirect('helloworld');
}
else
{
Session::set_flash('error', 'Could not save HelloWorld.');
}
}
else
{
Session::set_flash('error', $val->error());
}
}
$this->template->title = "Helloworlds";
$this->template->content = View::forge('helloworld/create');
}
public function action_edit($id = null)
{
is_null($id) and Response::redirect('helloworld');
if ( ! $HelloWorld = Model_HelloWorld::find($id))
{
Session::set_flash('error', 'Could not find HelloWorld #'.$id);
Response::redirect('helloworld');
}
$val = Model_HelloWorld::validate('edit');
if ($val->run())
{
if ($HelloWorld->save())
{
Session::set_flash('success', 'Updated HelloWorld #' . $id);
Response::redirect('helloworld');
}
else
{
Session::set_flash('error', 'Could not update HelloWorld #' . $id);
}
}
else
{
if (Input::method() == 'POST')
{
Session::set_flash('error', $val->error());
}
$this->template->set_global('HelloWorld', $HelloWorld, false);
}
$this->template->title = "HelloWorlds";
$this->template->content = View::forge('helloworld/edit');
}
public function action_delete($id = null)
{
is_null($id) and Response::redirect('helloworld');
if ($HelloWorld = Model_HelloWorld::find($id))
{
$HelloWorld->delete();
Session::set_flash('success', 'Deleted HelloWorld #'.$id);
}
else
{
Session::set_flash('error', 'Could not delete HelloWorld #'.$id);
}
Response::redirect('helloworld');
}
}
<file_sep><h2>Editing <span class='muted'>HelloWorld</span></h2>
<br>
<?php echo render('helloworld/_form'); ?>
<p>
<?php echo Html::anchor('helloworld/view/'.$HelloWorld->id, 'View'); ?> |
<?php echo Html::anchor('helloworld', 'Back'); ?></p>
|
73dbb1254d49b8e51d7ce3ebe54b869c9015e2e0
|
[
"PHP"
] | 8 |
PHP
|
miyahira/fuelphp_test
|
65003c78e705e9f240d2b0828812ac241e124c11
|
a30c94992c1232621938206879db079b035ec3ba
|
refs/heads/master
|
<repo_name>KrasnovaElizaveta/project.github.io<file_sep>/js/controller.js
"use strict"
let model = {
items: [
{
email: "<EMAIL>",
play: false,
error: false,
count: 0
}
]
},
keyCodes = {
comma: 188,
slash: 191,
enter: 13,
ctrlPlusV: 17
}
const myApp = angular.module("myApp", [])
myApp
.directive('emailsEditor', function () {
return {
template:
`<div class="emails-editor">
<div class="box" ng-repeat="item in emailBox.items" ng-class="item.error==true ? 'error':''">
<span ng-bind="item.email"></span>
<input class="checkbox" type="checkbox" ng-model="item.play" />
<label for="checkbox" ng-click="deleteEmails(item)"></label>
</div>
<input class="input" type="text" placeholder="add more people ..." ng-model="emailText" ng-keyup="keyUp()" ng-blur="inputBlur()" />
</div>`,
}
})
.controller("jsController", ['$scope', function ($scope) {
$scope.emailBox = model
$scope.deleteEmails = text => {
for (let i = 0; i < $scope.emailBox.items.length; i++) {
if (text.email === $scope.emailBox.items[i].email)
$scope.emailBox.items.splice(i, 1)
}
}
$scope.addEmails = (email = $scope.generateRandom(), error = false) => {
$scope.emailBox.items.push({
email,
play: false,
count: $scope.emailBox.items.length,
error
})
}
$scope.generateRandom = () => {
let str = "",
strRandom = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for (let i = 0 ; i < 7; i++)
str += strRandom.charAt(Math.floor(Math.random() * strRandom.length))
return str + <EMAIL>"
}
$scope.keyUp = () => {
let codeKey = event.keyCode
if (codeKey === keyCodes.enter
|| codeKey === keyCodes.slash
|| codeKey === keyCodes.comma
|| codeKey === keyCodes.ctrlPlusV)
{
if (codeKey === keyCodes.comma || codeKey === keyCodes.slash) {
let emailStr = $scope.emailText
$scope.emailText = emailStr.substring(0, emailStr.length - 1)
}
$scope.checkEmail($scope.emailText)
}
}
/*
* Если текстовое поле теряет фокус вызываем функцию проверки емэйла на корректность
* */
$scope.inputBlur = () => {
let text = $scope.emailText
if (text !== "")
$scope.checkEmail(text)
}
/*
* Проверка емэйла на корректность ввода и дальнейшее добавление в массив
* */
$scope.checkEmail = email => {
let check = /^[\w\.\d-_]+@[\w\.\d-_]+\.\w{2,4}$/i,
error = false
if (!check.test(email) || email === "")
error = true
$scope.addEmails(email,error)
$scope.emailText = ""
}
$scope.getEmailsCount = () => alert("Emails count " + $scope.emailBox.items.length)
}])<file_sep>/README.md
## npm install -g node-static
## static -p 8000
|
ac56ec5b432c4d2d53010994156b3867bdfbacb0
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
KrasnovaElizaveta/project.github.io
|
68ff0f2b6693a11eb8f2bfd2f67a1b86692ca8f8
|
8484569f633e4ac1d85a8b238245ac08500151e3
|
refs/heads/main
|
<repo_name>pavankalyan95/tastykitchn<file_sep>/src/components/RestaurantDetails/index.js
import {Component} from 'react'
import Cookies from 'js-cookie'
import Loader from 'react-loader-spinner'
import {FiStar} from 'react-icons/fi'
import {BiRupee} from 'react-icons/bi'
import Footer from '../Footer'
import NavHeader from '../NavHeader'
import FoodItems from '../FoodItems'
import './index.css'
const apiStatusConstants = {
initial: 'INITIAL',
success: 'SUCCESS',
failure: 'FAILURE',
inProgress: 'IN_PROGRESS',
}
class RestaurantDetails extends Component {
state = {
restaurantFoodData: [],
apiStatus: apiStatusConstants.initial,
restaurantInfo: {},
quantity: 1,
isBtnActive: true,
}
componentDidMount() {
this.getRestaurantData()
}
getBannerData = data => ({
id: data.id,
imageUrl: data.image_url,
rating: data.rating,
name: data.name,
costForTwo: data.cost_for_two,
cuisine: data.cuisine,
reviewsCount: data.reviews_count,
openAt: data.open_at,
location: data.location,
itemsCount: data.items_count,
})
getRestaurantData = async () => {
const {match} = this.props
const {params} = match
const {id} = params
this.setState({
apiStatus: apiStatusConstants.inProgress,
})
const jwtToken = Cookies.get('jwt_token')
const apiUrl = `https://apis.ccbp.in/restaurants-list/${id}`
const options = {
headers: {
Authorization: `Bearer ${jwtToken}`,
},
method: 'GET',
}
const response = await fetch(apiUrl, options)
if (response.ok) {
const fetchedData = await response.json()
const updatedBannerData = this.getBannerData(fetchedData)
const updatedRestaurantFoodDetails = fetchedData.food_items.map(each => ({
name: each.name,
cost: each.cost,
foodType: each.food_type,
imageUrl: each.image_url,
id: each.id,
}))
this.setState({
restaurantFoodData: updatedRestaurantFoodDetails,
restaurantInfo: updatedBannerData,
apiStatus: apiStatusConstants.success,
})
}
if (response.status === 404) {
this.setState({
apiStatus: apiStatusConstants.failure,
})
}
}
renderLoadingView = () => (
<div className="res-loader-container" testid="restaurant-details-loader">
<Loader type="Oval" color="#f7931e" height="50" width="50" />
</div>
)
renderRestaurantItemsDetailsView = () => {
const {
restaurantFoodData,
restaurantInfo,
quantity,
isBtnActive,
} = this.state
return (
<div className="restaurant-food-items-con" testid="foodItem">
<div className="restaurant-add-con">
<div className="hotel-main-img">
<img
className="restaurant-pic"
alt="restaurant"
src={restaurantInfo.imageUrl}
/>
<div className="res-address-con">
<h1 className="res-head">{restaurantInfo.name}</h1>
<p className="res-food-type">{restaurantInfo.cuisine}</p>
<p className="res-address">{restaurantInfo.location}</p>
<div className="rating-cost-con">
<div className="rating-con-ratings">
<div>
<div className="overall-rating-con">
<FiStar className="add-star" />
<p className="rating">{restaurantInfo.rating}</p>
</div>
<div className="total-ratings-container">
<p className="count-of-ratings">
{restaurantInfo.reviewsCount} +
</p>
<p className="reviews-count-para">Ratings</p>
</div>
</div>
<hr className="vr-line" />
<div>
<div className="price-of-two-container">
<div className="cost-for-two-con">
<BiRupee className="rupee-symbol" />
<p className="money">{restaurantInfo.costForTwo}</p>
</div>
<p className="cost-for-two-para">Cost for two</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<ul className="food-items-list">
{restaurantFoodData.map(each => (
<FoodItems
foodItems={each}
key={each.id}
isBtnActive={isBtnActive}
quantity={quantity}
restaurantInfo={restaurantInfo}
/>
))}
</ul>
</div>
)
}
renderRestaurantMenuDetails = () => {
const {apiStatus} = this.state
switch (apiStatus) {
case apiStatusConstants.success:
return this.renderRestaurantItemsDetailsView()
case apiStatusConstants.inProgress:
return this.renderLoadingView()
default:
return null
}
}
render() {
const {match} = this.props
const {params} = match
const {id} = params
return (
<>
<NavHeader resId={id} />
<div className="restaurant-item-details-container" testid="foodItem">
{this.renderRestaurantMenuDetails()}
</div>
<Footer />
</>
)
}
}
export default RestaurantDetails
<file_sep>/src/components/NotFound/index.js
import {Link} from 'react-router-dom'
import NavHeader from '../NavHeader'
import './index.css'
const NotFound = () => (
<>
<NavHeader />
<div className="not-found-container">
<img
src="https://res.cloudinary.com/dli8bxrdu/image/upload/v1635583346/Layer_1_requn8.png"
alt="not found"
className="not-found-img"
/>
<h1 className="page-not-found-head">Page Not Found</h1>
<p className="page-not-found-para">
we are sorry, the page you requested could not be found. Please go back
to the homepage
</p>
<Link to="/" className="nav">
<button className="not-found-page-btn" type="button">
Home Page
</button>
</Link>
</div>
</>
)
export default NotFound
<file_sep>/src/components/Cart/index.js
import {Component} from 'react'
import NavHeader from '../NavHeader'
import EmptyCartView from '../EmptyCartView'
import CartListView from '../CartListView'
import CartSummary from '../CartSummary'
import PlaceOrder from '../PlaceOrder'
import Footer from '../Footer'
import './index.css'
class Cart extends Component {
state = {
isOrderPlaced: false,
}
updateOrderStatus = val => {
this.setState({isOrderPlaced: val})
}
render() {
const {isOrderPlaced} = this.state
const reUpdateOrderStatus = val => {
this.updateOrderStatus(val)
}
const getLocalData = localStorage.getItem('cartData')
const parsedLocalData = JSON.parse(getLocalData)
let showEmptyView = 0
if (parsedLocalData === null) {
showEmptyView = 0
} else {
showEmptyView = parsedLocalData.length
}
return (
<>
<NavHeader />
{isOrderPlaced ? (
<PlaceOrder reUpdateOrderStatus={reUpdateOrderStatus} />
) : (
<>
{showEmptyView === 0 ? (
<EmptyCartView />
) : (
<div className="cart-container">
<div className="cart-conn">
<div className="cart-content-container" testid="cartItem">
<div className="cart-titles-con">
<h1 className="cart-hea-1">Item</h1>
<h1 className="cart-hea-2">Quantity</h1>
<h1 className="cart-hea-3">Price</h1>
</div>
<CartListView />
<hr className="hr-line" />
<CartSummary updateOrderStatus={this.updateOrderStatus} />
</div>
</div>
<Footer />
</div>
)}
</>
)}
</>
)
}
}
export default Cart
<file_sep>/src/components/CartItem/index.js
import {BsPlusSquare, BsDashSquare} from 'react-icons/bs'
import {BiRupee} from 'react-icons/bi'
import CartContext from '../../context/CartContext'
import './index.css'
const CartItem = props => (
<CartContext.Consumer>
{value => {
const {incrementCartItemQuantity, decrementCartItemQuantity} = value
const {cartItemDetails} = props
const {id, name, quantity, cost, imageUrl} = cartItemDetails
const onClickDecrement = () => {
decrementCartItemQuantity(id)
}
const onClickIncrement = () => {
incrementCartItemQuantity(id)
}
const totalPrice = cost * quantity
return (
<li className="cart-item">
<div className="img-and-title-con-for-small">
<div className="cart-restaurant-img">
<img className="cart-food-image" src={imageUrl} alt={imageUrl} />
<div className="cart-food-title-container">
<h1 className="cart-food-title">{name}</h1>
</div>
</div>
<div className="cart-quantity-container">
<div className="cart-food-title-container-for-small">
<h1 className="cart-food-title">{name}</h1>
</div>
<div className="increase-dec-btn">
<button
type="button"
className="quantity-controller-button"
testid="decrement-quantity"
onClick={onClickDecrement}
>
<BsDashSquare color="#52606D" size={28} />
</button>
<p className="cart-quantity" testid="item-quantity">
{quantity}
</p>
<button
type="button"
className="quantity-controller-button"
testid="increment-quantity"
onClick={onClickIncrement}
>
<BsPlusSquare color="#52606D" size={28} />
</button>
</div>
<div className="total-price-display-container">
<BiRupee color="#FFA412" size={16} />
<p className="cart-total-price" testid="total-price">
{totalPrice}
</p>
</div>
</div>
</div>
<div className="img-and-title-con-for-large-devices">
<div className="cart-restaurant-img-con-for-large">
<img className="cart-food-image" src={imageUrl} alt={imageUrl} />
<div className="cart-food-title-container">
<h1 className="cart-food-title">{name}</h1>
</div>
</div>
<div className="cart-quantity-container-for-large">
<button
type="button"
className="quantity-controller-button"
testid="decrement-quantity"
onClick={onClickDecrement}
>
<BsDashSquare color="#52606D" size={28} />
</button>
<p className="cart-quantity" testid="item-quantity">
{quantity}
</p>
<button
type="button"
className="quantity-controller-button"
testid="increment-quantity"
onClick={onClickIncrement}
>
<BsPlusSquare color="#52606D" size={28} />
</button>
</div>
<div className="total-price-display-container-for-large">
<BiRupee color="#FFA412" size={16} />
<p className="cart-total-price" testid="total-price">
{totalPrice}
</p>
</div>
</div>
</li>
)
}}
</CartContext.Consumer>
)
export default CartItem
<file_sep>/src/components/SortingOption/index.js
import './index.css'
const SortingOption = props => {
const {sortbyOptions} = props
return (
<option key={sortbyOptions.optionId} value={sortbyOptions.optionId}>
{sortbyOptions.displayText}
</option>
)
}
export default SortingOption
<file_sep>/src/components/NavHeader/index.js
import {Component} from 'react'
import {Link, withRouter} from 'react-router-dom'
import Cookies from 'js-cookie'
import {AiFillCloseCircle, AiOutlineMenu} from 'react-icons/ai'
import './index.css'
class NavHeader extends Component {
state = {
isNavOpen: false,
}
onClickLogout = () => {
const {history} = this.props
Cookies.remove('jwt_token')
history.replace('/login')
}
closeTheNav = () => {
this.setState({isNavOpen: false})
}
onClickOnMenu = () => {
this.setState({isNavOpen: true})
}
render() {
const {isNavOpen} = this.state
const {history, resId} = this.props
let stylingHome = ''
let stylingCart = ''
if (history.location.pathname === '/cart') {
stylingCart = 'cart-bg-change'
} else if (history.location.pathname === `/restaurant/${resId}`) {
stylingHome = 'home-bg-change'
} else if (history.location.pathname === '/') {
stylingHome = 'home-bg-change'
} else {
stylingHome = ''
stylingCart = ''
}
return (
<>
<nav className="nav-header">
<div className="nav-sub-con">
<div className="nav-barr-logo-container">
<Link to="/" className="nav-link">
<img
className="website-logo-l"
src="https://res.cloudinary.com/dli8bxrdu/image/upload/v1633955483/Group_7420_aua7rj.png"
alt="website logo"
/>
</Link>
<h1 className="head">Tasty Kitchens</h1>
</div>
<div className="content-nav">
<ul className="nav-menu">
<li className="nav-menu-item">
<Link to="/" className={`nav-link ${stylingHome}`}>
Home
</Link>
</li>
<li className="nav-menu-item">
<Link to="/cart" className={`nav-link ${stylingCart}`}>
Cart
</Link>
</li>
</ul>
<button
type="button"
className="logout-desktop-btn"
onClick={this.onClickLogout}
>
Logout
</button>
</div>
</div>
<div className="nav-view-for-mobile">
<div className="nav-head-logo-container">
<Link to="/" className="nav-link">
<img
className="website-logo-for-small"
src="https://res.cloudinary.com/dli8bxrdu/image/upload/v1633955483/Group_7420_aua7rj.png"
alt="website logo"
/>
</Link>
<h1 className="head">Tasty Kitchens</h1>
</div>
<button
className="menu-btn"
type="button"
onClick={this.onClickOnMenu}
>
<AiOutlineMenu />
</button>
</div>
</nav>
{isNavOpen && (
<div className="nav-con-for-small-devices">
<div className="content-nav-for-mobile">
<ul className="nav-menu">
<li className="nav-menu-item">
<Link to="/" className={`nav-link ${stylingHome}`}>
Home
</Link>
</li>
<li className="nav-menu-item">
<Link to="/cart" className={`nav-link ${stylingCart}`}>
Cart
</Link>
</li>
</ul>
<button
type="button"
className="logout-desktop-btn"
onClick={this.onClickLogout}
>
Logout
</button>
</div>
<button
className="close-btn"
type="button"
onClick={this.closeTheNav}
>
<AiFillCloseCircle />
</button>
</div>
)}
</>
)
}
}
export default withRouter(NavHeader)
<file_sep>/src/components/RestaurantItems/index.js
import {Link} from 'react-router-dom'
import {FiStar} from 'react-icons/fi'
import './index.css'
const RestaurantItems = props => {
const {eachHotel} = props
return (
<Link to={`/restaurant/${eachHotel.id}`} className="link-dec">
<li className="hotel-con" testid="restaurant-item">
<img
className="hotel-img"
src={eachHotel.imageUrl}
alt={eachHotel.name}
/>
<div className="restaurant-name-con">
<h1 className="res-name">{eachHotel.name}</h1>
<p className="food-type">{eachHotel.cuisine}</p>
<div className="rating-con">
<FiStar className="star-icon" />
<p className="rating-num">{eachHotel.userRating.rating}</p>
<p className="rating-count">
({eachHotel.userRating.totalReviews})
</p>
</div>
</div>
</li>
</Link>
)
}
export default RestaurantItems
<file_sep>/src/components/ReactSlick/index.js
import Slider from 'react-slick'
import Loader from 'react-loader-spinner'
import 'slick-carousel/slick/slick.css'
import 'slick-carousel/slick/slick-theme.css'
import './index.css'
const ReactSlick = props => {
const {offersList, apiStatus} = props
const renderLoadingView = () => (
<div className="images-loader-container" testid="restaurants-offers-loader">
<Loader type="Oval" color="#f7931e" height="50" width="50" />
</div>
)
const renderScrollingImages = () => {
const settings = {
dots: true,
autoplay: true,
}
return (
<div>
<Slider {...settings}>
{offersList.map(each => (
<div key={each.id}>
<img className="cursole-fig" src={each.imageUrl} alt="offer" />
</div>
))}
</Slider>
</div>
)
}
return (
<>
{apiStatus === 'IN_PROGRESS'
? renderLoadingView()
: renderScrollingImages()}
</>
)
}
export default ReactSlick
<file_sep>/src/components/Home/index.js
import {Component} from 'react'
import Cookies from 'js-cookie'
import Loader from 'react-loader-spinner'
import {
BsArrowLeftSquare,
BsFilterRight,
BsArrowRightSquare,
} from 'react-icons/bs'
import SortingOption from '../SortingOption'
import ReactSlick from '../ReactSlick'
import RestaurantItems from '../RestaurantItems'
import Footer from '../Footer'
import NavHeader from '../NavHeader'
import './index.css'
const sortByOptions = [
{
id: 2,
displayText: 'Lowest',
value: 'Lowest',
},
{
id: 0,
displayText: 'Highest',
value: 'Highest',
},
]
const apiStatusConstants = {
initial: 'INITIAL',
success: 'SUCCESS',
failure: 'FAILURE',
inProgress: 'IN_PROGRESS',
}
class Home extends Component {
state = {
apiStatus: apiStatusConstants.initial,
restaurantList: [],
activeOptionId: sortByOptions[0].value,
pageCount: 1,
limitVal: 9,
offsetVal: 0,
offersList: [],
}
componentDidMount() {
this.getPopularRestaurants()
}
getRating = data => ({
totalReviews: data.total_reviews,
rating: data.rating,
})
getPopularRestaurants = async () => {
this.setState({
apiStatus: apiStatusConstants.inProgress,
})
const {activeOptionId, limitVal, offsetVal} = this.state
const apiUrlForOffers = 'https://apis.ccbp.in/restaurants-list/offers'
const jwtToken = Cookies.get('jwt_token')
const apiUrl = `https://apis.ccbp.in/restaurants-list?offset=${offsetVal}&limit=${limitVal}&sort_by_rating=${activeOptionId}`
const options = {
headers: {
Authorization: `Bearer ${jwtToken}`,
},
method: 'GET',
}
const response = await fetch(apiUrl, options)
const offersResponse = await fetch(apiUrlForOffers, options)
if (offersResponse.ok && response.ok) {
const fetchedOfferData = await offersResponse.json()
const updatedOffersData = fetchedOfferData.offers.map(each => ({
imageUrl: each.image_url,
id: each.id,
}))
const fetchedData = await response.json()
const updatedData = fetchedData.restaurants.map(each => ({
userRating: this.getRating(each.user_rating),
name: each.name,
costForTwo: each.cost_for_two,
cuisine: each.cuisine,
imageUrl: each.image_url,
menuType: each.menu_type,
id: each.id,
location: each.location,
}))
this.setState({
restaurantList: updatedData,
offersList: updatedOffersData,
apiStatus: apiStatusConstants.success,
})
} else {
this.setState({
apiStatus: apiStatusConstants.failure,
})
}
}
renderRestaurantItems = () => {
const {restaurantList} = this.state
return (
<div className="restaurants-container">
<ul className="unordered-restaurants-con">
{restaurantList.map(each => (
<RestaurantItems eachHotel={each} key={each.id} />
))}
</ul>
</div>
)
}
changeSortby = event => {
this.setState(
{activeOptionId: event.target.value},
this.getPopularRestaurants,
)
}
decreaseCount = () => {
const {pageCount, limitVal} = this.state
if (pageCount > 1) {
const offsetValue = (pageCount - 1) * limitVal
this.setState(
prevState => ({
pageCount: prevState.pageCount - 1,
offsetVal: offsetValue,
}),
this.getPopularRestaurants,
)
}
}
increaseCount = () => {
const {pageCount, limitVal} = this.state
if (pageCount < 20) {
const offsetValue = (pageCount - 1) * limitVal
this.setState(
prevState => ({
pageCount: prevState.pageCount + 1,
offsetVal: offsetValue,
}),
this.getPopularRestaurants,
)
}
}
renderLoadingView = () => (
<div
className="offer-images-loader-container"
testid="restaurants-list-loader"
>
<Loader type="Oval" color="#f7931e" height="50" width="50" />
</div>
)
renderAllRestaurants = () => {
const {apiStatus} = this.state
switch (apiStatus) {
case apiStatusConstants.success:
return this.renderRestaurantItems()
case apiStatusConstants.inProgress:
return this.renderLoadingView()
default:
return null
}
}
render() {
const {apiStatus, activeOptionId, pageCount, offersList} = this.state
return (
<>
<NavHeader />
<div className="home-container" testid="restaurant-item">
<ReactSlick apiStatus={apiStatus} offersList={offersList} />
<div className="home-content-con">
<div className="content">
<h1 className="home-main-head">Popular Restaurants</h1>
<div className="filter-container">
<p className="home-para">
Select Your favourite restaurant special dish and make your
day happy...
</p>
<div className="by-container">
<div className="sort-by-container">
<BsFilterRight className="sort-by-icon" />
<p className="sort-by">Sort by</p>
<select
className="sort-by-select"
onChange={this.changeSortby}
>
{sortByOptions.map(each => (
<SortingOption
key={each.id}
sortbyOptions={each}
activeOptionId={activeOptionId}
changeSortby={this.changeSortby}
/>
))}
</select>
</div>
</div>
</div>
</div>
</div>
<hr className="horizontal-line" />
<div className="all-res-container" testid="restaurant-item">
{this.renderAllRestaurants()}
</div>
<div className="pageCount-container">
<button
testid="pagination-left-button"
className="limit-btn"
type="button"
onClick={this.decreaseCount}
>
<BsArrowLeftSquare className="back-word-icon" />
</button>
<div className="active-num-con">
<p className="count-para" testid="active-page-number">
{pageCount}
</p>
<p className="count-para-2">of 20</p>
</div>
<button
testid="pagination-right-button"
className="limit-btn"
type="button"
onClick={this.increaseCount}
>
<BsArrowRightSquare className="back-word-icon" />
</button>
</div>
</div>
<Footer />
</>
)
}
}
export default Home
<file_sep>/src/App.js
import {Component} from 'react'
import {Route, Switch} from 'react-router-dom'
import ProtectedRoute from './components/ProtectedRoute'
import Login from './components/Login'
import Home from './components/Home'
import RestaurantDetails from './components/RestaurantDetails'
import CartContext from './context/CartContext'
import Cart from './components/Cart'
import NotFound from './components/NotFound'
import './App.css'
class App extends Component {
state = {
foodItemsList: [],
}
componentDidMount() {
this.fetchingLocalData()
}
updateState = () => {
const localData = JSON.parse(localStorage.getItem('cartData'))
if (localData !== null) {
this.setState({
foodItemsList: localData,
})
}
}
storeData = () => {
const {foodItemsList} = this.state
localStorage.setItem('cartData', JSON.stringify(foodItemsList))
}
addFoodItemToCart = foodItem => {
const {foodItemsList} = this.state
const foodItemObject = foodItemsList.find(
eachCartItem => eachCartItem.id === foodItem.id,
)
if (foodItemObject) {
this.setState(prevState => ({
foodItemsList: prevState.foodItemsList.map(eachCartItem => {
if (foodItemObject.id === eachCartItem.id) {
const updatedQuantity = eachCartItem.quantity + foodItem.quantity
return {...eachCartItem, quantity: updatedQuantity}
}
return eachCartItem
}),
}))
} else {
const updatedCartList = [...foodItemsList, foodItem]
this.setState({foodItemsList: updatedCartList})
}
}
changeActiveBtnStatus = id => {
this.setState(prevState => ({
foodItemsList: prevState.foodItemsList.map(eachCartItem => {
if (id === eachCartItem.id) {
return {...eachCartItem, isBtnActive: false}
}
return eachCartItem
}),
}))
}
incrementCartItemQuantity = id => {
this.setState(prevState => ({
foodItemsList: prevState.foodItemsList.map(eachCartItem => {
if (id === eachCartItem.id) {
const updatedQuantity = eachCartItem.quantity + 1
return {...eachCartItem, quantity: updatedQuantity}
}
return eachCartItem
}),
}))
}
decrementCartItemQuantity = id => {
const {foodItemsList} = this.state
const localData = JSON.parse(localStorage.getItem('cartData'))
if (localData.length === 1) {
localStorage.removeItem('cartData')
}
const foodItemObject = foodItemsList.find(
eachCartItem => eachCartItem.id === id,
)
if (foodItemObject.quantity > 1) {
this.setState(prevState => ({
foodItemsList: prevState.foodItemsList.map(eachCartItem => {
if (id === eachCartItem.id) {
const updatedQuantity = eachCartItem.quantity - 1
return {...eachCartItem, quantity: updatedQuantity}
}
return eachCartItem
}),
}))
} else {
this.removeCartItem(id)
}
}
removeCartItem = id => {
const {foodItemsList} = this.state
const updatedCartList = foodItemsList.filter(
eachCartItem => eachCartItem.id !== id,
)
this.setState({foodItemsList: updatedCartList})
}
fetchingLocalData = () => {
const {foodItemsList} = this.state
if (foodItemsList.length === 0) {
this.updateState()
}
}
render() {
const {foodItemsList} = this.state
if (foodItemsList.length !== 0) {
this.storeData()
}
return (
<CartContext.Provider
value={{
changeActiveBtnStatus: this.changeActiveBtnStatus,
addFoodItemToCart: this.addFoodItemToCart,
incrementCartItemQuantity: this.incrementCartItemQuantity,
decrementCartItemQuantity: this.decrementCartItemQuantity,
}}
>
<Switch>
<Route exact path="/login" component={Login} />
<ProtectedRoute exact path="/" component={Home} />
<ProtectedRoute
exact
path="/restaurant/:id"
component={RestaurantDetails}
/>
<ProtectedRoute exact path="/cart" component={Cart} />
<Route component={NotFound} />
</Switch>
</CartContext.Provider>
)
}
}
export default App
<file_sep>/src/context/CartContext.js
import React from 'react'
const CartContext = React.createContext({
addFoodItemToCart: () => {},
changeActiveBtnStatus: () => {},
incrementCartItemQuantity: () => {},
decrementCartItemQuantity: () => {},
})
export default CartContext
<file_sep>/src/components/Footer/index.js
import {
FaFacebookSquare,
FaTwitter,
FaInstagram,
FaPinterestSquare,
} from 'react-icons/fa'
import './index.css'
const Footer = () => (
<div className="footer-container">
<div className="for-small-screen">
<img
className="footer-img"
src="https://res.cloudinary.com/dli8bxrdu/image/upload/v1635656574/Group_7420_1_ziaxz3.png"
alt="website-footer-logo"
/>
<h1 className="footer-small-head">Tasty Kitchen</h1>
</div>
<h1 className="footer-head">Tasty Kitchen</h1>
<p className="footer-para">
The only thing we are serious about is food.
<br /> Contact us on
</p>
<div className="social-media-icons">
<FaPinterestSquare
className="social-icon-p"
testid="pintrest-social-icon"
/>
<FaInstagram className="instagram" testid="instagram-social-icon" />
<FaTwitter className="twitter" testid="twitter-social-icon" />
<FaFacebookSquare className="face-book" testid="facebook-social-icon" />
</div>
</div>
)
export default Footer
|
d7a0393025a669578f251b188632248856c5cde3
|
[
"JavaScript"
] | 12 |
JavaScript
|
pavankalyan95/tastykitchn
|
0e8656f9c1bf4c06376fae7607e93d54406a52f7
|
e7d753c1f16bd5d7ec91dfa790d6b4c91aff281a
|
refs/heads/master
|
<file_sep>import React from 'react/addons';
function context(Component, params) {
var context = React.createClass({
displayName: 'ContextWrapper',
childContextTypes: {
styles: React.PropTypes.object,
flux: React.PropTypes.object,
presenter: React.PropTypes.bool
},
getChildContext() {
let styles = {};
if (this.props.location.query && 'print' in this.props.location.query) {
styles = params.print;
} else {
styles = params.styles;
}
return {
styles: styles,
flux: params.flux,
presenter: this.props.location.query &&
'presenter' in this.props.location.query
};
},
render: function render() {
return <Component {...this.props} />;
}
});
return context;
}
export default context;<file_sep>import React from 'react/addons';
import assign from 'object-assign';
import tweenState from 'react-tween-state';
import _ from 'lodash';
const Appear = React.createClass({
mixins: [tweenState.Mixin],
contextTypes: {
flux: React.PropTypes.object,
router: React.PropTypes.object,
slide: React.PropTypes.number
},
getInitialState() {
return {
active: false,
opacity: 0
}
},
componentDidMount() {
let state = this.context.flux.stores.SlideStore.getState();
this.context.flux.stores.SlideStore.listen(this._storeChange);
let slide = 'slide' in this.context.router.state.params ?
this.context.router.state.params.slide : 0;
this.context.flux.actions.SlideActions.addFragment({
slide: slide,
id: this._reactInternalInstance._rootNodeID,
visible: false
});
},
componentWillUnmount() {
this.context.flux.stores.SlideStore.unlisten(this._storeChange);
},
_storeChange(state) {
let slide = 'slide' in this.context.router.state.params ?
this.context.router.state.params.slide : 0;
let key = _.findKey(state.fragments[slide], {
'id': this._reactInternalInstance._rootNodeID
});
if(state.fragments[slide].hasOwnProperty(key)) {
this.setState({
active: state.fragments[slide][key].visible
}, () => {
let endVal = this.state.active ? 1 : 0;
if (this.context.router.state.location.query &&
'export' in this.context.router.state.location.query) {
endVal = 1;
}
this.tweenState('opacity', {
easing: tweenState.easingTypes.easeInOutQuad,
duration: 300,
endValue: endVal
});
});
}
},
render() {
let styles = {
opacity: this.getTweeningValue('opacity')
}
return (
<div style={styles} className="appear">
{this.props.children}
</div>
)
}
});
export default Appear;
<file_sep>import React from 'react/addons';
import assign from 'object-assign';
import Radium from 'radium';
@Radium
class Layout extends React.Component {
render() {
let styles = {
display: 'flex'
};
return (
<div style={[styles]}>
{this.props.children}
</div>
)
}
}
export default Layout;<file_sep>import React from 'react/addons';
import assign from 'object-assign';
import Base from './base';
import Radium from 'radium';
@Radium
class List extends Base {
render() {
return (
<ul style={[this.context.styles.components.list, this.getStyles()]}>
{this.props.children}
</ul>
)
}
}
List.contextTypes = {
styles: React.PropTypes.object
}
export default List;<file_sep>import React from 'react/addons';
import assign from 'object-assign';
import Base from './base';
import Radium from 'radium';
@Radium
class Image extends Base {
render() {
let styles = {
width: this.props.width || "",
height: this.props.height || "",
display: this.props.display || ""
};
return (
<img src={this.props.src} style={[this.context.styles.components.image, this.getStyles(), styles]} />
);
}
}
Image.contextTypes = {
styles: React.PropTypes.object
}
export default Image;<file_sep>import React from 'react/addons';
import assign from 'object-assign';
import Base from './base';
import Radium from 'radium';
@Radium
class Code extends Base {
render() {
return (
<code style={[this.context.styles.components.code, this.getStyles()]}>
{this.props.children}
</code>
)
}
}
Code.contextTypes = {
styles: React.PropTypes.object
}
export default Code;
|
a12074406a2b2fbc16757d89e90f2ae72fc9de0e
|
[
"JavaScript"
] | 6 |
JavaScript
|
ricdex/spectacle
|
c55a60b05bf4942a7fb82880ae60395dc0768186
|
fb621016b5bd4a690ce18b0ca001bf79c5547aa5
|
refs/heads/master
|
<file_sep>export const environment = {
production: true,
firebase: {
apiKey: '<KEY>',
authDomain: 'ng-fitness-tracker-ec675.firebaseapp.com',
databaseURL: 'https://ng-fitness-tracker-ec675.firebaseio.com',
projectId: 'ng-fitness-tracker-ec675',
storageBucket: 'ng-fitness-tracker-ec675.appspot.com',
messagingSenderId: '458391142147'
}
};
|
ff426936237c0758081ab09eea676d6da33611c8
|
[
"TypeScript"
] | 1 |
TypeScript
|
devSamsane/training_fitness-tracker
|
7cdd55efec91cd763fda4a5f2a933f97f26cb30f
|
fe6faf3941691b5d83e87ec6bec62488a06ccbb2
|
refs/heads/master
|
<repo_name>alexeybobkov47/grpc-gateway-swagger-ui<file_sep>/readme.md
Поиск по ИНН:
http://localhost:8082/getInfo/{ИНН}
Swagger:
http://localhost:8083/
Makefile:
gen:
protoc -I=api/proto \
--go_out=. \
--go-grpc_out=. \
--grpc-gateway_out ./api/proto \
--grpc-gateway_opt logtostderr=true \
--grpc-gateway_opt paths=source_relative \
--grpc-gateway_opt grpc_api_configuration=api/proto/getInfo.yaml \
--openapiv2_out ./api/swagger \
--openapiv2_opt logtostderr=true \
--openapiv2_opt generate_unbound_methods=true \
api/proto/getInfo.proto
up:
docker-compose up
down:
docker-compose down
<file_sep>/go.mod
module github.com/alexeybobkov47/grpc-gateway-swagger-ui
go 1.17
require (
github.com/gocolly/colly v1.2.0
github.com/golang/protobuf v1.5.2
github.com/grpc-ecosystem/grpc-gateway v1.16.0
github.com/grpc-ecosystem/grpc-gateway/v2 v2.6.0
google.golang.org/grpc v1.40.0
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0
google.golang.org/protobuf v1.27.1
)
require (
github.com/PuerkitoBio/goquery v1.7.1 // indirect
github.com/andybalholm/cascadia v1.2.0 // indirect
github.com/antchfx/htmlquery v1.2.3 // indirect
github.com/antchfx/xmlquery v1.3.6 // indirect
github.com/antchfx/xpath v1.2.0 // indirect
github.com/ghodss/yaml v1.0.0 // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/golang/glog v1.0.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/kennygrant/sanitize v1.2.4 // indirect
github.com/saintfish/chardet v0.0.0-20120816061221-3af4cd4741ca // indirect
github.com/temoto/robotstxt v1.1.2 // indirect
golang.org/x/net v0.0.0-20210917221730-978cfadd31cf // indirect
golang.org/x/sys v0.0.0-20210917161153-d61c044b1678 // indirect
golang.org/x/text v0.3.7 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20210917145530-b395a37504d4 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
<file_sep>/internal/models/info.go
package models
// Info - struct for response.
type Info struct {
INN string
KPP string
CompanyName string
ChiefName string
}
<file_sep>/internal/parser/check-inn.go
package parser
import "strconv"
// checkINN - Checking INN for symbols and number of symbols.
func checkINN(inn string) bool {
const lengthINN = 10
if len(inn) != lengthINN {
return false
}
for _, n := range inn {
i, err := strconv.Atoi(string(n))
if err != nil || i < 0 || i > 9 {
return false
}
}
return true
}
<file_sep>/cmd/grpc-server/main.go
package main
import (
"context"
"log"
"net"
"os"
pb "github.com/alexeybobkov47/grpc-gateway-swagger-ui/api/proto"
p "github.com/alexeybobkov47/grpc-gateway-swagger-ui/internal/parser"
"google.golang.org/grpc"
)
var port = os.Getenv("GRPC_PORT")
type Service struct {
pb.UnimplementedGetInfoServer
p p.ParseInterface
}
func main() {
srv := grpc.NewServer()
s := &Service{p: &p.ParseImpl{}}
pb.RegisterGetInfoServer(srv, s)
listener, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
log.Printf("Starting server on %v", listener.Addr())
if err := srv.Serve(listener); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
func (s *Service) GetInfoByINN(ctx context.Context, req *pb.GetInfoRequest) (*pb.GetInfoResponse, error) {
info, err := s.p.ParsePage(req.Inn)
if err != nil {
return nil, err
}
return &pb.GetInfoResponse{
Inn: info.INN, Kpp: info.KPP, CompanyName: info.CompanyName,
ChiefName: info.ChiefName,
}, nil
}
<file_sep>/internal/parser/parser.go
package parser
import (
"fmt"
"strings"
"github.com/alexeybobkov47/grpc-gateway-swagger-ui/internal/models"
"github.com/gocolly/colly"
)
type ParseInterface interface {
ParsePage(url string) (*models.Info, error)
}
type ParseImpl struct{}
// ParsePage - parse single page and received information of company.
func (impl *ParseImpl) ParsePage(reqInn string) (*models.Info, error) {
if !checkINN(reqInn) {
return nil, fmt.Errorf("неправильный ИНН")
}
url := fmt.Sprintf("https://www.rusprofile.ru/search?query=%v", reqInn)
c := colly.NewCollector()
info := models.Info{}
c.OnHTML("#main", func(e *colly.HTMLElement) {
if e.Attr("itemtype") == "https://schema.org/Organization" {
info.CompanyName = e.ChildText("div.company-name")
info.CompanyName = strings.ReplaceAll(info.CompanyName, `"`, ``)
e.ForEach("div.leftcol", func(_ int, ee *colly.HTMLElement) {
texts := strings.Split(ee.Text, "\n")
for i, t := range texts {
t = strings.TrimSpace(t)
if t == "Руководитель" {
info.ChiefName = strings.TrimSpace(texts[i+2])
}
}
})
}
})
c.OnHTML("#clip_inn", func(e *colly.HTMLElement) {
info.INN = strings.TrimSpace(e.Text)
})
c.OnHTML("#clip_kpp", func(e *colly.HTMLElement) {
info.KPP = strings.TrimSpace(e.Text)
})
if err := c.Visit(url); err != nil {
return nil, err
}
if (models.Info{}) == info {
return nil, fmt.Errorf("ничего не найдено по этому ИНН")
}
return &info, nil
}
<file_sep>/Makefile
gen:
protoc -I=api/proto \
--go_out=. \
--go-grpc_out=. \
--grpc-gateway_out ./api/proto \
--grpc-gateway_opt logtostderr=true \
--grpc-gateway_opt paths=source_relative \
--grpc-gateway_opt grpc_api_configuration=api/proto/getInfo.yaml \
--openapiv2_out ./api/swagger \
--openapiv2_opt logtostderr=true \
--openapiv2_opt generate_unbound_methods=true \
api/proto/getInfo.proto
up:
docker-compose up
down:
docker-compose down
|
d9dcce004acabfc1412b61cdfce7847ab86b15b9
|
[
"Markdown",
"Go Module",
"Go",
"Makefile"
] | 7 |
Markdown
|
alexeybobkov47/grpc-gateway-swagger-ui
|
bc1241223cdde99acd612e5574d85836312e7eb1
|
a4455bd7d300a54423ddeef1e0af9ae5612deae7
|
refs/heads/master
|
<file_sep>package prj;
import prj.action.DefaultAction;
import prj.action.Search;
import prj.action.SelectPointAction;
import prj.action.SelectRegionAction;
import prj.action.SelectThemeAction;
public class CommandFactory {
//싱글톤패턴
private static CommandFactory instance ;
private CommandFactory() {}
public static CommandFactory getInstance() {
if(instance==null) {
instance= new CommandFactory();
}
return instance;
}
public IAction getAction(String command) {
IAction action =null;
switch (command) {
case "Search":
action = new Search();
break;
case "SelectRegion":
action = new SelectRegionAction();
break;
case "SelectTheme":
action = new SelectThemeAction();
break;
case "SelectPoint":
action = new SelectPointAction();
break;
//Command가 기본 값일 경우
case "DefaultAction":
default:
action= new DefaultAction();
break;
}
return action;
}
}
<file_sep># 아동급식카드(서울시 꿈나무카드) 가맹점 위치확인 지도
### 개요
1) 아동급식카드을 사용하기위해 가입된 가맹점을 찾기 힘듦
2) 기존 대형 편의점 같은 경우 카드사용 가능-> data제외
3) 일반음식점은 아동급식카드를 사용하기위한 단말기설치를 해야함 -> 가입한 가맹점을 찾기힘듦
4) 편의점에 집중된 식단개선을 위해 웹페이지 제작
### 주요 기능
1) 구별 가맹점 확인
2) 음식별 가맹점 확인
3) 검색기능
4) 내위치 확인
5) 가맹점 기본정보 확인(주소,전화번호,이름,음식점종류,데이터갱신일)
6) 가맹점 위치 로드뷰
### 홈페이지




### 사용 DB: postgresql
지리정보를 위해 사용
### 사용 data : 공공데이터포털 가입된 가맹점 정보
(편의점 제외 총 1857개)csv파일 -> Qgis이용 (포인트 기본 좌표설정) shp파일 생성 -> postgresql import
->geoserver 와 postgresql 연동
### 사용한 open api
geoserver, openlayers3, Kakao 로드뷰 API
### 테이블설계

### 포인트별 심볼설정
geoserver SLD 이용 tbl_coor 에 있는 테마별 분류 해당 테마에 맞는 심볼 이미지 추가.
<file_sep>
var roadviewContainer = document.getElementById('roadview'); //로드뷰를 표시할 div
var roadview = new kakao.maps.Roadview(roadviewContainer); //로드뷰 객체
var roadviewClient = new kakao.maps.RoadviewClient(); //좌표로부터 로드뷰 파노ID를 가져올 로드뷰 helper객체
var x = localStorage.getItem('x');
var y = localStorage.getItem('y');
var position = new kakao.maps.LatLng(x,y);
roadviewClient.getNearestPanoId(position, 50, function(panoId) {
roadview.setPanoId(panoId, position); //panoId와 중심좌표를 통해 로드뷰 실행
});
<file_sep>package prj;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface IAction {
public ActionForward execute(HttpServletResponse response, HttpServletRequest request)throws Exception;
}
<file_sep>package prj.datasource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
public static Connection getInstance() throws SQLException, ClassNotFoundException{
Class.forName("org.postgresql.Driver");
Connection conn;
//URL, ID, PASSWORD 통하여 postgresql에 연결
String DB_URL = "jdbc:postgresql://localhost:5432/DB_CAMPSITEWEB";
String DB_ID = "postgres";
String DB_PASSWORD = "<PASSWORD>";
conn = DriverManager.getConnection(DB_URL, DB_ID, DB_PASSWORD);
return conn;
}
}
<file_sep>
var rodeX;
var rodeY;
/**
* 지도의 포인트를 클릭했을 때 피쳐 정보창 불러옴
* @param feature
*/
function FeatureInfoLoad (feature) {
console.log(feature.get('cam_id'));
var postdata = {
'action': 'SelectPoint',
'cam_id': feature.get('cam_id')
};
$.ajax({
url: "DreamTree.do",
cache: false,
data: postdata,
}).done(function(data) {
$("#FeatureInfo").html(data);
$("#FeatureInfo").show();
});
/**포인트 클릭시 해당 포인트 x y값 저장 */
var x = feature.values_.coord_lat;
var y = feature.values_.coord_lon;
rodeX=x;
rodeY=y;
console.log(x);
console.log(y);
Storage();
}
/**로드뷰에 쓸 x y 값 사용자 localStorage 에 저장 */
function Storage(){
localStorage.setItem('x',rodeX);
localStorage.setItem('y',rodeY);
}
function FeatureInfoWndClose() {
$("#FeatureInfo").hide();
$("#FeatureInfo h3").text("-");
$("#FeatureInfo td").text("-");
}
/**테마선택*/
function selectTheme(themename){
var postdata={'action':'SelectTheme','theme':themename};
console.log(postdata)
$.ajax({
url: "DreamTree.do",
cache: false,
dataType:"json",
data: postdata,
}).done(function(data) {
console.log(data);
var count = data.length;
var strTemp="";
for(var i =0;i<count;i++){
strTemp+=data[i];
strTemp+=(i<(count-1)?',':'');
}
console.log(strTemp);
setGIDList(strTemp);
});
}
/**지역선택*/
function selectRegion(regionname){
var postdata={'action':'SelectRegion','region':regionname};
$.ajax({
url: "DreamTree.do",
cache: false,
dataType:"json",
data: postdata,
}).done(function(data) {
var count = data.length;
var strTemp="";
for(var i =0;i<count;i++){
strTemp+=data[i];
strTemp+=(i<(count-1)?',':'');
}
console.log(strTemp);
setGIDList(strTemp);
});
switch (regionname) {
case "강남구":
zoom2(37.495482,127.055236);
break;
case "강동구":
zoom2(37.550519, 127.145054);
break;
case "강북구":
zoom2(37.630808, 127.023788);
break;
case "관악구":
zoom2(37.468996, 126.942513);
break;
case "광진구":
zoom2(37.547363, 127.084756);
break;
case "구로구":
zoom2(37.495523, 126.850869);
break;
case "금천구":
zoom2(37.462493, 126.900779);
break;
case "노원구":
zoom2(37.651828, 127.073594);
break;
case "도봉구":
zoom2(37.665883, 127.034386);
break;
case "동대문구":
zoom2(37.581636, 127.054231);
break;
case "동작구":
zoom2(37.502150, 126.939400);
break;
case "마포구":
zoom2(37.559166, 126.904047);
break;
case "서초구":
zoom2(37.470801, 127.032926);
break;
case "성동구":
zoom2(37.550258, 127.041821);
break;
case "성북구":
zoom2(37.599608, 127.017968);
break;
case "송파구":
zoom2(37.504318, 127.116535);
break;
case "양천구":
zoom2(37.519371, 126.856099);
break;
case "영등포구":
zoom2(37.519421, 126.911761);
break;
case "용산구":
zoom2(37.530860, 126.980624);
break;
case "은평구":
zoom2(37.616561, 126.924039);
break;
case "종로구":
zoom2(37.589535, 126.971528);
break;
case "중구":
zoom2(37.559987, 126.992191);
break;
case "중량구":
zoom2(37.597547, 127.092652);
break;
default:
break;
}
}
/**검색*/
function SearchSubmit()
{
var x = document.getElementById("searchtitle").value;
var postdata={'action':'Search','title':x};
console.log(postdata)
$.ajax({
url: "DreamTree.do",
cache: false,
dataType:"json",
data: postdata,
}).done(function(data) {
console.log(data);
var count = data.length;
var strTemp="";
for(var i =0;i<count;i++){
strTemp+=data[i];
strTemp+=(i<(count-1)?',':'');
}
console.log(strTemp);
setGIDList(strTemp);
});
}
/**
* geolocation 컴퓨터 에서 사용 시 위치정보가 정확하지 않음 (오차범위 +-50m 이내)
*/
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "이 브라우저에서는 Geolocation이 지원되지 않습니다.";
}
}
function showPosition(position) {
var x = position.coords.latitude;
var y = position.coords.longitude;
var marker = new ol.Overlay
({
position:ol.proj.transform([y,x],'EPSG:4326','EPSG:3857'),
offset:[-10,-10],
element: $('<img src="images/gps.png" alt="사람" width="90" height="90">'),
stopEvent: false
});
map.addOverlay(marker);
//지도확대
var markerCoordinate = ol.proj.transform([y,x],'EPSG:4326','EPSG:3857');
var view = map.getView();
view.setCenter (markerCoordinate);
view.setZoom(17);
}
//서울전체지역확대
function zoom(){
var markerCoordinate = ol.proj.transform([127.039361,37.551226],'EPSG:4326','EPSG:3857');
var view = map.getView();
view.setCenter (markerCoordinate);
view.setZoom(12);
}
//구별확대 x y값 받아서 확대
function zoom2(x,y){
var markerCoordinate = ol.proj.transform([y,x],'EPSG:4326','EPSG:3857');
var view = map.getView();
view.setCenter (markerCoordinate);
view.setZoom(14);
}
/**
* 좌측 GNB 메뉴를 선택했을 때의 처리
* @param gnbid
*/
function gnbMenuSelect(gnbid) {
$(".leftContents.contents1").hide();
$(".leftContents.contents2").hide();
$(".leftContents.contents3").hide();
$(".leftContents.contents4").hide();
$(".leftContents.contents5").hide();
$("li.icon1").removeClass("selected");
$("li.icon2").removeClass("selected");
$("li.icon3").removeClass("selected");
$("li.icon4").removeClass("selected");
$("li.icon5").removeClass("selected");
switch (gnbid) {
case 1:
$(".leftContents.contents1").show();
$("li.icon1").addClass("selected");
zoom();
break;
case 2:
$(".leftContents.contents2").show();
$("li.icon2").addClass("selected");
zoom();
break;
case 3:
$(".leftContents.contents3").show();
$("li.icon3").addClass("selected");
break;
case 4:
$(".leftContents.contents4").show();
$("li.icon4").addClass("selected");
break;
case 5:
$(".leftContents.contents5").show();
$("li.icon5").addClass("selected");
getLocation();
break;
default:
$(".leftContents.contents1").show();
$("li.icon1").addClass("selected");
break;
}
}
$(document).ready(function(){
gnbMenuSelect(1); //페이지 로드시 1번 표시
});
/**
테이블 펴고 접기
*/
$(document).ready(function(){
$(".menu>a").click(function(){
var submenu = $(this).next("ul");
if( submenu.is(":visible") ){
submenu.slideUp();
}else{
submenu.slideDown();
}
});
});
<file_sep>package prj.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import prj.ActionForward;
import prj.IAction;
import prj.dao.DreamTreeDAO;
public class SelectRegionAction implements IAction {
@Override
public ActionForward execute(HttpServletResponse response, HttpServletRequest request) throws Exception {
String region =request.getParameter("region");
String result= null;
DreamTreeDAO dao = new DreamTreeDAO();
List<String> list_ID =dao.selectRegion(region);
Gson gson = new Gson();
result =gson.toJson(list_ID);
System.out.println("json(처리전):"+list_ID);
System.out.println("json(처리후):"+result);
ActionForward forward = new ActionForward();
request.setAttribute("output", result);
forward.setPath("/WEB-INF/view/json.jsp");
return forward;
}
}
|
a65c563c0866a020864dc3c9f12ec30aa3792efc
|
[
"Markdown",
"Java",
"JavaScript"
] | 7 |
Java
|
nadeda/Dream-tree-card
|
add3f8ec1a2820d3913693962c1c554506292836
|
83490f065369360b69b3a7b02e9c619614680126
|
refs/heads/main
|
<file_sep>const express = require('express');
const bodyParser = require('body-parser');
//embeded js
const ejs = require('ejs');
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy;
const findOrCreate = require('mongoose-findorcreate');
require('dotenv').config();
const app = express();
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(
session({
secret: 'secret.',
resave: false,
saveUninitialized: false,
})
);
app.use(passport.initialize());
app.use(passport.session());
////////////////////////////////////////connection////////////////////////////////////////////////////
//mongoose
mongoose.connect(
'mongodb+srv://reem97:<EMAIL>/db?retryWrites=true&w=majority', { useNewUrlParser: true }
);
mongoose.set('useCreateIndex', true);
////////////////////////////////schema//////////////////////////////////////
const userSchema = new mongoose.Schema({
username: String,
email: String,
password: String,
googleId: String,
facebookId: String,
secret: String,
value: String,
image: String,
provider: String,
});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model('User', userSchema);
passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
/////////////////////google authetication//////////////////////
passport.use(
new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: 'http://localhost:4000/auth/google/secrets',
userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
User.findOrCreate({
provider: profile.provider,
username: profile.displayName,
value: profile.photos.value,
googleId: profile.id,
email: profile._json.email
},
function(err, user) {
return cb(err, user);
}
);
}
)
);
////////////////////////////facebook authentication/////////////////////////////////
passport.use(
new FacebookStrategy({
clientID: process.env.CLIENT_ID_FB,
clientSecret: process.env.CLIENT_SECRET_FB,
callbackURL: 'http://localhost:4000/auth/facebook/secrets',
profileFields: ["email", "name"]
},
function(accessToken, refreshToken, profile, done) {
console.log(profile);
console.log(accessToken);
//mommken use destruction _json
User.findOrCreate({
provider: profile.provider,
facebookId: profile.id,
username: profile._json.first_name + ' ' +
profile._json.last_name,
email: profile._json.email
},
function(err, user) {
if (err) {
return done(err);
}
done(null, user);
}
);
}
)
);
////////////////////////////////////////////////////////////
app.get('/', function(req, res) {
res.render('home');
});
//////////////////////apis///////google//////////////////////////
app.get(
'/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] })
);
app.get(
'/auth/google/secrets',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/secrets');
}
);
////////////////////facebook///////////////
app.get('/auth/facebook', passport.authenticate('facebook', {
scope: ['public_profile', 'email']
}));
// app.get('/auth/facebook');
app.get(
'/auth/facebook/secrets',
passport.authenticate('facebook', {
successRedirect: '/secrets',
failureRedirect: '/login',
})
);
////////////////////////////////////////////////////////////
app.get('/login', function(req, res) {
res.render('login');
});
app.get('/register', function(req, res) {
res.render('register');
});
app.get('/secrets', function(req, res) {
User.find({ secret: { $ne: null } }, function(err, foundUsers) {
if (err) {
console.log(err);
} else {
if (foundUsers) {
res.render('secrets');
}
}
});
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
app.post('/register', function(req, res) {
User.register({ username: req.body.username },
req.body.password,
function(err, user) {
if (err) {
console.log(err);
// res.redirect('/register');
} else {
passport.authenticate('local')(req, res, function() {
// res.redirect('/secrets');
// res.send('registred')
res.redirect('/register');
});
}
}
);
});
app.post('/login', function(req, res) {
const user = new User({
username: req.body.username,
password: req.body.password,
});
req.login(user, function(err) {
if (err) {
console.log(err);
} else {
passport.authenticate('local')(req, res, function() {
console.log('Logging in as: ' + req.user);
// res.send('logged'),
res.redirect('/secrets');
});
}
});
});
app.listen(4000, function() {
console.log('Server started on port 4000.');
});
|
a62b4bfb4d5fdabe1fd0d2bb01f89c1f8bb5cb0f
|
[
"JavaScript"
] | 1 |
JavaScript
|
re-em/login-signup
|
738929f206dc7a8fd29e553498c285d08b846883
|
126914e961ccd59298eeb4d4fdceb7ba0e3525e5
|
refs/heads/master
|
<file_sep>package com.example.daniel.project;
import android.util.Log;
/**
* Created by daniel on 22/02/15.
*/
public class StringInterface {
private static String LOG_TAG=StringInterface.class.getSimpleName();
public static String urlSpecifier="url";
public static String mailToSpecifier="mailTo";
public static String subjectSpecifier="subject";
public static String descriptURLMethod(String url){
String returnValue=urlSpecifier+':'+url;
return returnValue;
}
public static String descriptMailMethod(String mailTo, String subject){
String returnValue=mailToSpecifier+':'+mailTo+","+subjectSpecifier+':'+subject;
return returnValue;
}
public static String readURLMethod(String description){
String[] elements =description.split(":");
if (elements.length>1) {
return elements[1];
}else {
return description;
}
}
public static MailMethodSettings readMailMethod(String descrition){
String mailTo="", subject="";
String[] pairs = descrition.split(",");
for (int i=0;i<pairs.length;i++) {
String pair = pairs[i];
String[] keyValue = pair.split(":");
if(keyValue[0].compareTo(mailToSpecifier)==0) {
mailTo=keyValue[1];
}else if(keyValue[0].compareTo(subjectSpecifier)==0) {
subject=keyValue[1];
}
}
return new MailMethodSettings(mailTo,subject);
}
}
<file_sep>package com.example.daniel.project;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.daniel.project.data.PackagesContract;
import com.example.daniel.project.data.PackagesContract.PreferencesEntry;
import com.example.daniel.project.data.PackagesContract.PackageEntry;
/**
* Created by daniel on 7/02/15.
*/
public class PreferencesFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String LOG_TAG = PreferencesFragment.class.getSimpleName();
private static final int DETAIL_LOADER = 0;
private ListView mListView;
private static final String[] PREFERENCES_PACKAGE_COLUMNS = {
PackageEntry.TABLE_NAME + "." + PackageEntry._ID,
PackageEntry.COLUMN_PACKAGE_INFO,
PackageEntry.COLUMN_PACKAGE_ACTIVE,
PreferencesEntry.COLUMN_FORWARD_METHOD,
PreferencesEntry.COLUMN_EXTRA_PARAM,
PreferencesEntry.TABLE_NAME+"."+PreferencesEntry._ID
};
public static final int COL_PACKAGE_ID = 0;
public static final int COL_PACKAGE_INFO = 1;
public static final int COL_PACKAGE_ACTIVE = 2;
public static final int COL_FORWARD_METHOD = 3;
public static final int COL_EXTRA_PARAM = 4;
public static final int COL_PREFERENCES_ID=5;
private int mPackage;
private String mAppName;
private String mPackageInfo;
private TextView mAppNameView;
private Button mButtonNewMethod;
private PreferencesAdapter mPreferencesAdapter;
public interface Callback {
/**
* DetailFragmentCallback for when an item has been selected.
*/
public static String Package_ID = "Package_ID";
public static String Package_NAME = "Package_NAME";
public static String Package_INFO = "Package_INFO";
public static String Preference_ID = "Preference_ID";
public static String Preference_Method = "Preference_Method";
public static String Preference_Extra = "Preference_Extra";
public void onAddingMethod(Bundle bundle);
public void onUpdatingMethod(Bundle bundle);
public void onResetToPreferenceScreen(Bundle bundle);
}
public PreferencesFragment() {
setHasOptionsMenu(false);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(PreferencesActivity.PACKAGE_KEY, mPackage);
outState.putString(PreferencesActivity.APP_NAME,mAppName);
outState.putString(PreferencesActivity.PACKAGE_INFO,mPackageInfo);
super.onSaveInstanceState(outState);
}
@Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
mPackage = savedInstanceState.getInt(PreferencesActivity.PACKAGE_KEY);
mAppName = savedInstanceState.getString(PreferencesActivity.APP_NAME);
mPackageInfo = savedInstanceState.getString(PreferencesActivity.PACKAGE_INFO);
} else {
if(getArguments()!=null){
mPackage = getArguments().getInt(PreferencesActivity.PACKAGE_KEY);
mAppName = getArguments().getString(PreferencesActivity.APP_NAME);
mPackageInfo = getArguments().getString(PreferencesActivity.PACKAGE_INFO);
}
}
setHasOptionsMenu(false);
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/*Bundle arguments = getArguments();
if (arguments != null) {
z = arguments.getString(DetailActivity.DATE_KEY);
}*/
mPreferencesAdapter = new PreferencesAdapter(getActivity(), null, 0);
if (savedInstanceState != null) {
mPackage = savedInstanceState.getInt(PreferencesActivity.PACKAGE_KEY);
mAppName = savedInstanceState.getString(PreferencesActivity.APP_NAME);
mPackageInfo = savedInstanceState.getString(PreferencesActivity.PACKAGE_INFO);
}
View rootView = inflater.inflate(R.layout.preferences_fragment, container, false);
ImageView iconView = (ImageView) rootView.findViewById(R.id.appIconView);
IconLoader iconLoader = new IconLoader(getActivity(),iconView);
iconLoader.execute(mPackageInfo);
mAppNameView = (TextView) rootView.findViewById(R.id.packageNameView);
mButtonNewMethod = (Button) rootView.findViewById(R.id.new_preference_button);
mButtonNewMethod.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Activity activity = getActivity();
Bundle bundle = new Bundle();
bundle.putInt(NewPreferenceActivity.PACKAGE_KEY, mPackage);
bundle.putString(NewPreferenceActivity.APP_NAME, mAppName);
bundle.putString(NewPreferenceActivity.PACKAGE_INFO, mPackageInfo);
((Callback) activity).onAddingMethod(bundle);
}
});
mListView = (ListView) rootView.findViewById(R.id.listview_preferences);
mListView.setAdapter(mPreferencesAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Cursor cursor = mPreferencesAdapter.getCursor();
if (cursor != null && cursor.moveToPosition(position)) {
Bundle bundle = new Bundle();
int preferenceID = cursor.getInt(COL_PREFERENCES_ID);
String preferenceMethod = cursor.getString(COL_FORWARD_METHOD);
String preferenceExtra = cursor.getString(COL_EXTRA_PARAM);
bundle.putInt(Callback.Preference_ID, preferenceID);
bundle.putString(Callback.Package_NAME, mPackageInfo);
bundle.putInt(Callback.Package_ID, mPackage);
bundle.putString(Callback.Package_INFO,mPackageInfo);
bundle.putString(Callback.Preference_Method, preferenceMethod);
bundle.putString(Callback.Preference_Extra,preferenceExtra);
bundle.putString(Callback.Package_NAME,mAppName);
((Callback)getActivity())
.onUpdatingMethod(bundle);
}
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey(PreferencesActivity.PACKAGE_KEY)) {
getLoaderManager().restartLoader(DETAIL_LOADER, null, this);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
// Inflate the menu; this adds items to the action bar if it is present.
//inflater.inflate(R.menu.preferences, menu);
//super.onCreateOptionsMenu(menu,inflater);
/*// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// If onLoadFinished happens before this, we can go ahead and set the share intent now.
if (mForecast != null) {
mShareActionProvider.setShareIntent(createShareForecastIntent());
}*/
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mPackage = savedInstanceState.getInt(PreferencesActivity.PACKAGE_KEY);
}
Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey(PreferencesActivity.PACKAGE_KEY)) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
Uri queryUri = PreferencesEntry.CONTENT_URI_LIST.buildUpon().appendPath(Integer.toString(mPackage)).build();
return new CursorLoader(
getActivity(),
queryUri, // Table to Query
PREFERENCES_PACKAGE_COLUMNS, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // columns to group by
);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAppNameView.setText(mAppName);
mPreferencesAdapter.swapCursor(data);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mPreferencesAdapter.swapCursor(null);
}
}
<file_sep>package com.example.daniel.project;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import com.example.daniel.project.data.PackagesContract;
/**
* Created by daniel on 3/02/15.
*/
public class PackageAdapter extends CursorAdapter {
private static String LOG_TAG = PackageAdapter.class.getSimpleName();
// Flag to determine if we want to use a separate view for "today".
private boolean mUseTodayLayout = true;
/**
* Cache of the children views for a forecast list item.
*/
public static class ViewHolder {
public final ImageView iconView;
public final TextView packageNameView;
public final Switch packageForwardSwitch;
public String getPackageName() {
return packageName;
}
public void setPackageInfo(String packageName) {
this.packageName = packageName;
}
private String packageName;
public ViewHolder(View view) {
iconView = (ImageView) view.findViewById(R.id.packageIcon);
packageNameView = (TextView) view.findViewById(R.id.packageName);
packageForwardSwitch = (Switch) view.findViewById(R.id.forwardActivated);
}
}
public PackageAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Choose the layout type
int viewType = getItemViewType(cursor.getPosition());
int layoutId = -1;
layoutId = R.layout.list_item_package;
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
Switch packageSwitch = (Switch) view.findViewById(R.id.forwardActivated);
packageSwitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
String packageName = (String) buttonView.getTag();
ContentValues updatedValues = new ContentValues();
updatedValues.put(PackagesContract.PackageEntry.COLUMN_PACKAGE_ACTIVE, isChecked ? PackagesContract.PackageEntry.ACTIVE_STRING:PackagesContract.PackageEntry.INACTIVE_STRING);
int count = mContext.getContentResolver().update(
PackagesContract.PackageEntry.CONTENT_URI, updatedValues, PackagesContract.PackageEntry.COLUMN_PACKAGE_INFO + "= ?",
new String[] { packageName});
}
});
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
String packageInfo = cursor.getString(PackagesFragment.COL_PACKAGE_INFO);
viewHolder.setPackageInfo(packageInfo);
viewHolder.packageNameView.setText(cursor.getString(cursor.getColumnIndex(PackagesContract.PackageEntry.COLUMN_PACKAGE_NAME)));
IconLoader iconLoader = new IconLoader(context, viewHolder.iconView);
iconLoader.execute(packageInfo);
viewHolder.packageForwardSwitch.setTag(packageInfo);
viewHolder.packageForwardSwitch.setChecked(cursor.getString(PackagesFragment.COL_PACKAGE_ACTIVE).compareTo(PackagesContract.PackageEntry.ACTIVE_STRING)==0);
}
}<file_sep>package com.example.daniel.project;
import android.app.LoaderManager;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Loader;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.content.CursorLoader;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.example.daniel.project.data.PackagesContract;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.net.URL;
public class NLService extends NotificationListenerService {
private String TAG = this.getClass().getSimpleName();
private NLServiceReceiver nlservicereciver;
private static String LOG_TAG = NLService.class.getSimpleName();
//private static ForwardingExecution forwardingExecution;
private CursorLoader mCursorLoader;
private static int LOADER_PACKAGE_PREFERENCES=0;
/* private class ForwardingExecution implements LoaderManager.LoaderCallbacks<Cursor> {
private String LOG_TAG = ForwardingExecution.class.getSimpleName();
public String PACKAGE_NAME = "package_name";
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String packageName = args.getString(PACKAGE_NAME);
Uri queryUri = PackagesContract.PreferencesEntry.CONTENT_URI_STRING_LIST.buildUpon().appendPath(packageName).build();
Log.v(LOG_TAG, "uri used: " + queryUri);
CursorLoader cursorLoader = new CursorLoader(
getApplicationContext(),
queryUri, // Table to Query
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // columns to group by
);
return cursorLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.v(LOG_TAG,"onLoadFinished");
if (data!= null ){
Log.v(LOG_TAG,"data is not null");
for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
for(String columnName: data.getColumnNames()){
Log.v(LOG_TAG, "one column name: "+columnName);
}
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}*/
@Override
public void onCreate() {
super.onCreate();
nlservicereciver = new NLServiceReceiver();
//Looper.prepare();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.daniel.project.NOTIFICATION_LISTENER_SERVICE_EXAMPLE");
registerReceiver(nlservicereciver,filter);
//forwardingExecution = new ForwardingExecution();
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(nlservicereciver);
/*if (mCursorLoader != null) {
mCursorLoader.unregisterListener(this);
mCursorLoader.cancelLoad();
mCursorLoader.stopLoading();
}*/
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
PackageManager packageManager = getApplicationContext().getPackageManager();
ApplicationInfo applicationInfo = null;
try {
applicationInfo = packageManager.getApplicationInfo(sbn.getPackageName(), 0);
} catch (final PackageManager.NameNotFoundException e) {
}
final String title = (String) ((applicationInfo != null) ? packageManager.getApplicationLabel(applicationInfo) : "???");
Intent i = new Intent("com.example.daniel.project.NOTIFICATION_LISTENER_EXAMPLE");
i.putExtra("notification_event", "onNotificationPosted :" + title + "\n");
sendBroadcast(i);
ContentValues newPackageValues = new ContentValues();
newPackageValues.put(PackagesContract.PackageEntry.COLUMN_PACKAGE_INFO, sbn.getPackageName());
newPackageValues.put(PackagesContract.PackageEntry.COLUMN_PACKAGE_ACTIVE, PackagesContract.PackageEntry.ACTIVE_STRING);
try {
Uri packageUri = getApplicationContext().getContentResolver().
insert(PackagesContract.PackageEntry.CONTENT_URI, newPackageValues);
} catch (Exception e){
}
Uri queryUri = PackagesContract.PreferencesEntry.CONTENT_URI_STRING_LIST.buildUpon().appendPath(sbn.getPackageName()).build();
Cursor preferencesCursor = getApplicationContext().getContentResolver().query(
queryUri, // Table to Query
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // columns to group by
);
for (preferencesCursor.moveToFirst(); !preferencesCursor.isAfterLast(); preferencesCursor.moveToNext()) {
if(preferencesCursor.getString(preferencesCursor.getColumnIndex(PackagesContract.PackageEntry.COLUMN_PACKAGE_ACTIVE)).compareTo(PackagesContract.PackageEntry.ACTIVE_STRING)==0){
String method = preferencesCursor.getString(preferencesCursor.getColumnIndex(PackagesContract.PreferencesEntry.COLUMN_FORWARD_METHOD));
if (method.compareTo(PackagesContract.PreferencesEntry.MAIL_METHOD)==0){
MailMethodSettings mailMethodSettings = StringInterface.readMailMethod(preferencesCursor.getString(preferencesCursor.getColumnIndex(PackagesContract.PreferencesEntry.COLUMN_EXTRA_PARAM)));
try {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if(prefs.getAll().size()!=0) {
String mailUser = prefs.getString("edittext_preference","");
String mailPassword = prefs.getString("password_preference","");
GMailSender sender = new GMailSender(mailUser, mailPassword);
sender.sendMail(mailMethodSettings.getSubject(),
"",
mailUser,
mailMethodSettings.getMailTo());
}
} catch (Exception e) {
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder ncomp = new NotificationCompat.Builder(this);
ncomp.setContentTitle(getResources().getString(R.string.app_name));
String message = getResources().getString(R.string.mail_error_message)+mailMethodSettings.getMailTo();
ncomp.setContentText(message);
ncomp.setTicker(message);
ncomp.setSmallIcon(R.drawable.ic_launcher);
ncomp.setAutoCancel(true);
nManager.notify((int) System.currentTimeMillis(), ncomp.build());
}
} else if (method.compareTo(PackagesContract.PreferencesEntry.WEB_METHOD)==0){
String addressSettings = StringInterface.readURLMethod(preferencesCursor.getString(preferencesCursor.getColumnIndex(PackagesContract.PreferencesEntry.COLUMN_EXTRA_PARAM)));
String webAddress = new String(addressSettings);
if(!webAddress.startsWith("http://")){
webAddress="http://"+webAddress;
}
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
HttpGet httpGet = new HttpGet(webAddress);
HttpResponse response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
} catch (Exception e) {
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder ncomp = new NotificationCompat.Builder(this);
ncomp.setContentTitle(getResources().getString(R.string.app_name));
String message = getResources().getString(R.string.url_error_message)+addressSettings;
ncomp.setContentText(message);
ncomp.setTicker(message);
ncomp.setSmallIcon(R.drawable.ic_launcher);
ncomp.setAutoCancel(true);
nManager.notify((int) System.currentTimeMillis(), ncomp.build());
}
}
}
}
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Intent i = new Intent("com.example.daniel.project.NOTIFICATION_LISTENER_EXAMPLE");
i.putExtra("notification_event","onNotificationRemoved :" + sbn.getPackageName() + "\n");
sendBroadcast(i);
}
class NLServiceReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getStringExtra("command").equals("clearall")){
NLService.this.cancelAllNotifications();
}
else if(intent.getStringExtra("command").equals("list")){
Intent i1 = new Intent("com.example.daniel.project.NOTIFICATION_LISTENER_EXAMPLE");
i1.putExtra("notification_event","=====================");
sendBroadcast(i1);
int i=1;
for (StatusBarNotification sbn : NLService.this.getActiveNotifications()) {
Intent i2 = new Intent("com.example.daniel.project.NOTIFICATION_LISTENER_EXAMPLE");
i2.putExtra("notification_event",i +" " + sbn.getPackageName() + "\n");
sendBroadcast(i2);
i++;
}
Intent i3 = new Intent("com.example.daniel.project.NOTIFICATION_LISTENER_EXAMPLE");
i3.putExtra("notification_event","===== Notification List ====");
sendBroadcast(i3);
}
}
}
}
<file_sep>package com.example.daniel.project.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.daniel.project.data.PackagesContract.PackageEntry;
import com.example.daniel.project.data.PackagesContract.PreferencesEntry;
/**
* Created by daniel on 3/02/15.
*/
public class PackagesDbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "packages.db";
public PackagesDbHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_PACKAGES_TABLE = "CREATE TABLE " + PackageEntry.TABLE_NAME + " (" +
PackageEntry._ID + " INTEGER PRIMARY KEY," +
PackageEntry.COLUMN_PACKAGE_INFO + " TEXT UNIQUE NOT NULL, " +
PackageEntry.COLUMN_PACKAGE_ACTIVE + " TEXT NOT NULL, " +
"UNIQUE (" + PackageEntry.COLUMN_PACKAGE_INFO +") ON CONFLICT IGNORE"+
" );";
final String SQL_CREATE_PREFERENCES_TABLE = "CREATE TABLE " + PreferencesEntry.TABLE_NAME + " (" +
PreferencesEntry._ID + " INTEGER PRIMARY KEY," +
PreferencesEntry.COLUMN_PACKAGE_ID + " INTEGER NOT NULL, " +
PreferencesEntry.COLUMN_FORWARD_METHOD + " TEXT NOT NULL, " +
PreferencesEntry.COLUMN_EXTRA_PARAM + " TEXT NOT NULL, " +
" FOREIGN KEY (" + PreferencesEntry.COLUMN_PACKAGE_ID + ") REFERENCES " +
PackageEntry.TABLE_NAME + " (" + PackageEntry._ID + ") " +
//", UNIQUE (" + PreferencesEntry.COLUMN_PACKAGE_ID +","+PreferencesEntry.COLUMN_FORWARD_METHOD+") ON CONFLICT REPLACE"+
" );";
db.execSQL(SQL_CREATE_PACKAGES_TABLE);
db.execSQL(SQL_CREATE_PREFERENCES_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + PreferencesEntry.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + PackageEntry.TABLE_NAME);
onCreate(db);
}
}
<file_sep>package com.example.daniel.project;
import android.content.ContentValues;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.daniel.project.data.PackagesContract;
import java.util.ArrayList;
/**
* Created by daniel on 24/02/15.
*/
public class EditPreferenceFragment extends Fragment {
private static final String LOG_TAG = EditPreferenceFragment.class.getSimpleName();
private static final int DETAIL_LOADER = 0;
private static String MailState="MAIL_TO";
private static String SubjectState="SUBJECT";
private static String UrlState="URL";
private static String MethodState="METHOD";
private static String PrefereceIDState="PreferenceID";
private static String ExtraState="EXTRA";
private ArrayList<View> availableMethods;
private int mPackage;
private int mPreferenceID;
private String mAppName;
private String mPackageInfo;
private String mMailTo;
private String mSubject;
private String mUrl;
private int mMethod;
private Bundle mBundle;
private Spinner spinner;
private TextView mailTextView;
private TextView subjectTextView;
private TextView urlTextView;
public EditPreferenceFragment() {
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(PreferencesActivity.PACKAGE_KEY, mPackage);
outState.putString(PreferencesActivity.APP_NAME, mAppName);
outState.putString(PreferencesActivity.PACKAGE_INFO,mPackageInfo);
outState.putInt(MethodState, mMethod);
outState.putString(MailState, mailTextView.getText().toString());
outState.putString(SubjectState, subjectTextView.getText().toString());
outState.putString(UrlState, urlTextView.getText().toString());
outState.putInt(PrefereceIDState, mPreferenceID);
super.onSaveInstanceState(outState);
}
@Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
mPackage = savedInstanceState.getInt(PreferencesActivity.PACKAGE_KEY);
mAppName = savedInstanceState.getString(PreferencesActivity.APP_NAME);
mPackageInfo = savedInstanceState.getString(PreferencesActivity.PACKAGE_INFO);
mMailTo = savedInstanceState.getString(MailState);
mSubject = savedInstanceState.getString(SubjectState);
mUrl = savedInstanceState.getString(UrlState);
mMethod = savedInstanceState.getInt(MethodState);
mPreferenceID = savedInstanceState.getInt(PrefereceIDState);
} else {
if(getArguments()!=null){
mPackage = getArguments().getInt(PreferencesFragment.Callback.Package_ID);
mAppName = getArguments().getString(PreferencesFragment.Callback.Package_NAME);
mPackageInfo = getArguments().getString(PreferencesFragment.Callback.Package_INFO);
if (getArguments().getString(PreferencesFragment.Callback.Preference_Method).compareTo(PackagesContract.PreferencesEntry.MAIL_METHOD)==0){
mMethod = 0;
MailMethodSettings mailMethodSettings = StringInterface.readMailMethod(getArguments().getString(PreferencesFragment.Callback.Preference_Extra));
mMailTo = mailMethodSettings.getMailTo();
mSubject = mailMethodSettings.getSubject();
mUrl = "";
} else if (getArguments().getString(PreferencesFragment.Callback.Preference_Method).compareTo(PackagesContract.PreferencesEntry.WEB_METHOD)==0){
mMethod = 1;
mUrl = StringInterface.readURLMethod(getArguments().getString(PreferencesFragment.Callback.Preference_Extra));
mMailTo = "";
mSubject = "";
}
mPreferenceID = getArguments().getInt(PreferencesFragment.Callback.Preference_ID);
}
}
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.edit_preference_fragment, container, false);
availableMethods = new ArrayList<>();
availableMethods.add(rootView.findViewById(R.id.mail_settings));
availableMethods.add(rootView.findViewById(R.id.web_settings));
for(int i=0; i<availableMethods.size(); i++){
if (i!=mMethod){
availableMethods.get(i).setVisibility(View.GONE);
} else {
availableMethods.get(i).setVisibility(View.VISIBLE);
}
}
mailTextView = (TextView) rootView.findViewById(R.id.emailTextView);
mailTextView.setText(mMailTo);
subjectTextView = (TextView) rootView.findViewById(R.id.subjectTextView);
subjectTextView.setText(mSubject);
urlTextView = (TextView) rootView.findViewById(R.id.urlTextView);
urlTextView.setText(mUrl);
rootView.findViewById(R.id.addMethodButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addMethod();
}
});
View cancelButton = rootView.findViewById(R.id.cancelButton);
if (cancelButton != null){
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle cancelBundle = new Bundle();
cancelBundle.putString(PreferencesActivity.PACKAGE_INFO,mPackageInfo);
cancelBundle.putInt(PreferencesActivity.PACKAGE_KEY,mPackage);
cancelBundle.putString(PreferencesActivity.APP_NAME, mAppName);
((PreferencesFragment.Callback)getActivity()).onResetToPreferenceScreen(cancelBundle);
}
});
}
return rootView;
}
@Override
public void onResume() {
super.onResume();
}
private void addMethod(){
String method="";
String params="";
switch (mMethod) {
case 0:
method= PackagesContract.PreferencesEntry.MAIL_METHOD;
params=StringInterface.descriptMailMethod(mailTextView.getText().toString(),subjectTextView.getText().toString());
break;
case 1:
method=PackagesContract.PreferencesEntry.WEB_METHOD;
params=StringInterface.descriptURLMethod(urlTextView.getText().toString());
break;
}
ContentValues preferences = new ContentValues();
preferences.put(PackagesContract.PreferencesEntry.COLUMN_PACKAGE_ID, Integer.toString(mPackage));
preferences.put(PackagesContract.PreferencesEntry._ID, Integer.toString(mPreferenceID));
preferences.put(PackagesContract.PreferencesEntry.COLUMN_FORWARD_METHOD, method);
preferences.put(PackagesContract.PreferencesEntry.COLUMN_EXTRA_PARAM, params);
String[] valuesForWhere = {Integer.toString(mPreferenceID)};
int rowsUpdate = getActivity().getContentResolver()
.update(PackagesContract.PreferencesEntry.CONTENT_URI.buildUpon().appendQueryParameter(PackagesContract.PreferencesEntry.COLUMN_PACKAGE_ID, Integer.toString(mPackage)).build(),
preferences,
PackagesContract.PreferencesEntry._ID + "= ? ",
valuesForWhere);
Bundle cancelBundle = new Bundle();
cancelBundle.putString(PreferencesActivity.PACKAGE_INFO,mPackageInfo);
cancelBundle.putInt(PreferencesActivity.PACKAGE_KEY,mPackage);
cancelBundle.putString(PreferencesActivity.APP_NAME, mAppName);
((PreferencesFragment.Callback)getActivity()).onResetToPreferenceScreen(cancelBundle);
}
}<file_sep>package com.example.daniel.project;
/**
* Created by daniel on 5/02/15.
*/
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.example.daniel.project.data.PackagesContract.PackageEntry;
import com.example.daniel.project.data.PackagesContract.PreferencesEntry;
import junit.framework.Test;
public class TestProvider extends AndroidTestCase {
public static final String LOG_TAG = TestProvider.class.getSimpleName();
// brings our database to an empty state
public void deleteAllRecords() {
Log.v(LOG_TAG, "preferences entry path: "+PreferencesEntry.CONTENT_URI);
mContext.getContentResolver().delete(
PreferencesEntry.CONTENT_URI,
null,
null
);
Log.v(LOG_TAG, "packages entry path: "+PackageEntry.CONTENT_URI_LIST);
mContext.getContentResolver().delete(
PackageEntry.CONTENT_URI_LIST,
null,
null
);
Cursor cursor = mContext.getContentResolver().query(
PackageEntry.CONTENT_URI_LIST,
null,
null,
null,
null
);
assertEquals(0, cursor.getCount());
cursor.close();
cursor = mContext.getContentResolver().query(
PreferencesEntry.CONTENT_URI_LIST,
null,
null,
null,
null
);
assertEquals(0, cursor.getCount());
cursor.close();
}
// Since we want each test to start with a clean slate, run deleteAllRecords
// in setUp (called by the test runner before each test).
public void setUp() {
deleteAllRecords();
}
public void testInsertReadProvider() {
ContentValues testValues = TestDB.createFakePackageValues();
Uri packageUri = mContext.getContentResolver().insert(PackageEntry.CONTENT_URI, testValues);
long packageRowId = ContentUris.parseId(packageUri);
// Verify we got a row back.
assertTrue(packageRowId != -1);
// Data's inserted. IN THEORY. Now pull some out to stare at it and verify it made
// the round trip.
// A cursor is your primary interface to the query results.
Cursor cursor = mContext.getContentResolver().query(
PackageEntry.CONTENT_URI_LIST,
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestDB.validateCursor(cursor, testValues);
// Now see if we can successfully query if we include the row id
cursor = mContext.getContentResolver().query(
PackageEntry.buildPackageUri(packageRowId),
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestDB.validateCursor(cursor, testValues);
// Fantastic. Now that we have a location, add some weather!
ContentValues preferencesValues = TestDB.createFakePreferenceValues(packageRowId);
Uri preferencesInsertUri = mContext.getContentResolver()
.insert(PreferencesEntry.CONTENT_URI, preferencesValues);
assertTrue(preferencesInsertUri != null);
// A cursor is your primary interface to the query results.
Cursor preferencesCursor = mContext.getContentResolver().query(
PreferencesEntry.CONTENT_URI_LIST, // Table to Query
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // columns to group by
);
TestDB.validateCursor(preferencesCursor, preferencesValues);
// Add the location values in with the weather data so that we can make
// sure that the join worked and we actually get all the values back
addAllContentValues(preferencesValues, testValues);
// Get the joined Weather and Location data
preferencesCursor = mContext.getContentResolver().query(
PreferencesEntry.buildPrefrencesPackage(TestDB.TEST_PACKAGE),
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestDB.validateCursor(preferencesCursor, preferencesValues);
}
public void testGetType() {
// content://com.example.android.sunshine.app/weather/
String type = mContext.getContentResolver().getType(PreferencesEntry.CONTENT_URI_LIST);
// vnd.android.cursor.dir/com.example.android.sunshine.app/weather
assertEquals(PreferencesEntry.CONTENT_TYPE, type);
String testLocation = TestDB.TEST_PACKAGE;
// content://com.example.android.sunshine.app/weather/94074
type = mContext.getContentResolver().getType(
PreferencesEntry.buildPrefrencesPackage(testLocation));
// vnd.android.cursor.dir/com.example.android.sunshine.app/weather
assertEquals(PreferencesEntry.CONTENT_TYPE, type);
// content://com.example.android.sunshine.app/location/
type = mContext.getContentResolver().getType(PackageEntry.CONTENT_URI_LIST);
// vnd.android.cursor.dir/com.example.android.sunshine.app/location
assertEquals(PackageEntry.CONTENT_TYPE, type);
// content://com.example.android.sunshine.app/location/1
type = mContext.getContentResolver().getType(PackageEntry.buildPackageUri(1L));
// vnd.android.cursor.item/com.example.android.sunshine.app/location
assertEquals(PackageEntry.CONTENT_ITEM_TYPE, type);
}
public void testUpdatePackage() {
// Create a new map of values, where column names are the keys
ContentValues values = TestDB.createFakePackageValues();
Uri packageUri = mContext.getContentResolver().
insert(PackageEntry.CONTENT_URI, values);
long packageRowId = ContentUris.parseId(packageUri);
// Verify we got a row back.
assertTrue(packageRowId != -1);
Log.d(LOG_TAG, "New row id: " + packageRowId);
ContentValues updatedValues = new ContentValues(values);
updatedValues.put(PackageEntry._ID, packageRowId);
updatedValues.put(PackageEntry.COLUMN_PACKAGE_INFO, "eu.bleble.test");
int count = mContext.getContentResolver().update(
PackageEntry.CONTENT_URI, updatedValues, PackageEntry._ID + "= ?",
new String[] { Long.toString(packageRowId)});
assertEquals(count, 1);
// A cursor is your primary interface to the query results.
Cursor cursor = mContext.getContentResolver().query(
PackageEntry.buildPackageUri(packageRowId),
null,
null, // Columns for the "where" clause
null, // Values for the "where" clause
null // sort order
);
TestDB.validateCursor(cursor, updatedValues);
}
public void testInsertMultiplePreferences() {
// Create a new map of values, where column names are the keys
ContentValues values = TestDB.createFakePackageValues();
Uri packageUri = mContext.getContentResolver().
insert(PackageEntry.CONTENT_URI, values);
long packageRowId = ContentUris.parseId(packageUri);
// Verify we got a row back.
assertTrue(packageRowId != -1);
Log.d(LOG_TAG, "New row id: " + packageRowId);
ContentValues firstPreferences = TestDB.createFakePreferenceValues(packageRowId);
ContentValues secondPreferences = TestDB.createSecondFakePreferenceValues(packageRowId);
Uri preferencesInsertUri = mContext.getContentResolver()
.insert(PreferencesEntry.CONTENT_URI, firstPreferences);
assertTrue(preferencesInsertUri != null);
Uri preferencesInsertUri2 = mContext.getContentResolver()
.insert(PreferencesEntry.CONTENT_URI, secondPreferences);
assertTrue(preferencesInsertUri2 != null);
// A cursor is your primary interface to the query results.
Cursor preferencesCursor = mContext.getContentResolver().query(
PreferencesEntry.CONTENT_URI_LIST, // Table to Query
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // columns to group by
);
ContentValues[] preferencesValues = {firstPreferences, secondPreferences};
TestDB.validateCursor(preferencesCursor, preferencesValues);
}
// Make sure we can still delete after adding/updating stuff
public void testDeleteRecordsAtEnd() {
deleteAllRecords();
}
// The target api annotation is needed for the call to keySet -- we wouldn't want
// to use this in our app, but in a test it's fine to assume a higher target.
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
void addAllContentValues(ContentValues destination, ContentValues source) {
for (String key : source.keySet()) {
destination.put(key, source.getAsString(key));
}
}
static final String KALAMAZOO_LOCATION_SETTING = "kalamazoo";
static final String KALAMAZOO_WEATHER_START_DATE = "20140625";
long packageRowId;
// Inserts both the location and weather data for the Kalamazoo data set.
public void insertPackageData() {
ContentValues packageValues = TestDB.createFakePackageValues();
Uri packageInsertUri = mContext.getContentResolver()
.insert(PackageEntry.CONTENT_URI_LIST, packageValues);
assertTrue(packageInsertUri != null);
packageRowId = ContentUris.parseId(packageInsertUri);
ContentValues preferencesValues = TestDB.createFakePreferenceValues(packageRowId);
Uri weatherInsertUri = mContext.getContentResolver()
.insert(PreferencesEntry.CONTENT_URI, preferencesValues);
assertTrue(weatherInsertUri != null);
}
}
<file_sep>package com.example.daniel.project;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.example.daniel.project.data.PackagesContract;
/**
* Created by daniel on 7/02/15.
*/
public class PreferencesActivity extends ActionBarActivity implements PreferencesFragment.Callback{
public static final String PACKAGE_KEY ="package_key";
public static final String PACKAGE_INFO ="package_info";
public static final String APP_NAME ="app_name";
private static String LOG_TAG = PreferencesActivity.class.getSimpleName();
private Integer package_id;
private String packageName;
private String appName;
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(PACKAGE_INFO, packageName);
outState.putString(APP_NAME,appName);
outState.putInt(PACKAGE_KEY, package_id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
if (savedInstanceState == null) {
// Create the preferences fragment and add it to the activity
// using a fragment transaction.
packageName = getIntent().getStringExtra(PACKAGE_INFO);
appName = getIntent().getStringExtra(APP_NAME);
package_id = getIntent().getIntExtra(PACKAGE_KEY,-1);
//package_id = new Integer(packageName);
//Log.v(LOG_TAG, "package_id: " + package_id);
Bundle arguments = getIntent().getExtras();
PreferencesFragment fragment = new PreferencesFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.preferences_container, fragment)
.commit();
}else{
packageName = savedInstanceState.getString(PACKAGE_INFO);
appName = savedInstanceState.getString(APP_NAME);
package_id = savedInstanceState.getInt(PACKAGE_KEY,-1);
PreferencesFragment fragment = new PreferencesFragment();
fragment.setArguments(savedInstanceState);
getSupportFragmentManager().beginTransaction()
.add(R.id.preferences_container, fragment)
.commit();
}
}
/*@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
return true;
}*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.insert_preference) {
ContentValues firstPreferences = new ContentValues();
firstPreferences.put(PackagesContract.PreferencesEntry.COLUMN_PACKAGE_ID, package_id.toString());
firstPreferences.put(PackagesContract.PreferencesEntry.COLUMN_FORWARD_METHOD, PackagesContract.PreferencesEntry.WEB_METHOD);
firstPreferences.put(PackagesContract.PreferencesEntry.COLUMN_EXTRA_PARAM, "www.blabla.com");
Uri preferencesInsertUri = getApplicationContext().getContentResolver()
.insert(PackagesContract.PreferencesEntry.CONTENT_URI, firstPreferences);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onAddingMethod(Bundle bundle) {
Intent intent = new Intent(this, NewPreferenceActivity.class)
.putExtra(NewPreferenceActivity.APP_NAME,appName)
.putExtra(NewPreferenceActivity.PACKAGE_INFO,packageName)
.putExtra(NewPreferenceActivity.PACKAGE_KEY,package_id)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
@Override
public void onUpdatingMethod(Bundle bundle) {
Intent intent = new Intent(this, EditPreferenceActivity.class)
.putExtra(NewPreferenceActivity.APP_NAME,appName)
.putExtra(NewPreferenceActivity.PACKAGE_INFO,packageName)
.putExtra(NewPreferenceActivity.PACKAGE_KEY,package_id)
.putExtras(bundle)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
@Override
public void onResetToPreferenceScreen(Bundle bundle) {
}
}<file_sep>package com.example.daniel.project.data;
/**
* Created by daniel on 3/02/15.
*/
import android.content.ContentUris;
import android.net.Uri;
import android.provider.BaseColumns;
public class PackagesContract {
public static final String CONTENT_AUTHORITY = "com.example.daniel.project";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://"+CONTENT_AUTHORITY);
public static final String PATH_PACKAGES = "packages";
public static final String PATH_PACKAGE = "package";
public static final String PATH_PREFERENCE = "preference";
public static final String PATH_PREFERENCES = "preferences";
public static final String PATH_PREFERENCES_STRING = "preferences_string";
public static final class PackageEntry implements BaseColumns {
public static final Uri CONTENT_URI_LIST = BASE_CONTENT_URI.buildUpon().appendPath(PATH_PACKAGES).build();
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_PACKAGE).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/"+ CONTENT_AUTHORITY + "/" + PATH_PACKAGES;
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/"+ CONTENT_AUTHORITY + "/" + PATH_PACKAGES;
public static final String TABLE_NAME = "packages";
public static final String ACTIVE_STRING = "active";
public static final String INACTIVE_STRING = "inactive";
public static final String COLUMN_PACKAGE_INFO = "package_info";
public static final String COLUMN_PACKAGE_ACTIVE = "package_forward_active";
public static final String COLUMN_PACKAGE_ID = "_id";
public static final String COLUMN_PACKAGE_NAME = "package_name";
public static final String COLUMN_PACKAGE_ICON = "package_icon";
public static Uri buildPackageUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI_LIST, id);
}
public static String getPackageIdForUri(Uri uri) {
return uri.getPathSegments().get(1);
}
public static String getPackageNameForUri(Uri uri) {
return uri.getPathSegments().get(1);
}
}
public static final class PreferencesEntry implements BaseColumns {
public static final String TABLE_NAME = "preferences";
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_PREFERENCE).build();
public static final Uri CONTENT_URI_LIST = BASE_CONTENT_URI.buildUpon().appendPath(PATH_PREFERENCES).build();
public static final Uri CONTENT_URI_STRING_LIST = BASE_CONTENT_URI.buildUpon().appendPath(PATH_PREFERENCES_STRING).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/"+ CONTENT_AUTHORITY + "/" + PATH_PREFERENCE;
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/"+ CONTENT_AUTHORITY + "/" + PATH_PREFERENCE;
public static final String COLUMN_PACKAGE_ID = "package_id";
public static final String COLUMN_FORWARD_METHOD = "forward_method";
public static final String MAIL_METHOD = "mail";
public static final String WEB_METHOD = "web";
public static final String COLUMN_EXTRA_PARAM = "extra_param";
public static Uri buildPrefrencesPackage(String packageSetting) {
return CONTENT_URI.buildUpon().appendPath(packageSetting).build();
}
}
}
|
52e3241ceca487f325b46e9541b967b99e47dfe3
|
[
"Java"
] | 9 |
Java
|
cassisnaro/NotificationsForwarder
|
b3ffcadd1ea9c7927d80494f34c5bd8c2c6ff1af
|
e7d9f576930c736fea48ec03ce40241ec11b97d9
|
refs/heads/main
|
<repo_name>MaxenceR26/hdss-stream-scraping<file_sep>/main.py
from selenium import webdriver
import time
def namefilm(film=''):
# déclancher le driver
if film.lower()[0:4] != "none":
driver = webdriver.Chrome(executable_path="chromedriver.exe")
driver.get("https://hdss-stream.org/")
# recovers the search bar and add name of the film
driver.find_element_by_id("s").send_keys(film)
driver.find_element_by_css_selector("button.search-button").click()
# recover the results
time.sleep(2)
results = driver.find_elements_by_css_selector("div.details")
div = driver.find_elements_by_css_selector("div.title")
date = driver.find_elements_by_css_selector("div.meta")
contenant = driver.find_elements_by_css_selector("div.contenido")
print(f"Film disponible pour la recherche : {film}\n")
for i in div:
title = i.find_element_by_css_selector("a")
time.sleep(0.5)
print(f'\nNom: {title.text}')
else:
driver = webdriver.Chrome(executable_path="chromedriver.exe")
driver.get("https://hdss-stream.org/")
print("Selection de la semaine : ") # Afficher selection de la semaine
featured_items_container = driver.find_element_by_css_selector("div.items.featured")
featured_items = featured_items_container.find_elements_by_css_selector(".item.movies.smallWidthHomeItems")
for featured_item in featured_items:
data = featured_item.find_element_by_css_selector("div.data")
balise_h3 = data.find_element_by_css_selector("h3")
title = balise_h3.find_element_by_css_selector("a")
print(f"\nNom du film : {title.text}",)
namefilm(input("Nom du film ( Ou 'none' pour voir la selection de la semaine ) > "))
<file_sep>/README.md
# hdss-streams-craping
HDSS STREAM SCRAPING SCRIPT
C'est un script pour voir les film ou séries a la une du sites de streaming et voir si votre film ou séries est encore disponible !
--
Pour installer les requirements.txt : python3 -m pip install -r requirements.txt
Installer aussi chromedriver.exe ( pour faire fonctionner le script ) le mettre dans le meme dossier ou se situe main.py
|
57104667871ab147bb20589570652f41c520ae74
|
[
"Markdown",
"Python"
] | 2 |
Python
|
MaxenceR26/hdss-stream-scraping
|
903af0b7d6b46dc41a57bd03704de529963aa1b4
|
7b68c0b31dbc1a4fb37782d74e50c8ba7a92644e
|
refs/heads/master
|
<repo_name>danjiang/DTMessageBar<file_sep>/DTMessageBar iOS Example/ViewController.swift
//
// ViewController.swift
// DTMessageBar iOS Example
//
// Created by <NAME> on 2016/11/8.
//
//
import UIKit
import DTMessageBar
class ViewController: UIViewController {
@IBOutlet weak var iconSetSegmentedControl: UISegmentedControl!
@IBOutlet weak var typeSegmentedControl: UISegmentedControl!
@IBOutlet weak var positionSegmentedControl: UISegmentedControl!
@IBOutlet weak var themeSegmentedControl: UISegmentedControl!
@IBOutlet weak var messageTextField: UITextField!
@IBAction func chooseIconSet(_ sender: Any) {
switch iconSetSegmentedControl.selectedSegmentIndex {
case 1:
DTMessageBar.iconSet = .emoji
case 2:
DTMessageBar.iconSet = .custom
default:
DTMessageBar.iconSet = .standard
}
}
@IBAction func chooseTheme(_ sender: Any) {
switch themeSegmentedControl.selectedSegmentIndex {
case 1:
DTMessageBar.theme = DarkTheme()
default:
DTMessageBar.theme = DTMessageBar.DefaultTheme()
}
}
@IBAction func show(_ sender: Any) {
guard let message = messageTextField.text, !message.isEmpty else {
return
}
let position: DTMessageBar.Position
switch positionSegmentedControl.selectedSegmentIndex {
case 1:
position = .center
case 2:
position = .bottom
default:
position = .top
}
switch typeSegmentedControl.selectedSegmentIndex {
case 1:
DTMessageBar.info(message: message, position: position)
case 2:
DTMessageBar.warning(message: message, position: position)
case 3:
DTMessageBar.error(message: message, position: position)
default:
DTMessageBar.success(message: message, position: position)
}
}
@IBAction func hideKeyboard(_ sender: Any) {
view.endEditing(true)
}
}
struct DarkTheme: DTMessageBarTheme {
var successBorderColor: UIColor {
return UIColor.black
}
var successBackgroundColor: UIColor {
return UIColor(red:0.11, green:0.11, blue:0.15, alpha:0.8)
}
var successTextColor: UIColor {
return UIColor.white
}
var infoBorderColor: UIColor {
return UIColor.black
}
var infoBackgroundColor: UIColor {
return UIColor(red:0.11, green:0.11, blue:0.15, alpha:0.8)
}
var infoTextColor: UIColor {
return UIColor.white
}
var warningBorderColor: UIColor {
return UIColor.black
}
var warningBackgroundColor: UIColor {
return UIColor(red:0.11, green:0.11, blue:0.15, alpha:0.8)
}
var warningTextColor: UIColor {
return UIColor.white
}
var errorBorderColor: UIColor {
return UIColor.black
}
var errorBackgroundColor: UIColor {
return UIColor(red:0.11, green:0.11, blue:0.15, alpha:0.8)
}
var errorTextColor: UIColor {
return UIColor.white
}
}
<file_sep>/README.md
# DTMessageBar
[](https://swift.org/)
[](http://cocoadocs.org/docsets/DTMessageBar)
[](https://cocoapods.org/pods/DTMessageBar)
[](https://github.com/Carthage/Carthage)
## Introduction
Simple message bar.

Standard Style.




Emoji Style.




## Installation
### Requirement
iOS 8.4+
### [CocoaPods](http://cocoapods.org)
To install DTMessageBar add a dependency to your Podfile:
```
pod "DTMessageBar"
```
### [Carthage](https://github.com/Carthage/Carthage)
To install DTMessageBar add a dependency to your Cartfile:
```
github "danjiang/DTMessageBar"
```
```
carthage update --platform ios
```
## Usage
### Import
```swift
import DTMessageBar
```
### Use
```swift
DTMessageBar.error(message: "Good Jobs") // Top is default position
DTMessageBar.success(message: "Good Jobs", position: .top)
DTMessageBar.info(message: "Good Jobs", position: .center)
DTMessageBar.warning(message: "Good Jobs", position: .bottom)
```
### Customize
#### Icon Set
```swift
DTMessageBar.iconSet = .standard // Standard is default icon set
DTMessageBar.iconSet = .emoji
DTMessageBar.iconSet = .custom // You should put your own icon set in Assets.xcassets with name as success_custom, info_custom, warning_custom and error_custom.
```
#### Theme
```swift
DTMessageBar.theme = DTMessageBar.DefaultTheme() // Default theme
// Impelement DTMessageBarTheme to provide your own theme
struct DarkTheme: DTMessageBarTheme {
var successBorderColor: UIColor {
return UIColor.black
}
var successBackgroundColor: UIColor {
return UIColor(red:0.11, green:0.11, blue:0.15, alpha:0.8)
}
var successTextColor: UIColor {
return UIColor.white
}
var infoBorderColor: UIColor {
return UIColor.black
}
var infoBackgroundColor: UIColor {
return UIColor(red:0.11, green:0.11, blue:0.15, alpha:0.8)
}
var infoTextColor: UIColor {
return UIColor.white
}
var warningBorderColor: UIColor {
return UIColor.black
}
var warningBackgroundColor: UIColor {
return UIColor(red:0.11, green:0.11, blue:0.15, alpha:0.8)
}
var warningTextColor: UIColor {
return UIColor.white
}
var errorBorderColor: UIColor {
return UIColor.black
}
var errorBackgroundColor: UIColor {
return UIColor(red:0.11, green:0.11, blue:0.15, alpha:0.8)
}
var errorTextColor: UIColor {
return UIColor.white
}
}
DTMessageBar.theme = DarkTheme()
```<file_sep>/DTMessageBar.podspec
Pod::Spec.new do |spec|
spec.name = "DTMessageBar"
spec.version = "1.1.3"
spec.summary = "Simple message bar"
spec.homepage = "https://github.com/danjiang/DTMessageBar"
spec.license = { type: 'MIT', file: 'LICENSE' }
spec.authors = { "<NAME>" => '<EMAIL>' }
spec.social_media_url = "https://twitter.com/danjianglife"
spec.platform = :ios, "8.4"
spec.requires_arc = true
spec.swift_version = '4.0'
spec.source = { git: "https://github.com/danjiang/DTMessageBar.git", tag: spec.version, submodules: true }
spec.source_files = "Sources/**/*.{h,swift}"
spec.resources = "Sources/*.bundle"
end
<file_sep>/Sources/DTMessageBar.swift
//
// DTMessageBar.swift
// DTMessageBar
//
// Created by <NAME> on 2016/11/8.
//
//
import UIKit
public protocol DTMessageBarTheme {
var successBorderColor: UIColor { get }
var successBackgroundColor: UIColor { get }
var successTextColor: UIColor { get }
var infoBorderColor: UIColor { get }
var infoBackgroundColor: UIColor { get }
var infoTextColor: UIColor { get }
var warningBorderColor: UIColor { get }
var warningBackgroundColor: UIColor { get }
var warningTextColor: UIColor { get }
var errorBorderColor: UIColor { get }
var errorBackgroundColor: UIColor { get }
var errorTextColor: UIColor { get }
}
public extension DTMessageBarTheme {
var successBorderColor: UIColor {
return UIColor(red:0.84, green:0.91, blue:0.78, alpha:1.00)
}
var successBackgroundColor: UIColor {
return UIColor(red:0.87, green:0.94, blue:0.85, alpha:1.00)
}
var successTextColor: UIColor {
return UIColor(red:0.24, green:0.46, blue:0.24, alpha:1.00)
}
var infoBorderColor: UIColor {
return UIColor(red:0.74, green:0.91, blue:0.95, alpha:1.00)
}
var infoBackgroundColor: UIColor {
return UIColor(red:0.85, green:0.93, blue:0.97, alpha:1.00)
}
var infoTextColor: UIColor {
return UIColor(red:0.19, green:0.44, blue:0.56, alpha:1.00)
}
var warningBorderColor: UIColor {
return UIColor(red:0.98, green:0.92, blue:0.80, alpha:1.00)
}
var warningBackgroundColor: UIColor {
return UIColor(red:0.99, green:0.97, blue:0.89, alpha:1.00)
}
var warningTextColor: UIColor {
return UIColor(red:0.54, green:0.42, blue:0.23, alpha:1.00)
}
var errorBorderColor: UIColor {
return UIColor(red:0.92, green:0.80, blue:0.82, alpha:1.00)
}
var errorBackgroundColor: UIColor {
return UIColor(red:0.95, green:0.87, blue:0.87, alpha:1.00)
}
var errorTextColor: UIColor {
return UIColor(red:0.66, green:0.27, blue:0.26, alpha:1.00)
}
}
public class DTMessageBar: UIView {
public enum IconSet {
case standard
case emoji
case custom
}
public enum Style: String {
case success
case info
case warning
case error
}
public enum Position {
case top
case center
case bottom
}
public struct DefaultTheme: DTMessageBarTheme {
public init() {}
}
public static var iconSet: IconSet = .standard
public static var theme: DTMessageBarTheme = DefaultTheme()
public static var offset: CGFloat = 80
private static let sharedView = DTMessageBar()
private let typeImageView = UIImageView()
private let messageLabel = UILabel()
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override init(frame: CGRect) {
super.init(frame: frame)
layoutTypeImageView()
layoutMessageLabel()
}
public class func success(message: String, position: Position = .top) {
show(message: message, style: .success, position: position)
}
public class func info(message: String, position: Position = .top) {
show(message: message, style: .info, position: position)
}
public class func warning(message: String, position: Position = .top) {
show(message: message, style: .warning, position: position)
}
public class func error(message: String, position: Position = .top) {
show(message: message, style: .error, position: position)
}
public static func imageWithName(_ name: String) -> UIImage? {
let bundle = Bundle(for: DTMessageBar.self)
let url = bundle.url(forResource: "DTMessageBar", withExtension: "bundle")!
let imageBundle = Bundle(url: url)
return UIImage(named: name, in: imageBundle, compatibleWith: nil)
}
private class func show(message: String, style: Style, position: Position) {
if let _ = DTMessageBar.sharedView.superview {
return
}
if let w = UIApplication.shared.delegate?.window, let window = w {
DTMessageBar.sharedView.translatesAutoresizingMaskIntoConstraints = false
window.addSubview(DTMessageBar.sharedView)
let centerX = NSLayoutConstraint(item: DTMessageBar.sharedView, attribute: .centerX, relatedBy: .equal, toItem: window, attribute: .centerX, multiplier: 1, constant: 0)
window.addConstraint(centerX)
switch position {
case .top:
let top = NSLayoutConstraint(item: DTMessageBar.sharedView, attribute: .top, relatedBy: .equal, toItem: window, attribute: .top, multiplier: 1, constant: offset)
window.addConstraint(top)
case .center:
let centerY = NSLayoutConstraint(item: DTMessageBar.sharedView, attribute: .centerY, relatedBy: .equal, toItem: window, attribute: .centerY, multiplier: 1, constant: 0)
window.addConstraint(centerY)
case .bottom:
let bottom = NSLayoutConstraint(item: DTMessageBar.sharedView, attribute: .bottom, relatedBy: .equal, toItem: window, attribute: .bottom, multiplier: 1, constant: -offset)
window.addConstraint(bottom)
}
DTMessageBar.sharedView.customize(message: message, style: style)
DTMessageBar.sharedView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseOut, animations: {
DTMessageBar.sharedView.transform = CGAffineTransform.identity
}, completion: { _ in
UIView.animate(withDuration: 0.25, delay: 2, options: .curveEaseIn, animations: {
DTMessageBar.sharedView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
}, completion: { _ in
DTMessageBar.sharedView.removeFromSuperview()
})
})
}
}
// MARK: - Private
private func layoutTypeImageView() {
addSubview(typeImageView)
typeImageView.translatesAutoresizingMaskIntoConstraints = false
let top = NSLayoutConstraint(item: typeImageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 16)
let leading = NSLayoutConstraint(item: typeImageView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 16)
let bottom = NSLayoutConstraint(item: typeImageView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: -16)
addConstraints([top, leading, bottom])
}
private func layoutMessageLabel() {
messageLabel.font = UIFont.boldSystemFont(ofSize: 17)
addSubview(messageLabel)
messageLabel.translatesAutoresizingMaskIntoConstraints = false
let leading = NSLayoutConstraint(item: messageLabel, attribute: .leading, relatedBy: .equal, toItem: typeImageView, attribute: .trailing, multiplier: 1, constant: 16)
let trailing = NSLayoutConstraint(item: messageLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: -16)
let centerY = NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
addConstraints([leading, trailing, centerY])
}
private func customize(message: String, style: Style) {
layer.cornerRadius = 12
layer.borderWidth = 2
messageLabel.text = message
var borderColor: UIColor
var backgroundColor: UIColor
var textColor: UIColor
switch style {
case .success:
borderColor = DTMessageBar.theme.successBorderColor
backgroundColor = DTMessageBar.theme.successBackgroundColor
textColor = DTMessageBar.theme.successTextColor
case .info:
borderColor = DTMessageBar.theme.infoBorderColor
backgroundColor = DTMessageBar.theme.infoBackgroundColor
textColor = DTMessageBar.theme.infoTextColor
case .warning:
borderColor = DTMessageBar.theme.warningBorderColor
backgroundColor = DTMessageBar.theme.warningBackgroundColor
textColor = DTMessageBar.theme.warningTextColor
case .error:
borderColor = DTMessageBar.theme.errorBorderColor
backgroundColor = DTMessageBar.theme.errorBackgroundColor
textColor = DTMessageBar.theme.errorTextColor
}
var imageName: String
switch DTMessageBar.iconSet {
case .standard:
imageName = style.rawValue
case .emoji:
imageName = "\(style.rawValue)_emoji"
case .custom:
imageName = "\(style.rawValue)_custom"
}
layer.borderColor = borderColor.cgColor
self.backgroundColor = backgroundColor
messageLabel.textColor = textColor
if DTMessageBar.iconSet != .custom {
typeImageView.image = DTMessageBar.imageWithName(imageName)
} else {
typeImageView.image = UIImage(named: imageName)
}
}
}
|
47d0761ba0014196e7401be7245bc8835a71a6a1
|
[
"Swift",
"Ruby",
"Markdown"
] | 4 |
Swift
|
danjiang/DTMessageBar
|
e730f26a57e638fa1aa149d1f8431bc2dfe0d033
|
c2e1954bc4a9a7c39f78b68487d8082c31ea6272
|
refs/heads/master
|
<file_sep>const fs = require("fs");
const path = require("path");
const Blocker = require("ad-block");
const client = new Blocker.AdBlockClient();
const file = path.resolve(__dirname, "detector.buffer");
module.exports.client = client;
module.exports.initialize = () =>
new Promise((resolve, reject) => {
fs.readFile(file, (err, buffer) => {
if (err) {
return reject(err);
}
client.deserialize(buffer);
return resolve();
});
});
const none = Blocker.FilterOptions.noFilterOption;
const isAd = (req, base) => client.matches(req, none, base);
module.exports.containsAds = (req, base) => isAd(req, base);
module.exports.isAd = isAd;
<file_sep>function getEnabledPlugins(store) {
return store.get("plugins");
}
function isEnabled(store, plugin) {
return store.get("plugins").indexOf(plugin) > -1;
}
function enablePlugin(store, plugin) {
let plugins = getEnabledPlugins(store);
if (plugins.indexOf(plugin) === -1) {
plugins.push(plugin);
store.set("plugins", plugins);
}
}
function disablePlugin(store, plugin) {
let plugins = getEnabledPlugins(store);
let index = plugins.indexOf(plugin);
if (index > -1) {
plugins.splice(index, 1);
store.set("plugins", plugins);
}
}
module.exports = {
isEnabled : isEnabled,
getEnabledPlugins: getEnabledPlugins,
enablePlugin : enablePlugin,
disablePlugin : disablePlugin
};
<file_sep>const { blockWindowAds } = require("./blocker");
module.exports = win => blockWindowAds(win.webContents);
<file_sep>const { app, Menu } = require("electron");
const { getAllPlugins } = require("./plugins/utils");
const { isPluginEnabled, enablePlugin, disablePlugin } = require("./store");
module.exports.setApplicationMenu = () => {
const menuTemplate = [
{
label : "Plugins",
submenu: getAllPlugins().map(plugin => {
return {
label : plugin,
type : "checkbox",
checked: isPluginEnabled(plugin),
click : item => {
if (item.checked) {
enablePlugin(plugin);
} else {
disablePlugin(plugin);
}
}
};
})
}
];
if (process.platform === "darwin") {
const name = app.getName();
menuTemplate.unshift({
label : name,
submenu: [
{ role: "about" },
{ type: "separator" },
{ role: "hide" },
{ role: "hideothers" },
{ role: "unhide" },
{ type: "separator" },
{
label : "Select All",
accelerator: "CmdOrCtrl+A",
selector : "selectAll:"
},
{ label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
{ label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" },
{ label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" },
{ type: "separator" },
{ role: "minimize" },
{ role: "close" },
{ role: "quit" }
]
});
}
const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
};
|
7fb162d91155c268e65f590fced18e621c2fcde8
|
[
"JavaScript"
] | 4 |
JavaScript
|
pendowski/youtube-music
|
6fd10ea4a0f63e9a46e7307d811977f4e0f3213f
|
1289695a7c0624246506c1996c9b56ba40d2d1b2
|
refs/heads/main
|
<file_sep>
DROP DATABASE IF EXISTS haunted;
CREATE DATABASE haunted;<file_sep># Project-2
Our first full stack application!
# Table of Contents
1. [Description](#description)
2. [Installation](#installation)
3. [Usage](#usage)
4. [License](#license)
5. [Contribution](#contribution)
6. [Questions](#questions)
# Description
# Installation
The first step to installing our project is going to the repository on github(https://github.com/calebp80/Project-2). Once there you will go to the green button that says CODE on it. Click on that button and copy the repo to your clipboard.
The next step is go to your gitbash and navigate to your desktop. Once there you will write the following "git clone" then paste the repo link and press enter. You now have successfully installed our repository on your computer!
The next step is installing our modules that we used to create this project. To get there we first have to get this repo onto your vscode. Using gitbash, navigate to the repo you just created and write the following "code .". You now have vscode up with our project. Now open a new terminal for installing the modules. Write the following "npm install" then the following modules that you are required to install are "express", "express-session", "express-handlebars", "dotenv", "mysql2", and "sequelize".
# Usage
# License
MIT license Copyright
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software with restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS:, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
# Contribution
The following people that contributed to the project were <NAME>, <NAME>, <NAME>, and <NAME>
# Questions
If you have any questions, contact and of us thru our github usernames. Albert:(https://github.com/Alb-rod27), Caleb:(https://github.com/calebp80), Toby:(https://github.com/Tobydawg), and Evan:(https://github.com/evanteems).
<file_sep>
function initMap () {
var options = {
zoom:4,
center: { lat: 37.0902, lng: -95.7129 },
}
//new map
var map = new google.maps.Map(document.getElementById('map'), options);
/*
//marker
var marker = new google.maps.Marker({
position: { lat: 34.0522, lng: -118.2437 },
map:map,
icon: "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png"
});
var infoWindow = new google.maps.InfoWindow({
content: '<h1> Los Angeles, CA </h1>'
});
marker.addListener('click', function(){
infoWindow.open(map, marker);
});
*/
//array of markers
var markers = [
{
coords: { lat: 38.2106, lng: -119.0171},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: '<NAME>: Los Angeles, CA'
},
{
coords: {lat:38.2117, lng: -119.0113 },
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Gregory House Bridgeport, CA'
},
{
coords: {lat: 34.1148, lng: -118.3747},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Bessies Love cabin Los Angeles, CA'
},
{
coords: {lat: 34.1070, lng: -118.3759},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'The Comedy Store Los Angeles, CA'
},
{
coords: {lat: 34.1045, lng: -118.3499},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: '<NAME>s Westwood home Los Angeles, CA'
},
{
coords: {lat: 34.1045, lng: -118.3499},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Nelson House Hollywood, CA'
},
{
coords: {lat: 34.1028, lng: -118.3258},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'The Hollywood Pantages Theatre Hollywood, CA'
},
{
coords: {lat: 34.1024, lng: -118.3258},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: ' The Hollywood Roosevelt Hotel Hollywood, CA'
},
{
coords: {lat: 34.1029, lng: -118.3271},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Club Avalon Hollywood, CA'
},
{
coords: {lat: 36.5978, lng: -121.8976 },
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Colton Hall Museum Monterey, CA'
},
{
coords: {lat: 36.5957, lng: -121.8900},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Presidio Chapel and Rectory Monterey, CA'
},
{
coords: {lat: 32.7518, lng: -117.1932},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'El Camp Santo Cemetary San Diego, CA'
},
{
coords: {lat: 32.7104, lng: -117.1614},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Horton Grand Hotel San Diego, CA'
},
{
coords: {lat: 32.7204, lng: -117.1735},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Star of India San Diego, CA'
},
{
coords: {lat: 38.7324, lng: -120.8086},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Bee Bennett Mansion Placerville, CA'
},
{
coords: {lat: 38.7283, lng: -120.8025},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Cary House Hotel Placerville, CA'
},
{
coords: {lat: 38.5760, lng: -121.4964},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Sacramento Library Sacramento, CA'
},
{
coords: {lat: 38.5763, lng: -121.4978},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Stanford Mansion Sacramento, CA'
},
{
coords: {lat: 35.3777, lng: -119.0215},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Fox Theater Bakersfield, CA'
},
{
coords: {lat: 35.3923, lng: -119.0209},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Kern County Museum Pioneer Village Bakersfield, CA'
},
{
coords: {lat: 37.7728, lng: -122.3025},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'The USS Hornet – Sea, Air, and Space Museum Alameda, CA'
},
{
coords: {lat: 34.9049, lng: -117.0249},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Casa de Desierto Harvey House Museum Barstow, CA'
},
{
coords: {lat: 37.7908, lng: -122.4125},
iconImage: 'https://img.icons8.com/emoji/50/000000/ghost-emoji.png',
content: 'Nob Hill Inn San Francisco, CA'
}
];
//loop through markers
for(var i = 0;i < markers.length;i++){
addMarker(markers[i]);
}
//add marker function
function addMarker(props){
//marker
var marker = new google.maps.Marker({
position: props.coords,
map:map,
// icon:props.iconImage
});
//checking for custom icon
if (props.iconImage){
//set icon image
marker.setIcon(props.iconImage);
}
// check content
if (props.content){
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('click', function(){
infoWindow.open(map, marker);
});
}
}
}
|
c68829c35f7f01740f8273ace6e44e3262889b0f
|
[
"Markdown",
"SQL",
"JavaScript"
] | 3 |
SQL
|
calebp80/Project-2
|
f1ba61ab4f8b8ef511d10dbe9363131028fd183e
|
75503b7666ed5f2c8d57c538a61413e17b70fe7c
|
refs/heads/main
|
<file_sep># Changelog
## 1.5
- New official support for BeOS R5, Tru64 5.1B, SunOS 4.1 and IRIX 6.5,
with contributed support for the Mac OS X Public Beta, Cheetah and Puma,
NeXTSTEP 3.3 on 68K, Professional MachTen 2.3 on 68K, IRIX 6.5 with gcc
and Haiku R1.
- Fixed test failures on A/UX and Power MachTen.
- Compile-time options for reducing issues with unaligned pointers and
local variable size.
- Converts all comments to `/* */` for better compiler compatibility.
- Improves RFC 8422 compliance, fixing some server incompatibilities.
- Using secp521r1 due to issues with internal curve25519 implementation
(to be fixed).
- Adds `-N` option to `carl` and expands exit statuses.
## 1.0
- Initial release on Mac OS X 10.2+, Rhapsody/Mac OS Server, NeXTSTEP 3.3
on PA-RISC, macOS, Linux, NetBSD, A/UX 3.1, AIX 4+ and Power MachTen 4.1.4.
<file_sep>/*
* Crypto Ancienne Resource Loader "carl" (and example application)
* Copyright 2020-1 <NAME>. All rights reserved.
* BSD license (see README.md)
*/
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#if !defined(__AUX__) && (!defined(NS_TARGET_MAJOR) || (NS_TARGET_MAJOR > 3)) && !defined(__MACHTEN_68K__) && !defined(__sun) && !defined(__BEOS__) && (!defined(__hppa) && !defined(__hpux))
#include <sys/select.h>
#endif
#include <netinet/in.h>
#include <netdb.h>
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
/* stdint or equivalent set here */
#include "cryanc.c"
int quiet = 0;
int proxy = 0;
int http09 = 0;
#if defined(__BEOS__)
#include <fcntl.h>
#if defined(BONE_VERSION)
#warning not tested with BONE
#endif
/* ping-pong interval for semi-busy wait */
#define TIMESLICE 1000
/* BeOS is "special" with stdin, and select() doesn't work with it. */
int stdin_pending() {
int i, j;
char c;
/* hack: don't check if we're not in proxy mode, we don't use it. */
if (!proxy) return 0;
/* check tty ioctl first */
i = ioctl(0, 'ichr', &j);
if (i >= 0 && j > 0) return 1;
/* "peek" at stdin (must already be non-blocking) */
return (read(fileno(stdin), &c, 0) >= 0);
}
#endif
void error(char *msg, int code) {
if (proxy) {
if (!http09)
fprintf(stdout, "HTTP/1.0 502 Proxy Error\r\n"
"Content-type: text/html\r\n\r\n");
fprintf(stdout, "%s\n", msg);
exit(code);
}
if (!quiet) {
if (errno > 0) perror(msg); else fprintf(stdout, "%s\n", msg);
}
exit(code);
}
void timeout() { /* portable enough */
error("Timeout", 254);
}
int https_send_pending(int client_sock, struct TLSContext *context) {
unsigned int out_buffer_len = 0;
unsigned int out_buffer_index = 0;
int send_res = 0;
const unsigned char *out_buffer = tls_get_write_buffer(context, &out_buffer_len);
while ((out_buffer) && (out_buffer_len > 0)) {
int res = send(client_sock, (char *)&out_buffer[out_buffer_index], out_buffer_len, 0);
if (res <= 0) {
send_res = res;
break;
}
out_buffer_len -= res;
out_buffer_index += res;
}
tls_buffer_clear(context);
return send_res;
}
/* NYI */
int validate_certificate(struct TLSContext *context, struct TLSCertificate **certificate_chain, int len) {
int i;
if (certificate_chain) {
for (i = 0; i < len; i++) {
struct TLSCertificate *certificate = certificate_chain[i];
/* check certificate ... */
}
}
/* return certificate_expired;
// return certificate_revoked;
// return certificate_unknown; */
return no_error;
}
int scheme_is(char *url, char *scheme) {
if (strlen(url) <= strlen(scheme)) return 0;
return (strstr(url, scheme) == url);
}
/* given a URL string, set hostname, port and protocol (identified by well
known service port number) and return where in the string the path
starts (or NULL if it didn't parse correctly). */
char *parse_url(char *url, char *hostname, size_t *port, size_t *proto) {
char *h, *p, *pn;
unsigned int i;
if (scheme_is(url, "socks://")) {
*proto = 1080;
} else if (scheme_is(url, "socks5://")) {
*proto = 1080;
} else if (scheme_is(url, "http://")) {
*proto = 80;
} else if (scheme_is(url, "https://")) {
*proto = 443;
} else
return NULL; /* we don't know this protocol */
/* find the second slash: that's where the hostname starts. */
for (h=url,i=0;*h && i!=2;h++) if(*h=='/') i++;
if (i != 2) return NULL; /* ran off the end of the string */
/* find the third slash: that's where the selector starts. */
for (p=h;*p && i!=3;p++) if(*p=='/') i++;
/* if there is no third slash, treat as a zero-length path */
if (i == 3) p--;
/* hostname:port must be at least 1 character long. */
if ((p - h) < 1) return NULL;
if ((pn = strchr(h, ':')) && pn < p) {
/* automatic null termination */
char sport[6] = { 0, 0, 0, 0, 0, 0 };
/* check hostname and port lengths */
if (pn == h || (pn - h) > 255 || (p - pn) < 2 || (p - pn) > 6)
return NULL;
memcpy((void *)hostname, (void *)h, (pn - h));
*(hostname + (pn - h)) = '\0';
memcpy((void *)&sport, (void *)++pn, (p - pn));
*port = atoi(sport);
if (*port < 1 || *port > 65535) return NULL;
/* atoi will allow something like :3aa but we shouldn't */
if (*port < 10 && (p - pn) != 1) return NULL;
if (*port > 9 && *port < 100 && (p - pn) != 2) return NULL;
if (*port > 99 && *port < 1000 && (p - pn) != 3) return NULL;
if (*port > 999 && *port < 10000 && (p - pn) != 4) return NULL;
} else {
if ((p - h) > 255) return NULL;
memcpy((void *)hostname, (void *)h, (p - h));
*(hostname + (p - h)) = '\0';
*port = *proto;
}
/* we don't support authority information currently */
if (strchr(hostname, '@')) return NULL;
return p;
}
void help(int longdesc, char *me) {
fprintf(stderr, "Crypto Ancienne Resource Loader v1.5-git\n");
if (!longdesc) return;
fprintf(stderr,
"Copyright (C)2020-1 <NAME> and Contributors. All rights reserved.\n"
"usage: %s [option] [url (optional if -p)]\n\n"
"protocols: http https\n\n"
"-h This message\n"
"-v Version string\n"
"-p Proxy mode (accepts HTTP client request on stdin, ignores -i -q -H)\n"
" If url is also specified, it may be a socks:// URL only\n"
"-H HEAD request (default is GET)\n"
"-N Ignore ALL_PROXY environment variable\n"
"-q Emit no errors, only status code\n"
"-i Dump both headers and body (default is body only, irrelevant if -H or -p)\n"
"-t No timeout (default is 10s)\n"
"-u Upgrade HTTP requests to HTTPS transparently\n"
"-s Spoof HTTP/1.1 replies as HTTP/1.0 (irrelevant without -H, -p or -i)\n"
, me);
}
int main(int argc, char *argv[]) {
int sockfd, n, proxycon = 0, forever = 0, spoof10 = 0;
size_t portno, socksport, proto, socksproto, numcrs = 0, bytesread = 0;
struct sockaddr_in serv_addr;
struct hostent *server, *socksserver;
fd_set fdset;
char hostname[256], sockshost[256], *buffer;
unsigned char read_buffer[BIG_STRING_SIZE];
unsigned char client_message[8192];
int read_size;
int sent = 0, arg = 0, head_only = 0, with_headers = 0, upgrayedd = 0;
char *path = NULL, *url = NULL, *proxyurl = NULL;
struct TLSContext *context;
#if defined(__BEOS__)
struct timeval tv;
int i, j;
#endif
proxyurl = getenv("ALL_PROXY");
for(;;) {
if (++arg >= argc) {
if (proxy) break;
help(1, argv[0]);
return 1;
}
if (argv[arg][0] != '-') {
url = argv[arg];
break;
}
if (strchr(argv[arg], 'v')) { help(0, argv[0]); return 0; }
if (strchr(argv[arg], 'h')) { help(1, argv[0]); return 0; }
if (strchr(argv[arg], 'i')) { with_headers = 1; }
if (strchr(argv[arg], 'H')) { head_only = 1; with_headers = 1; }
if (strchr(argv[arg], 'N')) { proxyurl = NULL; }
if (strchr(argv[arg], 'u')) { upgrayedd = 1; }
if (strchr(argv[arg], 's')) { spoof10 = 1; }
if (strchr(argv[arg], 't')) { forever = 1; }
if (strchr(argv[arg], 'q')) { quiet = 1; }
if (strchr(argv[arg], 'p')) { proxy = 1; }
}
if (proxy) {
/* receiving a proxy request from stdin */
char method[10], purl[2048], c;
int mc = 0, mu = 0, got_method = 0, got_url = 0;
if (url) proxyurl = url;
head_only = 0; quiet = 1; with_headers = 0; http09 = 1;
method[0] = '\0'; purl[0] = '\0';
for(;;) {
if (!read(STDIN_FILENO, &c, 1))
return 1; /* something's wrong */
if (c == ' ') {
if (!got_method) { got_method = 1; continue; }
if (!got_url) { got_url = 1; http09 = 0; break; }
return 1; /* something's wrong here too */
}
if (c == '\r') {
if (!got_method) return 1;
if (got_url) return 1; /* ?! */
got_url = 1; continue;
}
if (c == '\n') {
if (got_method) break;
return 1; /* something's wrong here too */
}
if (!got_method) {
method[mc++] = (char)c; method[mc] = '\0';
if (mc == 9) return 1; /* bogus method */
continue;
}
if (!got_url) {
purl[mu++] = (char)c; purl[mu] = '\0';
if (mu == 2047) return 1; /* too long */
continue;
}
fprintf(stderr, "unhandled character: %c\n", (char)c);
return 255;
}
/* at this point, we either have a complete 0.9 request, or a 1.0/1.1
request with more bytes to follow. */
if (!strlen(method) || !strlen(purl)) return 1;
if (http09 && strcmp(method, "GET")) {
/* handle specially */
fprintf(stdout, "Only GET is supported for HTTP/0.9\n");
return 1;
}
if (!strcmp(method, "CONNECT")) {
error("CONNECT is not supported by this proxy", 1);
}
if (!(path = parse_url(purl, hostname, &portno, &proto))) {
error("Did not understand URL", 1);
}
if (proto != 80 && proto != 443) {
error("Unsupported protocol", 1);
}
if (upgrayedd && proto == 80) {
proto = 443;
if (portno == 80) portno = 443;
}
if (http09) {
/* convert into an HTTP/1.0 request, headers suppressed */
buffer = malloc(strlen(hostname) + strlen(path) + 256);
if (proto != portno) {
(void)sprintf(buffer,
"GET %s HTTP/1.0\r\n"
"Host: %s:%d\r\n"
"Connection: close\r\n"
"\r\n",
(strlen(path) ? path : "/"), hostname, portno);
} else {
(void)sprintf(buffer,
"GET %s HTTP/1.0\r\n"
"Host: %s\r\n"
"Connection: close\r\n"
"\r\n",
(strlen(path) ? path : "/"), hostname);
}
} else {
/* HTTP/1.0 or 1.1. read the rest of the headers */
char *has_host;
char hosthost[512], hostport[512];
int crlf = 0;
read_size = 0;
numcrs = 0;
with_headers = 1;
for(;;) {
if (!read(STDIN_FILENO, &c, 1))
return 1; /* underflow */
read_buffer[read_size++] = c;
if (read_size == BIG_STRING_SIZE) return 1; /* overflow */
if (c == '\n') {
if (++numcrs == 2) break; else continue;
}
if (c == '\r') continue;
numcrs = 0;
}
numcrs = 0;
if (read_size < 4) return 1; /* unpossible */
if (read_buffer[(read_size-1)] == read_buffer[(read_size-2)]) {
/* ends in \n\n, hmm */
read_buffer[(read_size-1)] = '\0';
} else if (read_buffer[(read_size-4)] == '\r' &&
read_buffer[(read_size-1)] == read_buffer[(read_size-3)]) {
/* can only end in \r\n\r\n */
read_buffer[(read_size-2)] = '\0';
crlf = 1;
} else return 1; /* huh? */
/* compute host header. we need to either add it or check it.
some clients will append :80 (WebTV), so generate both. */
(void)sprintf(hostport, "Host: %s:%d%s",
hostname, portno, (crlf) ? "\r\n" : "\n");
(void)sprintf(hosthost, "Host: %s%s",
hostname, (crlf) ? "\r\n" : "\n");
if (has_host = strstr((char *)read_buffer, "Host: ")) {
/* to make this simpler, RFC 7230 gives us a way to cheat.
if there is a Host: header here, it must match the hostname
in the URL. if it doesn't, abort. */
/* multiple Host: headers? eat my shorts. */
if (strstr(++has_host, "Host: ")) return 1;
/* header is bogus? eat more of my shorts. */
if (proto != portno) { /* only allow host:port */
if (!strstr((char *)read_buffer, hostport)) return 1;
} else { /* allow either */
if (!strstr((char *)read_buffer, hosthost) &&
!strstr((char *)read_buffer, hostport)) return 1;
}
/* acceptable; use client header set */
buffer = malloc(strlen(method) + strlen(path) +
strlen((char *)read_buffer) + 256);
(void)sprintf(buffer, "%s %s %s%s",
method, (strlen(path) ? path : "/"),
read_buffer, (crlf) ? "\r\n" : "\n");
} else {
/* add Host: header */
buffer = malloc(strlen(method) + strlen(path) +
strlen((char *)read_buffer) +
strlen((portno != proto) ? hostport :
hosthost) + 256);
(void)sprintf(buffer, "%s %s %s%s%s",
method, (strlen(path) ? path : "/"),
read_buffer,
(portno != proto) ? hostport : hosthost,
(crlf) ? "\r\n" : "\n");
}
}
} else {
/* url provided on command line */
if (!(path = parse_url(url, hostname, &portno, &proto))) {
if (!quiet) fprintf(stderr, "%s: couldn't parse url\n", argv[0]);
return 1;
}
if (proto == 1080) {
if (!quiet) fprintf(stderr, "%s: socks only allowed for proxies\n",
argv[0]);
return 1;
}
if (proto != 80 && proto != 443) {
if (!quiet) fprintf(stderr, "%s: unsupported protocol\n", argv[0]);
return 1;
}
if (upgrayedd && proto == 80) {
proto = 443;
if (portno == 80) portno = 443;
}
buffer = malloc(strlen(hostname) + strlen(path) + 256);
if (proto != portno) {
(void)sprintf(buffer,
"%s %s HTTP/1.0\r\n"
"Host: %s:%d\r\n"
"Connection: close\r\n"
"\r\n",
(head_only ? "HEAD" : "GET"), (strlen(path) ? path : "/"),
hostname, portno);
} else {
(void)sprintf(buffer,
"%s %s HTTP/1.0\r\n"
"Host: %s\r\n"
"Connection: close\r\n"
"\r\n",
(head_only ? "HEAD" : "GET"), (strlen(path) ? path : "/"),
hostname);
}
}
signal(SIGPIPE, SIG_IGN);
signal(SIGALRM, timeout);
if (!forever) (void)alarm(10);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("socket", 255);
server = gethostbyname(hostname);
if (server == NULL) {
if (proxy) error("Host not found", 2);
if (!quiet) fprintf(stderr, "host not found: %s\n", hostname);
return 2;
}
memset((char *) &serv_addr, 0, sizeof(serv_addr)); /* blocking socket */
serv_addr.sin_family = AF_INET;
if (proxyurl) {
/* basic socks 4 client, no NO_PROXY support yet */
if (parse_url(proxyurl, sockshost, &socksport, &socksproto)) {
unsigned char spacket[9];
size_t sbytes = 0;
if (socksproto != 1080) {
if (!quiet) fprintf(stderr, "unsupported proxy protocol\n");
return 1;
}
if (server->h_length != 4) {
if (!quiet) fprintf(stderr, "IPv6 not supported for SOCKS4\n");
return 3;
}
spacket[0] = 0x04; /* socks v4 */
spacket[1] = 0x01; /* connect */
spacket[2] = portno >> 8;
spacket[3] = portno & 0xff;
spacket[4] = (unsigned char)server->h_addr[0];
spacket[5] = (unsigned char)server->h_addr[1];
spacket[6] = (unsigned char)server->h_addr[2];
spacket[7] = (unsigned char)server->h_addr[3];
spacket[8] = 0x00;
socksserver = gethostbyname(sockshost);
if (socksserver == NULL) {
if (!quiet) fprintf(stderr, "SOCKS proxy not found: %s\n",
sockshost);
return 2;
}
memcpy((char *)&serv_addr.sin_addr.s_addr,
(char *)socksserver->h_addr, socksserver->h_length);
serv_addr.sin_port = htons(socksport);
if (connect(sockfd,(struct sockaddr *)&serv_addr,
sizeof(serv_addr)) < 0)
error("connect to SOCKS", 4);
/* we should be able to send this much without blocking */
if (send(sockfd, spacket, 9, 0) != 9)
error("send to SOCKS", 4);
while ((read_size = recv(sockfd, (char *)&spacket[sbytes],
9-sbytes, 0)) > 0) {
sbytes += read_size;
if (sbytes == 8) break;
}
if (sbytes != 8 || spacket[0] != 0x00 ||
spacket[1] < 0x5a || spacket[1] > 0x5d) {
error("SOCKS connect failed", 5);
}
if (spacket[1] != 0x5a) {
if (proxy) error("SOCKS connect failed", 5);
if (!quiet) fprintf(stderr, "SOCKS connect: %i\n", spacket[1]);
return 5;
}
proxycon = 1;
} else {
error("illegal proxy URL", 1);
}
}
/* connect to host */
if (!proxycon) {
memcpy((char *)&serv_addr.sin_addr.s_addr, (char *)server->h_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("connect", 5);
}
/* set up http or tls */
if (proto == 443) {
context = tls_create_context(0, TLS_V12);
if (!tls_sni_set(context, hostname)) error("TLS context failure", 255);
tls_client_connect(context);
https_send_pending(sockfd, context);
} else {
/* on plain HTTP, try to send the initial request right now */
size_t buffer_index = 0;
size_t buffer_len = strlen(buffer);
while (buffer_len) {
int res = send(sockfd, (char *)&buffer[buffer_index],
buffer_len, 0);
if (res > 0) {
buffer_len -= res;
buffer_index += res;
}
}
}
/* read from socket and, if needed, stdin */
#if defined(__BEOS__)
(void)fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
#endif
if (proto == 80) {
for(;;) {
if (!forever) (void)alarm(10);
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
#if !defined(__BEOS__)
FD_SET(STDIN_FILENO, &fdset);
(void)select(sockfd + 1, &fdset, NULL, NULL, NULL); /* wait */
/* send any post-headers data, like POST forms, etc. */
if (FD_ISSET(STDIN_FILENO, &fdset)) {
#else
/* In BeOS and Win32 select() only works on sockets, not on
standard file handles, so we must ping-pong. */
tv.tv_sec = 0;
tv.tv_usec = TIMESLICE;
(void)select(sockfd + 1, &fdset, NULL, NULL, &tv); /* wait */
if (stdin_pending()) {
#endif
size_t buffer_index = 0;
read_size = read(STDIN_FILENO, read_buffer, BIG_STRING_SIZE);
while (read_size) {
int res = send(sockfd, (char *)&read_buffer[buffer_index],
read_size, 0);
if (res > 0) {
read_size -= res;
buffer_index += res;
}
}
}
if (FD_ISSET(sockfd, &fdset)) {
if ((read_size = recv(sockfd, client_message, sizeof(client_message) , 0)) > 0) {
bytesread += read_size;
if (!with_headers) {
size_t i = 0;
for(i=0; i<read_size; i++) {
if (client_message[i] == '\r') continue;
if (client_message[i] == '\n') numcrs++;
else numcrs = 0;
if (numcrs == 2) { break; }
}
if (numcrs < 2) continue;
with_headers = 1; spoof10 = 0; /* paranoia */
for(i++; i<read_size; i++)
fwrite(&(client_message[i]), 1, 1, stdout);
} else {
if (spoof10) {
if (read_size > 7 &&
client_message[0] == 'H' &&
client_message[1] == 'T' &&
client_message[2] == 'T' &&
client_message[3] == 'P' &&
client_message[4] == '/' &&
client_message[5] == '1' &&
client_message[6] == '.' &&
client_message[7] == '1') {
client_message[7] = '0';
spoof10 = 0;
}
}
fwrite(client_message, read_size, 1, stdout);
}
} else break; /* ready socket, no bytes: connection closed */
}
/* some sort of signal, loop around */
}
} else if (proto == 443) {
for(;;) {
if (!forever) (void)alarm(10);
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
#if !defined(__BEOS__)
FD_SET(STDIN_FILENO, &fdset);
(void)select(sockfd + 1, &fdset, NULL, NULL, NULL); /* wait */
#else
tv.tv_sec = 0;
tv.tv_usec = TIMESLICE;
(void)select(sockfd + 1, &fdset, NULL, NULL, &tv); /* wait */
#endif
/* service socket first, since we may still be setting up TLS */
if (FD_ISSET(sockfd, &fdset)) {
if ((read_size = recv(sockfd, client_message, sizeof(client_message) , 0)) > 0) {
int i = tls_consume_stream(context, client_message, read_size, validate_certificate);
if (i < 0) {
if (errno > 0) perror("tls_consume_stream");
if (!quiet) fprintf(stderr, "fatal TLS error: %d\n", i);
return 6;
}
https_send_pending(sockfd, context);
/* no point in anything further until TLS established */
if (!tls_established(context)) continue;
/* TLS up, try to send initial portion of request now */
if (!sent) {
tls_write(context, (unsigned char *)buffer, strlen(buffer));
https_send_pending(sockfd, context);
sent = 1;
}
while (read_size = tls_read(context, read_buffer, BIG_STRING_SIZE - 1)) {
bytesread += read_size;
if (!with_headers) {
size_t i = 0;
for(i=0; i<read_size; i++) {
if (read_buffer[i] == '\r') continue;
if (read_buffer[i] == '\n') numcrs++;
else numcrs = 0;
if (numcrs == 2) { break; }
}
if (numcrs < 2) continue;
with_headers = 1; spoof10 = 0; /* paranoia */
for(i++; i<read_size; i++)
fwrite(&(read_buffer[i]), 1, 1, stdout);
} else {
if (spoof10) {
if (read_size > 7 &&
read_buffer[0] == 'H' &&
read_buffer[1] == 'T' &&
read_buffer[2] == 'T' &&
read_buffer[3] == 'P' &&
read_buffer[4] == '/' &&
read_buffer[5] == '1' &&
read_buffer[6] == '.' &&
read_buffer[7] == '1') {
read_buffer[7] = '0';
spoof10 = 0;
}
}
fwrite(read_buffer, read_size, 1, stdout);
}
}
} else break; /* ready socket, no bytes: connection closed */
}
/* send any post-headers data, like POST forms, etc. */
#if !defined(__BEOS__)
if (FD_ISSET(STDIN_FILENO, &fdset) && sent) {
#else
if (stdin_pending() && sent) {
#endif
size_t buffer_index = 0;
/* no point until TLS is established */
if (!tls_established(context)) continue;
read_size = read(STDIN_FILENO, read_buffer, BIG_STRING_SIZE);
tls_write(context, (unsigned char *)read_buffer, read_size);
https_send_pending(sockfd, context);
}
}
} else { /* profit! */ }
if (!bytesread) {
if (proto == 443 && context->error_code) {
(void)sprintf((char *)read_buffer,
"TLS alert received: %d\n", context->error_code);
error((char *)read_buffer, 6);
}
error("No data received", 253);
}
free(buffer);
return 0;
}
<file_sep># Crypto Ancienne: TLS for the Internet of Old Things
Copyright (C) 2020-1 <NAME> and Contributors. All rights reserved.
Crypto Ancienne, or Cryanc for short, is a TLS library
with an aim for compatibility with pre-C99 C compilers and
geriatric architectures. The [TLS apocalypse](http://tenfourfox.blogspot.com/2018/02/the-tls-apocalypse-reaches-power-macs.html) may have knocked these hulking beasts out
of the running for awhile, but now it's time for the Great Old Computing Ones
to reclaim the Earth. That old server in your closet? It's only been sleeping,
and now it's ready to take back the Web on the Web's own terms. 1997 just called and
it's *ticked*.
Cryanc is intended as a *client* library. Although it can facilitate acting as a server,
this is probably more efficiently and safely accomplished with a separate reverse proxy
to which the encryption can be offloaded.
**The use of this library does not make your application cryptographically
secure, and certain systems may entirely lack any technological means to
make that possible. Its functionality and security should be regarded as,
at best, "good enough to shoot yourself in the foot with."**
## Before you file an issue
- If you are filing an issue for a modern system, you should be using one of the upstream libraries, not this one. If you don't know what the upstreams are, you should read the next section before you do *anything else*.
- If you have not tested your issue against upstream, you should do that first. If it's an upstream bug, don't file it here.
- If you use this for something mission-critical, you are stupid. It may work, but you're still stupid.
- Issues without patches or PRs may or may not be addressed. Ever.
## Supported features
- TLS 1.2 with SNI (based on [TLSe](https://github.com/eduardsui/tlse) with local improvements)
- Most standard crypto algorithms (from [`libtomcrypt`](https://github.com/libtom/libtomcrypt))
- Built-in PRNG (`arc4random` from OpenBSD, allegedly, they tell me), with facultative seeding from `/dev/urandom` if present
In addition, `carl`, the included `curl`-like utility and the Cryanc example application, also has:
- SOCKSv4 client support (keep your Old Ones behind a firewall, they tend to cause mental derangement in weaker humans)
- HTTP and HTTPS proxy feature with similarly ancient browsers that do not insist on using `CONNECT` (requires `inetd` or `inetd`-like connecting piece such as [`micro_inetd`](https://acme.com/software/micro_inetd/))
See the `carl` manual page in this repo for more (in `man` and Markdown format).
## Not yet supported but coming soon
**Don't file issues about these.** If you do, they will be closed as "user doesn't read
documentation" and offenders will be ravenously eaten.
- TLS 1.3. Many sites work but some abort during transmission like Github.
- No 0-RTT or session resumption.
- No ECDSA support. As a result, although certificate validation is available in the library, it is not presently enabled in `carl` as it can't yet validate ECDSA certificates.
- ChaCha20 not yet supported on big-endian.
These are all acknowledged limitations in TLSe and should improve as upstream does.
- Support for other, possibly better (C)PRNGs or the old `prngd`/`egd` protocol.
## Working configurations
These are tested using `carl`, which is the included example. Most configurations can build simply with `gcc -O3 -o carl carl.c`. The magic for operating system support is almost all in `cryanc.c`.
- Linux (`gcc`). This is tested on `ppc64le` but pretty much any architecture should work.
- NetBSD (`gcc`). Ditto, and probably works on most other BSDs. If someone wants to give this a whack on 4.4BSD or Ultrix I would be highly amused.
Mach family:
- Mac OS X 10.2 through at least 10.14 (PowerPC, `i386`, `x86_64`; Xcode `gcc` 3.3+ or `clang`)
- Mac OS X Server v1.2/Rhapsody 5.6 (PowerPC; `cc` (actually `gcc` 2.7.2.1))
- Tru64 5.1B (Alpha; `cc` (actually Compaq C V6.5)). Must compile with `-misalign`.
- NeXTSTEP 3.3 (HP PA-RISC; `cc` (actually `gcc` 2.5))
- Power MachTen 4.1.4 (PowerPC; `gcc` 2.8.1; `setstackspace 1048576 /usr/bin/cpp` and `setstackspace 4194304 /usr/bin/as`)
OpenSTEP 4.0 probably also works given that these all do.
- IRIX 6.5.30 (SGI MIPS; `cc` (actually MIPSPro 7.4.4m)). For 6.5.22, you may need to use `c99` (older MIPSPro versions may also work with `c99`).
- AIX 4+ (PowerPC, Power ISA; `gcc` 2.7.2.2 and 4.8). This is tested on 4.1.5 and 6.1, and should "just work" on 5L and 7.
- A/UX 3.1 (68K; `gcc` 2.7.2.2, requires `-lbsd`)
- SunOS 4.1 (SPARC; `gcc` 2.95.2). Binary compatible with Solbourne OS/MP. Tested on OS/MP 4.1C (SunOS 4.1.3).
## Working contributed configurations
These are attested to be working but are maintained by others.
- Mac OS X Public Beta through 10.1 (PowerPC; Apple `cc` 912+ (actually `gcc` 2.95.2))
- NeXTSTEP 3.3 (68K; `cc` (actually `gcc` 2.5))
- Professional MachTen 2.3 (68K; `gcc` 2.7.2.f.1)
- IRIX 6.5 (SGI MIPS; `gcc` 9.2.0)
- Haiku R1/beta2 (`x86_64`; `gcc` 8.3.0, requires `-lnetwork`)
- Solaris 9 and 10 (`sparcv9`; `gcc` 2.95.3+, requires `-lsocket -lnsl`)
- OpenServer 6 (`i386`; `gcc` 7.3.0, requires `-lsocket`)
- HP-UX 11.31 (`ia64`; `cc` A.06.26 and `gcc` 4.7.4)
- HP-UX 11.11+ (`hppa`; `gcc` 4.7.1)
- HP-UX 10.20 (`hppa`; `gcc` 2.95.3, requires `-Doldhpux`)
## Partially working configurations
- BeOS R5 (PowerPC BeBox; `cc` (actually Metrowerks CodeWarrior `mwcc` 2.2)). Functions properly at optimization levels `-O2` and below (`-O3` miscompiles). Due to differences in the way BeOS treats standard input, reading proxy requests from the TTY doesn't currently work (it does from files). Should work with `x86`; not tested with Dano, ZETA, BONE or `gcc`.
## Not tested or not working but might in the future
- Classic Mac OS (PowerPC with GUSI and MPW `gcc` 2.5). For full function this port would also need an `inetd`-like tool such as [ToolDaemon](https://github.com/fblondiau/ToolDaemon). For now, your best bet is to use Power MachTen.
- It should be possible to port to Win32 with something like `mxe`; there are hooks for it in TLSe already.
- Solaris 2+ should work now that SunOS 4 does.
- HP-UX. We have 8.0 on 68K and 11i on PA-RISC locally.
## Porting it to your favourite geriatric platform
Most other platforms with `gcc` 2.5 or higher, support for 64-bit ints
(usually `long long`) and `stdarg.h` should "just work."
If your system lacks `stdint.h`, you can try using `-DNOT_POSIX=1` to use the built-in
definitions. You may also need to add `-include stdarg.h` and other headers. Consider
compiling with `-DDEBUG` if you get crashes so you can see where it dies (it's also
a neat way to see TLS under the hood).
Once you figure out the secret sauce, we encourage you to put some additional blocks
into `cryanc.c` to get the right header files and compiler flags loaded. PRs accepted for
these as long as no presently working configuration is regressed. Similarly, we would
love to further expand our compiler support, though we now support quite a few.
A few architectures, especially old RISC, may not like the liberties taken
with unaligned pointers. For these systems try `-DNO_FUNNY_ALIGNMENT`.
However, this is not well tested, and we may not have smoked all of them out
(for example, it's not good enough for DEC Alpha on Tru64, the king of alignment-finicky
configurations, and we still have to compile with `-misalign`). Currently this define assumes big-endian.
Large local stack allocations are occasionally used for buffering efficiency.
If your compiler doesn't like this (Metrowerks comes to mind), try
`-DBIG_STRING_SIZE=xx`, substituting a smaller buffer size like 16384 or 4096.
Some systems may be too slow for present-day server expectations and thus will appear
not to function even if the library otherwise works correctly. In our testing this starts to become
a problem for CPUs slower than 40MHz or so, regardless of architecture. Even built with `-O3`, our little NetBSD
Macintosh IIci with a 25MHz 68030 and no L2 card took 22 seconds
(give `carl` the `-t` option to
disable timeouts) for a single short TLS 1.2
transaction to a local test server; a number of Internet hosts we tested it with simply cut the
connection instead of waiting. Rude!
## Using it in your application
A simple `#include "cryanc.c"` is sufficient (add both `cryanc.c` and `cryanc.h` to your
source code). `cryanc.h` serves to document the more or less public interface and
can be used if you turn Cryanc into a library instead of simply merging it into your source.
`carl` demonstrates the basic notion:
- open a TCP socket
- `tls_create_context` creates the TLS context (`TLS_V12` or `TLS_V13`)
- `tls_sni_set` sets the SNI hostname for the context
- `tls_client_connect` initializes the connection
Your application then needs to service reads and writes. The loop at the end of
`carl` is a complete example, using `select(3)` to determine when data has
arrived.
As data accumulates from the TLS hello and calls to `tls_write`,
it should check `tls_get_write_buffer` and send this data down the socket. `carl`
has a helper function called `https_send_pending` which it calls periodically to
do this. Once the context write buffer is serviced, it
clears the context buffer with `tls_buffer_clear`.
Likewise, as data is read from the socket, it is sent to `tls_consume_stream`. When
the secure connection is established, `tls_established` will become true for the
context and you can read data from `tls_read`.
If a TLS alert occurs, it can be fetched from `context->error_code`.
## Language pedantry note
Here, "crypto" is short for *la cryptographie* and therefore the use of the feminine
singular *ancienne*, so there.
## Licenses and copyrights
Crypto Ancienne is released under the BSD license.
Copyright (C) 2020-1 <NAME> and Contributors. All rights reserved.
Based on TLSe. Copyright (C) 2016-2020 <NAME>. All rights reserved.
Based on Adam Langley's implementation of Curve25519. Copyright (C) 2008 Google, Inc. All rights reserved.
Based on OpenBSD's `arc4random` (allegedly). Copyright (C) 1996 <NAME>. All rights reserved.
Based on `libtomcrypt` by <NAME> and contributors.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
|
7806371daa9f855f8c7cd92427950235f78f84f5
|
[
"Markdown",
"C"
] | 3 |
Markdown
|
larb0b/cryanc
|
7eab587fb71de94460e9f905b4752b196c4bf79a
|
4c8915e142c8574678ca9e7cfd649f4b4ccbbff5
|
refs/heads/master
|
<repo_name>tanmaygr/OcrApp<file_sep>/app/src/main/java/com/example/tanmay/myapplication/camera.java
package com.example.tanmay.myapplication;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer;
import com.google.firebase.ml.vision.text.RecognizedLanguage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import static com.example.tanmay.myapplication.MainActivity.string;
public class camera extends AppCompatActivity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
private File output=null;
TextView vanshaj;
Canvas canvas;
String phrase;
Bitmap photo;
String currentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
vanshaj=findViewById(R.id.textView2);
vanshaj.setMovementMethod(new ScrollingMovementMethod());
imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
phrase= string;
canvas=new Canvas();
photoButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
// Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//// File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
//// output=new File(dir, FILENAME);
//
//// cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
//
//
// startActivityForResult(cameraIntent, CAMERA_REQUEST);
dispatchTakePictureIntent();
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
// Toast.makeText(this, "Fail Inside dispatchPicture", Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
// Toast.makeText(this, "In Uri", Toast.LENGTH_SHORT).show();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
// onActivityResult();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Vanshaj","Vanshajjjj");
// if(requestCode==CAMERA_REQUEST&&resultCode == Activity.RESULT_OK){
setPic();
// }
}
public void setPic() {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
// Toast.makeText(this, "In setPic", Toast.LENGTH_SHORT).show();
Log.d("aryan","aryan");
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
imageView.setImageBitmap(bitmap);
textRecognisition(bitmap);
}
public void textRecognisition(Bitmap photo){
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(photo);
FirebaseVisionTextRecognizer detector = FirebaseVision.getInstance()
.getOnDeviceTextRecognizer();
Task<FirebaseVisionText> result =
detector.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
@Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
String resultText = firebaseVisionText.getText();
for (FirebaseVisionText.TextBlock block: firebaseVisionText.getTextBlocks()) {
String blockText = block.getText();
Float blockConfidence = block.getConfidence();
Log.d("InLoop",blockText+" "+blockConfidence);
List<RecognizedLanguage> blockLanguages = block.getRecognizedLanguages();
Log.d("blockLang",blockLanguages.toString());
Point[] blockCornerPoints = block.getCornerPoints();
Rect blockFrame = block.getBoundingBox();
for (FirebaseVisionText.Line line: block.getLines()) {
String lineText = line.getText();
Log.d("InSecondLoop",lineText);
Float lineConfidence = line.getConfidence();
// Log.d("lineConf",lineConfidence);
List<RecognizedLanguage> lineLanguages = line.getRecognizedLanguages();
Point[] lineCornerPoints = line.getCornerPoints();
if(lineCornerPoints!=null)
Log.d("inLINEPOINTS",lineCornerPoints.toString());
Rect lineFrame = line.getBoundingBox();
// Paint paint=new Paint();
for (FirebaseVisionText.Element element: line.getElements()) {
String elementText = element.getText();
Float elementConfidence = element.getConfidence();
List<RecognizedLanguage> elementLanguages = element.getRecognizedLanguages();
Point[] elementCornerPoints = element.getCornerPoints();
Rect elementFrame = element.getBoundingBox();
Log.d("elementFrame",elementFrame.toString());
if (elementText.toLowerCase().equals(phrase.toLowerCase())){
// Log.d("PointAndRect",blockText+" -> "+blockFrame.toString());
Bitmap mutableBitmap = photo.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
Paint paint = new Paint();
paint.setStrokeWidth(12);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
Rect rectangle = new Rect(elementFrame);
canvas.drawRect(rectangle,paint);
imageView.setImageBitmap(mutableBitmap);
break;
}
}
}
}
// Toast.makeText(camera.this,resultText, Toast.LENGTH_LONG).show();
vanshaj.setText(resultText);
}
})
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(camera.this, "Unable to detect", Toast.LENGTH_LONG).show();
}
});
}
}
|
df6f769f7e3b3b2004ec05e1175dfed8f510fcf2
|
[
"Java"
] | 1 |
Java
|
tanmaygr/OcrApp
|
9d413d50fc367bc38799935ff11f9452ade113d6
|
4dc69b695c8752f4b8c67b8dd3134448bf5ef601
|
refs/heads/master
|
<repo_name>maciejminikowicz/PituPiter<file_sep>/src/main/java/pl/mm/pitupiter/service/TweetService.java
package pl.mm.pitupiter.service;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.mm.pitupiter.model.Comment;
import pl.mm.pitupiter.model.Tweet;
import pl.mm.pitupiter.model.User;
import pl.mm.pitupiter.repository.TweetRepository;
import pl.mm.pitupiter.repository.UserRepository;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class TweetService {
@Autowired
private TweetRepository tweetRepository;
@Autowired
private UserRepository userRepository;
public void createTweet(Tweet tweet, Long userId) {
Optional<User> optionalUser = userRepository.findById(userId);
if (optionalUser.isPresent()) {
User user = optionalUser.get();
tweet.setUser(user);
tweetRepository.save(tweet);
}
}
public Optional<Tweet> findById(Long tweetId) {
return tweetRepository.findById(tweetId);
}
public void deleteTweet(Long tweetId) {
tweetRepository.deleteById(tweetId);
}
public List<Tweet> getAllTweets(){
return tweetRepository.findAll().stream()
.sorted(Comparator.comparing(Tweet::getDateTweetAdded).reversed())
.collect(Collectors.toList());
}
public List<Tweet> getUserTweets(User user){
return tweetRepository.findAll().stream()
.filter(tweet -> tweet.getUser().equals(user))
.sorted(Comparator.comparing(Tweet::getDateTweetAdded).reversed())
.collect(Collectors.toList());
}
}
<file_sep>/src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/pitupiter_database?serverTimezone=Europe/Warsaw&createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.jpa.hibernate.ddl-auto=update
server.port=8080
server.error.whitelabel.enabled=false
<file_sep>/src/main/java/pl/mm/pitupiter/controller/MainController.java
package pl.mm.pitupiter.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import pl.mm.pitupiter.model.User;
import pl.mm.pitupiter.service.TweetService;
import pl.mm.pitupiter.service.UserService;
@Controller
public class MainController {
@Autowired
private TweetService tweetService;
@Autowired
private UserService userService;
@GetMapping("/")
public String tweetList(Model model){
model.addAttribute("allTweets", tweetService.getAllTweets());
model.addAttribute("newUser", new User());
return "home";
}
@PostMapping("/")
public String registerUser(User user) {
userService.registerUser(user);
return "redirect:/";
}
}
<file_sep>/src/main/java/pl/mm/pitupiter/security/WebSecurityConfig.java
package pl.mm.pitupiter.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import pl.mm.pitupiter.service.UserService;
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
private UserService userService;
public WebSecurityConfig(UserService userService) {
this.userService = userService;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().disable();
http.authorizeRequests()
.antMatchers("/user/**", "/tweet/**", "/comment/**").hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("<PASSWORD>")
.defaultSuccessUrl("/user/home")
.and()
.logout()
.logoutSuccessUrl("/");
}
}
<file_sep>/src/main/java/pl/mm/pitupiter/model/Comment.java
package pl.mm.pitupiter.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.springframework.context.annotation.DependsOn;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String content;
@CreationTimestamp
private LocalDateTime dateCommentAdded;
@ManyToOne
private Tweet tweet;
@ManyToOne
private User commentUser;
}
<file_sep>/src/main/java/pl/mm/pitupiter/controller/UserController.java
package pl.mm.pitupiter.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pl.mm.pitupiter.model.User;
import pl.mm.pitupiter.service.TweetService;
import pl.mm.pitupiter.service.UserService;
import java.security.Principal;
import java.util.Optional;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private TweetService tweetService;
//OLD
// @GetMapping("/edit/{userId}")
// public String editUser(Model model, @PathVariable Long userId) {
// return getUserToEdit(model, userId);
// }
// @GetMapping("/edit")
// public String editUserParam(Model model, @RequestParam(name = "userId") Long userId) {
// return getUserToEdit(model, userId);
// }
@GetMapping("/edit")
public String editUser(Model model) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
model.addAttribute("editedUser", user);
return "user-edit-form";
}
@PostMapping("/edit")
public String registerUser(User user) {
userService.registerUser(user);
return "redirect:/account_edited";
}
private String getUserToEdit(Model model, @RequestParam(name = "userId") Long userId) {
Optional<User> optionalUser = userService.findUserById(userId);
if (optionalUser.isPresent()) {
User user = optionalUser.get();
model.addAttribute("newUser", user);
return "user-form";
} else {
return "redirect:/";
}
}
@GetMapping("/delete")
public String deleteUser(Model model) {
User loggedInUser = getLoggedInUser(model);
userService.deleteUserById(loggedInUser.getId());
return "redirect:/account_deleted";
}
@GetMapping()
public String getUserDetails(Model model) {
getLoggedInUser(model);
return "user-details";
}
@GetMapping("/details")
public String getPublicUserDetails(Model model, @RequestParam String username){
User loggedInUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Optional<User> optionalUser = userService.findUserByUsername(username);
if (optionalUser.isPresent()){
User user = optionalUser.get();
model.addAttribute("userDetails", user);
model.addAttribute("id", user.getId());
model.addAttribute("loggedInUserId", loggedInUser.getId());
model.addAttribute("userTweets", tweetService.getUserTweets(user));
}
return "public-user";
}
private User getLoggedInUser(Model model) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
model.addAttribute("name", user.getUsername());
model.addAttribute("id", user.getId());
model.addAttribute("email", user.getEmail());
model.addAttribute("accountType", user.getUserAccountType());
model.addAttribute("role", user.getRole());
model.addAttribute("authorities", user.getAuthorities());
model.addAttribute("userDetails", user);
Optional<User> optionalUser = userService.findUserById(user.getId());
if (optionalUser.isPresent()){
User user2 = optionalUser.get();
model.addAttribute("userTweets", tweetService.getUserTweets(user2));
}
return user;
}
@GetMapping("/home")
public String hello(Principal principal, Model model) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
model.addAttribute("name", principal.getName());
model.addAttribute("id", user.getId());
model.addAttribute("allTweets", tweetService.getAllTweets());
return "home-user";
}
@GetMapping("/users")
public String getUsers(Model model, @RequestParam String username){
model.addAttribute("users", userService.findByName(username));
return "search-results";
}
}
<file_sep>/src/main/java/pl/mm/pitupiter/model/UserAccountType.java
package pl.mm.pitupiter.model;
public enum UserAccountType {
PRIVATE("private"),
PUBLIC("public");
private final String displayName;
UserAccountType(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
<file_sep>/src/main/java/pl/mm/pitupiter/service/CommentService.java
package pl.mm.pitupiter.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import pl.mm.pitupiter.model.Comment;
import pl.mm.pitupiter.model.Tweet;
import pl.mm.pitupiter.model.User;
import pl.mm.pitupiter.repository.CommentRepository;
import pl.mm.pitupiter.repository.TweetRepository;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class CommentService {
@Autowired
private TweetRepository tweetRepository;
@Autowired
private CommentRepository commentRepository;
public void saveComment(Comment comment, Long tweetId) {
User loggedInUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Optional<Tweet> optionalTweet = tweetRepository.findById(tweetId);
if (optionalTweet.isPresent()) {
Tweet tweet = optionalTweet.get();
comment.setTweet(tweet);
comment.setCommentUser(loggedInUser);
commentRepository.save(comment);
}
}
public void deleteComment(Long commentId) {
commentRepository.deleteById(commentId);
}
public Optional<Comment> findById(Long id) {
return commentRepository.findById(id);
}
}
|
489a7189ac339eb88ca74b1cf3b5adddb9cc86cc
|
[
"Java",
"INI"
] | 8 |
Java
|
maciejminikowicz/PituPiter
|
7f03161052f6941692a648f0d3720942710ac4ba
|
ae75b62a23f742aa971855621c1610afdd5f2142
|
refs/heads/master
|
<repo_name>culturadevops/lambda-template<file_sep>/LambdaAndRDS/EC2_stop_instances.py
#*************************************************
# lambda_function.lambda_handler
# recuerdas necesitas permisos sobre el lambda StopDBInstance y StartDBInstance
#*************************************************
import boto3
import json
instances_rds = ['']
def lambda_handler(event, context):
rds = boto3.client('rds')
for instance_rds in instances_rds:
rds.stop_db_instance(DBInstanceIdentifier = instance_rds)
return {
'statusCode': 200,
'body': json.dumps('stops rds')
}
<file_sep>/variableDeEntornos/index.js
exports.handler = async event => {
//esta variable se podra visualizar en el log del lambda
console.log("log:" + process.env.primeravariable);
const response = {
statusCode: 200,
//Esta variable sera enviada en la respuesta que retorna el lambda
body: JSON.stringify(process.env.primeravariable)
};
return response;
};
<file_sep>/LambdaAndAutoscaling/auto_scaling_start_instances.py
#*************************************************
# lambda_function.lambda_handler
# recuedas necesitas permisos sobre el lambda autoscaling:SetDesiredCapacity
#*************************************************
import boto3
def lambda_handler(event, context):
client = boto3.client('autoscaling')
response = client.set_desired_capacity(
AutoScalingGroupName='eks-workers-111111111111551110119000011111',
DesiredCapacity=4
)<file_sep>/LambdaAndSpotFleet/Spot_stop_instances.py
#*************************************************
# lambda_function.lambda_handler
# recuedas necesitas permisos sobre el lambda startInstance y stopInstance
#*************************************************
import boto3
import json
region = 'us-east-1'
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
ec2.modify_spot_fleet_request( SpotFleetRequestId='sfr-1111111-1111-1111-1111-111111111111',
TargetCapacity=0)
return {
'statusCode': 200,
'body': json.dumps('stop your instances: ')
}
<file_sep>/LambdaAndEC2/EC2_start_instances.py
#*************************************************
# lambda_function.lambda_handler
# recuedas necesitas permisos sobre el lambda startInstance y stopInstance
#*************************************************
import boto3
import json
region = 'us-east-1'
instances = ['i-0f41e5678d34ec40e','i-0f41e5678d34ec40e','i-0f41e5678d34ec40e']
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
ec2.start_instances(InstanceIds=instances)
return {
'statusCode': 200,
'body': json.dumps('started your instances: ' + str(instances))
}
<file_sep>/LambdaAndRDS/EC2_start_instances.py
#*************************************************
# lambda_function.lambda_handler
# recuedas necesitas permisos sobre el lambda startInstance y stopInstance
#*************************************************
import boto3
import json
instances_rds = ['']
def lambda_handler(event, context):
rds = boto3.client('rds')
for instance_rds in instances_rds:
rds.start_db_instance(DBInstanceIdentifier = instance_rds)
return {
'statusCode': 200,
'body': json.dumps('stops rds')
}
<file_sep>/README.md
# lambda-template
Recopilacion de codigo util sobre lambdas cloudformation,AWS SAM que puedas ver en culturadevops
https://www.youtube.com/channel/UCfJ67eVA7DkKbbIF5ceJDMA?view_as=subscriber o https://culturadevops.blogspot.com/
Indice
cloudformation de lambda y apigategay basico
Apagar Instancias EC2
Iniciar Instancias EC2
Apagar Spot intance
Iniciar Stop instance
Apagar
# Mis Libros:
[](https://amzn.to/3S8AGG9) [](https://amzn.to/3ga1c4E)
# Mi canal de cultura Devops
[](https://www.youtube.com/channel/UCfJ67eVA7DkKbbIF5ceJDMA?sub_confirmation=1)
|
6d81cab488d09e8a38d650a8ed65514f56cf66d5
|
[
"JavaScript",
"Python",
"Markdown"
] | 7 |
Python
|
culturadevops/lambda-template
|
43e49db65e0ef996fe508d8912d8b401784987c8
|
f2a57bbf5d921336f07725c0acc2171f880800ac
|
refs/heads/main
|
<file_sep>#' MAIC: A package for performing matched-adjusted indirect comparisons
#'
#' The MAIC package provides functions to help perform and summarize results
#' from matched-adjusted indirect comparisons
#'
#'
#' @docType package
#' @name MAIC
#' @importFrom magrittr "%>%"
NULL
<file_sep>
test_that("Test weight functions", {
require(dplyr)
require(ggplot2)
# test set
# wt is uniform 1
# wt_rs is 1 for age 50, 0 for age 60
test_weights <- data.frame(wt = 1,
wt_rs = c(rep(1,5), rep(0,5)),
age = c(rep(50,5), rep(60,5))
)
test_diag <- wt_diagnostics(test_weights, vars = "age")
#####################################################
# check diagnostics as expected
expect_equal(test_diag$ESS, 10)
expect_equal(test_diag$Summary_of_weights$mean, c(1, 0.5))
expect_equal(test_diag$Weight_profiles$age, c(50,60))
test_profile <- profile_wts(test_weights, vars = "age")
#####################################################
# check diagnostics as expected
expect_equal(test_profile$age, c(50,60))
expect_equal(test_profile$wt, c(1,1))
expect_equal(test_profile$wt_rs, c(1,0))
test_hist <- hist_wts(test_weights)
# extract plot data
# panel 1 is the rescaled weights and should be 5 for 0 and 5 for 1
test_hist_data <- layer_data(test_hist, 1) %>%
filter(count > 0, PANEL == 1)
#####################################################
# check diagnostics as expected
expect_equal(test_hist_data$x, c(0,1))
expect_equal(test_hist_data$y, c(5,5))
})
<file_sep># MAIC
[](https://zenodo.org/badge/latestdoi/419687389)
This package facilitates performing matching-adjusted indirect comparison (MAIC) analysis where the endpoint of interest is either time-to-event (e.g. overall survival) or binary (e.g. objective tumor response).
## installation code
```
devtools::install_github(
"roche/MAIC",
ref = "main"
)
```
## documentation
https://roche.github.io/MAIC/index.html
<file_sep>
# This example code combines weighted individual patient data for 'intervention'
# and pseudo individual patient data for 'comparator' and performs analyses for
# two endpoints: overall survival (a time to event outcome) and objective
# response (a binary outcome)
library(dplyr)
library(boot)
library(survival)
library(MAIC)
library(ggplot2)
library(survminer)
library(flextable)
library(officer)
# load intervention data with weights saved in est_weights
data(est_weights, package = "MAIC")
# Combine data -----------------------------------------------------------------
# Combine the the comparator pseudo data with the analysis data, outputted from
# the estimate_weights function
# Read in digitised pseudo survival data for the comparator
comparator_surv <- read.csv(system.file("extdata", "psuedo_IPD.csv",
package = "MAIC", mustWork = TRUE)) %>%
rename(Time=Time, Event=Event)
# Simulate response data based on the known proportion of responders
comparator_n <- nrow(comparator_surv) # total number of patients in the comparator data
comparator_prop_events <- 0.4 # proportion of responders
# Calculate number with event
# Use round() to ensure we end up with a whole number of people
# number without an event = Total N - number with event to ensure we keep the
# same number of patients
n_with_event <- round(comparator_n*comparator_prop_events, digits = 0)
comparator_binary <- data.frame("response"= c(rep(1, n_with_event), rep(0, comparator_n - n_with_event)))
# Join survival and response comparator data
# Note the rows do not represent observations from a particular patient
# i.e. there is no relationship between the survival time and response status
# for a given row since this is simulated data
# In a real data set this relationship would be present
comparator_input <- cbind(comparator_surv, comparator_binary) %>%
mutate(wt=1, wt_rs=1, ARM="Comparator") # All patients have weight = 1
head(comparator_input)
# Join comparator data with the intervention data (naming of variables should be
# consistent between both datasets)
# Set factor levels to ensure "Comparator" is the reference treatment
combined_data <- bind_rows(est_weights$analysis_data, comparator_input)
combined_data$ARM <- relevel(as.factor(combined_data$ARM), ref="Comparator")
#### Estimating the relative effect --------------------------------------------
### Example for survival data --------------------------------------------------
## Kaplan-Meier plot
# Unweighted intervention data
KM_int <- survfit(formula = Surv(Time, Event==1) ~ 1 ,
data = est_weights$analysis_data,
type="kaplan-meier")
# Weighted intervention data
KM_int_wtd <- survfit(formula = Surv(Time, Event==1) ~ 1 ,
data = est_weights$analysis_data,
weights = wt,
type="kaplan-meier")
# Comparator data
KM_comp <- survfit(formula = Surv(Time, Event==1) ~ 1 ,
data = comparator_input,
type="kaplan-meier")
# Combine the survfit objects ready for ggsurvplot
KM_list <- list(Intervention = KM_int,
Intervention_weighted = KM_int_wtd,
Comparator = KM_comp)
#Produce the Kaplan-Meier plot
KM_plot <- ggsurvplot(KM_list,
combine = TRUE,
risk.table=TRUE, # numbers at risk displayed on the plot
break.x.by=50,
xlab="Time (days)",
censor=FALSE,
legend.title = "Treatment",
title = "Kaplan-Meier plot of overall survival",
legend.labs=c("Intervention",
"Intervention weighted",
"Comparator"),
font.legend = list(size = 10)) +
guides(colour=guide_legend(nrow = 2))
## Estimating the hazard ratio (HR)
# Fit a Cox model without weights to estimate the unweighted HR
unweighted_cox <- coxph(Surv(Time, Event==1) ~ ARM, data = combined_data)
HR_CI_cox <- summary(unweighted_cox)$conf.int %>%
as.data.frame() %>%
transmute("HR" = `exp(coef)`,
"HR_low_CI" = `lower .95`,
"HR_upp_CI" = `upper .95`)
# Fit a Cox model with weights to estimate the weighted HR
weighted_cox <- coxph(Surv(Time, Event==1) ~ ARM,
data = combined_data,
weights = wt)
HR_CI_cox_wtd <- summary(weighted_cox)$conf.int %>%
as.data.frame() %>%
transmute("HR" = `exp(coef)`,
"HR_low_CI" = `lower .95`,
"HR_upp_CI" = `upper .95`)
## Bootstrap the confidence interval of the weighted HR
HR_bootstraps <- boot(data = est_weights$analysis_data, # intervention data
statistic = bootstrap_HR, # bootstrap the HR (defined in the MAIC package)
R=1000, # number of bootstrap samples
comparator_data = comparator_input, # comparator pseudo data
matching = est_weights$matching_vars, # matching variables
model = Surv(Time, Event==1) ~ ARM # model to fit
)
## Bootstrapping diagnostics
# Summarize bootstrap estimates in a histogram
# Vertical lines indicate the median and upper and lower CIs
hist(HR_bootstraps$t, main = "", xlab = "Boostrapped HR")
abline(v= quantile(HR_bootstraps$t, probs = c(0.025, 0.5, 0.975)), lty=2)
# Median of the bootstrap samples
HR_median <- median(HR_bootstraps$t)
# Bootstrap CI - Percentile CI
boot_ci_HR <- boot.ci(boot.out = HR_bootstraps, index=1, type="perc")
# Bootstrap CI - BCa CI
boot_ci_HR_BCA <- boot.ci(boot.out = HR_bootstraps, index=1, type="bca")
## Summary
# Produce a summary of HRs and CIs
HR_summ <- rbind(HR_CI_cox, HR_CI_cox_wtd) %>% # Unweighted and weighted HRs and CIs from Cox models
mutate(Method = c("HR (95% CI) from unadjusted Cox model",
"HR (95% CI) from weighted Cox model")) %>%
# Median bootstrapped HR and 95% percentile CI
rbind(data.frame("HR" = HR_median,
"HR_low_CI" = boot_ci_HR$percent[4],
"HR_upp_CI" = boot_ci_HR$percent[5],
"Method"="Bootstrap median HR (95% percentile CI)")) %>%
# Median bootstrapped HR and 95% bias-corrected and accelerated bootstrap CI
rbind(data.frame("HR" = HR_median,
"HR_low_CI" = boot_ci_HR_BCA$bca[4],
"HR_upp_CI" = boot_ci_HR_BCA$bca[5],
"Method"="Bootstrap median HR (95% BCa CI)")) %>%
#apply rounding for numeric columns
mutate_if(.predicate = is.numeric, sprintf, fmt = "%.3f") %>%
#format for output
transmute(Method, HR_95_CI = paste0(HR, " (", HR_low_CI, " to ", HR_upp_CI, ")"))
# Summarize the results in a table suitable for word/ powerpoint
HR_table <- HR_summ %>%
regulartable() %>% #make it a flextable object
set_header_labels(Method = "Method", HR_95_CI = "Hazard ratio (95% CI)") %>%
font(font = 'Arial', part = 'all') %>%
fontsize(size = 14, part = 'all') %>%
bold(part = 'header') %>%
align(align = 'center', part = 'all') %>%
align(j = 1, align = 'left', part = 'all') %>%
border_outer(border = fp_border()) %>%
border_inner_h(border = fp_border()) %>%
border_inner_v(border = fp_border()) %>%
autofit(add_w = 0.2, add_h = 2)
### Example for response data --------------------------------------------------
## Estimating the odds ratio (OR)
# Fit a logistic regression model without weights to estimate the unweighted OR
unweighted_OR <- glm(formula = response~ARM,
family = binomial(link="logit"),
data = combined_data)
# Log odds ratio
log_OR_CI_logit <- cbind(coef(unweighted_OR), confint.default(unweighted_OR, level = 0.95))[2,]
# Exponentiate to get Odds ratio
OR_CI_logit <- exp(log_OR_CI_logit)
#tidy up naming
names(OR_CI_logit) <- c("OR", "OR_low_CI", "OR_upp_CI")
# Fit a logistic regression model with weights to estimate the weighted OR
weighted_OR <- suppressWarnings(glm(formula = response~ARM,
family = binomial(link="logit"),
data = combined_data,
weight = wt))
# Weighted log odds ratio
log_OR_CI_logit_wtd <- cbind(coef(weighted_OR), confint.default(weighted_OR, level = 0.95))[2,]
# Exponentiate to get weighted odds ratio
OR_CI_logit_wtd <- exp(log_OR_CI_logit_wtd)
#tidy up naming
names(OR_CI_logit_wtd) <- c("OR", "OR_low_CI", "OR_upp_CI")
## Bootstrap the confidence interval of the weighted OR
OR_bootstraps <- boot(data = est_weights$analysis_data, # intervention data
statistic = bootstrap_OR, # bootstrap the OR
R = 1000, # number of bootstrap samples
comparator_data = comparator_input, # comparator pseudo data
matching = est_weights$matching_vars, # matching variables
model = 'response ~ ARM' # model to fit
)
## Bootstrapping diagnostics
# Summarize bootstrap estimates in a histogram
# Vertical lines indicate the median and upper and lower CIs
hist(OR_bootstraps$t, main = "", xlab = "Boostrapped OR")
abline(v= quantile(OR_bootstraps$t, probs = c(0.025,0.5,0.975)), lty=2)
# Median of the bootstrap samples
OR_median <- median(OR_bootstraps$t)
# Bootstrap CI - Percentile CI
boot_ci_OR <- boot.ci(boot.out = OR_bootstraps, index=1, type="perc")
# Bootstrap CI - BCa CI
boot_ci_OR_BCA <- boot.ci(boot.out = OR_bootstraps, index=1, type="bca")
## Summary
# Produce a summary of ORs and CIs
OR_summ <- rbind(OR_CI_logit, OR_CI_logit_wtd) %>% # Unweighted and weighted ORs and CIs
as.data.frame() %>%
mutate(Method = c("OR (95% CI) from unadjusted logistic regression model",
"OR (95% CI) from weighted logistic regression model")) %>%
# Median bootstrapped HR and 95% percentile CI
rbind(data.frame("OR" = OR_median,
"OR_low_CI" = boot_ci_OR$percent[4],
"OR_upp_CI" = boot_ci_OR$percent[5],
"Method"="Bootstrap median HR (95% percentile CI)")) %>%
# Median bootstrapped HR and 95% bias-corrected and accelerated bootstrap CI
rbind(data.frame("OR" = OR_median,
"OR_low_CI" = boot_ci_OR_BCA$bca[4],
"OR_upp_CI" = boot_ci_OR_BCA$bca[5],
"Method"="Bootstrap median HR (95% BCa CI)")) %>%
#apply rounding for numeric columns
mutate_if(.predicate = is.numeric, sprintf, fmt = "%.3f") %>%
#format for output
transmute(Method, OR_95_CI = paste0(OR, " (", OR_low_CI, " to ", OR_upp_CI, ")"))
# turns the results to a table suitable for word/ powerpoint
OR_table <- OR_summ %>%
regulartable() %>% #make it a flextable object
set_header_labels(Method = "Method", OR_95_CI = "Odds ratio (95% CI)") %>%
font(font = 'Arial', part = 'all') %>%
fontsize(size = 14, part = 'all') %>%
bold(part = 'header') %>%
align(align = 'center', part = 'all') %>%
align(j = 1, align = 'left', part = 'all') %>%
border_outer(border = fp_border()) %>%
border_inner_h(border = fp_border()) %>%
border_inner_v(border = fp_border()) %>%
autofit(add_w = 0.2)
<file_sep>
# This example code estimates weights for individual patient data from a single
# arm study of 'intervention' based on aggregate baseline characteristics from
# the comparator trial
library(dplyr)
library(MAIC)
#### Prepare the data ----------------------------------------------------------
### Intervention data
# Read in relevant ADaM data and rename variables of interest
adsl <- read.csv(system.file("extdata", "adsl.csv", package = "MAIC",
mustWork = TRUE))
adrs <- read.csv(system.file("extdata", "adrs.csv", package = "MAIC",
mustWork = TRUE))
adtte <- read.csv(system.file("extdata", "adtte.csv", package = "MAIC",
mustWork = TRUE))
adsl <- adsl %>% # Data containing the matching variables
mutate(SEX=ifelse(SEX=="Male", 1, 0)) # Coded 1 for males and 0 for females
adrs <- adrs %>% # Response data
filter(PARAM=="Response") %>%
transmute(USUBJID, ARM, response=AVAL)
adtte <- adtte %>% # Time to event data (overall survival)
filter(PARAMCD=="OS") %>%
mutate(Event=1-CNSR) %>% #Set up coding as Event = 1, Censor = 0
transmute(USUBJID, ARM, Time=AVAL, Event)
# Combine all intervention data
intervention_input <- adsl %>%
full_join(adrs, by=c("USUBJID", "ARM")) %>%
full_join(adtte, by=c("USUBJID", "ARM"))
# List out the variables in the intervention data that have been identified as
# prognostic factors or treatment effect modifiers and will be used in the
# matching
match_cov <- c("AGE",
"SEX",
"SMOKE",
"ECOG0")
## Baseline data from the comparator trial
# Baseline aggregate data for the comparator population
target_pop <- read.csv(system.file("extdata", "aggregate_data.csv",
package = "MAIC", mustWork = TRUE))
# Rename target population cols to be consistent with match_cov
target_pop_standard <- target_pop %>%
rename(
N=N,
Treatment=ARM,
AGE=age.mean,
SEX=prop.male,
SMOKE=prop.smoke,
ECOG0=prop.ecog0
) %>%
transmute(N, Treatment, AGE, SEX, SMOKE, ECOG0)
#### Estimate weights ----------------------------------------------------------
### Center baseline characteristics
# (subtract the aggregate comparator data from the corresponding column of
# intervention PLD)
intervention_data <- intervention_input %>%
mutate(
Age_centered = AGE - target_pop$age.mean,
# matching on both mean and standard deviation for continuous variables (optional)
Age_squared_centered = (AGE^2) - (target_pop$age.mean^2 + target_pop$age.sd^2),
Sex_centered = SEX - target_pop$prop.male,
Smoke_centered = SMOKE - target_pop$prop.smoke,
ECOG0_centered = ECOG0 - target_pop$prop.ecog0)
## Define the matching covariates
cent_match_cov <- c("Age_centered",
"Age_squared_centered",
"Sex_centered",
"Smoke_centered",
"ECOG0_centered")
## Optimization procedure
# Following the centering of the baseline characteristics of the intervention
# study, patient weights can be estimated using estimate_weights
# The function output is a list containing (1) a data set of the individual
# patient data with the assigned weights "analysis_data" and (2) a vector
# containing the matching variables "matching_vars"
est_weights <- estimate_weights(intervention_data = intervention_data,
matching_vars = cent_match_cov)
<file_sep>
# This example code uses the weighted individual patient data, outputted from
# the estimate_weights function to perform weight diagnostics. The weighted data
# is saved within est_weights. To check the weighted aggregate baseline
# characteristics for 'intervention' match those in the comparator data,
# standardized data "target_pop_standard" is used. Please see the package
# vignette for more information on how to use the estimate_weights function and
# derive the "target_pop_standard" data.
library(dplyr)
library(MAIC)
# load est_weights
data(est_weights, package = "MAIC")
# load target_pop_standard
data(target_pop_standard, package = "MAIC")
# List out the uncentered variables used in the matching
match_cov <- c("AGE",
"SEX",
"SMOKE",
"ECOG0")
# Are the weights sensible? ----------------------------------------------------
# The wt_diagnostics function requires the output from the estimate_weights
# function and will output:
# - the effective sample size (ESS)
# - a summary of the weights and rescaled weights (mean, standard deviation,
# median, minimum and maximum)
# - a unique set of weights with the corresponding patient profile based on the
# matching variables
diagnostics <- wt_diagnostics(est_weights$analysis_data,
vars = match_cov)
diagnostics$ESS
diagnostics$Summary_of_weights
diagnostics$Weight_profiles
# Each of the wt_diagnostics outputs can also be estimated individually
ESS <- estimate_ess(est_weights$analysis_data)
weight_summ <- summarize_wts(est_weights$analysis_data)
wts_profile <- profile_wts(est_weights$analysis_data, vars = match_cov)
# Plot histograms of unscaled and rescaled weights
# bin_width needs to be adapted depending on the sample size in the data set
histogram <- hist_wts(est_weights$analysis_data, bin = 50)
histogram
# Has the optimization worked? -------------------------------------------------
# The following code produces a summary table of the intervention baseline
# characteristics before and after matching compared with the comparator
# baseline characteristics:
check_weights(analysis_data = est_weights$analysis_data, matching_vars = match_cov,
target_pop_standard = target_pop_standard)
<file_sep>
test_that("MAIC full example", {
require(dplyr)
# load example data
adsl <- read.csv(system.file("extdata", "adsl.csv", package = "MAIC", mustWork = TRUE))
adrs <- read.csv(system.file("extdata", "adrs.csv", package = "MAIC", mustWork = TRUE))
adtte <- read.csv(system.file("extdata", "adtte.csv", package = "MAIC", mustWork = TRUE))
adsl <- adsl %>% # Data containing the matching variables
mutate(SEX=ifelse(SEX=="Male", 1, 0)) # Coded 1 for males and 0 for females
adrs <- adrs %>% # Response data
filter(PARAM=="Response") %>%
transmute(USUBJID, ARM, response=AVAL)
adtte <- adtte %>% # Time to event data (overall survival)
filter(PARAMCD=="OS") %>%
mutate(Event=1-CNSR) %>% #Set up coding as Event = 1, Censor = 0
transmute(USUBJID, ARM, Time=AVAL, Event)
intervention_input <- adsl %>%
full_join(adrs, by=c("USUBJID", "ARM")) %>%
full_join(adtte, by=c("USUBJID", "ARM"))
#####################################################
# check data loads correctly
expect_equal(nrow(intervention_input), 500)
#####################################################
# Baseline aggregate data for the comparator population
target_pop <- read.csv(system.file("extdata", "aggregate_data.csv",
package = "MAIC", mustWork = TRUE))
# estimate weights
match_cov <- c("AGE", "SEX", "SMOKE", "ECOG0")
target_pop_standard <- target_pop %>%
#EDIT
rename(N=N,
Treatment=ARM,
AGE=age.mean,
SEX=prop.male,
SMOKE=prop.smoke,
ECOG0=prop.ecog0
) %>%
transmute(N, Treatment, AGE, SEX, SMOKE, ECOG0)
intervention_data <- intervention_input %>%
mutate(Age_centered = AGE - target_pop$age.mean,
# matching on both mean and standard deviation for continuous variable (optional)
Age_squared_centered = (AGE^2) - (target_pop$age.mean^2 + target_pop$age.sd^2),
Sex_centered = SEX - target_pop$prop.male,
Smoke_centered = SMOKE - target_pop$prop.smoke,
ECOG0_centered = ECOG0 - target_pop$prop.ecog0)
# Set matching covariates
cent_match_cov <- c("Age_centered",
"Age_squared_centered",
"Sex_centered",
"Smoke_centered",
"ECOG0_centered")
est_weights <- estimate_weights(intervention_data = intervention_data,
matching_vars = cent_match_cov)
#####################################################
# check number of weights correct
expect_equal(nrow(est_weights$analysis_data), 500)
#####################################################
ESS <- estimate_ess(est_weights$analysis_data)
#####################################################
# check ESS is as expected
expect_equal(ESS, 157.07, tolerance = 0.01)
#####################################################
weight_summ <- summarize_wts(est_weights$analysis_data)
#####################################################
# check mean of weights are as expected
expect_equal(weight_summ$mean, c(0.376,1), tolerance = 0.01)
#####################################################
})
<file_sep>library(testthat)
library(MAIC)
test_check("MAIC")
<file_sep>#' Bootstrapping for MAIC weighted hazard ratios
#'
#' @param intervention_data A data frame containing individual patient data
#' from the intervention study.
#' @param matching A character vector giving the names of the covariates to use
#' in matching. These names must match the column names in intervention_data.
#' @param i Index used to select a sample within \code{\link{boot}}.
#' @param model A model formula in the form 'Surv(Time, Event==1) ~ ARM'.
#' Variable names need to match the corresponding columns in intervention_data.
#' @param comparator_data A data frame containing pseudo individual patient data
#' from the comparator study needed to derive the relative treatment effect.
#' The outcome variables names must match intervention_data.
#' @param min_weight A numeric value that defines the minimum weight allowed.
#' This value (default 0.0001) will replace weights estimated at 0 in a sample.
#'
#' @details This function is intended to be used in conjunction with the
#' \code{\link{boot}} function to return the statistic to be
#' bootstrapped. In this case by performing MAIC weighting using
#' {\link{estimate_weights}} and returning a weighted hazard ratio (HR) from a
#' Cox proportional hazards model. This is used as the 'statistic' argument in
#' the boot function.
#'
#' @return The HR as a numeric value.
#' @seealso \code{\link{estimate_weights}}, \code{\link{boot}}
#' @example inst/examples/MAIC_example_analysis.R
#' @export
bootstrap_HR <- function(intervention_data, matching, i, model, comparator_data, min_weight = 0.0001){
# create a visible binding for R CMD check
wt <- NULL
# Samples the data
bootstrap_data <- intervention_data[i,]
# Estimates weights
perform_wt <- estimate_weights(intervention_data=bootstrap_data, matching_vars=matching)
# Give comparator data weights of 1
comparator_data_wts <- comparator_data %>% dplyr::mutate(wt=1, wt_rs=1, ARM="Comparator")
# Add the comparator data
combined_data <- dplyr::bind_rows(perform_wt$analysis_data, comparator_data_wts)
combined_data$ARM <- stats::relevel(as.factor(combined_data$ARM), ref="Comparator")
# set weights that are below min_weight to min_weight to avoid issues with 0 values
combined_data$wt <- ifelse(combined_data$wt < min_weight, min_weight, combined_data$wt)
# survival data stat
cox_model <- survival::coxph(model, data = combined_data, weights = wt)
HR <- exp(cox_model$coefficients)
}
#' Bootstrapping for MAIC weighted odds ratios
#'
#' @param intervention_data A data frame containing individual patient data
#' from the intervention study.
#' @param matching A character vector giving the names of the covariates to use
#' in matching. These names must match the column names in intervention_data.
#' @param i Index used to select a sample within \code{\link{boot}}.
#' @param model A model formula in the form 'endpoint ~ treatment_var'. Variable
#' names need to match the corresponding columns in intervention_data.
#' @param comparator_data A data frame containing pseudo individual patient data
#' from the comparator study needed to derive the relative treatment effect.
#' The outcome variables names must match intervention_data.
#' @param min_weight A numeric value that defines the minimum weight allowed.
#' This value (default 0.0001) will replace weights estimated at 0 in a sample.
#'
#' @details This function is intended to be used in conjunction with the
#' \code{\link{boot}} function to return the statistic to be
#' bootstrapped. In this case by performing MAIC weighting using
#' {\link{estimate_weights}} and returning a weighted odds ratio (OR) from a
#' logistic regression model. This is used as the 'statistic' argument in
#' the boot function.
#'
#' @return The OR as a numeric value.
#'
#' @seealso \code{\link{estimate_weights}}, \code{\link{boot}}
#'
#' @example inst/examples/MAIC_example_analysis.R
#'
#' @export
bootstrap_OR <- function(intervention_data, matching, i, model, comparator_data, min_weight = 0.0001){
# create a visible binding for R CMD check
wt <- NULL
# Samples the data
bootstrap_data <- intervention_data[i,]
# Estimates weights
perform_wt <- estimate_weights(intervention_data=bootstrap_data, matching_vars=matching)
# Give comparator data weights of 1
comparator_data_wts <- comparator_data %>% dplyr::mutate(wt=1, wt_rs=1, ARM="Comparator")
# Add the comparator data
combined_data <- dplyr::bind_rows(perform_wt$analysis_data, comparator_data_wts)
combined_data$ARM <- stats::relevel(as.factor(combined_data$ARM), ref="Comparator")
# set weights that are below eta to eta to avoid issues with 0 values
combined_data$wt <- ifelse(combined_data$wt < min_weight, min_weight, combined_data$wt)
# Perform logistic regression and extract the OR estimate
logistic.regr <- suppressWarnings(stats::glm(formula = model, family=stats::binomial(link="logit"), data = combined_data, weight = wt))
OR <- exp(as.numeric(stats::coef(logistic.regr)[2]))
}
<file_sep>
test_that("Test bootstrapping functions", {
require(dplyr)
require(survival)
# load intervention data with weights saved in est_weights
data(est_weights, package = "MAIC")
# Combine data -----------------------------------------------------------------
# Combine the the comparator pseudo data with the analysis data, outputted from
# the estimate_weights function
# Read in digitised pseudo survival data for the comparator
comparator_surv <- read.csv(system.file("extdata", "psuedo_IPD.csv",
package = "MAIC", mustWork = TRUE)) %>%
rename(Time=Time, Event=Event)
# Simulate response data based on the known proportion of responders
comparator_n <- nrow(comparator_surv) # total number of patients in the comparator data
comparator_prop_events <- 0.4 # proportion of responders
# Calculate number with event
# Use round() to ensure we end up with a whole number of people
# number without an event = Total N - number with event to ensure we keep the
# same number of patients
n_with_event <- round(comparator_n*comparator_prop_events, digits = 0)
comparator_binary <- data.frame("response"= c(rep(1, n_with_event), rep(0, comparator_n - n_with_event)))
# Join survival and response comparator data
# Note the rows do not represent observations from a particular patient
# i.e. there is no relationship between the survival time and response status
# for a given row since this is simulated data
# In a real data set this relationship would be present
comparator_input <- cbind(comparator_surv, comparator_binary) %>%
mutate(wt=1, wt_rs=1, ARM="Comparator") # All patients have weight = 1
# Join comparator data with the intervention data (naming of variables should be
# consistent between both datasets)
# Set factor levels to ensure "Comparator" is the reference treatment
combined_data <- bind_rows(est_weights$analysis_data, comparator_input)
combined_data$ARM <- relevel(as.factor(combined_data$ARM), ref="Comparator")
unweighted_cox <- coxph(Surv(Time, Event==1) ~ ARM, data = combined_data)
# Fit a Cox model with weights to estimate the weighted HR
weighted_cox <- coxph(Surv(Time, Event==1) ~ ARM,
data = combined_data,
weights = wt)
# check the bootstrap function returns same value on full data
boot_test_HR <- bootstrap_HR(intervention_data = est_weights$analysis_data,
i =c(1:500),
comparator_data = comparator_input, # comparator pseudo data
matching = est_weights$matching_vars, # matching variables
model = Surv(Time, Event==1) ~ ARM # model to fit
)
# check matches to normal weighted cox on full data
expect_equal(exp(weighted_cox$coefficients), boot_test_HR, tolerance = 0.01)
# Fit a logistic regression model with weights to estimate the weighted OR
# this is a nonsense model on censoring to test function only
weighted_OR <- suppressWarnings(glm(formula = Event~ARM,
family = binomial(link="logit"),
data = combined_data,
weight = wt))
boot_test_OR <- bootstrap_OR(intervention_data = est_weights$analysis_data,
i =c(1:500),
comparator_data = comparator_input, # comparator pseudo data
matching = est_weights$matching_vars, # matching variables
model = 'Event ~ ARM' )
# check matches to normal weighted logistic regression on full data
expect_equal(exp(as.numeric(coef(weighted_OR)[2])), boot_test_OR, tolerance = 0.01)
})
<file_sep>
# Functions for the estimation of propensity weights
# Internal functions - Not exported ---------------------------------------
# Objective function
objfn <- function(a1, X){
sum(exp(X %*% a1))
}
# Gradient function
gradfn <- function(a1, X){
colSums(sweep(X, 1, exp(X %*% a1), "*"))
}
# External functions ------------------------------------------------------
#' Estimate MAIC propensity weights
#'
#' Estimate propensity weights for matching-adjusted indirect comparison (MAIC).
#'
#' @param intervention_data A data frame containing individual patient data from
#' the intervention study.
#' @param matching_vars A character vector giving the names of the covariates to
#' use in matching. These names must match the column names in intervention_data.
#' @param method The method used for optimisation - The default is method =
#' "BFGS". Refer to \code{\link[stats]{optim}} for options.
#' @param ... Additional arguments to be passed to optimisation functions such
#' as the method for maximum likelihood optimisation. Refer to \code{\link[stats]{optim}}
#' for options.
#'
#' @details The premise of MAIC methods is to adjust for between-trial
#' differences in patient demographic or disease characteristics at baseline.
#' When a common treatment comparator or ‘linked network’ are unavailable, a
#' MAIC assumes that differences between absolute outcomes that would be
#' observed in each trial are entirely explained by imbalances in prognostic
#' variables and treatment effect modifiers.
#'
#' The aim of the MAIC method is to estimate a set of propensity weights based
#' on prognostic variables and treatment effect modifiers. These weights can
#' be used in subsequent statistical analysis to adjust for differences in
#' patient characteristics between the population in the intervention trial
#' and the population in a comparator study. For additional details on the
#' statistical methods, refer to the package vignette.
#'
#' The data required for an unanchored MAIC are:
#'
#' \itemize{
#' \item Individual patient data from a single arm study of 'intervention'
#' \item Aggregate summary data for 'comparator'. This could be from a
#' single arm study of the comparator or from one arm of a randomized
#' controlled trial.
#' \item Psuedo patient data from the comparator study. This is not required
#' for the matching process but is needed to derive the relative treatment
#' effects between the intervention and comparator.
#' }
#'
#' For the matching process:
#'
#' \enumerate{
#' \item All binary variables to be used in the matching should be coded 1
#' and 0
#' \item The variable names need to be listed in a character vector called
#' match_cov
#' \item Aggregate baseline characteristics (number of patients, mean and
#' SD for continuous variables and proportion for binary variables) from
#' the comparator trial are needed as a data frame. Naming of the
#' covariates in this data frame should be consistent with variable names
#' in the intervention data.
#' \item Patient baseline characteristics in the intervention study are
#' centered on the value of the aggregate data from the comparator study
#' \item The estimate_weights function can then be used to estimate
#' propensity weights for each patient in the intervention study
#' }
#'
#' For full details refer to the example below and the package vignette
#'
#' @return A list containing 2 objects. First, a data frame named analysis_data
#' containing intervention_data with additional columns named wt (weights) and
#' wt_rs (rescaled weights). Second, a vector called matching_vars of the
#' names of the centered matching variables used.
#' @references NICE DSU TECHNICAL SUPPORT DOCUMENT 18: METHODS FOR
#' POPULATION-ADJUSTED INDIRECT COMPARISONS IN SUBMSISSIONS TO NICE, REPORT BY
#' THE DECISION SUPPORT UNIT, December 2016
#' @seealso \code{\link{optim}}
#'
#' @example inst/examples/MAIC_example_weights.R
#'
#' @export
estimate_weights <- function(intervention_data, matching_vars, method = "BFGS", ...){
#Basic checks of inputs before proceeding
#Check intervention data is a data frame
assertthat::assert_that(
is.data.frame(intervention_data),
msg = "intervention_data is expected to be a data frame"
)
#Check that matching_vars is a character vector
assertthat::assert_that(
is.character(matching_vars),
msg = "matching_vars is expected to be a character vector"
)
#Check that all named matching variables are in the intervention dataset
assertthat::assert_that(
all(matching_vars %in% colnames(intervention_data)),
msg = "matching_vars contains variable names that are not in the intervention dataset"
)
# create visible local bindings for R CMD check
wt <- NULL
# Optimise Q(b) using Newton-Raphson techniques
opt1 <- stats::optim(par = rep(0,dim(as.data.frame(intervention_data[,matching_vars]))[2]),
fn = objfn,
gr = gradfn,
X = as.matrix(intervention_data[,matching_vars]),
method = method,
...)
a1 <- opt1$par
# Calculate weights for intervention data and combine with dataset
data_with_wts <- dplyr::mutate(intervention_data,
wt = as.vector(exp(as.matrix(intervention_data[,matching_vars]) %*% a1)), # weights
wt_rs = (wt / sum(wt)) * nrow(intervention_data), # rescaled weights
ARM = "Intervention"
)
# Outputs are:
# - the analysis data (intervention PLD with weights )
# - A character vector with the name of the matching variables
output <- list(
matching_vars = matching_vars,
analysis_data = data_with_wts
)
return(output)
}
# Functions for summarizing the weights ----------------------------------------
#' Estimate effective sample size
#'
#' Estimate the effective sample size (ESS).
#'
#' @param data A data frame containing individual patient data from
#' the intervention study, including a column containing the weights (derived
#' using \code{\link{estimate_weights}}).
#' @param wt_col The name of the weights column in the data frame containing the
#' intervention individual patient data and the MAIC propensity weights. The
#' default is wt.
#'
#' @details For a weighted estimate, the effective sample size (ESS) is the
#' number of independent non-weighted individuals that would be required to
#' give an estimate with the same precision as the weighted sample estimate. A
#' small ESS, relative to the original sample size, is an indication that the
#' weights are highly variable and that the estimate may be unstable. This
#' often occurs if there is very limited overlap in the distribution of the
#' matching variables between the populations being compared. If there is
#' insufficient overlap between populations it may not be possible to obtain
#' reliable estimates of the weights
#'
#' @return The effective sample size (ESS) as a numeric value.
#'
#' @references NICE DSU TECHNICAL SUPPORT DOCUMENT 18: METHODS FOR
#' POPULATION-ADJUSTED INDIRECT COMPARISONS IN SUBMSISSIONS TO NICE, REPORT BY
#' THE DECISION SUPPORT UNIT, December 2016
#'
#' @seealso \code{\link{estimate_weights}}
#'
#' @example inst/examples/MAIC_example_weight_diagnostics.R
#'
#' @export
estimate_ess <- function(data, wt_col="wt"){
ess <- sum(data[,wt_col])^2/sum(data[,wt_col]^2)
return(ess)
}
#' Summarize the weight values
#'
#' Produce a summary of the weights (minimum, maximum, median, mean, standard
#' deviation). Mean and standard deviation are provided for completeness.
#' In practice the distribution of weights may be skewed in which case mean and
#' SD should be interpreted with caution.
#'
#' @param data A data frame containing individual patient data from
#' the intervention study, including a column containing the weights (derived
#' using \code{\link{estimate_weights}}).
#' @param wt_col The name of the weights column in the data frame containing the
#' intervention individual patient data and the MAIC propensity weights. The
#' default is wt.
#' @param rs_wt_col The name of the rescaled weights column in the data frame
#' containing the intervention individual patient data and the MAIC propensity
#' weights. The default is wt_rs.
#'
#' @return A data frame that includes a summary (minimum, maximum, median, mean,
#' standard deviation) of the weights and rescaled weights.
#'
#' @seealso \code{\link{estimate_weights}}
#'
#' @example inst/examples/MAIC_example_weight_diagnostics.R
#'
#' @export
summarize_wts <- function(data, wt_col="wt", rs_wt_col="wt_rs"){
summary <- data.frame(
type = c("Weights", "Rescaled weights"),
mean = c(mean(data[,wt_col]), mean(data[,rs_wt_col])),
sd = c(stats::sd(data[,wt_col]), stats::sd(data[,rs_wt_col])),
median = c(stats::median(data[,wt_col]), stats::median(data[,rs_wt_col])),
min = c(min(data[,wt_col]), min(data[,rs_wt_col])),
max = c(max(data[,wt_col]), max(data[,rs_wt_col]))
)
return(summary)
}
#' Produce histograms of weights and rescaled weights
#'
#' Produce a plot containing two histograms (one of the weights and one of the
#' rescaled weights).
#'
#' @param data A data frame containing individual patient data from
#' the intervention study, including a column containing the weights (derived
#' using \code{\link{estimate_weights}}).
#' @param wt_col The name of the weights column in the data frame containing the
#' intervention individual patient data and the MAIC propensity weights. The
#' default is wt.
#' @param rs_wt_col The name of the rescaled weights column in the data frame
#' containing the intervention individual patient data and the MAIC propensity
#' weights. The default is wt_rs.
#' @param bin Number of bins to plot histogram. The default is 30.
#'
#' @return A histogram plot of the weights and rescaled weights.
#'
#' @seealso \code{\link{estimate_weights}}
#'
#' @example inst/examples/MAIC_example_weight_diagnostics.R
#'
#' @export
hist_wts <- function(data, wt_col="wt", rs_wt_col="wt_rs", bin = 30) {
# create visible local bindings for R CMD check
value <- `Rescaled weights` <- Weights <- NULL
wt_data1 <- data %>%
dplyr::select(tidyselect::all_of(c(wt_col, rs_wt_col))) %>% # select only the weights and rescaled weights
dplyr::rename("Weights" = tidyselect::all_of(wt_col), "Rescaled weights" = tidyselect::all_of(rs_wt_col)) # rename so for plots
# tidyr::gather() # weights and rescaled weights in one column for plotting
wt_data <- dplyr::bind_rows(
dplyr::transmute(wt_data1, key = "Weights", value = Weights),
dplyr::transmute(wt_data1, key = "Rescaled weights", value = `Rescaled weights`)
)
hist_plot <- ggplot2::ggplot(wt_data) + ggplot2::geom_histogram(ggplot2::aes(value), bins = bin) +
ggplot2::facet_wrap(~key, ncol=1) + # gives the two plots (one on top of the other)
ggplot2::theme_bw()+
ggplot2::theme(axis.title = ggplot2::element_text(size = 16),
axis.text = ggplot2::element_text(size = 16)) +
ggplot2::ylab("Frequency") +
ggplot2::xlab("Weight")
return(hist_plot)
}
#' Produce a data frame of the weights assigned to patient profiles
#'
#' Select the patient characteristics used in the matching and the MAIC weights
#' and output a data frame of unique propensity weight values with the
#' associated summary baseline characteristics. This data frame helps to
#' understand how different patient profiles are contributing to the analyses by
#' illustrating the patient characteristics associated with different weight
#' values. For example, min, max and median weights. This function is most
#' useful when only matching on binary variables as there are fewer unique
#' values.
#'
#' @param data A data frame containing individual patient data from
#' the intervention study, including a column containing the weights (derived
#' using \code{\link{estimate_weights}}).
#' @param wt_col The name of the weights column in the data frame containing the
#' intervention individual patient data and the MAIC propensity weights. The
#' default is wt.
#' @param wt_rs The name of the rescaled weights column in the data frame
#' containing the intervention individual patient data and the MAIC propensity
#' weights. The default is wt_rs.
#' @param vars A character vector giving the variable names of the baseline
#' characteristics (not centered). These names must match the column names in
#' the data.
#'
#' @return A data frame that includes a summary of patient characteristics
#' associated with each weight value.
#'
#' @seealso \code{\link{estimate_weights}}
#' @example inst/examples/MAIC_example_weight_diagnostics.R
#' @export
profile_wts <- function(data, wt_col="wt", wt_rs="wt_rs", vars){
profile_data <- data %>%
dplyr::select(tidyselect::all_of(vars), tidyselect::all_of(wt_col), tidyselect::all_of(wt_rs))
profile_wts <- profile_data %>%
dplyr::distinct()
return(profile_wts)
}
#' Weight diagnostics
#'
#' Produce a set of useful diagnostic metrics to summarize propensity weights
#' \itemize{
#' \item ESS (\code{\link{estimate_ess}})
#' \item Summary statistics of the weights: minimum, maximum, median, mean, SD (\code{\link{summarize_wts}})
#' \item Patient profile associated with weight values (\code{\link{profile_wts}})
#' }
#'
#' @param data A data frame containing individual patient data from
#' the intervention study, including a column containing the weights (derived
#' using estimate_weights).
#' @param wt_col The name of the weights column in the data frame containing the
#' intervention individual patient data and the MAIC propensity weights. The
#' default is wt.
#' @param wt_rs The name of the rescaled weights column in the data frame
#' containing the intervention individual patient data and the MAIC propensity
#' weights. The default is wt_rs.
#' @param vars A character vector giving the variable names of the baseline
#' characteristics (not centered). These names must match the column names in
#' the data.
#'
#' @return List of the following:
#' \itemize{
#' \item The effective sample size (ESS) as a numeric value.
#' \item A data frame that includes a summary (minimum, maximum, median, mean,
#' standard deviation) of the weights and rescaled weights.
#' \item A data frame that includes a summary of patient characteristics
#' associated with each weight value.
#' }
#'
#' @seealso \code{\link{estimate_weights}}, \code{\link{estimate_ess}}, \code{\link{summarize_wts}}, \code{\link{profile_wts}}
#' @example inst/examples/MAIC_example_weight_diagnostics.R
#' @export
wt_diagnostics <- function(data, wt_col="wt", wt_rs="wt_rs", vars){
# ESS
ESS <- estimate_ess(data, wt_col)
# Summary
summ_wts <- summarize_wts(data, wt_col, wt_rs)
# Weight profiles
profile <- profile_wts(data, wt_col, wt_rs, vars)
output <- list("ESS" = ESS,
"Summary_of_weights" = summ_wts,
"Weight_profiles" = profile
)
return(output)
}
#' Checking whether optimization has worked
#'
#' Convenient function to check whether the re-weighted baseline characteristics for
#' the intervention-treated patients match those aggregate characteristics from the
#' comparator trial and outputs a summary that can be used for reporting
#'
#' @param analysis_data A data frame containing individual patient data from
#' the intervention study, including a column containing the weights (derived
#' using estimate_weights).
#' @param matching_vars A character vector giving the names of the covariates that were used to estimate weights
#' @param target_pop_standard aggregate characteristics of the comparator trial with the same naming as the analysis_data
#' @example inst/examples/MAIC_example_weight_diagnostics.R
#' @seealso \code{\link{estimate_weights}}
#' @return Summary of patient characteristics before and after matching, including ESS and comparator trial aggregate summary
#' @export
check_weights <- function(analysis_data = NULL, matching_vars = NULL,
target_pop_standard = NULL){
ARM <- c("Intervention", "Intervention_weighted", "Comparator")
ESS <- round(c(nrow(analysis_data), estimate_ess(analysis_data),
target_pop_standard$N))
weighted_cov <- analysis_data %>% summarise_at(matching_vars, list(~ weighted.mean(., wt)))
unweighted_cov <- analysis_data %>% summarise_at(matching_vars, list(~ mean(.)))
comparator_cov <- select(target_pop_standard, all_of(matching_vars))
cov <- rbind(unweighted_cov, weighted_cov, comparator_cov)
baseline_summary <- cbind(ARM, ESS, cov)
return(baseline_summary)
}<file_sep># script to update the documentation and vignettes hosted at https://roche.github.io/
# for each package once a change is made update the following files then run the appropriate section of code
# this will pre-compile all the vignettes and documentation to the website
##############################################
# Updates to add a new package
# when adding a new package is necessary to include links/make updates in the following files as well as in this script:
# all existing _pkgdown.yml files (update the navbar section for other packages)
# 1) make any updates to the package
# 2) update documentation using devtools
devtools::document()
# 3) reinstall the updated package
devtools::install()
# run checks
covr::package_coverage()
devtools::test()
rcmdcheck::rcmdcheck()
# 4) update the file _pkgdown.yml
# 5) rebuild documentation using pkgdown
pkgdown::build_site()
# Note as the vignettes for some packages can take a long time to run it is
# also possible just to update partial sections by just running the
# below functions without regenerating the vignettes
pkgdown::build_home()
pkgdown::build_reference()
pkgdown::build_articles_index()
<file_sep>#' est_weights
#'
#' An object containing weighted intervention data (est_weights$analysis_data)
#' and a vector of the centered matching variables (est_weights$matching_vars).
#'
#' @format est_weights$analysis_data is a data frame with 500 rows and 16 variables:
#' \describe{
#' \item{USUBJID}{unique patient number}
#' \item{ARM}{Name of the arm of the trial the patient was randomized to}
#' \item{AGE}{Patient age, years}
#' \item{SEX}{Patient gender: 1 for males and 0 for females}
#' \item{SMOKE}{Variable to indicate whether the patients smokes: 1 for yes and 0 for no}
#' \item{ECOG0}{ECOOG PS: 1 for ECOG PS 0 and 0 for ECOG PS >=1}
#' \item{response}{Objective response}
#' \item{Time}{Time to overall survival event/censor}
#' \item{Event}{Overall survival event = 1, censor = 0}
#' \item{response}{Objective response}
#' \item{Age_centered}{Patient's age minus average age in the comparator population}
#' \item{Age_squared_centered}{Patient's age squared - (Mean age in the target population squared + Standard deviation of age in the target population squared)}
#' \item{Sex_centered}{SEX variable minus the proportion of males in the comparator population}
#' \item{Smoke_centered}{SMOKE variable minus the proportion of smokers in the comparator population}
#' \item{ECOG0_centered}{ECOG0 variable minus the proportion of patients with ECOG0 in the comparator population}
#' \item{wt}{Propensity weight assigned to patient}
#' \item{wt_rs}{Propensity weight rescaled}
#'
#' }
"est_weights"
#' target_pop_standard
#'
#' A data frame containing the aggregate baseline characteristics in the
#' comparator population.
#'
#' @format A data frame with 1 row and 6 variables:
#' \describe{
#' \item{N}{Total number of patients in the comparator population}
#' \item{Treatment}{Treatment received in the comparator population}
#' \item{AGE}{Mean age}
#' \item{SEX}{Proportion of males}
#' \item{SMOKE}{Proportion of patients who smoke}
#' \item{ECOG0}{Proportion of patients with ECOG 0}
#'
#'
#' }
"target_pop_standard"
|
685ca73bdb1d6a4f8d18b88dfc53d417ae9c6319
|
[
"Markdown",
"R"
] | 13 |
R
|
Roche/MAIC
|
f5a2746ca0379aed67908d3b885f7f26adf48a2e
|
d909fc053117904e4a4d29062cefd749fddbabf2
|
refs/heads/master
|
<repo_name>MouseZero/scaling-game<file_sep>/README.md
#Get Started
- NodeJS must be installed on you computer.
- Open the projects root dir in your computers command line.
- Root has the "src" and "package.json" files/folders in it.
- Use the command ```npm install```.
- This will take a bit while it installs all the dependencies.
- Use the command ```npm run build```.
- This will transpile the JavaScript code.
- Use the command ```npm start```.
- This will start an http server on port 8000. Make sure not to close the window.
- Open a web browser up and navigate to ```http://localhost:8000```.
- The page should show up.
## File Locations
- public/index.html
- Start page
- src/data/data.json
- Data that the app uses to create game objects
- src/main.js
- The entry point for my JavaScript
## Custom Data (src/data/data.json)
The custom data is in JSON format. Change the following file to add you own data "src/public/data/data.json". When this file is changed you will have to run ```npm run build``` before the changes will take effect. Images should be 1000x1000 pixals.
```
{
"name": "Name to be displayed in menu",
"size": "This can be any unit of measure as long as it is consistent with all objects. I use miles",
"image": "Path to image"
}
```
See the default file for more examples
<file_sep>/src/scripts/gameScene.js
const createCelestialBody = require('./createCelestialBody')
const createjs = require('createjs-collection')
const animation = require('./animation')
const TICKER_NAME = 'tick'
function newScene (stage, canvasSize, celestialBodyData) {
const bodies = createCelestialBody(canvasSize, celestialBodyData.bodies)
placeBodies(stage, bodies)
animation.introAnimation(stage, canvasSize, bodies)
createjs.Ticker.setFPS(30)
createjs.Ticker.addEventListener(TICKER_NAME, stage)
}
function placeBodies (stage, bodies) {
bodies.slice().reverse()
.forEach(body => {
const futureScale = body.calcScaleFromLargestBody(bodies[0].solarSize)
body.scaleX = futureScale
body.scaleY = futureScale
body.x = body.cordsFromCenter(futureScale)
body.y = body.cordsFromCenter(futureScale)
stage.addChild(body)
})
}
module.exports.newScene = newScene
<file_sep>/src/scripts/animation.js
const createjs = require('createjs-collection')
const ZOOM_TIME = 1700
var lastZoomScale
function introAnimation (stage, canvasSize, shapes) {
lastZoomScale = shapes[0].solarSize
changeZoom(stage, canvasSize, shapes[6].solarSize)
}
// TODO look into deleting options
function changeZoom (stage, canvasSize, scale, options) {
options = options || {}
options.zoomTime = numberOfBodiesBetween(lastZoomScale, scale, stage) * ZOOM_TIME
if (lastZoomScale > scale) {
options.ease = createjs.Ease.getPowIn(8)
} else {
options.ease = createjs.Ease.getPowOut(8)
}
animateEachBody(stage, canvasSize, scale, options)
lastZoomScale = scale
}
function animateEachBody (stage, canvasSize, scale, options) {
stage.children.forEach(function (x) {
const futureScale = x.calcScaleFromLargestBody(scale)
if (x.calcScaleFromLargestBody) {
createjs.Tween.get(x)
.to({
scaleX: futureScale,
scaleY: futureScale,
x: x.cordsFromCenter(futureScale),
y: x.cordsFromCenter(futureScale)
}, options.zoomTime,
options.ease)
}
})
}
function numberOfBodiesBetween (scale1, scale2, stage) {
const largerScale = Math.max(scale1, scale2)
const smallerScale = Math.min(scale1, scale2)
return stage.children.reduce(function (p, x) {
if (x.solarSize <= largerScale && x.solarSize >= smallerScale) return p + 1
return p
}, 0)
}
module.exports.introAnimation = introAnimation
module.exports.changeZoom = changeZoom
<file_sep>/src/scripts/scaler.js
function solarMultiplier (canvasSize, largestSize) {
return canvasSize / largestSize
}
function scaleOf (targetSize, compareSize) {
return targetSize / compareSize
}
module.exports.solarMultiplier = solarMultiplier
module.exports.scaleOf = scaleOf
|
f6bb68a9ac62156948f981694c60897745544ab3
|
[
"Markdown",
"JavaScript"
] | 4 |
Markdown
|
MouseZero/scaling-game
|
7278752fc4af2a947bfa8668669148c537b1eb45
|
9254cbe87b0dab58f109356687b6da37843cc5b6
|
refs/heads/master
|
<repo_name>zvr/opensource-definition<file_sep>/tools/get_defs
#!/usr/bin/env python3
import glob
import os
import sys
import yaml
def get_def(fname):
with open(fname) as f:
t=f.read()
d=yaml.load(t)
return d['def']
def get_default_args():
dir = '.'
if os.getcwd() == os.path.dirname(os.path.realpath(sys.argv[0])):
dir = '..'
return glob.glob(dir + '/*.yaml')
if len(sys.argv) > 1:
args = sys.argv[1:]
else:
args = get_default_args()
for fn in args:
defn = get_def(fn)
print(defn)
<file_sep>/README.rst
Legal definitions of Open Source Software
=========================================
What is *Open Source* ?
There is the common need of having to define
what "Open Source Software" is.
The most common example is in legal documents
(software licenses, legal agreements, etc.)
or documents describing sofwtare
(documentation, RFPs, etc.)
A common answer is
"code that is under a license conforming
with the Open Source Definition,
as published by the Open Source Initiative".
On the
`Open Source Initiative website <https://opensource.org/>`_
one can read the
`Open Source Definition <https://opensource.org/osd>`_,
as well as an
`annotated version <https://opensource.org/osd-annotated>`_.
Unfortunately, this indirect definition
is not always convenient for legal documents.
It should be noted that a *lot* of EULAs
make reference to "Open Source software"
without providing any definition.
This repository collects different defintions
of "Open Source Software" as found in various legal documents.
Contributions welcome!
----------------------
If you have found a defintition
of "Open Source Software"
in a legal document,
I'd be happy to include it in the collection.
If you don't want to go to the trouble
of preparing and submitting a pull request,
you can simply
`open an issue <https://github.com/zvr/opensource-definition/issues/new>`_.
and provide the link to the document.
I'll integrate as soon as possible.
Thank you!
|
a7c90dcd95e711474262785247085302722223c0
|
[
"Python",
"reStructuredText"
] | 2 |
Python
|
zvr/opensource-definition
|
2d898020c667bd4e38561e0e9bcbec6a1a6c3401
|
a22430d25bbecdfb7785f3d2bc26817ba137bc11
|
refs/heads/master
|
<repo_name>gkovacs/do-not-automatically-add-other-search-engines<file_sep>/contentscript.js
for (var x of document.querySelectorAll('link[type="application/opensearchdescription+xml"]')) {
x.remove();
}
<file_sep>/readme.md
# Do not automatically add other search engines
Chrome automatically adds sites to your list of custom search engines list when you visit them. This extension prevents this behavior.
[Chrome Web Store](https://chrome.google.com/webstore/detail/lejpfpoaicennngnbmkhgagndoiijjip)
Note that Chrome uses a number of heuristics to add search engines, and while this extension prevents the most common approach, we cannot prevent all of them. Hence, some search engines may still get through. To remove added search engines (in this case, those that contain '.' in the keyword), navigate to chrome://settings/searchEngines and run the following code a few times (via the developer console, `Command-Option-J` or `Ctrl-Shift-J`)
```javascript
for (var x of document.querySelectorAll('.keyword-column')) {
if (x.innerText.indexOf('.') != -1) {
x.parentNode.parentNode.childNodes[1].click()
}
}
```
|
adbd0eeb72fb31ca1e027f89b23486ab20fa7723
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
gkovacs/do-not-automatically-add-other-search-engines
|
353e093547a1fe25a9c1652fce2b72248b38c1f2
|
f27a338f0c60f87bafa5df5f5209342d2b23dd62
|
refs/heads/master
|
<repo_name>miserylee/mango.ts<file_sep>/src/definitions.d.ts
declare module 'mongoose-timestamp' {
import { Schema } from 'mongoose';
function mongooseTimestamp(schema: Schema): void;
namespace mongooseTimestamp {
}
export = mongooseTimestamp;
}
<file_sep>/src/transaction.ts
import { Connection, Document, Model, Schema, SchemaDefinition } from 'mongoose';
import * as timestamp from 'mongoose-timestamp';
import { IRecycleModel } from './recycle';
import { IObjectId } from './types';
export interface IError extends Error {
type: string;
}
const TRANSACTION_STATE = {
initialized: 'initialized',
pending: 'pending',
committed: 'committed',
finished: 'finished',
rollback: 'rollback',
cancelled: 'cancelled',
};
const definition: SchemaDefinition = {
state: {
type: String,
required: true,
enums: Object.keys(TRANSACTION_STATE),
default: TRANSACTION_STATE.initialized,
},
models: [],
error: {
message: String,
stack: String,
type: { type: String },
name: String,
},
mark: String,
memo: {},
initializedAt: Date,
cost: Number,
};
export interface ITransactionDocument extends Document {
state: string;
models: string[];
error: {
message: string;
stack: string;
type: string;
name: string;
};
mark: string;
memo: any;
initializedAt: Date;
cost: string;
}
export interface ITransactionModel extends Model<ITransactionDocument> {
bindModel<T>(UsedModel: T): T;
_checkModel(modelName: string): Model<any>;
initialize(mark?: string, memo?: any): IObjectId;
pend(id: IObjectId, modelName: string): void;
commit(id: IObjectId): void;
cancel(id: IObjectId, error: IError): void;
try<T extends any>(fn: (tid: IObjectId) => T, mark?: string, memo?: any): T;
cure(timeout?: number): void;
}
export default (connection: Connection, Recycle: IRecycleModel, {
didTransactionInitialized = () => null,
didTransactionPended = () => null,
didTransactionCommitted = () => null,
didTransactionCancelled = () => null,
didTransactionCured = () => null,
}: {
didTransactionInitialized?: (t: ITransactionDocument, mark: string, memo: any) => void;
didTransactionPended?: (t: ITransactionDocument, modelName: string) => void;
didTransactionCommitted?: (t: ITransactionDocument, cost: number) => void;
didTransactionCancelled?: (t: ITransactionDocument, cost: number, error: IError) => void;
didTransactionCured?: (transactions: ITransactionDocument[]) => void;
} = {}): ITransactionModel => {
const schema = new Schema(definition);
schema.index({ _id: 1, state: 1 });
schema.plugin(timestamp);
schema.statics.bindModel = function(UsedModel: Model<any>) {
if (!this.models) {
this.models = {};
}
this.models[UsedModel.modelName] = UsedModel;
return UsedModel;
};
schema.statics._checkModel = function(modelName: string) {
if (!this.models || !this.models[modelName]) {
throw new Error(`Should bind model [${modelName}] to Transaction.models first.`);
}
return this.models[modelName];
};
schema.statics.initialize = async function(mark: string, memo: any) {
const t = await this.create({ mark, memo, initializedAt: new Date() });
await didTransactionInitialized(t, mark, memo);
return t._id;
};
schema.statics.pend = async function(id: IObjectId, modelName: string) {
const t = await this.findOneAndUpdate({
_id: id,
state: {
$in: [
TRANSACTION_STATE.initialized,
TRANSACTION_STATE.pending,
],
},
}, {
$set: {
state: TRANSACTION_STATE.pending,
},
$addToSet: {
models: modelName,
},
}).setOptions({ read: 'primary' });
if (!t) {
throw new Error(`Transaction [${id}] is not valid.`);
}
await didTransactionPended(t, modelName);
};
schema.statics.commit = async function(id: IObjectId) {
const t = await this.findOneAndUpdate({
_id: id,
state: {
$in: [
TRANSACTION_STATE.pending,
TRANSACTION_STATE.initialized,
TRANSACTION_STATE.committed,
],
},
}, {
$set: {
state: TRANSACTION_STATE.committed,
},
}, { new: true }).setOptions({ read: 'primary' });
if (!t) {
throw new Error(`Transaction [${id}] cannot commit.`);
}
for (const modelName of t.models) {
const UsedModel = this._checkModel(modelName) as Model<any>;
// remove backup and unlock.
await UsedModel.update({ __t: id }, {
$unset: {
__b: 1,
__t: 1,
},
}, { multi: true });
}
t.state = TRANSACTION_STATE.finished;
t.cost = Date.now() - t.initializedAt.getTime();
await t.save();
await didTransactionCommitted(t, t.cost);
};
schema.statics.cancel = async function(id: IObjectId, error: IError) {
const t = await this.findOneAndUpdate({
_id: id,
state: {
$in: [
TRANSACTION_STATE.initialized,
TRANSACTION_STATE.pending,
TRANSACTION_STATE.rollback,
],
},
}, {
$set: {
state: TRANSACTION_STATE.rollback,
},
}, { new: true }).setOptions({ read: 'primary' });
if (!t) {
throw new Error(`Transaction [${id}] cannot cancel. Cancel reason: ${error.message}`);
}
// recover recycle.
const trashes = await Recycle.find({ tid: id }).setOptions({ read: 'primary' });
for (const trash of trashes) {
const UsedModel = this._checkModel(trash.srcModel) as Model<any>;
if (!(await UsedModel.findById(trash.srcId).setOptions({ read: 'primary' }))) {
const doc = Object.assign({
__t: id,
}, trash.data);
await UsedModel.insertMany(doc);
}
await trash.remove();
}
for (const modelName of t.models) {
const UsedModel = this._checkModel(modelName) as Model<any>;
// recover backup and unlock.
const docs = await UsedModel.find({ __t: id }).setOptions({ read: 'primary' });
for (const doc of docs) {
if (doc.__b) {
// doc has updated
// use backup to rewrite doc.
await UsedModel.replaceOne({ _id: doc._id, __t: id }, doc.__b);
} else if (typeof doc.__b === 'undefined') {
// doc has lock with no backup.
// only unlock.
await UsedModel.update({ _id: doc._id, __t: id }, {
$unset: {
__t: 1,
__b: 1,
},
});
} else {
// doc is created
// remove the doc
await UsedModel.remove({ _id: doc._id, __t: id });
}
}
}
if (!t.error || !t.error.name) {
t.error = {
name: error.name,
type: error.type,
message: error.message,
stack: error.stack,
};
}
t.state = TRANSACTION_STATE.cancelled;
t.cost = Date.now() - t.initializedAt.getTime();
await t.save();
await didTransactionCancelled(t, t.cost, error);
};
schema.statics.try = async function(fn: (tid: IObjectId) => {}, mark: string, memo: any) {
const t = await this.initialize(mark, memo);
try {
const result = await fn.bind(fn)(t);
await this.commit(t);
return result;
} catch (error) {
await this.cancel(t, error);
throw error;
}
};
schema.statics.cure = async function(timeout = 6e4) {
const transactions = await this.find({
initializedAt: { $lte: Date.now() - timeout },
state: {
$nin: [
TRANSACTION_STATE.finished,
TRANSACTION_STATE.cancelled,
],
},
}).setOptions({ read: 'primary' });
for (const t of transactions) {
if (t.state === TRANSACTION_STATE.committed) {
await this.commit(t);
} else {
await this.cancel(t, new Error('Cancel unprocessed.'));
}
}
await didTransactionCured(transactions);
};
return connection.model<ITransactionDocument, ITransactionModel>('transaction', schema);
};
<file_sep>/src/index.ts
import { Connection, Schema } from 'mongoose';
import plugin, { IPluggedDocument, IPluggedModel } from './plugin';
import recycle, { IRecycleModel } from './recycle';
import transaction, { IError, ITransactionDocument, ITransactionModel } from './transaction';
import { IObjectId } from './types';
export interface IMango {
Recycle: IRecycleModel;
Transaction: ITransactionModel;
plugin: (schema: Schema) => void;
}
export * from './types';
export * from './plugin';
export * from './recycle';
export * from './transaction';
export interface IHooks {
didInstanceCreated?: (instance: IMango) => void;
didDocumentLocked?: <T extends IPluggedDocument>(tid: IObjectId, model: IPluggedModel<T>, doc: T) => void;
didTransactionInitialized?: (t: ITransactionDocument, mark: string, memo: any) => void;
didTransactionPended?: (t: ITransactionDocument, modelName: string) => void;
didTransactionCommitted?: (t: ITransactionDocument, cost: number) => void;
didTransactionCancelled?: (t: ITransactionDocument, cost: number, error: IError) => void;
didTransactionCured?: (transactions: ITransactionDocument[]) => void;
}
let instance: IMango;
export default (connection: Connection, {
didInstanceCreated = () => null,
didDocumentLocked = () => null,
didTransactionInitialized = () => null,
didTransactionPended = () => null,
didTransactionCommitted = () => null,
didTransactionCancelled = () => null,
didTransactionCured = () => null,
}: IHooks = {}): IMango => {
if (!instance) {
const Recycle = recycle(connection);
const Transaction = transaction(connection, Recycle, {
didTransactionInitialized,
didTransactionPended,
didTransactionCommitted,
didTransactionCancelled,
didTransactionCured,
});
instance = {
Recycle,
Transaction,
plugin: plugin(Transaction, Recycle, { didDocumentLocked }),
};
didInstanceCreated(instance);
}
return instance;
};
<file_sep>/test/config/mangoInstance.ts
import { Connection, Schema } from 'mongoose';
import mango, { IRecycleModel, ITransactionModel } from '../../src';
import connection from './connection';
const mangoInstance: {
Recycle: IRecycleModel;
Transaction: ITransactionModel;
plugin: (schema: Schema) => void;
connection: Connection
} = {
...mango(connection, {
didInstanceCreated: _ => console.log('instance created'),
didDocumentLocked: (tid, model, doc) => console.log(`doc ${model.modelName}[${doc._id}] locked by ${tid}`),
didTransactionInitialized: (t, mark) => console.log(`transaction [${t._id}] initialized. ${mark}`),
didTransactionPended: (t, modelName) => console.log(`transaction [${t._id}] pended ${modelName}`),
didTransactionCommitted: (t, cost) => console.log(`transaction [${t._id}] committed cost ${cost}ms`),
didTransactionCancelled: (t, cost, error) =>
console.log(`transaction [${t._id}] cancelled cost ${cost}ms, ${error.message}`),
didTransactionCured: transactions => console.log('cured transactions'),
}),
connection,
};
export = mangoInstance;
<file_sep>/src/recycle.ts
import { Connection, Document, Model, Schema, SchemaDefinition } from 'mongoose';
import * as mongooseTimestamp from 'mongoose-timestamp';
import { IObjectId } from './types';
export interface IRecycleDocument extends Document {
tid: IObjectId;
srcModel: string;
srcId: string;
data: any;
}
const definition: SchemaDefinition = {
tid: { type: Schema.Types.ObjectId, required: true },
srcModel: { type: String, required: true },
srcId: { type: String, required: true },
data: {},
};
export interface IRecycleModel extends Model<IRecycleDocument> {
}
export default (connection: Connection): IRecycleModel => {
const schema = new Schema(definition);
schema.index({ tid: 1, srcModel: 1, srcId: 1 }, { unique: true });
schema.index({ createdAt: 1 }, { expires: 2592000000 as any });
schema.plugin(mongooseTimestamp);
return connection.model<IRecycleDocument, IRecycleModel>('recycle', schema);
};
<file_sep>/test/all-in-one.spec.ts
import * as assert from 'assert';
import { connection, Transaction } from './config/mangoInstance';
import Person, { IPersonDocument } from './config/Person';
import Wallet, { IWalletDocument } from './config/Wallet';
describe('All in a transaction', () => {
it('drop database', async () => {
await connection.dropDatabase();
});
it('should ok', async () => {
let { person, wallet } = await Transaction.try(async t => {
// Create a person
const p = await Person.create({
name: 'Misery',
gender: 'male',
profile: {
nickname: 'Mis',
},
__t: t, // Inject transaction
});
// Update nickname
await Person.findByIdAndUpdate(p._id, {
$set: {
'profile.nickname': 'Luna',
},
}, {
__t: t,
});
// Unset gender
await Person.findByIdAndUpdate(p._id, {
$unset: { gender: 1 },
}, {
__t: t,
});
// Create a wallet
const w = await Wallet.create({
person: p._id,
__t: t,
});
// Recharge it
w.__t = t;
w.money += 100;
await w.save();
return {
person: p,
wallet: w,
};
}, 'create a person with wallet recharged.');
assert(person);
assert(wallet);
person = await Person.findById(person._id) as IPersonDocument;
wallet = await Wallet.findById(wallet._id) as IWalletDocument;
assert(person.name === 'Misery');
assert(person.profile.nickname === 'Luna');
assert(!person.gender);
assert(wallet.person.toString() === person._id.toString());
assert(wallet.money === 100);
});
});
after(async () => {
connection.close();
});
<file_sep>/src/types.ts
import { Types } from 'mongoose';
export type IObjectId = Types.ObjectId | string | number | Buffer;
<file_sep>/test/config/Person.ts
import { Schema } from 'mongoose';
import * as mongooseTimestamp from 'mongoose-timestamp';
import { IPluggedDocument, IPluggedModel } from '../../src';
import { connection, plugin, Transaction } from './mangoInstance';
const schema = new Schema({
name: String,
gender: String,
profile: {
nickname: String,
},
});
export interface IPersonDocument extends IPluggedDocument {
name: string;
gender: string;
profile: {
nickname: string;
};
}
export interface IPersonModel extends IPluggedModel<IPersonDocument> {
}
schema.plugin(mongooseTimestamp);
schema.plugin(plugin);
export default Transaction.bindModel<IPersonModel>(connection.model<IPersonDocument, IPersonModel>('person', schema));
<file_sep>/test/index.spec.ts
import * as assert from 'assert';
import { IObjectId } from '../src';
import { connection, Transaction } from './config/mangoInstance';
import Person, { IPersonDocument } from './config/Person';
import Wallet from './config/Wallet';
describe('Transaction', () => {
it('drop database', async () => {
await connection.dropDatabase();
});
let person: IPersonDocument;
it('create a person', async () => {
person = await createAPerson();
});
it('update nickname', async () => {
await updateNickName(person._id);
});
it('unset person gender', async () => {
await unsetPersonGender(person._id);
});
it('create a wallet and recharge', async () => {
await createAWalletAndRecharge(person._id);
});
it('close connection', async () => {
await connection.close();
});
});
async function createAPerson(): Promise<IPersonDocument> {
const p = await Transaction.try(async t => {
return await Person.create({
name: 'Misery',
gender: 'male',
profile: {
nickname: 'Mis',
},
__t: t, // Inject transaction
});
}, 'create a person');
const person = await Person.findById(p._id);
assert(person);
if (person) {
assert(person.name === 'Misery');
assert(person.gender === 'male');
assert(person.profile.nickname === 'Mis');
}
return person as IPersonDocument;
}
async function updateNickName(id: IObjectId) {
await Transaction.try(async t => {
await Person.findByIdAndUpdate(id, {
$set: { 'profile.nickname': 'Luna' },
}, {
__t: t,
});
}, 'update nickname');
const person = await Person.findById(id);
assert(person);
if (person) {
assert(person.name === 'Misery');
assert(person.profile.nickname === 'Luna');
}
}
async function unsetPersonGender(id: IObjectId) {
await Transaction.try(async t => {
await Person.findByIdAndUpdate(id, {
$unset: { gender: 1 },
}, {
__t: t,
});
}, 'unset person gender');
const person = await Person.findById(id);
assert(person);
if (person) {
assert(person.name === 'Misery');
assert(!person.gender);
}
}
async function createAWalletAndRecharge(persnId: IObjectId) {
let wallet = await Transaction.try(async t => {
const person = await Person.findById(persnId);
assert(person);
if (!person) {
return null;
}
const w = await Wallet.create({
person: person._id,
__t: t,
});
return await Wallet.findByIdAndUpdate(w._id, {
$set: {
money: 100,
},
}, {
__t: t,
});
}, 'create wallet and recharge');
if (wallet) {
wallet = await Wallet.findById(wallet._id);
assert(wallet);
if (wallet) {
assert(wallet.person.toString() === persnId.toString());
assert(wallet.money === 100);
}
}
}
after(async () => {
connection.close();
});
<file_sep>/test/config/connection.ts
import * as mongoose from 'mongoose';
(mongoose as any).Promise = global.Promise;
const connection = mongoose.createConnection('mongodb://localhost/mangots');
connection.on('connected', () => {
console.log('db connected.');
});
connection.on('close', () => {
console.log('db closed.');
});
connection.on('error', err => {
console.error(err);
});
export default connection;
<file_sep>/src/plugin.ts
import {
Document, DocumentQuery,
Model, ModelFindByIdAndUpdateOptions,
ModelFindOneAndUpdateOptions, ModelUpdateOptions, Query, Schema,
} from 'mongoose';
import { IRecycleModel } from './recycle';
import { ITransactionModel } from './transaction';
import { IObjectId } from './types';
export interface IPluggedDocument extends Document {
__t: IObjectId;
__b: any;
constructor: IPluggedModel<this>;
lock(tid: IObjectId): void;
}
export interface IModelFindOneAndUpdateOptions extends ModelFindOneAndUpdateOptions {
__t: IObjectId;
}
export interface IModelFindByIdAndUpdateOptions extends ModelFindByIdAndUpdateOptions {
__t: IObjectId;
}
export interface IModelUpdateOptions extends ModelUpdateOptions {
__t: IObjectId;
}
export interface IModelFindOneAndRemoveOptions {
/**
* if multiple docs are found by the conditions, sets the sort order to choose
* which doc to update
*/
sort?: any;
/** puts a time limit on the query - requires mongodb >= 2.6.0 */
maxTimeMS?: number;
/** sets the document fields to return */
select?: any;
__t: IObjectId;
}
export interface IModelFindByIdAndRemoveOptions {
/** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */
sort?: any;
/** sets the document fields to return */
select?: any;
__t: IObjectId;
}
export interface IPluggedModel<T extends IPluggedDocument> extends Model<T> {
__lock(tid: IObjectId, conditions?: any): Promise<T>;
findByIdAndUpdate(): DocumentQuery<T | null, T>;
findByIdAndUpdate(id: any | number | string, update: any,
callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T>;
findByIdAndUpdate(id: any | number | string, update: any,
options: IModelFindByIdAndUpdateOptions,
callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T>;
findOneAndUpdate(): DocumentQuery<T | null, T>;
findOneAndUpdate(conditions: any, update: any,
callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery<T | null, T>;
findOneAndUpdate(conditions: any, update: any,
options: IModelFindOneAndUpdateOptions,
callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery<T | null, T>;
update(conditions: any, doc: any,
callback?: (err: any, raw: any) => void): Query<any>;
update(conditions: any, doc: any, options: IModelUpdateOptions,
callback?: (err: any, raw: any) => void): Query<any>;
updateOne(conditions: any, doc: any,
callback?: (err: any, raw: any) => void): Query<any>;
updateOne(conditions: any, doc: any, options: IModelUpdateOptions,
callback?: (err: any, raw: any) => void): Query<any>;
updateMany(conditions: any, doc: any,
callback?: (err: any, raw: any) => void): Query<any>;
updateMany(conditions: any, doc: any, options: IModelUpdateOptions,
callback?: (err: any, raw: any) => void): Query<any>;
findOneAndRemove(conditions?: any,
callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T>;
findOneAndRemove(conditions: any,
options: IModelFindOneAndRemoveOptions,
callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T>;
findByIdAndRemove(id?: any | number | string,
callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T>;
findByIdAndRemove(id: any | number | string,
options: IModelFindByIdAndRemoveOptions,
callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T>;
}
export interface IQuery<T extends IPluggedDocument> extends Query<IPluggedDocument> {
options: any;
model: IPluggedModel<T>;
_conditions: any;
}
export default (Transaction: ITransactionModel, Recycle: IRecycleModel, {
didDocumentLocked = () => null,
}: {
didDocumentLocked?: <T extends IPluggedDocument>(tid: IObjectId, model: IPluggedModel<T>, doc: T) => void;
} = {}) => {
return (schema: Schema) => {
schema.add({
__t: { type: Schema.Types.ObjectId, index: true },
__b: {},
});
schema.statics.__lock = async function <T extends IPluggedDocument>(this: IPluggedModel<T>,
tid: IObjectId, conditions: any): Promise<T | null> {
// set transaction pending.
// record used models.
await Transaction.pend(tid, this.modelName);
// lock data.
if (!conditions) {
return null;
}
const doc = await this.findOneAndUpdate({
$and: [conditions, {
$or: [{
__t: tid,
}, {
__t: { $exists: false },
}],
}],
}, {
$set: {
__t: tid,
},
});
if (!doc) {
throw new Error('Resource is busy or not exists.');
} else {
didDocumentLocked(tid, this, doc);
}
// save backup
if (typeof doc.__b === 'undefined') {
const b = doc.toJSON();
Reflect.deleteProperty(b, '__t');
Reflect.deleteProperty(b, '__v');
await this.findByIdAndUpdate(doc._id, {
$set: {
__b: b,
},
});
}
doc.set('__t', undefined);
doc.set('__b', undefined);
return doc;
};
schema.methods.lock = async function <T extends IPluggedDocument>(this: T, tid: IObjectId): Promise<T | null> {
return await this.constructor.__lock(tid, { _id: this._id });
};
schema.pre('save', function(this: IPluggedDocument, next) {
const tid = this.__t;
if (!tid) {
return next();
}
(async _ => {
if (this.isNew) {
await this.constructor.__lock(this.__t);
this.__b = null;
next();
} else {
await this.constructor.__lock(this.__t, { _id: this._id });
next();
}
})().catch(next);
});
schema.pre('findOneAndUpdate', function(this: IQuery<IPluggedDocument>, next) {
const tid = this.options.__t;
if (!tid) {
return next();
}
(async _ => {
const doc = await this.model.__lock(tid, this._conditions);
// rewrite condition.
this._conditions = { _id: doc._id };
next();
})().catch(next);
});
schema.pre('update', function(this: IQuery<IPluggedDocument>, next) {
const tid = this.options.__t;
if (!tid) {
return next();
}
(async _ => {
if (!this.options.multi) {
const doc = await this.model.__lock(tid, this._conditions);
this._conditions = { _id: doc._id };
} else {
const docs = await this.model.find(this._conditions);
for (const doc of docs) {
await this.model.__lock(tid, { _id: doc._id });
}
this._conditions = { $and: [this._conditions, { __t: tid }] };
}
next();
})().catch(next);
});
schema.pre('findOneAndRemove', function(this: IQuery<IPluggedDocument>, next) {
const tid = this.options.__t;
if (!tid) {
return next();
}
(async _ => {
const doc = await this.model.__lock(tid, this._conditions);
await Recycle.create({
tid,
model: this.model.modelName,
id: doc._id,
data: doc,
});
next();
})().catch(next);
});
schema.pre('remove', function(this: IPluggedDocument, next) {
const tid = this.__t;
if (!tid) {
return next();
}
(async _ => {
const doc = await this.constructor.__lock(tid, { _id: this._id });
await Recycle.create({
tid,
model: this.constructor.modelName,
id: doc._id,
data: doc,
});
next();
})().catch(next);
});
schema.pre('find', () => {
// console.log(this);
});
schema.pre('findOne', () => {
// console.log(this);
});
};
};
<file_sep>/test/config/Wallet.ts
import { Schema } from 'mongoose';
import * as mongooseTimestamp from 'mongoose-timestamp';
import { IPluggedDocument, IPluggedModel } from '../../src';
import { IObjectId } from '../../src';
import { connection, plugin, Transaction } from './mangoInstance';
const schema = new Schema({
person: { type: Schema.Types.ObjectId, ref: 'person' },
money: { type: Number, default: 0, min: 0 },
});
schema.plugin(mongooseTimestamp);
schema.plugin(plugin);
export interface IWalletDocument extends IPluggedDocument {
person: IObjectId;
money: number;
}
export interface IWalletModal extends IPluggedModel<IWalletDocument> {
}
export default Transaction.bindModel<IWalletModal>(connection.model<IWalletDocument, IWalletModal>('wallet', schema));
<file_sep>/README.md
# mango.ts
## 
### Example
Check the test please.
|
82e0c65fc2efff50f2704bc4c2ab4d3051df5973
|
[
"Markdown",
"TypeScript"
] | 13 |
TypeScript
|
miserylee/mango.ts
|
fe848e92fc0edf7eecec73389cc3bd5e3b872bbf
|
8c559e83d81be2d4208a8b89b0e8bbde7c4874bd
|
refs/heads/main
|
<repo_name>VadimAlkhimenok/blog_project<file_sep>/src/webapp/react/src/components/comment/Comment.js
import React from "react";
import PropTypes from 'prop-types';
import classes from './Comment.module.css';
import Typography from "@material-ui/core/Typography";
import {Grid} from "@material-ui/core";
import {Textarea} from "../UI/textarea/Textarea";
import {Btn} from "../UI/button/Button";
export const Comment = ({title, value}) => {
return (
<div className={classes.comment}>
<Typography variant='subtitle1'>{title}</Typography>
<Grid container>
<Grid item xs={12}>
<Textarea value={value} />
</Grid>
<Grid item xs={1}>
<Btn title='Edit'
color='primary'
variant='text'
/>
</Grid>
<Grid item xs={1}>
<Btn title='Remove'
color='secondary'
variant='text'
/>
</Grid>
</Grid>
</div>
)
}
Comment.propTypes = {
title: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
}<file_sep>/src/webapp/react/src/components/helpers/test.js
export const authorsAll = [
{id: 1, name: "Author 1"},
{id: 2, name: "Author 2"},
{id: 3, name: "Author 3"},
{id: 4, name: "Author 4"},
{id: 5, name: "Author 5"},
]
export const authorsFavourite = [
{id: 1, name: "Author 1"},
{id: 4, name: "Author 4"},
{id: 5, name: "Author 5"},
]
export const authors = [
{
id: 1,
name: "<NAME>",
biography: "Biography's author 1",
subscribers: 1,
posts: [
{
id: 1,
title: "Post title 1",
description: "Description post title 1",
like: null,
comments: [
{id: 1, name: "Reader 1", text: "Description post comment 1"},
{id: 2, name: "Reader 2", text: "Description post comment 2"},
{id: 3, name: "Reader 2", text: "Description post comment 2"},
{id: 4, name: "Reader 2", text: "Description post comment 2"},
]
},
]
},
{
id: 2,
name: "<NAME>",
biography: "Biography's author 2",
subscribers: 2,
posts: [
{id: 6, title: "Post title 6", description: "Description post title 5", like: null},
{id: 7, title: "Post title 7", description: "Description post title 6", like: null,},
]
},
{
id: 3,
name: "<NAME>",
biography: "Biography's author 3",
subscribers: 3,
posts: [
{id: 1, title: "Post title 1", description: "Description post title 1"},
{id: 2, title: "Post title 2", description: "Description post title 2"},
{id: 3, title: "Post title 3", description: "Description post title 3"},
]
},
{
id: 4,
name: "<NAME>",
biography: "Biography's author 4",
subscribers: 4,
posts: [
{id: 7, title: "Post title 7", description: "Description post title 6"},
{id: 8, title: "Post title 8", description: "Description post title 7"},
{id: 9, title: "Post title 9", description: "Description post title 8"},
{id: 10, title: "Post title 10", description: "Description post title 9"},
]
},
{
id: 5,
name: "<NAME>",
biography: "Biography's author 5",
subscribers: 52342344,
posts: [
{id: 6, title: "Post title 6", description: "Description post title 5"},
{id: 7, title: "Post title 7", description: "Description post title 6"},
{id: 8, title: "Post title 8", description: "Description post title 7"},
{id: 9, title: "Post title 9", description: "Description post title 8"},
{id: 10, title: "Post title 10", description: "Description post title 9"},
{id: 11, title: "Post title 10", description: "Description post title 9"},
{id: 12, title: "Post title 10", description: "Description post title 9"},
]
},
]<file_sep>/src/main/java/com/blog/services/impl/SubscribeServiceImpl.java
package com.blog.services.impl;
import com.blog.models.Subscribe;
import com.blog.models.User;
import com.blog.repositories.SubscribeRepository;
import com.blog.services.SubscribeService;
import com.blog.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SubscribeServiceImpl implements SubscribeService {
@Autowired
private SubscribeRepository subscribeRepository;
@Autowired
private UserService userService;
@Override
public Subscribe subscribe(int idAuthor, int idSubscriber) {
User subscriber = userService.getUser(idSubscriber);
User author = userService.getUser(idAuthor);
Subscribe subscribe = new Subscribe();
subscribe.setSubscriber(subscriber);
subscribe.setAuthor(author);
return subscribeRepository.save(subscribe);
}
}
<file_sep>/src/main/java/com/blog/controllers/AuthController.java
package com.blog.controllers;
import com.blog.models.User;
import com.blog.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class AuthController {
@Autowired
UserService userService;
@GetMapping(value = "/login")
public User login() {
return userService.getAuthUser();
}
@PostMapping(value = "/registration")
public ResponseEntity<?> registration(@RequestBody User user) {
userService.create(user);
return new ResponseEntity<>(HttpStatus.CREATED);
}
}<file_sep>/src/webapp/react/src/components/navigation/Navigation.js
import React from 'react';
import { NavLink } from 'react-router-dom';
import classes from './Navigation.module.css';
import {useParams} from "react-router";
export const Navigation = () => {
const {id} = useParams();
return (
<nav className={classes.Navigation}>
<ul className={classes.List}>
<li className={classes.LinkItem}>
<NavLink to={`/users/${id}`}
className={classes.Link}
activeClassName={classes.Active}
>
Main page
</NavLink>
</li>
</ul>
</nav>
);
};
<file_sep>/src/main/java/com/blog/services/impl/CommentServiceImpl.java
package com.blog.services.impl;
import com.blog.services.CommentService;
public class CommentServiceImpl implements CommentService {
}
<file_sep>/src/webapp/react/src/components/article/Article.js
import React from "react";
import PropTypes from 'prop-types';
import classes from './Article.module.css';
import ThumbUpAltIcon from "@material-ui/icons/ThumbUpAlt";
import ThumbDownIcon from "@material-ui/icons/ThumbDown";
import {Btn} from "../UI/button/Button";
import {Textarea} from "../UI/textarea/Textarea";
import {Like} from "../UI/like/Like";
export const Article = ({id, handleOpen, title, value, isLike, isDislike, handleLike, handleDislike}) => {
return (
<div className={classes.article}>
<Btn onClick={handleOpen(id)} title={title} color='primary' variant='text' />
<div className={classes.content}>
<Textarea value={value} />
<div className={classes.likes}>
<Like color='primary' disabled={isLike} onClick={handleLike}>
<ThumbUpAltIcon />
</Like>
<Like color='secondary' disabled={isDislike} onClick={handleDislike}>
<ThumbDownIcon />
</Like>
</div>
</div>
</div>
)
}
Article.propTypes = {
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
isLike: PropTypes.bool.isRequired,
isDislike: PropTypes.bool.isRequired,
handleOpen: PropTypes.func.isRequired,
handleLike: PropTypes.func.isRequired,
handleDislike: PropTypes.func.isRequired,
};<file_sep>/src/main/java/com/blog/controllers/SubscribeController.java
package com.blog.controllers;
import com.blog.models.User;
import com.blog.services.SubscribeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class SubscribeController {
@Autowired
SubscribeService subscribeService;
@PutMapping(value = "/users/{id}/subscribe")
public ResponseEntity<?> subscribe(@PathVariable int id, @RequestBody User author) {
subscribeService.subscribe(author.getId(), id);
return new ResponseEntity<>(HttpStatus.OK);
}
}
<file_sep>/src/main/java/com/blog/repositories/CommentRepository.java
package com.blog.repositories;
import com.blog.models.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CommentRepository extends JpaRepository<Comment, Integer> {
}
<file_sep>/src/webapp/react/src/components/article-info/ArticleInfo.js
import React, {useState} from "react";
import PropTypes from 'prop-types';
import classes from './ArticleInfo.module.css';
import Dialog from '@material-ui/core/Dialog';
import Divider from '@material-ui/core/Divider';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import CloseIcon from '@material-ui/icons/Close';
import ThumbUpAltIcon from "@material-ui/icons/ThumbUpAlt";
import ThumbDownIcon from "@material-ui/icons/ThumbDown";
import {Like} from "../UI/like/Like";
import {Btn} from "../UI/button/Button";
import {CommentForm} from "../controls/CommentForm";
import {Comment} from "../comment/Comment";
export const ArticleInfo = ({open, handleClose, post, handleDislike, handleLike, isDislike, isLike}) => {
const [isComment, setComment] = useState(false);
const handleAddComment = () => {
setComment(true);
}
const handleAddCommentCancel = () => {
setComment(false);
}
return (
<Dialog fullScreen open={open} onClose={handleClose}>
<AppBar className={classes.appBar}>
<Toolbar>
<IconButton edge="start" color="inherit" onClick={handleClose} aria-label="close">
<CloseIcon />
</IconButton>
<Typography variant="h6" className={classes.title}>
{post.title}
</Typography>
</Toolbar>
</AppBar>
<div className={classes.main}>
<div className={classes.description}>
{post.description}
</div>
<Divider />
<div className={classes.manage}>
<Like color='primary' disabled={isLike} onClick={handleLike}>
<ThumbUpAltIcon />
</Like>
<Like color='secondary' disabled={isDislike} onClick={handleDislike}>
<ThumbDownIcon />
</Like>
<Btn onClick={handleAddComment}
color='primary'
title='Add a comment'
variant='text'
fullWidth={false}
/>
</div>
<Divider />
{ isComment ? <CommentForm handleAddCommentCancel={handleAddCommentCancel} /> : null }
<div className={classes.comments}>
{ post.comments.map(comment => <Comment key={comment.idcomment} value={comment.description} title={comment.name} />) }
</div>
</div>
</Dialog>
);
}
ArticleInfo.defaultProps = {
post: []
}
ArticleInfo.propTypes = {
open: PropTypes.bool.isRequired,
handleClose: PropTypes.func.isRequired,
isLike: PropTypes.bool.isRequired,
isDislike: PropTypes.bool.isRequired,
handleLike: PropTypes.func.isRequired,
handleDislike: PropTypes.func.isRequired,
};<file_sep>/src/webapp/react/src/components/UI/textarea/Textarea.js
import React from "react";
import classes from './Textarea.module.css';
import {TextareaAutosize} from "@material-ui/core";
export const Textarea = ({value}) => {
return (
<TextareaAutosize
rowsMax={7}
rowsMin={5}
value={value}
className={classes.textarea}
disabled
/>
)
}<file_sep>/src/main/java/com/blog/services/impl/PostServiceImpl.java
package com.blog.services.impl;
import com.blog.services.PostService;
public class PostServiceImpl implements PostService {
}
<file_sep>/src/webapp/react/src/main/auth/login/Login.js
import React, {useState} from "react";
import PropTypes from 'prop-types';
import classes from './Login.module.css';
import {Grid} from "@material-ui/core";
import {Title} from "../../../components/UI/title/TItle";
import {FormControl} from "../../../components/controls/FormControl";
import {Link} from "react-router-dom";
import {Input} from "../../../components/UI/input/Input";
import {inputsLogin} from "../../../components/helpers/common-data/inputsLogin";
import {isValidEmail} from "../../../components/helpers/validators/isValidEmail";
import {Btn} from "../../../components/UI/button/Button";
export const Login = ({handleLogin, setStatus}) => {
const [login, setLogin] = useState({
email: null,
password: null
});
const [error, setError] = useState({});
const [disabled, setDisabled] = useState(false);
const validateLogin = () => {
const {email, password} = login;
let inputErrors = {};
inputErrors.email = isValidEmail(email) ? null : "Email is not valid!";
inputErrors.password = password ? null : "This field is required!";
setError({...inputErrors});
return Object.values(inputErrors).every(x => x === null);
}
const handleChangeInput = ({target: {name, value}}) => {
validateLogin(undefined, login.password);
setLogin({
...login,
[name]: value,
})
}
const handleSubmit = async () => {
try {
if (validateLogin(login.email, login.password)) {
setDisabled(true);
await handleLogin(login.email, login.password);
setStatus(true);
}
} catch (error) {
console.log(error);
setDisabled(false);
}
}
return (
<div className={classes.login}>
<Title text="Login form" />
<FormControl>
<Grid container spacing={2}>
{
inputsLogin.map(input => (
<Grid item xs={12} key={input.label}>
<Input label={input.label}
name={input.name}
type={input.type}
onChange={handleChangeInput}
error={error}
disabled={disabled}
/>
</Grid>
))
}
<Grid item xs={3}>
<Btn title='Sign in'
color='primary'
onClick={handleSubmit}
disabled={disabled}
/>
</Grid>
<Grid item xs={3}>
<Link to='/registration' className={classes.Link}>
<Btn title='Registration'
color='secondary'
disabled={disabled}
/>
</Link>
</Grid>
</Grid>
</FormControl>
</div>
)
}
Login.propTypes = {
handleLogin: PropTypes.func.isRequired,
setStatus: PropTypes.func.isRequired,
}<file_sep>/src/main/java/com/blog/services/SubscribeService.java
package com.blog.services;
import com.blog.models.Subscribe;
public interface SubscribeService {
Subscribe subscribe(int subscriber, int author);
}
<file_sep>/src/main/java/com/blog/controllers/UserController.java
package com.blog.controllers;
import com.blog.models.User;
import com.blog.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value = "/authors") // ?
public List<User> authors() {
return userService.getByRole("author");
}
@GetMapping(value = "/users/{id}")
public User user(@PathVariable int id) {
return userService.getUser(id);
}
}
<file_sep>/src/webapp/react/src/App.js
import React, {useState} from "react";
import classes from './App.module.css';
import {Routing} from "./routing/Routing";
import {CustomizedSnackbar} from "./components/snackbar/Snackbar";
import axios from "axios";
export const App = () => {
const [isLogin, setLogin] = useState(false);
const [status, setStatus] = useState(false);
const [authUser, setAuthUser] = useState({});
const handleLogin = async (email, password) => {
try {
const response = await axios.get("http://localhost:8080/login", {headers: {authorization: 'Basic ' + window.btoa(email + ":" + password)}});
setAuthUser(response.data);
setLogin(true)
} catch (error) {
console.log(error)
}
}
const routes = Routing(isLogin, handleLogin, setStatus, authUser, setAuthUser);
return (
<div className={classes.container}>
{routes}
{status ? <CustomizedSnackbar message='Welcome to the system!' /> : null}
</div>
)
}
<file_sep>/src/main/java/com/blog/services/PostService.java
package com.blog.services;
public interface PostService {
}
|
b76424cc3041d5aca3088d39b542a35f70e0dbb5
|
[
"JavaScript",
"Java"
] | 17 |
JavaScript
|
VadimAlkhimenok/blog_project
|
7def4d39b7fb9351739f97ba3acf02de5651ed18
|
376a3f98ae487e7eab3b00215a88c05d7150614c
|
refs/heads/master
|
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.common.concur.lock;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* This lock is intended to be used inside of storage to request lock on any data modifications. Writes can be prohibited from one
* thread, but then allowed from other thread.
*
* IMPORTANT ! Prohibit/allow changes methods are not reentrant.
*
* @author <NAME> <a href="mailto:<EMAIL>"><NAME></a>
* @since 15.06.12
*/
public class OModificationLock {
private volatile boolean veto = false;
private volatile boolean throwException = false;
private final ConcurrentLinkedQueue<Thread> waiters = new ConcurrentLinkedQueue<Thread>();
private final ReadWriteLock lock = new ReentrantReadWriteLock();
/**
* Tells the lock that thread is going to perform data modifications in storage. This method allows to perform several data
* modifications in parallel.
*/
public void requestModificationLock() {
lock.readLock().lock();
if (!veto)
return;
if (throwException) {
lock.readLock().unlock();
throw new OModificationOperationProhibitedException("Modification requests are prohibited");
}
boolean wasInterrupted = false;
Thread thread = Thread.currentThread();
waiters.add(thread);
while (veto) {
LockSupport.park(this);
if (Thread.interrupted())
wasInterrupted = true;
}
waiters.remove(thread);
if (wasInterrupted)
thread.interrupt();
}
/**
* Tells the lock that thread is finished to perform to perform modifications in storage.
*/
public void releaseModificationLock() {
lock.readLock().unlock();
}
/**
* After this method finished it's execution, all threads that are going to perform data modifications in storage should wait till
* {@link #allowModifications()} method will be called. This method will wait till all ongoing modifications will be finished.
*/
public void prohibitModifications() {
lock.writeLock().lock();
try {
throwException = false;
veto = true;
} finally {
lock.writeLock().unlock();
}
}
/**
* After this method finished it's execution, all threads that are going to perform data modifications in storage should wait till
* {@link #allowModifications()} method will be called. This method will wait till all ongoing modifications will be finished.
*
* @param throwException
* If <code>true</code> {@link OModificationOperationProhibitedException} exception will be thrown on
* {@link #requestModificationLock()} call.
*/
public void prohibitModifications(boolean throwException) {
lock.writeLock().lock();
try {
this.throwException = throwException;
veto = true;
} finally {
lock.writeLock().unlock();
}
}
/**
* After this method finished execution all threads that are waiting to perform data modifications in storage will be awaken and
* will be allowed to continue their execution.
*/
public void allowModifications() {
veto = false;
for (Thread thread : waiters)
LockSupport.unpark(thread);
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.hazelcast;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import com.hazelcast.nio.DataSerializable;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
/**
* Serialization-optimized implementation to transfer only the needed information on the network for the distributed create
* operation.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*/
public class OHazelcastPhysicalPosition extends OPhysicalPosition implements DataSerializable {
private static final long serialVersionUID = 1L;
public OHazelcastPhysicalPosition() {
}
public OHazelcastPhysicalPosition(final OPhysicalPosition iFrom) {
clusterPosition = iFrom.clusterPosition;
recordVersion = iFrom.recordVersion;
}
@Override
public void readData(final DataInput in) throws IOException {
clusterPosition = OClusterPositionFactory.INSTANCE.fromStream(in);
recordVersion.getSerializer().readFrom(in, recordVersion);
}
@Override
public void writeData(final DataOutput out) throws IOException {
out.write(clusterPosition.toStream());
recordVersion.getSerializer().writeTo(out, recordVersion);
}
}
<file_sep>/*
*
* Copyright 2012 <NAME> (molino.luca--AT--gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.object.fetch;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.orientechnologies.orient.core.db.OUserObject2RecordHandler;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.entity.OEntityManager;
import com.orientechnologies.orient.core.exception.OFetchException;
import com.orientechnologies.orient.core.fetch.OFetchContext;
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.object.db.OLazyObjectList;
import com.orientechnologies.orient.object.db.OLazyObjectMap;
import com.orientechnologies.orient.object.db.OLazyObjectSet;
import com.orientechnologies.orient.object.serialization.OObjectSerializerHelper;
/**
* @author luca.molino
*
*/
public class OObjectFetchContext implements OFetchContext {
protected final String fetchPlan;
protected final boolean lazyLoading;
protected final OEntityManager entityManager;
protected final OUserObject2RecordHandler obj2RecHandler;
public OObjectFetchContext(final String iFetchPlan, final boolean iLazyLoading, final OEntityManager iEntityManager,
final OUserObject2RecordHandler iObj2RecHandler) {
fetchPlan = iFetchPlan;
lazyLoading = iLazyLoading;
obj2RecHandler = iObj2RecHandler;
entityManager = iEntityManager;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void onBeforeMap(ORecordSchemaAware<?> iRootRecord, String iFieldName, final Object iUserObject) throws OFetchException {
final Map<Object, Object> map = (Map<Object, Object>) iRootRecord.field(iFieldName);
final Map<Object, Object> target;
if (lazyLoading)
target = new OLazyObjectMap<Object>(iRootRecord, map).setFetchPlan(fetchPlan);
else {
target = new HashMap();
}
OObjectSerializerHelper.setFieldValue(iUserObject, iFieldName, target);
}
public void onBeforeArray(ORecordSchemaAware<?> iRootRecord, String iFieldName, Object iUserObject, OIdentifiable[] iArray)
throws OFetchException {
OObjectSerializerHelper.setFieldValue(iUserObject, iFieldName,
Array.newInstance(iRootRecord.getSchemaClass().getProperty(iFieldName).getLinkedClass().getJavaClass(), iArray.length));
}
public void onAfterDocument(ORecordSchemaAware<?> iRootRecord, ORecordSchemaAware<?> iDocument, String iFieldName,
Object iUserObject) throws OFetchException {
}
public void onBeforeDocument(ORecordSchemaAware<?> iRecord, ORecordSchemaAware<?> iDocument, String iFieldName, Object iUserObject)
throws OFetchException {
}
public void onAfterArray(ORecordSchemaAware<?> iRootRecord, String iFieldName, Object iUserObject) throws OFetchException {
}
public void onAfterMap(ORecordSchemaAware<?> iRootRecord, String iFieldName, final Object iUserObject) throws OFetchException {
}
public void onBeforeDocument(ORecordSchemaAware<?> iRecord, String iFieldName, final Object iUserObject) throws OFetchException {
}
public void onAfterDocument(ORecordSchemaAware<?> iRootRecord, String iFieldName, final Object iUserObject)
throws OFetchException {
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void onBeforeCollection(ORecordSchemaAware<?> iRootRecord, String iFieldName, final Object iUserObject,
final Collection<?> iCollection) throws OFetchException {
final Class<?> type = OObjectSerializerHelper.getFieldType(iUserObject, iFieldName);
final Collection target;
if (type != null && Set.class.isAssignableFrom(type)) {
if (lazyLoading)
target = new OLazyObjectSet<Object>(iRootRecord, (Collection<Object>) iCollection).setFetchPlan(fetchPlan);
else {
target = new HashSet();
}
} else {
final Collection<Object> list = (Collection<Object>) iCollection;
if (lazyLoading)
target = new OLazyObjectList<Object>(iRootRecord, list).setFetchPlan(fetchPlan);
else {
target = new ArrayList();
}
}
OObjectSerializerHelper.setFieldValue(iUserObject, iFieldName, target);
}
public void onAfterCollection(ORecordSchemaAware<?> iRootRecord, String iFieldName, final Object iUserObject)
throws OFetchException {
}
public void onAfterFetch(ORecordSchemaAware<?> iRootRecord) throws OFetchException {
}
public void onBeforeFetch(ORecordSchemaAware<?> iRootRecord) throws OFetchException {
}
public void onBeforeStandardField(Object iFieldValue, String iFieldName, Object iUserObject) {
}
public void onAfterStandardField(Object iFieldValue, String iFieldName, Object iUserObject) {
}
public OUserObject2RecordHandler getObj2RecHandler() {
return obj2RecHandler;
}
public OEntityManager getEntityManager() {
return entityManager;
}
public boolean isLazyLoading() {
return lazyLoading;
}
public String getFetchPlan() {
return fetchPlan;
}
public boolean fetchEmbeddedDocuments() {
return true;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.command.traverse;
import java.util.Iterator;
import com.orientechnologies.common.collection.OMultiValue;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.record.impl.ODocument;
public class OTraverseFieldProcess extends OTraverseAbstractProcess<Iterator<String>> {
protected String fieldName;
public OTraverseFieldProcess(final OTraverse iCommand, final Iterator<String> iTarget) {
super(iCommand, iTarget);
}
public OIdentifiable process() {
while (target.hasNext()) {
fieldName = target.next();
final Object fieldValue = ((OTraverseRecordProcess) command.getContext().peek(-2)).getTarget().rawField(fieldName);
if (fieldValue != null) {
final OTraverseAbstractProcess<?> subProcess;
if (OMultiValue.isMultiValue(fieldValue))
subProcess = new OTraverseMultiValueProcess(command, OMultiValue.getMultiValueIterator(fieldValue));
else if (fieldValue instanceof OIdentifiable && ((OIdentifiable) fieldValue).getRecord() instanceof ODocument)
subProcess = new OTraverseRecordProcess(command, (ODocument) ((OIdentifiable) fieldValue).getRecord());
else
continue;
final OIdentifiable subValue = subProcess.process();
if (subValue != null)
return subValue;
}
}
return drop();
}
@Override
public String getStatus() {
return fieldName != null ? fieldName : null;
}
@Override
public String toString() {
return fieldName != null ? "[field:" + fieldName + "]" : null;
}
}<file_sep>package com.orientechnologies.orient.server.hazelcast.sharding.distributed;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
import com.orientechnologies.common.concur.lock.OLockManager;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.command.OCommandManager;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
import com.orientechnologies.orient.core.exception.ORecordNotFoundException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.iterator.ORecordIteratorCluster;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate;
import com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.version.ORecordVersion;
import com.orientechnologies.orient.server.OServerMain;
import com.orientechnologies.orient.server.config.OServerUserConfiguration;
import com.orientechnologies.orient.server.distributed.ODistributedThreadLocal;
import com.orientechnologies.orient.server.hazelcast.sharding.OCommandResultSerializationHelper;
import com.orientechnologies.orient.server.hazelcast.sharding.hazelcast.OHazelcastResultListener;
/**
* @author <NAME>
* @since 17.08.12
*/
public class OLocalDHTNode implements ODHTNode {
public static final String REPLICATOR_USER = "replicator";
private AtomicLong predecessor = new AtomicLong(-1);
private final long id;
private final AtomicLongArray fingerPoints = new AtomicLongArray(63);
private volatile long migrationId = -1;
private volatile ODHTNodeLookup nodeLookup;
private volatile ODHTConfiguration dhtConfiguration;
private final AtomicInteger next = new AtomicInteger(1);
private final OLockManager<ORID, Runnable> lockManager = new OLockManager<ORID, Runnable>(true, 500);
private final ExecutorService executorService = Executors.newCachedThreadPool();
private final Queue<Long> notificationQueue = new ConcurrentLinkedQueue<Long>();
private volatile NodeState state;
private boolean inheritedDatabase;
private static final OServerUserConfiguration replicatorUser = OServerMain.server().getUser(REPLICATOR_USER);
public OLocalDHTNode(long id) {
this.id = id;
for (int i = 0; i < fingerPoints.length(); i++)
fingerPoints.set(i, -1);
}
public ODHTNodeLookup getNodeLookup() {
return nodeLookup;
}
public void setNodeLookup(ODHTNodeLookup nodeLookup) {
this.nodeLookup = nodeLookup;
}
public void setDhtConfiguration(ODHTConfiguration dhtConfiguration) {
this.dhtConfiguration = dhtConfiguration;
}
public void create() {
log("New ring creation was started");
predecessor.set(-1);
fingerPoints.set(0, id);
state = NodeState.STABLE;
log("New ring was created");
}
public long getNodeId() {
return id;
}
public boolean join(long joinNodeId) {
try {
log("Join is started using node with id " + joinNodeId);
final ODHTNode node = nodeLookup.findById(joinNodeId);
if (node == null) {
log("Node with id " + joinNodeId + " is absent.");
return false;
}
state = NodeState.JOIN;
predecessor.set(-1);
fingerPoints.set(0, node.findSuccessor(id));
log("Join completed, successor is " + fingerPoints.get(0));
ODHTNode successor = nodeLookup.findById(fingerPoints.get(0));
if (successor == null) {
log("Node with id " + fingerPoints.get(0) + " is absent .");
return false;
}
successor.notify(id);
log("Join was finished");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long findSuccessor(long keyId) {
final long successorId = fingerPoints.get(0);
if (insideInterval(id, successorId, keyId, true))
return successorId;
long nodeId = findClosestPrecedingFinger(keyId);
ODHTNode node = nodeLookup.findById(nodeId);
return node.findSuccessor(keyId);
}
private long findClosestPrecedingFinger(long keyId) {
for (int i = fingerPoints.length() - 1; i >= 0; i--) {
final long fingerPoint = fingerPoints.get(i);
if (fingerPoint > -1 && insideInterval(this.id, keyId, fingerPoint, false)) {
return fingerPoint;
}
}
return this.id;
}
public long getSuccessor() {
return fingerPoints.get(0);
}
public Long getPredecessor() {
return predecessor.get();
}
public void requestMigration(long requesterId) {
executorService.submit(new MergeCallable(requesterId));
log("Data migration was started for node " + requesterId);
}
@Override
public OPhysicalPosition createRecord(String storageName, ORecordId iRecordId, byte[] iContent, ORecordVersion iRecordVersion,
byte iRecordType) {
while (state == NodeState.JOIN) {
log("Wait till node will be joined.");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
OLogManager.instance().error(this, "Interrupted", e);
}
}
return executeCreateRecord(storageName, iRecordId, iContent, iRecordVersion, iRecordType);
}
private OPhysicalPosition executeCreateRecord(String storageName, ORecordId iRecordId, byte[] iContent,
ORecordVersion iRecordVersion, byte iRecordType) {
ODistributedThreadLocal.INSTANCE.distributedExecution = true;
try {
final ORecordInternal<?> record = Orient.instance().getRecordFactoryManager().newInstance(iRecordType);
final ODatabaseDocumentTx database = openDatabase(storageName);
try {
record.fill(iRecordId, iRecordVersion, iContent, true);
if (iRecordId.getClusterId() == -1)
record.save(true);
else
record.save(database.getClusterNameById(iRecordId.getClusterId()), true);
return new OPhysicalPosition(record.getIdentity().getClusterPosition(), record.getRecordVersion());
} finally {
closeDatabase(database);
}
} finally {
ODistributedThreadLocal.INSTANCE.distributedExecution = false;
}
}
@Override
public ORawBuffer readRecord(String storageName, ORID iRid) {
while (state == NodeState.JOIN) {
log("Wait till node will be joined.");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (state == NodeState.MERGING) {
ORawBuffer data = executeReadRecord(storageName, iRid);
if (data == null) {
final ODHTNode successorNode = nodeLookup.findById(fingerPoints.get(0));
data = successorNode.readRecord(storageName, iRid);
if (data == null && successorNode.getNodeId() != id)
return executeReadRecord(storageName, iRid);
else
return data;
} else
return data;
}
return executeReadRecord(storageName, iRid);
}
private ORawBuffer executeReadRecord(String storageName, ORID iRid) {
lockManager.acquireLock(Thread.currentThread(), iRid, OLockManager.LOCK.EXCLUSIVE);
try {
final ODatabaseDocumentTx database = openDatabase(storageName);
try {
final ORecordInternal<?> record = database.load(iRid);
if (record != null) {
return new ORawBuffer(record);
} else {
return null;
}
} finally {
closeDatabase(database);
}
} finally {
lockManager.releaseLock(Thread.currentThread(), iRid, OLockManager.LOCK.EXCLUSIVE);
}
}
@Override
public ORecordVersion updateRecord(String storageName, ORecordId iRecordId, byte[] iContent, ORecordVersion iVersion,
byte iRecordType) {
final ORecordInternal<?> newRecord = Orient.instance().getRecordFactoryManager().newInstance(iRecordType);
lockManager.acquireLock(Thread.currentThread(), iRecordId, OLockManager.LOCK.EXCLUSIVE);
try {
final ODatabaseDocumentTx database = openDatabase(storageName);
try {
newRecord.fill(iRecordId, iVersion, iContent, true);
final ORecordInternal<?> currentRecord;
if (newRecord instanceof ODocument) {
currentRecord = database.load(iRecordId);
if (currentRecord == null) {
throw new ORecordNotFoundException(iRecordId.toString());
}
((ODocument) currentRecord).merge((ODocument) newRecord, false, false);
} else {
currentRecord = newRecord;
}
currentRecord.getRecordVersion().copyFrom(iVersion);
if (iRecordId.getClusterId() == -1)
currentRecord.save();
else
currentRecord.save(database.getClusterNameById(iRecordId.getClusterId()));
if (currentRecord.getIdentity().toString().equals(database.getStorage().getConfiguration().indexMgrRecordId)
&& !database.getStatus().equals(ODatabase.STATUS.IMPORTING)) {
// FORCE INDEX MANAGER UPDATE. THIS HAPPENS FOR DIRECT CHANGES FROM REMOTE LIKE IN GRAPH
database.getMetadata().getIndexManager().reload();
}
return currentRecord.getRecordVersion();
} finally {
closeDatabase(database);
}
} finally {
lockManager.releaseLock(Thread.currentThread(), iRecordId, OLockManager.LOCK.EXCLUSIVE);
}
}
@Override
public boolean deleteRecord(String storageName, ORecordId iRecordId, ORecordVersion iVersion) {
boolean result = false;
while (state == NodeState.JOIN) {
log("Wait till node will be joined.");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (state == NodeState.MERGING) {
final ODHTNode successorNode = nodeLookup.findById(fingerPoints.get(0));
result = successorNode.deleteRecord(storageName, iRecordId, iVersion);
}
result = result | executeDeleteRecord(storageName, iRecordId, iVersion);
return result;
}
@Override
public Object command(String storageName, OCommandRequestText request, boolean serializeResult) {
while (state != NodeState.STABLE) {
log("Wait till node will be joined.");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
final ODatabaseDocumentTx database = openDatabase(storageName);
final OCommandExecutor executor = OCommandManager.instance().getExecutor(request);
executor.setProgressListener(request.getProgressListener());
executor.parse(request);
final long from;
if (predecessor.get() == -1) {
if (fingerPoints.get(0) == id) {
// single node in dht
from = id;
} else {
throw new OCommandExecutionException("Predecessor node has failed");
}
} else {
from = predecessor.get();
}
final OCommandExecutorSQLSelect selectExecutor;
if (executor instanceof OCommandExecutorSQLDelegate
&& ((OCommandExecutorSQLDelegate) executor).getDelegate() instanceof OCommandExecutorSQLSelect) {
selectExecutor = ((OCommandExecutorSQLSelect) ((OCommandExecutorSQLDelegate) executor).getDelegate());
} else if (executor instanceof OCommandExecutorSQLSelect) {
selectExecutor = ((OCommandExecutorSQLSelect) executor);
} else {
selectExecutor = null;
}
if (request.isIdempotent() && !executor.isIdempotent())
throw new OCommandExecutionException("Cannot execute non idempotent command");
if (selectExecutor != null) {
selectExecutor.boundToLocalNode(from, id);
}
try {
Object result = executor.execute(request.getParameters());
request.setContext(executor.getContext());
if (serializeResult) {
result = OCommandResultSerializationHelper.writeToStream(result);
}
if (selectExecutor != null && request.getResultListener() instanceof OHazelcastResultListener) {
request.getResultListener().result(new OHazelcastResultListener.EndOfResult(id));
}
return result;
} catch (OException e) {
// PASS THROUGHT
throw e;
} catch (Exception e) {
throw new OCommandExecutionException("Error on execution of command: " + request, e);
} finally {
closeDatabase(database);
}
}
@Override
public boolean isLocal() {
return true;
}
private boolean executeDeleteRecord(String storageName, final ORecordId iRecordId, ORecordVersion iVersion) {
lockManager.acquireLock(Thread.currentThread(), iRecordId, OLockManager.LOCK.EXCLUSIVE);
try {
final ODatabaseDocumentTx database = openDatabase(storageName);
try {
final ORecordInternal record = database.load(iRecordId);
if (record != null) {
record.getRecordVersion().copyFrom(iVersion);
record.delete();
return true;
}
return false;
} finally {
closeDatabase(database);
}
} finally {
lockManager.releaseLock(Thread.currentThread(), iRecordId, OLockManager.LOCK.EXCLUSIVE);
}
}
protected ODatabaseDocumentTx openDatabase(String databaseName) {
inheritedDatabase = true;
final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
if (db != null && db.getName().equals(databaseName) && !db.isClosed()) {
if (db instanceof ODatabaseDocumentTx)
return (ODatabaseDocumentTx) db;
else if (db.getDatabaseOwner() instanceof ODatabaseDocumentTx)
return (ODatabaseDocumentTx) db.getDatabaseOwner();
}
inheritedDatabase = false;
return (ODatabaseDocumentTx) OServerMain.server().openDatabase("document", databaseName, replicatorUser.name,
replicatorUser.password);
}
protected void closeDatabase(final ODatabaseDocumentTx iDatabase) {
if (!inheritedDatabase)
iDatabase.close();
}
public void stabilize() {
// log("Stabilization is started");
boolean result = false;
ODHTNode successor = null;
while (!result) {
long successorId = fingerPoints.get(0);
successor = nodeLookup.findById(successorId);
Long predecessor = successor.getPredecessor();
if (predecessor > -1 && insideInterval(this.id, successorId, predecessor, false)) {
log("Successor was " + successorId + " is going to be changed to " + predecessor);
result = fingerPoints.compareAndSet(0, successorId, predecessor);
if (result)
log("Successor was successfully changed");
else
log("Successor change was failed");
if (result)
successor = nodeLookup.findById(predecessor);
drawRing();
} else
result = true;
}
if (successor.getNodeId() != id)
successor.notify(id);
// drawRing();
// log("Stabilization is finished");
}
public void fixFingers() {
int nextValue = next.intValue();
// log("Fix of fingers is started for interval " + ((id + 1 << nextValue) & Long.MAX_VALUE));
fingerPoints.set(nextValue, findSuccessor((id + 1 << nextValue) & Long.MAX_VALUE));
next.compareAndSet(nextValue, nextValue + 1);
while (next.intValue() > 62) {
nextValue = next.intValue();
if (nextValue > 62)
next.compareAndSet(nextValue, 1);
// log("Next value is changed to 1");
}
// log("Fix of fingers was finished.");
}
public void fixPredecessor() {
// log("Fix of predecessor is started");
boolean result = false;
while (!result) {
long predecessorId = predecessor.longValue();
if (predecessorId > -1 && nodeLookup.findById(predecessorId) == null) {
result = predecessor.compareAndSet(predecessorId, -1);
// log("Predecessor " + predecessorId + " left the cluster");
} else
result = true;
}
// log("Fix of predecessor is finished");
}
public void notify(long nodeId) {
// log("Node " + nodeId + " thinks it can be our parent");
boolean result = false;
while (!result) {
long predecessorId = predecessor.longValue();
if (predecessorId < 0 || (insideInterval(predecessorId, this.id, nodeId, false))) {
result = predecessor.compareAndSet(predecessorId, nodeId);
if (result)
log("New predecessor is " + nodeId);
else
log("Predecessor setup was failed.");
if (result && predecessorId < 0 && state == NodeState.JOIN) {
migrationId = fingerPoints.get(0);
final ODHTNode mergeNode = nodeLookup.findById(migrationId);
mergeNode.requestMigration(id);
state = NodeState.MERGING;
log("Status was changed to " + state);
}
drawRing();
} else
result = true;
}
// log("Parent check is finished.");
}
public void notifyMigrationEnd(long nodeId) {
log("Migration completion notification from " + nodeId);
while (state == NodeState.JOIN) {
log("Wait till node will be joined.");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (nodeId == migrationId) {
state = NodeState.STABLE;
log("State was changed to " + state);
Long nodeToNotifyId = notificationQueue.poll();
while (nodeToNotifyId != null) {
final ODHTNode node = nodeLookup.findById(nodeToNotifyId);
node.notifyMigrationEnd(id);
nodeToNotifyId = notificationQueue.poll();
}
}
}
private boolean insideInterval(long from, long to, long value, boolean rightIsIncluded) {
if (to > from) {
if (rightIsIncluded)
return from < value && to >= value;
else
return from < value && to > value;
} else {
if (rightIsIncluded)
return !(value > to && value <= from);
else
return !(value >= to && value <= from);
}
}
private void log(String message) {
DateFormat dateFormat = DateFormat.getDateTimeInstance();
System.out.println(state + " : " + Thread.currentThread().getName() + " : " + id + " : " + dateFormat.format(new Date())
+ " : " + message);
}
private void drawRing() {
StringBuilder builder = new StringBuilder();
builder.append("Ring : ");
builder.append(id);
ODHTNode node = this;
Set<Long> processedIds = new HashSet<Long>();
processedIds.add(id);
long successor = node.getSuccessor();
while (!processedIds.contains(successor)) {
builder.append("-").append(successor);
processedIds.add(successor);
node = nodeLookup.findById(successor);
successor = node.getSuccessor();
}
builder.append(".");
log(builder.toString());
}
private enum NodeState {
JOIN, MERGING, STABLE
}
private final class MergeCallable implements Callable<Void> {
private final long requesterNode;
private MergeCallable(long requesterNode) {
this.requesterNode = requesterNode;
}
public Void call() throws Exception {
for (String storageName : dhtConfiguration.getDistributedStorageNames()) {
final ODatabaseDocumentTx db = openDatabase(storageName);
final Set<String> clusterNames = db.getStorage().getClusterNames();
for (String clusterName : clusterNames) {
if (dhtConfiguration.getUndistributableClusters().contains(clusterName.toLowerCase())) {
continue;
}
final ORecordIteratorCluster<? extends ORecordInternal<?>> it = db.browseCluster(clusterName);
while (it.hasNext()) {
final ORecordInternal<?> rec = it.next();
lockManager.acquireLock(Thread.currentThread(), rec.getIdentity(), OLockManager.LOCK.EXCLUSIVE);
try {
final long successorId = findSuccessor(rec.getIdentity().getClusterPosition().longValue());
if (successorId != id) {
final ODHTNode node = nodeLookup.findById(successorId);
node.createRecord(storageName, (ORecordId) rec.getIdentity(), rec.toStream(), rec.getRecordVersion(),
rec.getRecordType());
ODistributedThreadLocal.INSTANCE.distributedExecution = true;
try {
rec.delete();
} finally {
ODistributedThreadLocal.INSTANCE.distributedExecution = false;
}
}
} finally {
lockManager.releaseLock(Thread.currentThread(), rec.getIdentity(), OLockManager.LOCK.EXCLUSIVE);
}
}
}
}
if (state == NodeState.STABLE) {
final ODHTNode node = nodeLookup.findById(requesterNode);
node.notifyMigrationEnd(id);
} else {
notificationQueue.add(requesterNode);
if (state == NodeState.STABLE) {
Long nodeToNotifyId = notificationQueue.poll();
while (nodeToNotifyId != null) {
final ODHTNode node = nodeLookup.findById(nodeToNotifyId);
node.notifyMigrationEnd(id);
nodeToNotifyId = notificationQueue.poll();
}
}
}
log("Migration was successfully finished for node " + requesterNode);
return null;
}
}
}
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.storage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import junit.framework.Assert;
import org.testng.annotations.Test;
import com.orientechnologies.common.concur.lock.OModificationLock;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><NAME></a>
* @since 15.06.12
*/
@Test
public class StorageModificationLockTest {
private final static int THREAD_COUNT = 100;
private final static int CYCLES_COUNT = 20;
private final AtomicLong counter = new AtomicLong();
private final OModificationLock modificationLock = new OModificationLock();
private final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT + 1);
private final List<Future<Void>> futures = new ArrayList<Future<Void>>(THREAD_COUNT);
private final CountDownLatch countDownLatch = new CountDownLatch(1);
@Test
public void testLock() throws Exception {
for (int i = 0; i < THREAD_COUNT; i++) {
futures.add(executorService.submit(new Counter()));
}
Future<Void> prohibiter = executorService.submit(new Prohibiter());
countDownLatch.countDown();
prohibiter.get();
for (Future<Void> future : futures)
future.get();
}
private final class Counter implements Callable<Void> {
private final Random random = new Random();
public Void call() throws Exception {
countDownLatch.await();
for (int n = 0; n < CYCLES_COUNT; n++) {
final int modificationsCount = random.nextInt(255);
modificationLock.requestModificationLock();
try {
for (int i = 0; i < modificationsCount; i++) {
counter.incrementAndGet();
Thread.sleep(random.nextInt(5));
}
} finally {
modificationLock.releaseModificationLock();
}
}
return null;
}
}
private final class Prohibiter implements Callable<Void> {
public Void call() throws Exception {
countDownLatch.await();
for (int n = 0; n < CYCLES_COUNT; n++) {
modificationLock.prohibitModifications();
long beforeModification = counter.get();
Thread.sleep(50);
if (n % 10 == 0)
System.out
.println("After prohibit modifications " + beforeModification + " before allow modifications " + counter.get());
Assert.assertEquals(beforeModification, counter.get());
modificationLock.allowModifications();
Thread.sleep(50);
}
return null;
}
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.index;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
/**
* Iterator that allow to iterate against multiple collection of elements.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*
* @param <T>
*/
public class OFlattenIterator<T> implements Iterator<OIdentifiable> {
private Iterator<? extends Collection<OIdentifiable>> subIterator;
private Iterator<OIdentifiable> partialIterator;
public OFlattenIterator(final Iterator<? extends Collection<OIdentifiable>> iterator) {
subIterator = iterator;
getNextPartial();
}
@Override
public boolean hasNext() {
if (partialIterator == null)
return false;
if (partialIterator.hasNext())
return true;
else if (subIterator.hasNext())
return getNextPartial();
return false;
}
@Override
public OIdentifiable next() {
if (!hasNext())
throw new NoSuchElementException();
return partialIterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("OFlattenIterator.remove()");
}
protected boolean getNextPartial() {
if (subIterator != null)
while (subIterator.hasNext()) {
final Collection<OIdentifiable> next = subIterator.next();
if (next != null && !next.isEmpty()) {
partialIterator = next.iterator();
return true;
}
}
return false;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.config;
public class OStoragePhysicalClusterConfigurationLocal extends OStorageSegmentConfiguration implements
OStoragePhysicalClusterConfiguration {
private static final long serialVersionUID = 1L;
private static final String START_SIZE = "1Mb";
private OStorageFileConfiguration holeFile;
private int dataSegmentId;
public OStoragePhysicalClusterConfigurationLocal(final OStorageConfiguration iStorageConfiguration, final int iId,
final int iDataSegmentId) {
super(iStorageConfiguration, null, iId);
fileStartSize = START_SIZE;
dataSegmentId = iDataSegmentId;
}
public OStoragePhysicalClusterConfigurationLocal(final OStorageConfiguration iStorageConfiguration, final int iId,
final int iDataSegmentId, final String iSegmentName) {
super(iStorageConfiguration, iSegmentName, iId);
fileStartSize = START_SIZE;
dataSegmentId = iDataSegmentId;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
@Override
public void setRoot(final OStorageConfiguration root) {
super.setRoot(root);
holeFile.parent = this;
}
public int getDataSegmentId() {
return dataSegmentId;
}
public OStorageFileConfiguration[] getInfoFiles() {
return infoFiles;
}
public String getMaxSize() {
return maxSize;
}
public OStorageFileConfiguration getHoleFile() {
return holeFile;
}
public void setHoleFile(OStorageFileConfiguration holeFile) {
this.holeFile = holeFile;
}
public void setDataSegmentId(int dataSegmentId) {
this.dataSegmentId = dataSegmentId;
}
}
<file_sep>package com.orientechnologies.common.collection;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
public class OIdentityHashSet<E> extends AbstractSet<E> implements Serializable {
private static final long serialVersionUID = 1L;
private static final Object VALUE = new Object();
private transient IdentityHashMap<E, Object> identityHashMap;
public OIdentityHashSet() {
identityHashMap = new IdentityHashMap<E, Object>();
}
@Override
public Iterator<E> iterator() {
return identityHashMap.keySet().iterator();
}
@Override
public int size() {
return identityHashMap.size();
}
@Override
public boolean add(E e) {
return identityHashMap.put(e, VALUE) == null;
}
@Override
public boolean remove(Object o) {
return identityHashMap.remove(o) == VALUE;
}
@Override
public boolean contains(Object o) {
return identityHashMap.containsKey(o);
}
@Override
public boolean isEmpty() {
return identityHashMap.isEmpty();
}
@Override
public void clear() {
identityHashMap.clear();
}
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
s.defaultWriteObject();
s.write(identityHashMap.size());
for (E e : identityHashMap.keySet())
s.writeObject(e);
}
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
int size = s.readInt();
identityHashMap = new IdentityHashMap<E, Object>(size);
for (int i = 0; i < size; i++)
identityHashMap.put((E) s.readObject(), VALUE);
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.sql.functions.graph;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.graph.OGraphDatabase;
import com.orientechnologies.orient.core.db.graph.OGraphDatabase.DIRECTION;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.functions.math.OSQLFunctionMathAbstract;
/**
* Abstract class to find paths between nodes.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*
*/
public abstract class OSQLFunctionPathFinder<T extends Comparable<T>> extends OSQLFunctionMathAbstract {
protected OGraphDatabase db;
protected Set<OIdentifiable> settledNodes;
protected Set<OIdentifiable> unSettledNodes;
protected Map<OIdentifiable, OIdentifiable> predecessors;
protected Map<OIdentifiable, T> distance;
protected OIdentifiable paramSourceVertex;
protected OIdentifiable paramDestinationVertex;
protected OGraphDatabase.DIRECTION paramDirection = DIRECTION.OUT;
public OSQLFunctionPathFinder(final String iName, final int iMinParams, final int iMaxParams) {
super(iName, iMinParams, iMaxParams);
}
protected abstract T getDistance(OIdentifiable node, OIdentifiable target);
protected abstract T getShortestDistance(OIdentifiable destination);
protected abstract T getMinimumDistance();
protected abstract T sumDistances(T iDistance1, T iDistance2);
public Object execute(final Object[] iParameters, final OCommandContext iContext) {
settledNodes = new HashSet<OIdentifiable>();
unSettledNodes = new HashSet<OIdentifiable>();
distance = new HashMap<OIdentifiable, T>();
predecessors = new HashMap<OIdentifiable, OIdentifiable>();
distance.put(paramSourceVertex, getMinimumDistance());
unSettledNodes.add(paramSourceVertex);
while (continueTraversing()) {
final OIdentifiable node = getMinimum(unSettledNodes);
settledNodes.add(node);
unSettledNodes.remove(node);
findMinimalDistances(node);
}
return getPath(paramDestinationVertex);
}
/*
* This method returns the path from the source to the selected target and NULL if no path exists
*/
public LinkedList<OIdentifiable> getPath(final OIdentifiable target) {
final LinkedList<OIdentifiable> path = new LinkedList<OIdentifiable>();
OIdentifiable step = target;
// Check if a path exists
if (predecessors.get(step) == null) {
return null;
}
path.add(step);
while (predecessors.get(step) != null) {
step = predecessors.get(step);
path.add(step);
}
// Put it into the correct order
Collections.reverse(path);
return path;
}
public boolean aggregateResults() {
return false;
}
@Override
public Object getResult() {
return settledNodes;
}
protected void findMinimalDistances(final OIdentifiable node) {
final List<OIdentifiable> adjacentNodes = getNeighbors(node);
for (OIdentifiable target : adjacentNodes) {
final T d = sumDistances(getShortestDistance(node), getDistance(node, target));
if (getShortestDistance(target).compareTo(d) > 0) {
distance.put(target, d);
predecessors.put(target, node);
unSettledNodes.add(target);
}
}
}
protected List<OIdentifiable> getNeighbors(final OIdentifiable node) {
final List<OIdentifiable> neighbors = new ArrayList<OIdentifiable>();
if (node != null) {
if (paramDirection == DIRECTION.BOTH || paramDirection == DIRECTION.OUT)
for (OIdentifiable edge : db.getOutEdges(node)) {
final ODocument inVertex = db.getInVertex(edge);
if (inVertex != null && !isSettled(inVertex))
neighbors.add(inVertex);
}
if (paramDirection == DIRECTION.BOTH || paramDirection == DIRECTION.IN)
for (OIdentifiable edge : db.getInEdges(node)) {
final ODocument outVertex = db.getOutVertex(edge);
if (outVertex != null && !isSettled(outVertex))
neighbors.add(outVertex);
}
}
return neighbors;
}
protected OIdentifiable getMinimum(final Set<OIdentifiable> vertexes) {
OIdentifiable minimum = null;
for (OIdentifiable vertex : vertexes) {
if (minimum == null || getShortestDistance(vertex).compareTo(getShortestDistance(minimum)) < 0)
minimum = vertex;
}
return minimum;
}
protected boolean isSettled(final OIdentifiable vertex) {
return settledNodes.contains(vertex);
}
protected boolean continueTraversing() {
return unSettledNodes.size() > 0;
}
}
<file_sep>package com.orientechnologies.orient.core.cache;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Map;
import org.testng.annotations.Test;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODocument;
@Test
public class ODefaultCacheCleanUpTest {
public void removesGivenAmountOfRecords() {
// Given filled cache backend
ODefaultCache.OLinkedHashMapCache sut = filledCacheBackend();
int originalSize = sut.size();
// When asked to remove eldest items
int amount = 10;
sut.removeEldest(amount);
// Then new cache size should be of original size minus amount of deleted items
assertEquals(sut.size(), originalSize - amount);
}
public void doesNotTakeDirtyRecordsIntoAccountWhenSkips() {
// Given filled cache backend
// With some dirty records in it
ODefaultCache.OLinkedHashMapCache sut = filledCacheBackendWithSomeDirtyRecords();
int originalSize = sut.size();
// When asked to remove eldest items
int amount = 10;
sut.removeEldest(amount);
// Then removes less then asked
assertTrue(amount > originalSize - sut.size());
}
public void clearsWholeCacheIfMemoryCriticallyLow() {
// Given running filled cache
ODefaultCache sut = runningFilledCache();
// When watchdog listener invoked with critically low memory
int freeMemoryPercentageBelowCriticalPoint = 8;
sut.lowMemoryListener.memoryUsageLow(1, freeMemoryPercentageBelowCriticalPoint);
// Then whole cache cleared
assertEquals(sut.size(), 0, "Cache has entries in it yet");
}
public void removesPartOfEntriesInCaseOfLowMemory() {
// Given running filled cache
ODefaultCache sut = runningFilledCache();
int originalSize = sut.size();
// When watchdog listener invoked with critically low memory
int freeMemoryPercentageBelowCriticalPoint = 20;
sut.lowMemoryListener.memoryUsageLow(1, freeMemoryPercentageBelowCriticalPoint);
// Then whole cache cleared
assertTrue(sut.size() < originalSize, "Cache was not cleaned");
assertTrue(sut.size() > 0, "Cache was cleared wholly");
}
private ODefaultCache.OLinkedHashMapCache filledCacheBackend() {
ODefaultCache.OLinkedHashMapCache cache = new ODefaultCache.OLinkedHashMapCache(100, 0.75f, 100);
for (int i = 100; i > 0; i--) {
ODocument entry = new ODocument(new ORecordId(i, OClusterPositionFactory.INSTANCE.valueOf(i)));
cache.put(entry.getIdentity(), entry);
}
return cache;
}
private ODefaultCache.OLinkedHashMapCache filledCacheBackendWithSomeDirtyRecords() {
ODefaultCache.OLinkedHashMapCache cache = filledCacheBackend();
int i = 0;
for (Map.Entry<ORID, ORecordInternal<?>> entry : cache.entrySet()) {
if (i++ % 3 == 0)
entry.getValue().setDirty();
}
return cache;
}
private ODefaultCache runningFilledCache() {
ODefaultCache cache = new ODefaultCache(null, 100);
cache.startup();
for (int i = 100; i > 0; i--)
cache.put(new ODocument(new ORecordId(i, OClusterPositionFactory.INSTANCE.valueOf(i))));
return cache;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.db.document;
import com.orientechnologies.orient.core.db.ODatabaseSchemaAware;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.iterator.ORecordIteratorClass;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* Generic interface for document based Database implementations.
*
* @author <NAME>
*/
public interface ODatabaseDocument extends ODatabaseRecord, ODatabaseSchemaAware<ORecordInternal<?>> {
final static String TYPE = "document";
/**
* Browses all the records of the specified class and also all the subclasses. If you've a class Vehicle and Car that extends
* Vehicle then a db.browseClass("Vehicle", true) will return all the instances of Vehicle and Car. The order of the returned
* instance starts from record id with position 0 until the end. Base classes are worked at first.
*
* @param iClassName
* Class name to iterate
* @return Iterator of ODocument instances
*/
public ORecordIteratorClass<ODocument> browseClass(String iClassName);
/**
* Browses all the records of the specified class and if iPolymorphic is true also all the subclasses. If you've a class Vehicle
* and Car that extends Vehicle then a db.browseClass("Vehicle", true) will return all the instances of Vehicle and Car. The order
* of the returned instance starts from record id with position 0 until the end. Base classes are worked at first.
*
* @param iClassName
* Class name to iterate
* @param iPolymorphic
* Consider also the instances of the subclasses or not
* @return Iterator of ODocument instances
*/
public ORecordIteratorClass<ODocument> browseClass(String iClassName, boolean iPolymorphic);
/**
* Flush all indexes and cached storage content to the disk.
*
* After this call users can perform only select queries. All write-related commands will queued till {@link #release()} command
* will be called.
*
* Given command waits till all on going modifications in indexes or DB will be finished.
*
* IMPORTANT: This command is not reentrant.
*/
public void freeze();
/**
* Allows to execute write-related commands on DB. Called after {@link #freeze()} command.
*/
public void release();
/**
* Flush all indexes and cached storage content to the disk.
*
* After this call users can perform only select queries. All write-related commands will queued till {@link #release()} command
* will be called or exception will be thrown on attempt to modify DB data. Concrete behaviour depends on
* <code>throwException</code> parameter.
*
* IMPORTANT: This command is not reentrant.
*
* @param throwException
* If <code>true</code> {@link com.orientechnologies.common.concur.lock.OModificationOperationProhibitedException}
* exception will be thrown in case of write command will be performed.
*/
void freeze(boolean throwException);
}
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.common.directmemory.collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import com.orientechnologies.common.directmemory.OBuddyMemory;
import com.orientechnologies.common.directmemory.ODirectMemory;
import com.orientechnologies.common.serialization.types.OIntegerSerializer;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author <NAME>
* @since 19.08.12
*/
@Test
public class DirectMemoryHashMapPutTest {
private ODirectMemory memory;
private ODirectMemoryHashMap<Integer, Integer> hashMap;
@BeforeMethod
public void setUp() {
memory = new OBuddyMemory(16000000, 32);
hashMap = new ODirectMemoryHashMap<Integer, Integer>(memory, OIntegerSerializer.INSTANCE, OIntegerSerializer.INSTANCE, 2, 2);
}
public void testAddOneItem() {
final int clusterId = 1;
hashMap.put(clusterId, 10);
Assert.assertEquals(10, (int) hashMap.get(clusterId));
Assert.assertEquals(1, hashMap.size());
}
public void testAddTwoItems() {
final int clusterIdOne = 0;
final int clusterIdTwo = 4;
hashMap.put(clusterIdOne, 10);
hashMap.put(clusterIdTwo, 20);
Assert.assertEquals(10, (int) hashMap.get(clusterIdOne));
Assert.assertEquals(20, (int) hashMap.get(clusterIdTwo));
Assert.assertEquals(2, hashMap.size());
}
public void testAddThreeItems() {
final int clusterIdOne = 0;
final int clusterIdTwo = 1;
final int clusterIdThree = 4;
hashMap.put(clusterIdOne, 10);
hashMap.put(clusterIdTwo, 20);
hashMap.put(clusterIdThree, 30);
Assert.assertEquals(10, (int) hashMap.get(clusterIdOne));
Assert.assertEquals(20, (int) hashMap.get(clusterIdTwo));
Assert.assertEquals(30, (int) hashMap.get(clusterIdThree));
Assert.assertEquals(3, (int) hashMap.size());
}
public void testAddFourItems() {
final int clusterIdOne = 0;
final int clusterIdTwo = 1;
final int clusterIdThree = 4;
final int clusterIdFour = 2;
hashMap.put(clusterIdOne, 10);
hashMap.put(clusterIdTwo, 20);
hashMap.put(clusterIdThree, 30);
hashMap.put(clusterIdFour, 40);
Assert.assertEquals(10, (int) hashMap.get(clusterIdOne));
Assert.assertEquals(20, (int) hashMap.get(clusterIdTwo));
Assert.assertEquals(30, (int) hashMap.get(clusterIdThree));
Assert.assertEquals(40, (int) hashMap.get(clusterIdFour));
Assert.assertEquals(4, hashMap.size());
}
public void testAddThreeItemsUpdateOne() {
final int clusterIdOne = 0;
final int clusterIdTwo = 1;
final int clusterIdThree = 4;
hashMap.put(clusterIdOne, 10);
hashMap.put(clusterIdTwo, 20);
hashMap.put(clusterIdThree, 30);
hashMap.put(clusterIdOne, 40);
Assert.assertEquals(40, (int) hashMap.get(clusterIdOne));
Assert.assertEquals(20, (int) hashMap.get(clusterIdTwo));
Assert.assertEquals(30, (int) hashMap.get(clusterIdThree));
Assert.assertEquals(3, hashMap.size());
}
public void testAddFourItemsUpdateTwo() {
final int clusterIdOne = 0;
final int clusterIdTwo = 1;
final int clusterIdThree = 4;
final int clusterIdFour = 2;
hashMap.put(clusterIdOne, 10);
hashMap.put(clusterIdTwo, 20);
hashMap.put(clusterIdThree, 30);
hashMap.put(clusterIdFour, 40);
hashMap.put(clusterIdTwo, 50);
hashMap.put(clusterIdOne, 60);
Assert.assertEquals(60, (int) hashMap.get(clusterIdOne));
Assert.assertEquals(50, (int) hashMap.get(clusterIdTwo));
Assert.assertEquals(30, (int) hashMap.get(clusterIdThree));
Assert.assertEquals(40, (int) hashMap.get(clusterIdFour));
Assert.assertEquals(4, hashMap.size());
}
public void testAdd10000RandomItems() {
final Map<Integer, Integer> addedItems = new HashMap<Integer, Integer>();
final Random random = new Random();
for (int i = 0; i < 10000; i++) {
int clusterId = random.nextInt();
while (addedItems.containsKey(clusterId))
clusterId = random.nextInt();
final int pointer = random.nextInt();
hashMap.put(clusterId, pointer);
addedItems.put(clusterId, pointer);
}
for (Map.Entry<Integer, Integer> addedItem : addedItems.entrySet())
Assert.assertEquals(addedItem.getValue().intValue(), (int) hashMap.get(addedItem.getKey()));
Assert.assertEquals(10000, hashMap.size());
}
public void testAdd10000RandomItemsUpdateHalf() {
final Map<Integer, Integer> addedItems = new HashMap<Integer, Integer>();
final Random random = new Random();
for (int i = 0; i < 10000; i++) {
int clusterId = random.nextInt();
while (addedItems.containsKey(clusterId))
clusterId = random.nextInt();
final int pointer = random.nextInt();
hashMap.put(clusterId, pointer);
if (random.nextInt(2) > 0) {
hashMap.put(clusterId, pointer / 2);
addedItems.put(clusterId, pointer / 2);
} else
addedItems.put(clusterId, pointer);
}
for (Map.Entry<Integer, Integer> addedItem : addedItems.entrySet())
Assert.assertEquals(addedItem.getValue().intValue(), (int) hashMap.get(addedItem.getKey()));
Assert.assertEquals(10000, hashMap.size());
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.common.concur.lock;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class OLockManager<RESOURCE_TYPE, REQUESTER_TYPE> {
public enum LOCK {
SHARED, EXCLUSIVE
}
private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
protected long acquireTimeout;
protected final ConcurrentHashMap<RESOURCE_TYPE, CountableLock> map;
private final boolean enabled;
private final int shift;
private final int mask;
private final Object[] locks;
@SuppressWarnings("serial")
protected static class CountableLock extends ReentrantReadWriteLock {
protected int countLocks = 0;
public CountableLock(final boolean iFair) {
super(false);
}
}
public OLockManager(final boolean iEnabled, final int iAcquireTimeout) {
this(iEnabled, iAcquireTimeout, defaultConcurrency());
}
public OLockManager(final boolean iEnabled, final int iAcquireTimeout, final int concurrencyLevel) {
int cL = 1;
int sh = 0;
while (cL < concurrencyLevel) {
cL <<= 1;
sh++;
}
shift = 32 - sh;
mask = cL - 1;
map = new ConcurrentHashMap<RESOURCE_TYPE, CountableLock>(cL);
locks = new Object[cL];
for (int i = 0; i < locks.length; i++) {
locks[i] = new Object();
}
acquireTimeout = iAcquireTimeout;
enabled = iEnabled;
}
public void acquireLock(final REQUESTER_TYPE iRequester, final RESOURCE_TYPE iResourceId, final LOCK iLockType) {
acquireLock(iRequester, iResourceId, iLockType, acquireTimeout);
}
public void acquireLock(final REQUESTER_TYPE iRequester, final RESOURCE_TYPE iResourceId, final LOCK iLockType, long iTimeout) {
if (!enabled)
return;
CountableLock lock;
final Object internalLock = internalLock(iResourceId);
synchronized (internalLock) {
lock = map.get(iResourceId);
if (lock == null) {
final CountableLock newLock = new CountableLock(iTimeout > 0);
lock = map.putIfAbsent(getImmutableResourceId(iResourceId), newLock);
if (lock == null)
lock = newLock;
}
lock.countLocks++;
}
try {
if (iTimeout <= 0) {
if (iLockType == LOCK.SHARED)
lock.readLock().lock();
else
lock.writeLock().lock();
} else {
try {
if (iLockType == LOCK.SHARED) {
if (!lock.readLock().tryLock(iTimeout, TimeUnit.MILLISECONDS))
throw new OLockException("Timeout on acquiring resource '" + iResourceId + "' because is locked from another thread");
} else {
if (!lock.writeLock().tryLock(iTimeout, TimeUnit.MILLISECONDS))
throw new OLockException("Timeout on acquiring resource '" + iResourceId + "' because is locked from another thread");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new OLockException("Thread interrupted while waiting for resource '" + iResourceId + "'");
}
}
} catch (RuntimeException e) {
synchronized (internalLock) {
lock.countLocks--;
if (lock.countLocks == 0)
map.remove(iResourceId);
}
throw e;
}
}
public void releaseLock(final REQUESTER_TYPE iRequester, final RESOURCE_TYPE iResourceId, final LOCK iLockType)
throws OLockException {
if (!enabled)
return;
final CountableLock lock;
final Object internalLock = internalLock(iResourceId);
synchronized (internalLock) {
lock = map.get(iResourceId);
if (lock == null)
throw new OLockException("Error on releasing a non acquired lock by the requester '" + iRequester
+ "' against the resource: '" + iResourceId + "'");
lock.countLocks--;
if (lock.countLocks == 0)
map.remove(iResourceId);
}
if (iLockType == LOCK.SHARED)
lock.readLock().unlock();
else
lock.writeLock().unlock();
}
public void clear() {
map.clear();
}
// For tests purposes.
public int getCountCurrentLocks() {
return map.size();
}
protected RESOURCE_TYPE getImmutableResourceId(final RESOURCE_TYPE iResourceId) {
return iResourceId;
}
private Object internalLock(final RESOURCE_TYPE iResourceId) {
final int hashCode = iResourceId.hashCode();
final int index = (hashCode >>> shift) & mask;
return locks[index];
}
private static int defaultConcurrency() {
return Runtime.getRuntime().availableProcessors() > DEFAULT_CONCURRENCY_LEVEL ? Runtime.getRuntime().availableProcessors()
: DEFAULT_CONCURRENCY_LEVEL;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.command.script;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.command.script.formatter.OJSScriptFormatter;
import com.orientechnologies.orient.core.command.script.formatter.ORubyScriptFormatter;
import com.orientechnologies.orient.core.command.script.formatter.OSQLScriptFormatter;
import com.orientechnologies.orient.core.command.script.formatter.OScriptFormatter;
import com.orientechnologies.orient.core.db.ODatabaseComplex;
import com.orientechnologies.orient.core.db.record.ODatabaseRecordTx;
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.core.metadata.function.OFunction;
import com.orientechnologies.orient.core.sql.OSQLScriptEngine;
import com.orientechnologies.orient.core.sql.OSQLScriptEngineFactory;
/**
* Executes Script Commands.
*
* @see OCommandScript
* @author <NAME>
*
*/
public class OScriptManager {
protected final String DEF_LANGUAGE = "javascript";
protected ScriptEngineManager scriptEngineManager;
protected Map<String, ScriptEngine> engines;
protected String defaultLanguage = DEF_LANGUAGE;
protected Map<String, OScriptFormatter> formatters = new HashMap<String, OScriptFormatter>();
protected List<OScriptInjection> injections = new ArrayList<OScriptInjection>();
protected static final Object[] EMPTY_PARAMS = new Object[] {};
public OScriptManager() {
if (engines == null) {
engines = new HashMap<String, ScriptEngine>();
scriptEngineManager = new ScriptEngineManager();
registerEngine(OSQLScriptEngine.NAME, new OSQLScriptEngineFactory().getScriptEngine());
for (ScriptEngineFactory f : scriptEngineManager.getEngineFactories()) {
registerEngine(f.getLanguageName().toLowerCase(), f.getScriptEngine());
if (defaultLanguage == null)
defaultLanguage = f.getLanguageName();
}
if (!engines.containsKey(DEF_LANGUAGE)) {
registerEngine(DEF_LANGUAGE, scriptEngineManager.getEngineByName(DEF_LANGUAGE));
defaultLanguage = DEF_LANGUAGE;
}
registerFormatter(OSQLScriptEngine.NAME, new OSQLScriptFormatter());
registerFormatter(DEF_LANGUAGE, new OJSScriptFormatter());
registerFormatter("ruby", new ORubyScriptFormatter());
}
}
public String getFunctionDefinition(final OFunction iFunction) {
final OScriptFormatter formatter = formatters.get(iFunction.getLanguage().toLowerCase());
if (formatter == null)
throw new IllegalArgumentException("Cannot find script formatter for the language '" + iFunction.getLanguage() + "'");
return formatter.getFunctionDefinition(iFunction);
}
public String getFunctionInvoke(final OFunction iFunction, final Object[] iArgs) {
final OScriptFormatter formatter = formatters.get(iFunction.getLanguage().toLowerCase());
if (formatter == null)
throw new IllegalArgumentException("Cannot find script formatter for the language '" + iFunction.getLanguage() + "'");
return formatter.getFunctionInvoke(iFunction, iArgs);
}
/**
* Format the library of functions for a language.
*
* @param db
* Current database instance
* @param iLanguage
* Language as filter
* @return String containing all the functions
*/
public String getLibrary(final ODatabaseComplex<?> db, final String iLanguage) {
if (db == null)
// NO DB = NO LIBRARY
return null;
final StringBuilder code = new StringBuilder();
final Set<String> functions = db.getMetadata().getFunctionLibrary().getFunctionNames();
for (String fName : functions) {
final OFunction f = db.getMetadata().getFunctionLibrary().getFunction(fName);
if (f.getLanguage() == null)
throw new OConfigurationException("Database function '" + fName + "' has no language");
if (f.getLanguage().equalsIgnoreCase(iLanguage)) {
final String def = getFunctionDefinition(f);
if (def != null) {
code.append(def);
code.append("\n");
}
}
}
return code.length() == 0 ? null : code.toString();
}
public ScriptEngine getEngine(final String iLanguage) {
if (iLanguage == null)
throw new OCommandScriptException("No language was specified");
final String lang = iLanguage.toLowerCase();
if (!engines.containsKey(lang))
throw new OCommandScriptException("Unsupported language: " + iLanguage + ". Supported languages are: " + engines);
final ScriptEngine scriptEngine = engines.get(lang);
if (scriptEngine == null)
throw new OCommandScriptException("Cannot find script engine: " + iLanguage);
return scriptEngine;
}
public Bindings bind(final ScriptEngine iEngine, final ODatabaseRecordTx db, final OCommandContext iContext,
final Map<Object, Object> iArgs) {
final Bindings binding = iEngine.createBindings();
for (OScriptInjection i : injections)
i.bind(binding);
if (db != null) {
// BIND FIXED VARIABLES
binding.put("db", new OScriptDocumentDatabaseWrapper(db));
binding.put("gdb", new OScriptGraphDatabaseWrapper(db));
}
// BIND CONTEXT VARIABLE INTO THE SCRIPT
if (iContext != null) {
for (Entry<String, Object> a : iContext.getVariables().entrySet())
binding.put(a.getKey(), a.getValue());
}
// BIND PARAMETERS INTO THE SCRIPT
if (iArgs != null) {
for (Entry<Object, Object> a : iArgs.entrySet())
binding.put(a.getKey().toString(), a.getValue());
binding.put("params", iArgs.values().toArray());
} else
binding.put("params", EMPTY_PARAMS);
return binding;
}
/**
* Unbinds variables
*
* @param binding
*/
public void unbind(Bindings binding) {
for (OScriptInjection i : injections)
i.unbind(binding);
}
public void registerInjection(final OScriptInjection iInj) {
if (!injections.contains(iInj))
injections.add(iInj);
}
public void unregisterInjection(final OScriptInjection iInj) {
injections.remove(iInj);
}
public OScriptManager registerEngine(final String iLanguage, final ScriptEngine iEngine) {
engines.put(iLanguage, iEngine);
return this;
}
public OScriptManager registerFormatter(final String iLanguage, final OScriptFormatter iFormatterImpl) {
formatters.put(iLanguage, iFormatterImpl);
return this;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.test.database.auto;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import org.testng.Assert;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.ODatabaseFlat;
import com.orientechnologies.orient.core.exception.OConcurrentModificationException;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ORecordFlat;
import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE;
@Test(groups = "dictionary")
public class TransactionOptimisticTest {
private String url;
@Parameters(value = "url")
public TransactionOptimisticTest(String iURL) {
url = iURL;
}
@Test
public void testTransactionOptimisticRollback() throws IOException {
ODatabaseFlat db1 = new ODatabaseFlat(url);
db1.open("admin", "admin");
long rec = db1.countClusterElements("binary");
db1.begin();
ORecordFlat record1 = new ORecordFlat(db1);
record1.value("This is the first version").save();
db1.rollback();
Assert.assertEquals(db1.countClusterElements("binary"), rec);
db1.close();
}
@Test(dependsOnMethods = "testTransactionOptimisticRollback")
public void testTransactionOptimisticCommit() throws IOException {
ODatabaseFlat db1 = new ODatabaseFlat(url);
db1.open("admin", "admin");
long tot = db1.countClusterElements("binary");
db1.begin();
ORecordFlat record1 = new ORecordFlat(db1);
record1.value("This is the first version").save("binary");
db1.commit();
Assert.assertEquals(db1.countClusterElements("binary"), tot + 1);
db1.close();
}
@Test(dependsOnMethods = "testTransactionOptimisticCommit")
public void testTransactionOptimisticCuncurrentException() throws IOException {
ODatabaseFlat db1 = new ODatabaseFlat(url);
db1.open("admin", "admin");
ODatabaseFlat db2 = new ODatabaseFlat(url);
db2.open("admin", "admin");
ORecordFlat record1 = new ORecordFlat(db1);
record1.value("This is the first version").save();
try {
db1.begin();
// RE-READ THE RECORD
record1.load();
ORecordFlat record2 = db2.load(record1.getIdentity());
db2.save(record2.value("This is the second version"));
db1.save(record1.value("This is the third version"));
db1.commit();
Assert.assertTrue(false);
} catch (OConcurrentModificationException e) {
Assert.assertTrue(true);
db1.rollback();
} finally {
db1.close();
db2.close();
}
}
@Test(dependsOnMethods = "testTransactionOptimisticCuncurrentException")
public void testTransactionOptimisticCacheMgmt1Db() throws IOException {
ODatabaseFlat db = new ODatabaseFlat(url);
db.open("admin", "admin");
ORecordFlat record = new ORecordFlat(db);
record.value("This is the first version").save();
try {
db.begin();
// RE-READ THE RECORD
record.load();
int v1 = record.getVersion();
record.value("This is the second version").save();
db.commit();
record.reload();
Assert.assertEquals(record.getVersion(), v1 + 1);
Assert.assertTrue(record.value().contains("second"));
} finally {
db.close();
}
}
@Test(dependsOnMethods = "testTransactionOptimisticCacheMgmt1Db")
public void testTransactionOptimisticCacheMgmt2Db() throws IOException {
ODatabaseFlat db1 = new ODatabaseFlat(url);
db1.open("admin", "admin");
ODatabaseFlat db2 = new ODatabaseFlat(url);
db2.open("admin", "admin");
ORecordFlat record1 = new ORecordFlat(db1);
record1.value("This is the first version").save();
try {
db1.begin();
// RE-READ THE RECORD
record1.load();
int v1 = record1.getVersion();
record1.value("This is the second version").save();
db1.commit();
ORecordFlat record2 = db2.load(record1.getIdentity());
Assert.assertEquals(record2.getVersion(), v1 + 1);
Assert.assertTrue(record2.value().contains("second"));
} finally {
db1.close();
db2.close();
}
}
@Test(dependsOnMethods = "testTransactionOptimisticCacheMgmt2Db")
public void testTransactionMultipleRecords() throws IOException {
ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
db.open("admin", "admin");
long totalAccounts = db.countClusterElements("Account");
String json = "{ \"@class\": \"Account\", \"type\": \"Residence\", \"street\": \"Piazza di Spagna\"}";
db.begin(TXTYPE.OPTIMISTIC);
for (int g = 0; g < 1000; g++) {
ODocument doc = new ODocument("Account");
doc.fromJSON(json);
doc.field("nr", g);
doc.save();
}
db.commit();
Assert.assertEquals(db.countClusterElements("Account"), totalAccounts + 1000);
db.close();
}
@SuppressWarnings("unchecked")
@Test
public void createGraphInTx() {
ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
db.open("admin", "admin");
db.begin();
ODocument kim = new ODocument("Profile").field("name", "Kim").field("surname", "Bauer");
ODocument teri = new ODocument("Profile").field("name", "Teri").field("surname", "Bauer");
ODocument jack = new ODocument("Profile").field("name", "Jack").field("surname", "Bauer");
((HashSet<ODocument>) jack.field("following", new HashSet<ODocument>()).field("following")).add(kim);
((HashSet<ODocument>) kim.field("following", new HashSet<ODocument>()).field("following")).add(teri);
((HashSet<ODocument>) teri.field("following", new HashSet<ODocument>()).field("following")).add(jack);
jack.save();
db.commit();
System.out
.println("Kim indexed: " + db.getMetadata().getSchema().getClass("Profile").getProperty("name").getIndex().get("Kim"));
db.close();
db.open("admin", "admin");
ODocument loadedJack = db.load(jack.getIdentity());
Assert.assertEquals(loadedJack.field("name"), "Jack");
Collection<ODocument> jackFollowings = loadedJack.field("following");
Assert.assertNotNull(jackFollowings);
Assert.assertEquals(jackFollowings.size(), 1);
ODocument loadedKim = jackFollowings.iterator().next();
Assert.assertEquals(loadedKim.field("name"), "Kim");
Collection<ODocument> kimFollowings = loadedKim.field("following");
Assert.assertNotNull(kimFollowings);
Assert.assertEquals(kimFollowings.size(), 1);
ODocument loadedTeri = kimFollowings.iterator().next();
Assert.assertEquals(loadedTeri.field("name"), "Teri");
Collection<ODocument> teriFollowings = loadedTeri.field("following");
Assert.assertNotNull(teriFollowings);
Assert.assertEquals(teriFollowings.size(), 1);
Assert.assertEquals(teriFollowings.iterator().next().field("name"), "Jack");
db.close();
}
//
// @SuppressWarnings("unchecked")
// @Test
// public void createGraphInTxWithSchemaDefined() {
// ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
// db.open("admin", "admin");
//
// OClass profileClass = db.getMetadata().getSchema().getClass("Profile");
// profileClass.createProperty("following", OType.LINKSET, profileClass);
//
// db.begin();
//
// ODocument kim = new ODocument( "Profile").field("name", "Kim").field("surname", "Bauer");
// ODocument teri = new ODocument( "Profile").field("name", "Teri").field("surname", "Bauer");
// ODocument jack = new ODocument( "Profile").field("name", "Jack").field("surname", "Bauer");
//
// ((HashSet<ODocument>) jack.field("following", new HashSet<ODocument>()).field("following")).add(kim);
// ((HashSet<ODocument>) kim.field("following", new HashSet<ODocument>()).field("following")).add(teri);
// ((HashSet<ODocument>) teri.field("following", new HashSet<ODocument>()).field("following")).add(jack);
//
// jack.save();
//
// db.commit();
//
// db.close();
// db.open("admin", "admin");
//
// ODocument loadedJack = db.load(jack.getIdentity());
// Assert.assertEquals(loadedJack.field("name"), "Jack");
// Collection<ODocument> jackFollowings = loadedJack.field("following");
// Assert.assertNotNull(jackFollowings.size());
// Assert.assertEquals(jackFollowings.size(), 1);
//
// ODocument loadedKim = jackFollowings.iterator().next();
// Assert.assertEquals(loadedKim.field("name"), "Kim");
// Collection<ODocument> kimFollowings = loadedKim.field("following");
// Assert.assertNotNull(kimFollowings.size());
// Assert.assertEquals(kimFollowings.size(), 1);
//
// ODocument loadedTeri = kimFollowings.iterator().next();
// Assert.assertEquals(loadedTeri.field("name"), "Teri");
// Collection<ODocument> teriFollowings = loadedTeri.field("following");
// Assert.assertNotNull(teriFollowings.size());
// Assert.assertEquals(teriFollowings.size(), 1);
//
// Assert.assertEquals(teriFollowings.iterator().next().field("name"), "Jack");
//
// db.close();
// }
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.processor.block;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.metadata.function.OFunction;
import com.orientechnologies.orient.core.processor.OComposableProcessor;
import com.orientechnologies.orient.core.processor.OProcessException;
import com.orientechnologies.orient.core.record.impl.ODocument;
public class OFunctionBlock extends OAbstractBlock {
@SuppressWarnings("unchecked")
@Override
public Object processBlock(OComposableProcessor iManager, final OCommandContext iContext, final ODocument iConfig,
ODocument iOutput, final boolean iReadOnly) {
final String function = getRequiredFieldOfClass(iContext, iConfig, "function", String.class);
final Object[] args;
final Collection<Object> configuredArgs = getFieldOfClass(iContext, iConfig, "args", Collection.class);
if (configuredArgs != null) {
args = new Object[configuredArgs.size()];
int argIdx = 0;
for (Object arg : configuredArgs) {
Object value = resolveValue(iContext, arg);
if (value instanceof List<?>)
// RHINO DOESN'T TREAT LIST AS ARRAY: CONVERT IT
value = ((List<?>) value).toArray();
args[argIdx++] = value;
}
} else
args = null;
final OFunction f = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getFunctionLibrary().getFunction(function);
if (f == null)
throw new OProcessException("Function '" + function + "' was not found");
debug(iContext, "Calling: " + function + "(" + Arrays.toString(args) + ")...");
return f.executeInContext(iContext, args);
}
@Override
public String getName() {
return "function";
}
}<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.version;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.Externalizable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.orientechnologies.orient.core.storage.fs.OFile;
/**
* Abstraction for record version. In non distributed environment it is just a number represented by {@link OSimpleVersion}. In
* distributed environment records can be processed concurrently, so simple number is not enough, as we need some additional
* information to prevent generation of two different versions of document with the same version number. This interface provide an
* ability to create extended versions.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @see OSimpleVersion
* @see ODistributedVersion
*/
public interface ORecordVersion extends Comparable<ORecordVersion>, Externalizable {
static final ORecordVersion TOMBSTONE = OVersionFactory.instance().createTombstone();
void increment();
void decrement();
boolean isUntracked();
boolean isTemporary();
boolean isValid();
void setCounter(int iVersion);
int getCounter();
void copyFrom(ORecordVersion version);
void reset();
void setRollbackMode();
void clearRollbackMode();
void disable();
void revive();
ORecordVersion copy();
ORecordVersionSerializer getSerializer();
boolean equals(Object other);
int hashCode();
String toString();
boolean isTombstone();
void convertToTombstone();
/**
* Provides serialization to different sources.
*/
public interface ORecordVersionSerializer {
void writeTo(DataOutput out, ORecordVersion version) throws IOException;
void readFrom(DataInput in, ORecordVersion version) throws IOException;
void readFrom(InputStream stream, ORecordVersion version) throws IOException;
void writeTo(OutputStream stream, ORecordVersion version) throws IOException;
/**
* Writes version to stream.
*
*
* @param iStream
* stream to write data.
* @param pos
* the beginning index, inclusive.
* @param version
* @return size of serialized object
*/
int writeTo(byte[] iStream, int pos, ORecordVersion version);
/**
* Reads version from stream.
*
*
* @param iStream
* stream that contains serialized data.
* @param pos
* the beginning index, inclusive.
* @param version
* @return size of deserialized object
*/
int readFrom(byte[] iStream, int pos, ORecordVersion version);
int writeTo(OFile file, long offset, ORecordVersion version) throws IOException;
long readFrom(OFile file, long offset, ORecordVersion version) throws IOException;
/**
* The same as {@link #writeTo(byte[], int, ORecordVersion)}, but uses platform dependent optimization to speed up writing.
*
*
* @param iStream
* @param pos
* @param version
* @return size of serialized object
*/
int fastWriteTo(byte[] iStream, int pos, ORecordVersion version);
/**
* The same as {@link #readFrom(byte[], int, ORecordVersion)}, but uses platform dependent optimization to speed up reading.
*
*
* @param iStream
* @param pos
* @param version
* @return size of deserialized object
*/
int fastReadFrom(byte[] iStream, int pos, ORecordVersion version);
/**
* Can use platform dependant optimization.
*
* @return serialized version
* @param version
*/
byte[] toByteArray(ORecordVersion version);
String toString();
String toString(ORecordVersion version);
void fromString(String string, ORecordVersion version);
}
}
<file_sep>package com.orientechnologies.orient.core.db.record;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.orientechnologies.common.types.ORef;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.OMemoryInputStream;
import com.orientechnologies.orient.core.serialization.OMemoryStream;
@Test
public class TrackedListTest {
public void testAddNotificationOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD);
Assert.assertNull(event.getOldValue());
Assert.assertEquals(event.getKey().intValue(), 0);
Assert.assertEquals(event.getValue(), "value1");
changed.value = true;
}
});
trackedList.add("value1");
Assert.assertTrue(changed.value);
Assert.assertTrue(doc.isDirty());
}
public void testAddNotificationTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD);
Assert.assertNull(event.getOldValue());
Assert.assertEquals(event.getKey().intValue(), 2);
Assert.assertEquals(event.getValue(), "value3");
changed.value = true;
}
});
trackedList.add("value3");
Assert.assertTrue(changed.value);
Assert.assertTrue(doc.isDirty());
}
public void testAddNotificationThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
Assert.assertTrue(doc.isDirty());
}
public void testAddNotificationFour() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.add("value3");
Assert.assertEquals(changed.value, Boolean.FALSE);
Assert.assertFalse(doc.isDirty());
}
public void testAddAllNotificationOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
final List<String> valuesToAdd = new ArrayList<String>();
valuesToAdd.add("value1");
valuesToAdd.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>();
firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.ADD, 0, "value1"));
firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.ADD, 1, "value3"));
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
if (firedEvents.get(0).equals(event))
firedEvents.remove(0);
else
Assert.fail();
}
});
trackedList.addAll(valuesToAdd);
Assert.assertEquals(firedEvents.size(), 0);
Assert.assertTrue(doc.isDirty());
}
public void testAddAllNotificationTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
final List<String> valuesToAdd = new ArrayList<String>();
valuesToAdd.add("value1");
valuesToAdd.add("value3");
trackedList.addAll(valuesToAdd);
Assert.assertTrue(doc.isDirty());
}
public void testAddAllNotificationThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
final List<String> valuesToAdd = new ArrayList<String>();
valuesToAdd.add("value1");
valuesToAdd.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.addAll(valuesToAdd);
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testAddIndexNotificationOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD);
Assert.assertNull(event.getOldValue());
Assert.assertEquals(event.getKey().intValue(), 1);
Assert.assertEquals(event.getValue(), "value3");
changed.value = true;
}
});
trackedList.add(1, "value3");
Assert.assertEquals(changed.value, Boolean.TRUE);
Assert.assertTrue(doc.isDirty());
}
public void testAddIndexNotificationTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.add(1, "value3");
Assert.assertTrue(doc.isDirty());
}
public void testAddIndexNotificationThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.add(1, "value3");
Assert.assertEquals(changed.value, Boolean.FALSE);
Assert.assertFalse(doc.isDirty());
}
public void testSetNotificationOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.UPDATE);
Assert.assertEquals(event.getOldValue(), "value2");
Assert.assertEquals(event.getKey().intValue(), 1);
Assert.assertEquals(event.getValue(), "value4");
changed.value = true;
}
});
trackedList.set(1, "value4");
Assert.assertEquals(changed.value, Boolean.TRUE);
Assert.assertTrue(doc.isDirty());
}
public void testSetNotificationTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.set(1, "value4");
Assert.assertTrue(doc.isDirty());
}
public void testSetNotificationThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.set(1, "value4");
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testRemoveNotificationOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.REMOVE);
Assert.assertEquals(event.getOldValue(), "value2");
Assert.assertEquals(event.getKey().intValue(), 1);
Assert.assertNull(event.getValue());
changed.value = true;
}
});
trackedList.remove("value2");
Assert.assertTrue(changed.value);
Assert.assertTrue(doc.isDirty());
}
public void testRemoveNotificationTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.remove("value2");
Assert.assertTrue(doc.isDirty());
}
public void testRemoveNotificationThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.remove("value2");
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testRemoveNotificationFour() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.remove("value4");
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testRemoveIndexOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.REMOVE);
Assert.assertEquals(event.getOldValue(), "value2");
Assert.assertEquals(event.getKey().intValue(), 1);
Assert.assertNull(event.getValue());
changed.value = true;
}
});
trackedList.remove(1);
Assert.assertTrue(changed.value);
Assert.assertTrue(doc.isDirty());
}
public void testRemoveIndexTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.remove(1);
Assert.assertTrue(doc.isDirty());
}
public void testRemoveIndexThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.remove(1);
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testClearOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>();
firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.REMOVE, 2, null, "value3"));
firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.REMOVE, 1, null, "value2"));
firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.REMOVE, 0, null, "value1"));
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
if (firedEvents.get(0).equals(event))
firedEvents.remove(0);
else
Assert.fail();
}
});
trackedList.clear();
Assert.assertEquals(0, firedEvents.size());
Assert.assertTrue(doc.isDirty());
}
public void testClearTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.clear();
Assert.assertTrue(doc.isDirty());
}
public void testClearThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.clear();
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testReturnOriginalStateOne() {
final ODocument doc = new ODocument();
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
trackedList.add("value4");
trackedList.add("value5");
final List<String> original = new ArrayList<String>(trackedList);
final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>();
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
firedEvents.add(event);
}
});
trackedList.add("value6");
trackedList.add("value7");
trackedList.set(2, "value10");
trackedList.add(1, "value8");
trackedList.add(1, "value8");
trackedList.remove(3);
trackedList.remove("value7");
trackedList.add(0, "value9");
trackedList.add(0, "value9");
trackedList.add(0, "value9");
trackedList.add(0, "value9");
trackedList.remove("value9");
trackedList.remove("value9");
trackedList.add(4, "value11");
Assert.assertEquals(original, trackedList.returnOriginalState(firedEvents));
}
public void testReturnOriginalStateTwo() {
final ODocument doc = new ODocument();
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
trackedList.add("value4");
trackedList.add("value5");
final List<String> original = new ArrayList<String>(trackedList);
final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>();
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
firedEvents.add(event);
}
});
trackedList.add("value6");
trackedList.add("value7");
trackedList.set(2, "value10");
trackedList.add(1, "value8");
trackedList.remove(3);
trackedList.clear();
trackedList.remove("value7");
trackedList.add(0, "value9");
trackedList.add("value11");
trackedList.add(0, "value12");
trackedList.add("value12");
Assert.assertEquals(original, trackedList.returnOriginalState(firedEvents));
}
/**
* Test that {@link OTrackedList} is serialised correctly.
*/
@Test
public void testSerialization() throws Exception {
class NotSerializableDocument extends ODocument {
private static final long serialVersionUID = 1L;
private void writeObject(ObjectOutputStream oos) throws IOException {
throw new NotSerializableException();
}
}
final OTrackedList<String> beforeSerialization = new OTrackedList<String>(new NotSerializableDocument());
beforeSerialization.add("firstVal");
beforeSerialization.add("secondVal");
final OMemoryStream memoryStream = new OMemoryStream();
ObjectOutputStream out = new ObjectOutputStream(memoryStream);
out.writeObject(beforeSerialization);
out.close();
final ObjectInputStream input = new ObjectInputStream(new OMemoryInputStream(memoryStream.copy()));
@SuppressWarnings("unchecked")
final List<String> afterSerialization = (List<String>) input.readObject();
Assert.assertEquals(afterSerialization.size(), beforeSerialization.size(), "List size");
for (int i = 0; i < afterSerialization.size(); i++) {
Assert.assertEquals(afterSerialization.get(i), beforeSerialization.get(i));
}
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.network.protocol.http.command.get;
import java.io.StringWriter;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.serialization.serializer.OJSONWriter;
import com.orientechnologies.orient.server.network.protocol.http.OHttpRequest;
import com.orientechnologies.orient.server.network.protocol.http.OHttpResponse;
import com.orientechnologies.orient.server.network.protocol.http.OHttpUtils;
import com.orientechnologies.orient.server.network.protocol.http.command.OServerCommandAuthenticatedServerAbstract;
public class OServerCommandGetProfiler extends OServerCommandAuthenticatedServerAbstract {
private static final String[] NAMES = { "GET|profiler/*", "POST|profiler/*" };
public OServerCommandGetProfiler() {
super("server.profiler");
}
@Override
public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception {
final String[] parts = checkSyntax(iRequest.url, 2, "Syntax error: profiler/<command>/[<config>]|[<from>/<to>]");
iRequest.data.commandInfo = "Profiler information";
try {
final String command = parts[1];
if (command.equalsIgnoreCase("start")) {
Orient.instance().getProfiler().startRecording();
iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_TEXT_PLAIN, "Recording started", null);
} else if (command.equalsIgnoreCase("stop")) {
Orient.instance().getProfiler().stopRecording();
iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_TEXT_PLAIN, "Recording stopped", null);
} else if (command.equalsIgnoreCase("reset")) {
Orient.instance().getProfiler().stopRecording();
Orient.instance().getProfiler().startRecording();
iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_TEXT_PLAIN, "Profiler restarted", null);
} else if (command.equalsIgnoreCase("configure")) {
Orient.instance().getProfiler().configure(parts[2]);
iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_TEXT_PLAIN, "Profiler configured with: " + parts[2],
null);
} else if (command.equalsIgnoreCase("status")) {
final String status = Orient.instance().getProfiler().isRecording() ? "on" : "off";
iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_TEXT_PLAIN, status, null);
} else if (command.equalsIgnoreCase("metadata")) {
iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, Orient.instance().getProfiler().metadataToJSON(),
null);
} else {
final String par1 = parts.length > 2 ? parts[2] : null;
final String par2 = parts.length > 3 ? parts[3] : null;
StringWriter jsonBuffer = new StringWriter();
OJSONWriter json = new OJSONWriter(jsonBuffer);
json.append(Orient.instance().getProfiler().toJSON(command, par1, par2));
iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, jsonBuffer.toString(), null);
}
} catch (Exception e) {
iResponse.send(OHttpUtils.STATUS_BADREQ_CODE, OHttpUtils.STATUS_BADREQ_DESCRIPTION, OHttpUtils.CONTENT_TEXT_PLAIN, e, null);
}
return false;
}
@Override
public String[] getNames() {
return NAMES;
}
}
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.id;
/**
* Abstraction of records position in cluster. You can think about it as about of n-bit number. Real instances of cluster position
* should be created using {@link OClusterPositionFactory} factory. Cluster positions are immutable objects.
*
* @author <NAME>
* @since 12.11.12
*/
public abstract class OClusterPosition extends Number implements Comparable<OClusterPosition> {
public final static OClusterPosition INVALID_POSITION = OClusterPositionFactory.INSTANCE.valueOf(-1);
/**
* Creates custer position with value which is higher than current value by one.
*
* @return custer position with value which is higher than current value by one.
*/
public abstract OClusterPosition inc();
/**
* Creates custer position with value which is less than current value by one.
*
* @return custer position with value which is less than current value by one.
*/
public abstract OClusterPosition dec();
/**
* @return <code>true</code> if current cluster position values does not equal to {@link #INVALID_POSITION}
*/
public abstract boolean isValid();
/**
* @return <code>true</code> if record with current cluster position can be stored in DB. (non-negative value)
*/
public abstract boolean isPersistent();
/**
* @return <code>true</code> if record with current cluster position can not be stored in DB. (negative value)
*/
public abstract boolean isNew();
/**
* @return <code>true</code> if record with current cluster position is not intended to be stored in DB and used for internal
* (system) needs.
*/
public abstract boolean isTemporary();
/**
* @return Serialized presentation of cluster position. Does not matter which value it holds it will be the same length equals to
* result of the function {@link com.orientechnologies.orient.core.id.OClusterPositionFactory#getSerializedSize()}
*/
public abstract byte[] toStream();
}
<file_sep>package com.orientechnologies.orient.server.handler;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.OConstants;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.config.OServerParameterConfiguration;
import com.orientechnologies.orient.server.managed.OrientServer;
public class OJMXPlugin extends OServerHandlerAbstract {
private OrientServer managedServer;
private ObjectName onProfiler;
private ObjectName onServer;
private boolean profilerManaged;
public OJMXPlugin() {
}
@Override
public void config(final OServer oServer, final OServerParameterConfiguration[] iParams) {
for (OServerParameterConfiguration param : iParams) {
if (param.name.equalsIgnoreCase("enabled")) {
if (!Boolean.parseBoolean(param.value))
// DISABLE IT
return;
} else if (param.name.equalsIgnoreCase("profilerManaged"))
profilerManaged = Boolean.parseBoolean(param.value);
}
OLogManager.instance().info(this, "JMX plugin installed and active: profilerManaged=%s", profilerManaged);
final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
try {
if (profilerManaged) {
// REGISTER THE PROFILER
onProfiler = new ObjectName("OrientDB:type=Profiler");
mBeanServer.registerMBean(Orient.instance().getProfiler(), onProfiler);
}
// REGISTER SERVER
onServer = new ObjectName("OrientDB:type=Server");
managedServer = new OrientServer();
mBeanServer.registerMBean(managedServer, onServer);
} catch (Exception e) {
throw new OConfigurationException("Cannot initialize JMX server", e);
}
}
/*
* (non-Javadoc)
*
* @see com.orientechnologies.orient.server.handler.OServerHandlerAbstract#shutdown()
*/
@Override
public void shutdown() {
try {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
if (mBeanServer.isRegistered(onProfiler))
mBeanServer.unregisterMBean(onProfiler);
if (mBeanServer.isRegistered(onServer))
mBeanServer.unregisterMBean(onServer);
} catch (Exception e) {
OLogManager.instance().error(this, "OrientDB Server v" + OConstants.ORIENT_VERSION + " unregisterMBean error.", e);
}
}
@Override
public String getName() {
return "jmx";
}
public OrientServer getManagedServer() {
return managedServer;
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.orientechnologies</groupId>
<artifactId>orientdb-parent</artifactId>
<version>1.3.0-SNAPSHOT</version>
</parent>
<artifactId>orientdb-distributed</artifactId>
<name>OrientDB Distributed Server</name>
<properties>
<javac.src.version>1.6</javac.src.version>
<javac.target.version>1.6</javac.target.version>
<jar.manifest.mainclass>com.orientechnologies.orient.server.OServerMain</jar.manifest.mainclass>
<osgi.import>*</osgi.import>
<osgi.export>com.orientechnologies.orient.server.cluster.hazelcast.*</osgi.export>
</properties>
<dependencies>
<dependency>
<groupId>com.orientechnologies</groupId>
<artifactId>orientdb-server</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>2.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>${jar.manifest.mainclass}</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.storage.impl.memory;
import java.io.IOException;
import com.orientechnologies.common.concur.resource.OSharedResourceAdaptive;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.config.OStorageClusterConfiguration;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OClusterEntryIterator;
import com.orientechnologies.orient.core.storage.OStorage;
public abstract class OClusterMemory extends OSharedResourceAdaptive implements OCluster {
public static final String TYPE = "MEMORY";
private OStorage storage;
private int id;
private String name;
private int dataSegmentId;
public OClusterMemory() {
super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean());
}
public void configure(final OStorage iStorage, final OStorageClusterConfiguration iConfig) throws IOException {
configure(iStorage, iConfig.getId(), iConfig.getName(), iConfig.getLocation(), iConfig.getDataSegmentId());
}
public void configure(final OStorage iStorage, final int iId, final String iClusterName, final String iLocation,
final int iDataSegmentId, final Object... iParameters) {
this.storage = iStorage;
this.id = iId;
this.name = iClusterName;
this.dataSegmentId = iDataSegmentId;
}
public int getDataSegmentId() {
acquireSharedLock();
try {
return dataSegmentId;
} finally {
releaseSharedLock();
}
}
public OClusterEntryIterator absoluteIterator() {
return new OClusterEntryIterator(this);
}
public void close() {
acquireExclusiveLock();
try {
clear();
} finally {
releaseExclusiveLock();
}
}
public void open() throws IOException {
}
public void create(final int iStartSize) throws IOException {
}
public void delete() throws IOException {
acquireExclusiveLock();
try {
close();
} finally {
releaseExclusiveLock();
}
}
public void truncate() throws IOException {
storage.checkForClusterPermissions(getName());
acquireExclusiveLock();
try {
clear();
} finally {
releaseExclusiveLock();
}
}
public void set(OCluster.ATTRIBUTES iAttribute, Object iValue) throws IOException {
if (iAttribute == null)
throw new IllegalArgumentException("attribute is null");
final String stringValue = iValue != null ? iValue.toString() : null;
switch (iAttribute) {
case NAME:
name = stringValue;
break;
case DATASEGMENT:
dataSegmentId = storage.getDataSegmentIdByName(stringValue);
break;
}
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void synch() {
}
public void setSoftlyClosed(boolean softlyClosed) throws IOException {
}
public void lock() {
acquireSharedLock();
}
public void unlock() {
releaseSharedLock();
}
public String getType() {
return TYPE;
}
protected abstract void clear();
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.storage.impl.memory.lh;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* @author <NAME> (<EMAIL>)
*/
// TODO optimize it to use Array instead of list!
class OGroupOverflowTable {
public static class GroupOverflowInfo {
byte group;
int startingPage;
public GroupOverflowInfo(byte group, int startingPage) {
this.group = group;
this.startingPage = startingPage;
}
}
List<GroupOverflowInfo> overflowInfo = new LinkedList<GroupOverflowInfo>();
private static final byte DUMMY_GROUP_NUMBER = -1;
public OGroupOverflowTable() {
overflowInfo.add(new GroupOverflowInfo(DUMMY_GROUP_NUMBER, 2));
}
public void clear() {
overflowInfo.clear();
overflowInfo.add(new GroupOverflowInfo(DUMMY_GROUP_NUMBER, 2));
}
public byte getGroupWithStartingPageLessThenOrEqual(int pageToStore) {
for (GroupOverflowInfo groupOverflowInfo : overflowInfo) {
if (groupOverflowInfo.startingPage <= pageToStore) {
return groupOverflowInfo.group;
}
}
return -2;
}
public int[] searchForGroupOrCreate(byte groupNumber, int groupSize) {
int dummyGroup = -1;
for (int i = 0, overflowInfoSize = overflowInfo.size() - 1; i < overflowInfoSize; i++) {
GroupOverflowInfo groupOverflowInfo = overflowInfo.get(i);
if (groupOverflowInfo.group == groupNumber) {
return new int[] { groupOverflowInfo.startingPage, overflowInfo.get(i + 1).startingPage - groupOverflowInfo.startingPage };
}
if (dummyGroup == -1 && groupOverflowInfo.group == DUMMY_GROUP_NUMBER) {
dummyGroup = i;
}
}
if (dummyGroup == -1) {
dummyGroup = overflowInfo.size() - 1;
}
// search is not successful so create new group on place of first dummy group
// assert overflowInfo.get(dummyGroup).group == DUMMY_GROUP_NUMBER;
overflowInfo.get(dummyGroup).group = groupNumber;
createDummyGroupIfNeeded(groupSize);
assert overflowInfo.get(dummyGroup).startingPage <= overflowInfo.get(overflowInfo.size() - 1).startingPage;
return new int[] { overflowInfo.get(dummyGroup).startingPage, groupSize };
}
public int getPageForGroup(byte groupNumber) {
for (GroupOverflowInfo groupOverflowInfo : overflowInfo) {
if (groupOverflowInfo.group == groupNumber) {
return groupOverflowInfo.startingPage;
}
}
return -1;
}
public GroupOverflowInfo findDummyGroup() {
return findDummyGroup(0);
}
public int move(byte groupNumber, int groupSize) {
removeGroup(groupNumber);
GroupOverflowInfo dummyGroup = findDummyGroup(groupSize);
dummyGroup.group = groupNumber;
createDummyGroupIfNeeded(groupSize);
return dummyGroup.startingPage;
}
private GroupOverflowInfo findDummyGroup(int minGroupSize) {
for (int i = 0, overflowInfoSize = overflowInfo.size() - 1; i < overflowInfoSize; i++) {
if ((overflowInfo.get(i).group == DUMMY_GROUP_NUMBER)
&& ((overflowInfo.get(i + 1).startingPage - overflowInfo.get(i).startingPage) >= minGroupSize)) {
return overflowInfo.get(i);
}
}
if (overflowInfo.get(overflowInfo.size() - 1).group == DUMMY_GROUP_NUMBER) {
return overflowInfo.get(overflowInfo.size() - 1);
}
return null;
}
private void removeGroup(byte groupNumber) {
for (GroupOverflowInfo groupOverflowInfo : overflowInfo) {
if (groupOverflowInfo.group == groupNumber) {
overflowInfo.remove(groupOverflowInfo);
break;
}
}
}
private void createDummyGroupIfNeeded(int groupSize) {
if (findDummyGroup() == null) {
createDummyGroup(groupSize);
}
if (overflowInfo.get(overflowInfo.size() - 1).group != DUMMY_GROUP_NUMBER) {
createDummyGroup(groupSize);
}
}
private void createDummyGroup(int groupSize) {
int startingPage = overflowInfo.get(overflowInfo.size() - 1).startingPage;
overflowInfo.add(new GroupOverflowInfo(DUMMY_GROUP_NUMBER, startingPage + groupSize));
}
public void moveDummyGroup(final int groupSize) {
if (isSecondDummyGroupExists()) {
removeGroup(DUMMY_GROUP_NUMBER);
} else {
overflowInfo.get(overflowInfo.size() - 1).startingPage = overflowInfo.get(overflowInfo.size() - 1).startingPage + groupSize;
}
}
public void moveDummyGroupIfNeeded(int lastPage, int groupSize) {
if (findDummyGroup().startingPage <= lastPage) {
moveDummyGroup(groupSize);
collapseDummyGroups();
}
}
public void removeUnusedGroups(OPageIndicator pageIndicator) {
for (int i = 0, overflowInfoSize = overflowInfo.size() - 1; i < overflowInfoSize; i++) {
for (int j = overflowInfo.get(i).startingPage; j < overflowInfo.get(i + 1).startingPage; ++j) {
if (pageIndicator.get(j)) {
break;
} else if (j == overflowInfo.get(i + 1).startingPage - 1) {
overflowInfo.get(i).group = DUMMY_GROUP_NUMBER;
}
}
}
collapseDummyGroups();
}
private void collapseDummyGroups() {
for (int i = overflowInfo.size() - 1; i > 0; --i) {
if (overflowInfo.get(i).group == DUMMY_GROUP_NUMBER && overflowInfo.get(i - 1).group == DUMMY_GROUP_NUMBER) {
GroupOverflowInfo groupOverflowInfo = overflowInfo.get(i);
overflowInfo.remove(groupOverflowInfo);
}
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (GroupOverflowInfo groupOverflowInfo : overflowInfo) {
builder.append("|\t").append(groupOverflowInfo.group).append("\t|\t").append(groupOverflowInfo.startingPage).append("\t|\n");
}
return builder.toString();
}
public List<GroupOverflowInfo> getOverflowGroupsInfoToMove(int page) {
List<GroupOverflowInfo> result = new ArrayList<GroupOverflowInfo>(overflowInfo.size());
for (GroupOverflowInfo groupOverflowInfo : overflowInfo) {
if (groupOverflowInfo.startingPage <= page) {
result.add(groupOverflowInfo);
}
}
return result;
}
public boolean isSecondDummyGroupExists() {
int counter = 0;
for (GroupOverflowInfo groupOverflowInfo : overflowInfo) {
if (groupOverflowInfo.group == DUMMY_GROUP_NUMBER) {
counter++;
}
}
return counter > 1;
}
public int getSizeForGroup(byte groupNumber) {
for (int i = 0, overflowInfoSize = overflowInfo.size() - 1; i < overflowInfoSize; i++) {
GroupOverflowInfo groupOverflowInfo = overflowInfo.get(i);
if (groupOverflowInfo.group == groupNumber) {
return overflowInfo.get(i + 1).startingPage - groupOverflowInfo.startingPage;
}
}
return -1;
}
public int enlargeGroupSize(final byte groupNumber, final int newGroupSize) {
for (GroupOverflowInfo groupOverflowInfo : overflowInfo) {
if (groupNumber == groupOverflowInfo.group) {
groupOverflowInfo.group = DUMMY_GROUP_NUMBER;
break;
}
}
assert overflowInfo.get(overflowInfo.size() - 1).group == DUMMY_GROUP_NUMBER;
int newStartingPage = overflowInfo.get(overflowInfo.size() - 1).startingPage;
overflowInfo.set(overflowInfo.size() - 1, new GroupOverflowInfo(groupNumber, newStartingPage));
overflowInfo.add(new GroupOverflowInfo(DUMMY_GROUP_NUMBER, newStartingPage + newGroupSize));
return newStartingPage;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.type.tree;
import java.io.IOException;
import com.orientechnologies.common.collection.OMVRBTreeEntry;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.type.tree.provider.OIdentityChangedListener;
import com.orientechnologies.orient.core.type.tree.provider.OMVRBTreeEntryDataProvider;
/**
*
* Serialized as:
* <table>
* <tr>
* <td>FROM</td>
* <td>TO</td>
* <td>FIELD</td>
* </tr>
* <tr>
* <td>00</td>
* <td>04</td>
* <td>PAGE SIZE</td>
* </tr>
* <tr>
* <td>04</td>
* <td>14</td>
* <td>PARENT RID</td>
* </tr>
* <tr>
* <td>14</td>
* <td>24</td>
* <td>LEFT RID</td>
* </tr>
* <tr>
* <td>24</td>
* <td>34</td>
* <td>RIGHT RID</td>
* </tr>
* <tr>
* <td>34</td>
* <td>35</td>
* <td>COLOR</td>
* </tr>
* <tr>
* <td>35</td>
* <td>37</td>
* <td>SIZE</td>
* </tr>
* </table>
* VARIABLE
*
* @author <NAME> (<EMAIL>--at--orient<EMAIL>)
*
* @param <K>
* @param <V>
*/
public class OMVRBTreeEntryPersistent<K, V> extends OMVRBTreeEntry<K, V> implements OIdentityChangedListener {
protected OMVRBTreeEntryDataProvider<K, V> dataProvider;
protected OMVRBTreePersistent<K, V> pTree;
protected OMVRBTreeEntryPersistent<K, V> parent;
protected OMVRBTreeEntryPersistent<K, V> left;
protected OMVRBTreeEntryPersistent<K, V> right;
/**
* Called upon unmarshalling.
*
* @param iTree
* Tree which belong
* @param iParent
* Parent node if any
* @param iRecordId
* Record to unmarshall
*/
public OMVRBTreeEntryPersistent(final OMVRBTreePersistent<K, V> iTree, final OMVRBTreeEntryPersistent<K, V> iParent,
final ORID iRecordId) {
super(iTree);
pTree = iTree;
dataProvider = pTree.dataProvider.getEntry(iRecordId);
dataProvider.setIdentityChangedListener(this);
init();
parent = iParent;
// setParent(iParent);
pTree.addNodeInMemory(this);
}
/**
* Make a new cell with given key, value, and parent, and with <tt>null</tt> child links, and BLACK color.
*/
public OMVRBTreeEntryPersistent(final OMVRBTreePersistent<K, V> iTree, final K iKey, final V iValue,
final OMVRBTreeEntryPersistent<K, V> iParent) {
super(iTree);
pTree = iTree;
dataProvider = pTree.dataProvider.createEntry();
dataProvider.setIdentityChangedListener(this);
dataProvider.insertAt(0, iKey, iValue);
init();
setParent(iParent);
pTree.addNodeInMemory(this);
// created entry : force dispatch dirty node.
markDirty();
}
/**
* Called on event of splitting an entry. Copy values from the parent node.
*
* @param iParent
* Parent node
* @param iPosition
* Current position
*/
public OMVRBTreeEntryPersistent(final OMVRBTreeEntry<K, V> iParent, final int iPosition) {
super(((OMVRBTreeEntryPersistent<K, V>) iParent).getTree());
pTree = (OMVRBTreePersistent<K, V>) tree;
OMVRBTreeEntryPersistent<K, V> pParent = (OMVRBTreeEntryPersistent<K, V>) iParent;
dataProvider = pTree.dataProvider.createEntry();
dataProvider.setIdentityChangedListener(this);
dataProvider.copyDataFrom(pParent.dataProvider, iPosition);
if (pParent.dataProvider.truncate(iPosition))
pParent.markDirty();
init();
setParent(pParent);
pTree.addNodeInMemory(this);
// created entry : force dispatch dirty node.
markDirty();
}
public OMVRBTreeEntryDataProvider<K, V> getProvider() {
return dataProvider;
}
/**
* Assures that all the links versus parent, left and right are consistent.
*
*/
public OMVRBTreeEntryPersistent<K, V> save() throws OSerializationException {
if (!dataProvider.isEntryDirty())
return this;
final boolean isNew = dataProvider.getIdentity().isNew();
// FOR EACH NEW LINK, SAVE BEFORE
if (left != null && left.dataProvider.getIdentity().isNew()) {
if (isNew) {
// TEMPORARY INCORRECT SAVE FOR GETTING AN ID. WILL BE SET DIRTY AGAIN JUST AFTER
left.dataProvider.save();
} else
left.save();
}
if (right != null && right.dataProvider.getIdentity().isNew()) {
if (isNew) {
// TEMPORARY INCORRECT SAVE FOR GETTING AN ID. WILL BE SET DIRTY AGAIN JUST AFTER
right.dataProvider.save();
} else
right.save();
}
if (parent != null && parent.dataProvider.getIdentity().isNew()) {
if (isNew) {
// TEMPORARY INCORRECT SAVE FOR GETTING AN ID. WILL BE SET DIRTY AGAIN JUST AFTER
parent.dataProvider.save();
} else
parent.save();
}
dataProvider.save();
// if (parent != null)
// if (!parent.record.getIdentity().equals(parentRid))
// OLogManager.instance().error(this,
// "[save]: Tree node %s has parentRid '%s' different by the rid of the assigned parent node: %s", record.getIdentity(),
// parentRid, parent.record.getIdentity());
checkEntryStructure();
if (pTree.searchNodeInCache(dataProvider.getIdentity()) != this) {
// UPDATE THE CACHE
pTree.addNodeInMemory(this);
}
return this;
}
/**
* Delete all the nodes recursively. IF they are not loaded in memory, load all the tree.
*
* @throws IOException
*/
public OMVRBTreeEntryPersistent<K, V> delete() throws IOException {
if (dataProvider != null) {
pTree.removeNodeFromMemory(this);
pTree.removeEntry(dataProvider.getIdentity());
// EARLY LOAD LEFT AND DELETE IT RECURSIVELY
if (getLeft() != null)
((OMVRBTreeEntryPersistent<K, V>) getLeft()).delete();
// EARLY LOAD RIGHT AND DELETE IT RECURSIVELY
if (getRight() != null)
((OMVRBTreeEntryPersistent<K, V>) getRight()).delete();
// DELETE MYSELF
dataProvider.removeIdentityChangedListener(this);
dataProvider.delete();
clear();
}
return this;
}
/**
* Disconnect the current node from others.
*
* @param iForceDirty
* Force disconnection also if the record it's dirty
* @param iLevel
* @return count of nodes that has been disconnected
*/
protected int disconnect(final boolean iForceDirty, final int iLevel) {
if (dataProvider == null)
// DIRTY NODE, JUST REMOVE IT
return 1;
int totalDisconnected = 0;
final ORID rid = dataProvider.getIdentity();
boolean disconnectedFromParent = false;
if (parent != null) {
// DISCONNECT RECURSIVELY THE PARENT NODE
if (canDisconnectFrom(parent) || iForceDirty) {
if (parent.left == this) {
parent.left = null;
} else if (parent.right == this) {
parent.right = null;
} else
OLogManager.instance().warn(this,
"Node " + rid + " has the parent (" + parent + ") unlinked to itself. It links to " + parent);
totalDisconnected += parent.disconnect(iForceDirty, iLevel + 1);
parent = null;
disconnectedFromParent = true;
}
} else {
disconnectedFromParent = true;
}
boolean disconnectedFromLeft = false;
if (left != null) {
// DISCONNECT RECURSIVELY THE LEFT NODE
if (canDisconnectFrom(left) || iForceDirty) {
if (left.parent == this)
left.parent = null;
else
OLogManager.instance().warn(this,
"Node " + rid + " has the left (" + left + ") unlinked to itself. It links to " + left.parent);
totalDisconnected += left.disconnect(iForceDirty, iLevel + 1);
left = null;
disconnectedFromLeft = true;
}
} else {
disconnectedFromLeft = true;
}
boolean disconnectedFromRight = false;
if (right != null) {
// DISCONNECT RECURSIVELY THE RIGHT NODE
if (canDisconnectFrom(right) || iForceDirty) {
if (right.parent == this)
right.parent = null;
else
OLogManager.instance().warn(this,
"Node " + rid + " has the right (" + right + ") unlinked to itself. It links to " + right.parent);
totalDisconnected += right.disconnect(iForceDirty, iLevel + 1);
right = null;
disconnectedFromRight = true;
}
} else {
disconnectedFromLeft = true;
}
if (disconnectedFromParent && disconnectedFromLeft && disconnectedFromRight)
if ((!dataProvider.isEntryDirty() && !dataProvider.getIdentity().isTemporary() || iForceDirty)
&& !pTree.isNodeEntryPoint(this)) {
totalDisconnected++;
pTree.removeNodeFromMemory(this);
clear();
}
return totalDisconnected;
}
private boolean canDisconnectFrom(OMVRBTreeEntryPersistent<K, V> entry) {
return dataProvider == null || !dataProvider.getIdentity().isNew() && !entry.dataProvider.getIdentity().isNew();
}
protected void clear() {
// SPEED UP MEMORY CLAIM BY RESETTING INTERNAL FIELDS
pTree = null;
tree = null;
dataProvider.removeIdentityChangedListener(this);
dataProvider.clear();
dataProvider = null;
}
/**
* Clear links and current node only if it's not an entry point.
*
* @param iForceDirty
*
* @param iSource
*/
protected int disconnectLinked(final boolean iForce) {
return disconnect(iForce, 0);
}
public int getDepthInMemory() {
int level = 0;
OMVRBTreeEntryPersistent<K, V> entry = this;
while (entry.parent != null) {
level++;
entry = entry.parent;
}
return level;
}
@Override
public int getDepth() {
int level = 0;
OMVRBTreeEntryPersistent<K, V> entry = this;
while (entry.getParent() != null) {
level++;
entry = (OMVRBTreeEntryPersistent<K, V>) entry.getParent();
}
return level;
}
@Override
public OMVRBTreeEntry<K, V> getParent() {
if (dataProvider == null)
return null;
if (parent == null && dataProvider.getParent().isValid()) {
// System.out.println("Node " + record.getIdentity() + " is loading PARENT node " + parentRid + "...");
// LAZY LOADING OF THE PARENT NODE
parent = pTree.loadEntry(null, dataProvider.getParent());
checkEntryStructure();
if (parent != null) {
// TRY TO ASSIGN IT FOLLOWING THE RID
if (parent.dataProvider.getLeft().isValid() && parent.dataProvider.getLeft().equals(dataProvider.getIdentity()))
parent.left = this;
else if (parent.dataProvider.getRight().isValid() && parent.dataProvider.getRight().equals(dataProvider.getIdentity()))
parent.right = this;
else {
OLogManager.instance().error(this, "getParent: Cannot assign node %s to parent. Nodes parent-left=%s, parent-right=%s",
dataProvider.getParent(), parent.dataProvider.getLeft(), parent.dataProvider.getRight());
}
}
}
return parent;
}
@Override
public OMVRBTreeEntry<K, V> setParent(final OMVRBTreeEntry<K, V> iParent) {
if (iParent != parent) {
OMVRBTreeEntryPersistent<K, V> newParent = (OMVRBTreeEntryPersistent<K, V>) iParent;
ORID newParentId = iParent == null ? ORecordId.EMPTY_RECORD_ID : newParent.dataProvider.getIdentity();
parent = newParent;
if (dataProvider.setParent(newParentId))
markDirty();
if (parent != null) {
ORID thisRid = dataProvider.getIdentity();
if (parent.left == this && !parent.dataProvider.getLeft().equals(thisRid))
if (parent.dataProvider.setLeft(thisRid))
parent.markDirty();
if (parent.left != this && parent.dataProvider.getLeft().isValid() && parent.dataProvider.getLeft().equals(thisRid))
parent.left = this;
if (parent.right == this && !parent.dataProvider.getRight().equals(thisRid))
if (parent.dataProvider.setRight(thisRid))
parent.markDirty();
if (parent.right != this && parent.dataProvider.getRight().isValid() && parent.dataProvider.getRight().equals(thisRid))
parent.right = this;
}
}
return iParent;
}
@Override
public OMVRBTreeEntry<K, V> getLeft() {
if (dataProvider == null)
return null;
if (left == null && dataProvider.getLeft().isValid()) {
// LAZY LOADING OF THE LEFT LEAF
left = pTree.loadEntry(this, dataProvider.getLeft());
checkEntryStructure();
}
return left;
}
@Override
public void setLeft(final OMVRBTreeEntry<K, V> iLeft) {
if (iLeft != left) {
OMVRBTreeEntryPersistent<K, V> newLeft = (OMVRBTreeEntryPersistent<K, V>) iLeft;
ORID newLeftId = iLeft == null ? ORecordId.EMPTY_RECORD_ID : newLeft.dataProvider.getIdentity();
left = newLeft;
if (dataProvider.setLeft(newLeftId))
markDirty();
if (left != null && left.parent != this)
left.setParent(this);
checkEntryStructure();
}
}
@Override
public OMVRBTreeEntry<K, V> getRight() {
if (dataProvider == null)
return null;
if (right == null && dataProvider.getRight().isValid()) {
// LAZY LOADING OF THE RIGHT LEAF
right = pTree.loadEntry(this, dataProvider.getRight());
checkEntryStructure();
}
return right;
}
@Override
public void setRight(final OMVRBTreeEntry<K, V> iRight) {
if (iRight != right) {
OMVRBTreeEntryPersistent<K, V> newRight = (OMVRBTreeEntryPersistent<K, V>) iRight;
ORID newRightId = iRight == null ? ORecordId.EMPTY_RECORD_ID : newRight.dataProvider.getIdentity();
right = newRight;
if (dataProvider.setRight(newRightId))
markDirty();
if (right != null && right.parent != this)
right.setParent(this);
checkEntryStructure();
}
}
public void checkEntryStructure() {
if (!tree.isRuntimeCheckEnabled())
return;
if (dataProvider.getParent() == null)
OLogManager.instance().error(this, "checkEntryStructure: Node %s has parentRid null!\n", this);
if (dataProvider.getLeft() == null)
OLogManager.instance().error(this, "checkEntryStructure: Node %s has leftRid null!\n", this);
if (dataProvider.getRight() == null)
OLogManager.instance().error(this, "checkEntryStructure: Node %s has rightRid null!\n", this);
if (this == left || dataProvider.getIdentity().isValid() && dataProvider.getIdentity().equals(dataProvider.getLeft()))
OLogManager.instance().error(this, "checkEntryStructure: Node %s has left that points to itself!\n", this);
if (this == right || dataProvider.getIdentity().isValid() && dataProvider.getIdentity().equals(dataProvider.getRight()))
OLogManager.instance().error(this, "checkEntryStructure: Node %s has right that points to itself!\n", this);
if (left != null && left == right)
OLogManager.instance().error(this, "checkEntryStructure: Node %s has left and right equals!\n", this);
if (left != null) {
if (!left.dataProvider.getIdentity().equals(dataProvider.getLeft()))
OLogManager.instance().error(this, "checkEntryStructure: Wrong left node loaded: " + dataProvider.getLeft());
if (left.parent != this)
OLogManager.instance().error(this,
"checkEntryStructure: Left node is not correctly connected to the parent" + dataProvider.getLeft());
}
if (right != null) {
if (!right.dataProvider.getIdentity().equals(dataProvider.getRight()))
OLogManager.instance().error(this, "checkEntryStructure: Wrong right node loaded: " + dataProvider.getRight());
if (right.parent != this)
OLogManager.instance().error(this,
"checkEntryStructure: Right node is not correctly connected to the parent" + dataProvider.getRight());
}
}
@Override
protected void copyFrom(final OMVRBTreeEntry<K, V> iSource) {
if (dataProvider.copyFrom(((OMVRBTreeEntryPersistent<K, V>) iSource).dataProvider))
markDirty();
}
@Override
protected void insert(final int iIndex, final K iKey, final V iValue) {
K oldKey = iIndex == 0 ? dataProvider.getKeyAt(0) : null;
if (dataProvider.insertAt(iIndex, iKey, iValue))
markDirty();
if (iIndex == 0)
pTree.updateEntryPoint(oldKey, this);
}
@Override
protected void remove() {
final int index = tree.getPageIndex();
final K oldKey = index == 0 ? getKeyAt(0) : null;
if (dataProvider.removeAt(index))
markDirty();
tree.setPageIndex(index - 1);
if (index == 0)
pTree.updateEntryPoint(oldKey, this);
}
@Override
public K getKeyAt(final int iIndex) {
return dataProvider.getKeyAt(iIndex);
}
@Override
protected V getValueAt(final int iIndex) {
return dataProvider.getValueAt(iIndex);
}
/**
* Invalidate serialized Value associated in order to be re-marshalled on the next node storing.
*/
public V setValue(final V iValue) {
V oldValue = getValue();
int index = tree.getPageIndex();
if (dataProvider.setValueAt(index, iValue))
markDirty();
return oldValue;
}
public int getSize() {
return dataProvider != null ? dataProvider.getSize() : 0;
}
public int getPageSize() {
return dataProvider.getPageSize();
}
public int getMaxDepthInMemory() {
return getMaxDepthInMemory(0);
}
private int getMaxDepthInMemory(final int iCurrDepthLevel) {
int depth;
if (left != null)
// GET THE LEFT'S DEPTH LEVEL AS GOOD
depth = left.getMaxDepthInMemory(iCurrDepthLevel + 1);
else
// GET THE CURRENT DEPTH LEVEL AS GOOD
depth = iCurrDepthLevel;
if (right != null) {
int rightDepth = right.getMaxDepthInMemory(iCurrDepthLevel + 1);
if (rightDepth > depth)
depth = rightDepth;
}
return depth;
}
/**
* Returns the successor of the current Entry only by traversing the memory, or null if no such.
*/
@Override
public OMVRBTreeEntryPersistent<K, V> getNextInMemory() {
OMVRBTreeEntryPersistent<K, V> t = this;
OMVRBTreeEntryPersistent<K, V> p = null;
if (t.right != null) {
p = t.right;
while (p.left != null)
p = p.left;
} else {
p = t.parent;
while (p != null && t == p.right) {
t = p;
p = p.parent;
}
}
return p;
}
@Override
public boolean getColor() {
return dataProvider.getColor();
}
@Override
protected void setColor(final boolean iColor) {
if (dataProvider.setColor(iColor))
markDirty();
}
public void markDirty() {
pTree.signalNodeChanged(this);
}
@Override
protected OMVRBTreeEntry<K, V> getLeftInMemory() {
return left;
}
@Override
protected OMVRBTreeEntry<K, V> getParentInMemory() {
return parent;
}
@Override
protected OMVRBTreeEntry<K, V> getRightInMemory() {
return right;
}
public void onIdentityChanged(ORID rid) {
if (left != null) {
if (left.dataProvider.setParent(rid))
left.markDirty();
}
if (right != null) {
if (right.dataProvider.setParent(rid))
right.markDirty();
}
if (parent != null) {
if (parent.left == this) {
if (parent.dataProvider.setLeft(rid))
parent.markDirty();
} else if (parent.right == this) {
if (parent.dataProvider.setRight(rid))
parent.markDirty();
} else {
OLogManager.instance().error(this, "[save]: Tree inconsistent entries.");
}
} else if (pTree.getRoot() == this) {
if (pTree.dataProvider.setRoot(rid))
pTree.markDirty();
}
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.processor.block;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import com.orientechnologies.common.collection.OMultiValue;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.processor.OComposableProcessor;
import com.orientechnologies.orient.core.processor.OProcessException;
import com.orientechnologies.orient.core.record.impl.ODocument;
public class OExecuteBlock extends OAbstractBlock {
@Override
public Object processBlock(OComposableProcessor iManager, final OCommandContext iContext, final ODocument iConfig,
ODocument iOutput, final boolean iReadOnly) {
final Object foreach = getField(iContext, iConfig, "foreach");
String returnType = (String) getFieldOfClass(iContext, iConfig, "returnType", String.class);
Object returnValue = null;
if (returnType == null)
returnType = "last";
else if ("list".equalsIgnoreCase(returnType))
returnValue = new ArrayList<Object>();
else if ("set".equalsIgnoreCase(returnType))
returnValue = new HashSet<Object>();
int iterated = 0;
if (foreach != null) {
Object result;
if (foreach instanceof ODocument)
result = delegate("foreach", iManager, (ODocument) foreach, iContext, iOutput, iReadOnly);
else if (foreach instanceof Map)
result = ((Map<?, ?>) foreach).values();
else
result = foreach;
if (!OMultiValue.isIterable(result))
throw new OProcessException("Result of 'foreach' block (" + foreach + ") must be iterable but found " + result.getClass());
for (Object current : OMultiValue.getMultiValueIterable(result)) {
if (current instanceof Map.Entry)
current = ((Entry<?, ?>) current).getValue();
assignVariable(iContext, "current", current);
debug(iContext, "Executing...");
final Object doClause = getRequiredField(iContext, iConfig, "do");
returnValue = executeDo(iManager, iContext, doClause, returnType, returnValue, iOutput, iReadOnly);
debug(iContext, "Done");
iterated++;
}
} else {
debug(iContext, "Executing...");
final Object doClause = getRequiredField(iContext, iConfig, "do");
returnValue = executeDo(iManager, iContext, doClause, returnType, returnValue, iOutput, iReadOnly);
debug(iContext, "Done");
}
debug(iContext, "Executed %d iteration and returned type %s", iterated, returnType);
return returnValue;
}
private Object executeDo(OComposableProcessor iManager, final OCommandContext iContext, final Object iDoClause,
final String returnType, Object returnValue, ODocument iOutput, final boolean iReadOnly) {
int i = 0;
if (isBlock(iDoClause)) {
returnValue = executeBlock(iManager, iContext, "do", iDoClause, iOutput, iReadOnly, returnType, returnValue);
} else
for (Object item : OMultiValue.getMultiValueIterable(iDoClause)) {
final String blockId = "do[" + i + "]";
returnValue = executeBlock(iManager, iContext, blockId, item, iOutput, iReadOnly, returnType, returnValue);
++i;
}
return returnValue;
}
@SuppressWarnings("unchecked")
private Object executeBlock(OComposableProcessor iManager, final OCommandContext iContext, final String iName,
final Object iValue, ODocument iOutput, final boolean iReadOnly, final String returnType, Object returnValue) {
Boolean merge = iValue instanceof ODocument ? getFieldOfClass(iContext, (ODocument) iValue, "merge", Boolean.class)
: Boolean.FALSE;
if (merge == null)
merge = Boolean.FALSE;
Object result;
if (isBlock(iValue))
// EXECUTE SINGLE BLOCK
result = delegate(iName, iManager, (ODocument) iValue, iContext, iOutput, iReadOnly);
else {
// EXECUTE ENTIRE PROCESS
try {
result = iManager.processFromFile(iName, iContext, iReadOnly);
} catch (Exception e) {
throw new OProcessException("Error on processing '" + iName + "' field of '" + getName() + "' block", e);
}
}
if ("last".equalsIgnoreCase(returnType))
returnValue = result;
else if (result != null && ("list".equalsIgnoreCase(returnType) || "set".equalsIgnoreCase(returnType))) {
if (result instanceof Collection<?> && merge) {
debug(iContext, "Merging content of collection with size %d with the master with size %d",
((Collection<? extends Object>) result).size(), ((Collection<? extends Object>) returnValue).size());
((Collection<Object>) returnValue).addAll((Collection<? extends Object>) result);
} else
((Collection<Object>) returnValue).add(result);
}
return returnValue;
}
@Override
public String getName() {
return "execute";
}
}<file_sep>package com.orientechnologies.common.util;
import java.util.Comparator;
/**
* Compares strings without taking into account their case.
*/
public class OCaseIncentiveComparator implements Comparator<String> {
public int compare(final String stringOne, final String stringTwo) {
return stringOne.toLowerCase().compareTo(stringTwo.toLowerCase());
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.query.nativ;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import com.orientechnologies.orient.core.query.OQueryContext;
import com.orientechnologies.orient.core.query.OQueryHelper;
import com.orientechnologies.orient.core.record.impl.ODocument;
@SuppressWarnings("unchecked")
public class OQueryContextNative extends OQueryContext {
protected Boolean finalResult;
protected Boolean partialResult;
protected Object currentValue;
public OQueryContextNative column(final String iName) {
field(iName);
return this;
}
@Override
public void setRecord(final ODocument iRecord) {
super.setRecord(iRecord);
finalResult = null;
partialResult = null;
currentValue = null;
}
public OQueryContextNative field(final String iName) {
if (finalResult != null && finalResult.booleanValue())
return this;
if (iName == null)
// ERROR: BREAK CHAIN
return error();
final ODocument currentRecord = currentValue != null && currentValue instanceof ODocument ? (ODocument) currentValue
: initialRecord;
currentValue = currentRecord.field(iName);
return this;
}
/**
* Sets as current value the map's value by key.
*
* @param iKey
* Key to use for the lookup
* @return This object to allow fluent expressions in chain.
*/
public OQueryContextNative key(final Object iKey) {
if (finalResult != null && finalResult.booleanValue())
return this;
if (iKey == null)
// ERROR: BREAK CHAIN
return error();
if (currentValue != null && currentValue instanceof Map)
currentValue = ((Map<Object, Object>) currentValue).get(iKey);
return this;
}
/**
* Sets as current value TRUE if the key exists, otherwise FALSE. For Maps and Collections the contains() method is called.
* Against Documents containsField() is invoked.
*
*
* @param iKey
* Key to use for the lookup
* @return This object to allow fluent expressions in chain.
*/
public OQueryContextNative contains(final Object iKey) {
if (finalResult != null && finalResult.booleanValue())
return this;
if (iKey == null)
// ERROR: BREAK CHAIN
return error();
if (currentValue != null)
if (currentValue instanceof Map)
currentValue = ((Map<Object, Object>) currentValue).containsKey(iKey);
else if (currentValue instanceof Collection)
currentValue = ((Collection<Object>) currentValue).contains(iKey);
else if (currentValue instanceof ODocument)
currentValue = ((ODocument) currentValue).containsField(iKey.toString());
return this;
}
/**
* Executes logical AND operator between left and right conditions.
*
* @return This object to allow fluent expressions in chain.
*/
public OQueryContextNative and() {
if (finalResult == null) {
if (partialResult != null && !partialResult)
finalResult = false;
}
return this;
}
/**
* Executes logical OR operator between left and right conditions.
*
* @return This object to allow fluent expressions in chain.
*/
public OQueryContextNative or() {
if (finalResult == null) {
if (partialResult != null && partialResult)
finalResult = true;
}
return this;
}
public OQueryContextNative not() {
if (finalResult == null) {
if (partialResult != null)
partialResult = !partialResult;
}
return this;
}
public OQueryContextNative like(final String iValue) {
if (checkOperator())
partialResult = OQueryHelper.like(currentValue.toString(), iValue);
return this;
}
public OQueryContextNative matches(final Object iValue) {
if (checkOperator())
partialResult = currentValue.toString().matches(iValue.toString());
return this;
}
public OQueryContextNative eq(final Object iValue) {
if (checkOperator())
partialResult = currentValue.equals(iValue);
return this;
}
public OQueryContextNative different(final Object iValue) {
if (checkOperator())
partialResult = !currentValue.equals(iValue);
return this;
}
public OQueryContextNative between(final Object iFrom, final Object iTo) {
if (checkOperator())
partialResult = ((Comparable<Object>) currentValue).compareTo(iFrom) >= 0
&& ((Comparable<Object>) currentValue).compareTo(iTo) <= 0;
return this;
}
public OQueryContextNative minor(final Object iValue) {
if (checkOperator())
partialResult = ((Comparable<Object>) currentValue).compareTo(iValue) < 0;
return this;
}
public OQueryContextNative minorEq(final Object iValue) {
if (checkOperator())
partialResult = ((Comparable<Object>) currentValue).compareTo(iValue) <= 0;
return this;
}
public OQueryContextNative major(final Object iValue) {
if (checkOperator())
partialResult = ((Comparable<Object>) currentValue).compareTo(iValue) > 0;
return this;
}
public OQueryContextNative majorEq(final Object iValue) {
if (checkOperator())
partialResult = ((Comparable<Object>) currentValue).compareTo(iValue) >= 0;
return this;
}
public OQueryContextNative toInt() {
if (checkOperator())
currentValue = Integer.valueOf(currentValue.toString());
return this;
}
public OQueryContextNative toLong() {
if (checkOperator())
currentValue = Long.valueOf(currentValue.toString());
return this;
}
public OQueryContextNative toFloat() {
if (checkOperator())
currentValue = Float.valueOf(currentValue.toString());
return this;
}
public OQueryContextNative toDouble() {
if (checkOperator())
currentValue = Double.valueOf(currentValue.toString());
return this;
}
public OQueryContextNative toChar() {
if (checkOperator())
currentValue = currentValue.toString().charAt(0);
return this;
}
public OQueryContextNative toDate() {
if (checkOperator())
currentValue = new Date(Long.valueOf(currentValue.toString()));
return this;
}
public boolean go() {
return finalResult != null ? finalResult : partialResult != null ? partialResult : false;
}
protected boolean checkOperator() {
if (finalResult != null)
return false;
if (currentValue == null) {
finalResult = false;
return false;
}
return true;
}
/**
* Breaks the chain.
*/
protected OQueryContextNative error() {
currentValue = null;
finalResult = Boolean.FALSE;
partialResult = null;
return this;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.hazelcast.sharding;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.command.OCommandManager;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.sql.*;
import com.orientechnologies.orient.core.storage.OStorageEmbedded;
import com.orientechnologies.orient.server.hazelcast.sharding.hazelcast.ServerInstance;
/**
* Factory that determines and returns valid OQueryExecutor class instance based on query
*
* @author edegtyarenko
* @since 25.10.12 8:11
*/
public class OQueryExecutorsFactory {
public static final OQueryExecutorsFactory INSTANCE = new OQueryExecutorsFactory();
private static final Set<Class> ALWAYS_DISTRIBUTABLE = new HashSet<Class>(Arrays.<Class> asList(
OCommandExecutorSQLCreateClass.class,// int
OCommandExecutorSQLAlterClass.class,// null
OCommandExecutorSQLTruncateClass.class,// long
OCommandExecutorSQLDropClass.class,// boolean
OCommandExecutorSQLCreateCluster.class,// int
OCommandExecutorSQLAlterCluster.class,// null
OCommandExecutorSQLTruncateCluster.class,// long
OCommandExecutorSQLDropCluster.class,// boolean
OCommandExecutorSQLCreateProperty.class,// int
OCommandExecutorSQLAlterProperty.class,// null
OCommandExecutorSQLDropProperty.class,// null
OCommandExecutorSQLCreateIndex.class,// long
OCommandExecutorSQLRebuildIndex.class,// long
OCommandExecutorSQLDropIndex.class// null
));
private OQueryExecutorsFactory() {
}
public OQueryExecutor getExecutor(OCommandRequestText iCommand, OStorageEmbedded wrapped, ServerInstance serverInstance,
Set<Integer> undistributedClusters) {
final OCommandExecutor executorDelegate = OCommandManager.instance().getExecutor(iCommand);
executorDelegate.parse(iCommand);
final OCommandExecutor actualExecutor = executorDelegate instanceof OCommandExecutorSQLDelegate ? ((OCommandExecutorSQLDelegate) executorDelegate)
.getDelegate() : executorDelegate;
if (actualExecutor instanceof OCommandExecutorSQLSelect) {
final OCommandExecutorSQLSelect selectExecutor = (OCommandExecutorSQLSelect) actualExecutor;
if (isSelectDistributable(selectExecutor, undistributedClusters)) {
return new ODistributedSelectQueryExecutor(iCommand, selectExecutor, wrapped, serverInstance);
} else {
return new OLocalQueryExecutor(iCommand, wrapped);
}
} else {
if (isCommandDistributable(actualExecutor)) {
return new ODistributedQueryExecutor(iCommand, wrapped, serverInstance);
} else {
return new OLocalQueryExecutor(iCommand, wrapped);
}
}
}
private static boolean isSelectDistributable(OCommandExecutorSQLSelect selectExecutor, Set<Integer> undistributedClusters) {
for (Integer c : selectExecutor.getInvolvedClusters()) {
if (undistributedClusters.contains(c)) {
return false;
}
}
return true;
}
private static boolean isCommandDistributable(OCommandExecutor executor) {
return ALWAYS_DISTRIBUTABLE.contains(executor.getClass());
}
}
<file_sep>package com.orientechnologies.orient.core.storage.impl.local;
import com.orientechnologies.common.serialization.OBinaryConverter;
import com.orientechnologies.common.serialization.OBinaryConverterFactory;
import com.orientechnologies.orient.core.id.OClusterPositionNodeId;
import com.orientechnologies.orient.core.id.ONodeId;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
import com.orientechnologies.orient.core.version.ORecordVersion;
import com.orientechnologies.orient.core.version.OVersionFactory;
/**
* @author <NAME>
* @since 26.07.12
*/
public final class OClusterLocalLHPEBucket {
private static final OBinaryConverter CONVERTER = OBinaryConverterFactory.getConverter();
private static final boolean nativeAcceleration = CONVERTER.nativeAccelerationUsed();
public static final int BUCKET_CAPACITY = 64;
private static final int VALUE_SIZE = 13 + OVersionFactory.instance().getVersionSize();
private static final int KEY_SIZE = 192;
private static final int BUCKET_SIZE_SIZE = 1;
private static final int OVERFLOW_BUCKET_SIZE = 8;
public static final int BUCKET_SIZE_IN_BYTES = BUCKET_CAPACITY * (KEY_SIZE + VALUE_SIZE) + BUCKET_SIZE_SIZE
+ OVERFLOW_BUCKET_SIZE;
private static final int OVERFLOW_POS = BUCKET_CAPACITY * (KEY_SIZE + VALUE_SIZE) + BUCKET_SIZE_SIZE;
private static final int FIRST_VALUE_POS = BUCKET_CAPACITY * KEY_SIZE + BUCKET_SIZE_SIZE;
private byte[] buffer;
private long overflowBucketIndex = -2;
private final ONodeId[] keys = new ONodeId[BUCKET_CAPACITY];
private final OPhysicalPosition[] positions = new OPhysicalPosition[BUCKET_CAPACITY];
private final boolean[] positionsToUpdate = new boolean[BUCKET_CAPACITY];
private final boolean[] keysToUpdate = new boolean[BUCKET_CAPACITY];
private boolean overflowWasChanged;
private final OClusterLocalLHPEPS clusterLocal;
private final long position;
private final boolean isOverflowBucket;
public OClusterLocalLHPEBucket(byte[] buffer, final OClusterLocalLHPEPS clusterLocal, final long position,
final boolean overflowBucket) {
this.buffer = buffer;
this.clusterLocal = clusterLocal;
this.position = position;
this.isOverflowBucket = overflowBucket;
}
public OClusterLocalLHPEBucket(final OClusterLocalLHPEPS clusterLocal, final long position, final boolean overflowBucket) {
this.buffer = new byte[BUCKET_SIZE_IN_BYTES];
this.clusterLocal = clusterLocal;
this.position = position;
this.isOverflowBucket = overflowBucket;
}
public long getFilePosition() {
return position;
}
public int getSize() {
return buffer[0];
}
public boolean isOverflowBucket() {
return isOverflowBucket;
}
public long getOverflowBucket() {
if (nativeAcceleration)
return CONVERTER.getLong(buffer, OVERFLOW_POS) - 1;
if (overflowBucketIndex != -2)
return overflowBucketIndex;
overflowBucketIndex = CONVERTER.getLong(buffer, OVERFLOW_POS) - 1;
return overflowBucketIndex;
}
public void addPhysicalPosition(OPhysicalPosition physicalPosition) {
int index = buffer[0];
setKey(((OClusterPositionNodeId) physicalPosition.clusterPosition).getNodeId(), index);
positions[index] = physicalPosition;
buffer[0]++;
positionsToUpdate[index] = true;
addToStoreList();
}
public void removePhysicalPosition(int index) {
// buffer[0]--;
//
// if (buffer[0] > 0) {
// setKey(getKey(buffer[0]), index);
// positions[index] = getPhysicalPosition(buffer[0]);
//
// keysToUpdate[index] = true;
// positionsToUpdate[index] = true;
// }
//
// addToStoreList();
}
public void setOverflowBucket(long overflowBucket) {
if (nativeAcceleration) {
CONVERTER.putLong(buffer, OVERFLOW_POS, overflowBucket + 1);
addToStoreList();
return;
}
this.overflowBucketIndex = overflowBucket;
overflowWasChanged = true;
addToStoreList();
}
public long getKey(int index) {
// if (nativeAcceleration)
// return CONVERTER.getLong(buffer, index * KEY_SIZE + BUCKET_SIZE_SIZE);
//
// long result = keys[index];
//
// if (result > -1)
// return result;
//
// result = CONVERTER.getLong(buffer, index * KEY_SIZE + BUCKET_SIZE_SIZE);
//
// keys[index] = result;
//
return -1;
}
public OPhysicalPosition getPhysicalPosition(int index) {
OPhysicalPosition physicalPosition = positions[index];
if (physicalPosition != null)
return physicalPosition;
physicalPosition = new OPhysicalPosition();
int position = BUCKET_SIZE_SIZE + BUCKET_CAPACITY * KEY_SIZE + VALUE_SIZE * index;
// physicalPosition.clusterPosition = getKey(index);
physicalPosition.dataSegmentId = CONVERTER.getInt(buffer, position);
position += 4;
physicalPosition.dataSegmentPos = CONVERTER.getLong(buffer, position);
position += 8;
physicalPosition.recordType = buffer[position];
position += 1;
physicalPosition.recordVersion.getSerializer().fastReadFrom(buffer, position, physicalPosition.recordVersion);
return physicalPosition;
}
public static int getDataSegmentIdOffset(int index) {
return FIRST_VALUE_POS + index * VALUE_SIZE;
}
public static byte[] serializeDataSegmentId(int dataSegmentId) {
final byte[] serializedDataSegmentId = new byte[4];
CONVERTER.putInt(serializedDataSegmentId, 0, dataSegmentId);
return serializedDataSegmentId;
}
public static byte[] serializeDataPosition(long dataPosition) {
final byte[] serializedDataPosition = new byte[8];
CONVERTER.putLong(serializedDataPosition, 0, dataPosition);
return serializedDataPosition;
}
public static int getRecordTypeOffset(int index) {
return FIRST_VALUE_POS + index * VALUE_SIZE + 12;
}
public static int getVersionOffset(int index) {
return FIRST_VALUE_POS + index * VALUE_SIZE + 13;
}
public static byte[] serializeVersion(ORecordVersion version) {
return version.getSerializer().toByteArray(version);
}
public byte[] getBuffer() {
return buffer;
}
public void serialize() {
int position = 1;
int size = buffer[0];
if (!nativeAcceleration)
for (int i = 0; i < size; i++) {
if (keysToUpdate[i]) {
// CONVERTER.putLong(buffer, position, keys[i]);
keysToUpdate[i] = false;
}
position += KEY_SIZE;
}
position = FIRST_VALUE_POS;
for (int i = 0; i < size; i++) {
if (positionsToUpdate[i]) {
OPhysicalPosition physicalPosition = positions[i];
CONVERTER.putInt(buffer, position, physicalPosition.dataSegmentId);
position += 4;
CONVERTER.putLong(buffer, position, physicalPosition.dataSegmentPos);
position += 8;
buffer[position] = physicalPosition.recordType;
position += 1;
position += physicalPosition.recordVersion.getSerializer().fastWriteTo(
buffer, position, physicalPosition.recordVersion);
positionsToUpdate[i] = false;
} else
position += VALUE_SIZE;
}
if (overflowWasChanged)
CONVERTER.putLong(buffer, OVERFLOW_POS, overflowBucketIndex + 1);
}
private void setKey(final ONodeId key, int index) {
// if (nativeAcceleration) {
// CONVERTER.putLong(buffer, index * KEY_SIZE + BUCKET_SIZE_SIZE, key);
// } else {
// keys[index] = key;
// keysToUpdate[index] = true;
// }
}
private void addToStoreList() {
if (isOverflowBucket)
clusterLocal.addToOverflowStoreList(this);
else
clusterLocal.addToMainStoreList(this);
}
}
<file_sep>package com.orientechnologies.orient.server.handler;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimerTask;
import com.orientechnologies.common.io.OIOUtils;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.parser.OSystemVariableResolver;
import com.orientechnologies.common.parser.OVariableParser;
import com.orientechnologies.common.parser.OVariableParserListener;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandOutputListener;
import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.tool.ODatabaseExport;
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerMain;
import com.orientechnologies.orient.server.config.OServerParameterConfiguration;
public class OAutomaticBackup extends OServerHandlerAbstract {
public enum VARIABLES {
DBNAME, DATE
}
private Date firstTime = null;
private long delay = -1;
private String targetDirectory = "backup";
private String targetFileName;
private Set<String> includeDatabases = new HashSet<String>();
private Set<String> excludeDatabases = new HashSet<String>();
@Override
public void config(final OServer iServer, final OServerParameterConfiguration[] iParams) {
for (OServerParameterConfiguration param : iParams) {
if (param.name.equalsIgnoreCase("enabled")) {
if (!Boolean.parseBoolean(param.value))
// DISABLE IT
return;
} else if (param.name.equalsIgnoreCase("delay"))
delay = OIOUtils.getTimeAsMillisecs(param.value);
else if (param.name.equalsIgnoreCase("firsttime")) {
try {
firstTime = OIOUtils.getTodayWithTime(param.value);
} catch (ParseException e) {
throw new OConfigurationException("Parameter 'firstTime' has invalid format, expected: HH:mm:ss", e);
}
} else if (param.name.equalsIgnoreCase("target.directory"))
targetDirectory = param.value;
else if (param.name.equalsIgnoreCase("db.include") && param.value.trim().length() > 0)
for (String db : param.value.split(","))
includeDatabases.add(db);
else if (param.name.equalsIgnoreCase("db.exclude") && param.value.trim().length() > 0)
for (String db : param.value.split(","))
excludeDatabases.add(db);
else if (param.name.equalsIgnoreCase("target.fileName"))
targetFileName = param.value;
}
if (delay <= 0)
throw new OConfigurationException("Cannot find mandatory parameter 'delay'");
if (!targetDirectory.endsWith("/"))
targetDirectory += "/";
final File filePath = new File(targetDirectory);
if (filePath.exists()) {
if (!filePath.isDirectory())
throw new OConfigurationException("Parameter 'path' points to a file, not a directory");
} else
// CREATE BACKUP FOLDER(S) IF ANY
filePath.mkdirs();
OLogManager.instance().info(this, "Automatic backup plugin installed and active: delay=%dms, firstTime=%s, targetDirectory=%s",
delay, firstTime, targetDirectory);
final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
OLogManager.instance().info(this, "[OAutomaticBackup] Scanning databases to backup...");
int ok = 0, errors = 0;
final Map<String, String> databaseNames = OServerMain.server().getAvailableStorageNames();
for (final Entry<String, String> dbName : databaseNames.entrySet()) {
boolean include;
if (includeDatabases.size() > 0)
include = includeDatabases.contains(dbName.getKey());
else
include = true;
if (excludeDatabases.contains(dbName.getKey()))
include = false;
if (include) {
final String fileName = (String) OVariableParser.resolveVariables(targetFileName, OSystemVariableResolver.VAR_BEGIN,
OSystemVariableResolver.VAR_END, new OVariableParserListener() {
@Override
public String resolve(final String iVariable) {
if (iVariable.equalsIgnoreCase(VARIABLES.DBNAME.toString()))
return dbName.getKey();
else if (iVariable.startsWith(VARIABLES.DATE.toString())) {
return new SimpleDateFormat(iVariable.substring(VARIABLES.DATE.toString().length() + 1)).format(new Date());
}
// NOT FOUND
throw new IllegalArgumentException("Variable '" + iVariable + "' wasn't found");
}
});
final String exportFilePath = targetDirectory + fileName;
ODatabaseDocumentTx db = null;
try {
db = new ODatabaseDocumentTx(dbName.getValue());
db.setProperty(ODatabase.OPTIONS.SECURITY.toString(), Boolean.FALSE);
db.open("admin", "aaa");
final long begin = System.currentTimeMillis();
new ODatabaseExport(db, exportFilePath, new OCommandOutputListener() {
@Override
public void onMessage(final String iText) {
}
}).exportDatabase();
OLogManager.instance().info(
this,
"[OAutomaticBackup] - Backup of database '" + dbName.getValue() + "' completed in "
+ (System.currentTimeMillis() - begin) + "ms");
ok++;
} catch (Exception e) {
OLogManager.instance().error(this,
"[OAutomaticBackup] - Error on exporting database '" + dbName.getValue() + "' to file: " + exportFilePath, e);
errors++;
} finally {
if (db != null)
db.close();
}
}
}
OLogManager.instance().info(this, "[OAutomaticBackup] Backup finished: %d ok, %d errors", ok, errors);
}
};
if (firstTime == null)
Orient.getTimer().schedule(timerTask, delay, delay);
else
Orient.getTimer().schedule(timerTask, firstTime, delay);
}
@Override
public String getName() {
return "automaticBackup";
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.storage.fs;
/**
* @author <NAME> (logart) <EMAIL> Date: 5/17/12 Time: 5:24 PM
* <p/>
* This is universal MMapManager interface. If you would like implement your version of mmap manager, you should implement
* this interface.
*/
public interface OMMapManager {
/**
* This method used to initialize manager after creation. Constructor should be empty. Init method is called after creation an
* manager so you can do all initialization steps in this method.
*/
void init();
/**
* Types of operation on files that was mmapped.
*/
public enum OPERATION_TYPE {
READ, WRITE
}
/**
* Strategy that determine how mmap should work.
*/
public enum ALLOC_STRATEGY {
MMAP_ALWAYS, MMAP_WRITE_ALWAYS_READ_IF_AVAIL_POOL, MMAP_WRITE_ALWAYS_READ_IF_IN_MEM, MMAP_ONLY_AVAIL_POOL, MMAP_NEVER
}
/**
* This method tries to mmap file. If mapping is impossible method returns null.
*
* @param iFile
* file that will be mmapped.
* @param iBeginOffset
* position in file that should be mapped.
* @param iSize
* size that should be mapped.
* @param iOperationType
* operation (read/write) that will be performed on file.
* @param iStrategy
* allocation strategy. @see com.orientechnologies.orient.core.storage.fs.OMMapManager.ALLOC_STRATEGY
* @return array of entries that represent mapped files as byte buffers. Or null on error.
*/
OMMapBufferEntry[] acquire(OFileMMap iFile, long iBeginOffset, int iSize, OPERATION_TYPE iOperationType, ALLOC_STRATEGY iStrategy);
/**
* This method call unlock on all mapped entries from array.
*
* @param entries
* that will be unlocked.
*/
void release(OMMapBufferEntry[] entries, OPERATION_TYPE operationType);
/**
* This method should flush all the records in all files on disk.
*/
void flush();
/**
* This method close file flush it's content and remove information about file from manager.
*
* @param iFile
* that will be removed
*/
void removeFile(OFileMMap iFile);
/**
* This method is the same as flush but on single file. This method store all file content on disk from memory to prevent data
* loosing.
*
* @param iFile
* that will be flushed.
*/
void flushFile(OFileMMap iFile);
/**
* This method flush all files and clear information about mmap from itself.
*/
void shutdown();
}
<file_sep>service.id=OrientDB
service.name=OrientDB Server
service.description=OrientDB Server instance. For more information goto: http://www.orientechnologies.com
classpath.1=../lib/*
main.class=com.orientechnologies.orient.server.OServerMain
vm.version.min=1.6
vmarg.1=-Dorient.config.file=../config/orientdb-server-config.xml
vmarg.2=-Dorient.www.path=../www
vmarg.3=-Dorient.log.level=warning
vmarg.4=-Djava.util.logging.config.file=../config/orientdb-server-log.properties
vmarg.5=-DORIENTDB_HOME=..<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.storage.fs;
import java.io.IOException;
import com.orientechnologies.common.factory.ODynamicFactory;
import com.orientechnologies.orient.core.exception.OConfigurationException;
/**
* OFile factory. To register 3rd party implementations use: OFileFactory.instance().register(<name>, <class>);
*
* @author Luca
*
*/
public class OFileFactory extends ODynamicFactory<String, Class<? extends OFile>> {
public static final String MMAP = "mmap";
public static final String CLASSIC = "classic";
protected static final OFileFactory instance = new OFileFactory();
public OFileFactory() {
register(MMAP, OFileMMap.class);
register(CLASSIC, OFileClassic.class);
}
public OFile create(final String iType, final String iFileName, final String iOpenMode) throws IOException {
final Class<? extends OFile> fileClass = registry.get(iType);
if (fileClass == null)
throw new OConfigurationException("File type '" + iType + "' is not configured");
try {
final OFile f = fileClass.newInstance();
f.init(iFileName, iOpenMode);
return f;
} catch (final Exception e) {
throw new OConfigurationException("Cannot create file of type '" + iType + "'", e);
}
}
public static OFileFactory instance() {
return instance;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.db.record;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.record.ORecord;
/**
* Implementation of LinkedHashMap bound to a source ORecord object to keep track of changes. This avoid to call the makeDirty() by
* hand when the map is changed.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*
*/
@SuppressWarnings("serial")
public class OTrackedMap<T> extends LinkedHashMap<Object, T> implements ORecordElement, OTrackedMultiValue<Object, T>, Serializable {
final protected ORecord<?> sourceRecord;
private STATUS status = STATUS.NOT_LOADED;
private Set<OMultiValueChangeListener<Object, T>> changeListeners = Collections
.newSetFromMap(new WeakHashMap<OMultiValueChangeListener<Object, T>, Boolean>());
protected Class<?> genericClass;
public OTrackedMap(final ORecord<?> iRecord, final Map<Object, T> iOrigin, final Class<?> cls) {
this(iRecord);
genericClass = cls;
if (iOrigin != null && !iOrigin.isEmpty())
putAll(iOrigin);
}
public OTrackedMap(final ORecord<?> iSourceRecord) {
this.sourceRecord = iSourceRecord;
}
@Override
public T put(final Object iKey, final T iValue) {
boolean containsKey = containsKey(iKey);
T oldValue = super.put(iKey, iValue);
if (containsKey && oldValue == iValue)
return oldValue;
if (containsKey)
fireCollectionChangedEvent(new OMultiValueChangeEvent<Object, T>(OMultiValueChangeEvent.OChangeType.UPDATE, iKey, iValue,
oldValue));
else
fireCollectionChangedEvent(new OMultiValueChangeEvent<Object, T>(OMultiValueChangeEvent.OChangeType.ADD, iKey, iValue));
return oldValue;
}
@Override
public T remove(final Object iKey) {
boolean containsKey = containsKey(iKey);
final T oldValue = super.remove(iKey);
if (containsKey)
fireCollectionChangedEvent(new OMultiValueChangeEvent<Object, T>(OMultiValueChangeEvent.OChangeType.REMOVE, iKey, null,
oldValue));
return oldValue;
}
@Override
public void clear() {
final Map<Object, T> origValues;
if (changeListeners.isEmpty())
origValues = null;
else
origValues = new HashMap<Object, T>(this);
super.clear();
if (origValues != null) {
for (Map.Entry<Object, T> entry : origValues.entrySet())
fireCollectionChangedEvent(new OMultiValueChangeEvent<Object, T>(OMultiValueChangeEvent.OChangeType.REMOVE, entry.getKey(),
null, entry.getValue()));
} else
setDirty();
}
@Override
public void putAll(Map<? extends Object, ? extends T> m) {
super.putAll(m);
}
@SuppressWarnings({ "unchecked" })
public OTrackedMap<T> setDirty() {
if (status != STATUS.UNMARSHALLING && sourceRecord != null && !sourceRecord.isDirty())
sourceRecord.setDirty();
return this;
}
public void onBeforeIdentityChanged(final ORID iRID) {
remove(iRID);
}
@SuppressWarnings("unchecked")
public void onAfterIdentityChanged(final ORecord<?> iRecord) {
super.put(iRecord.getIdentity(), (T) iRecord);
}
public STATUS getInternalStatus() {
return status;
}
public void setInternalStatus(final STATUS iStatus) {
status = iStatus;
}
public void addChangeListener(OMultiValueChangeListener<Object, T> changeListener) {
changeListeners.add(changeListener);
}
public void removeRecordChangeListener(OMultiValueChangeListener<Object, T> changeListener) {
changeListeners.remove(changeListener);
}
public Map<Object, T> returnOriginalState(final List<OMultiValueChangeEvent<Object, T>> multiValueChangeEvents) {
final Map<Object, T> reverted = new HashMap<Object, T>(this);
final ListIterator<OMultiValueChangeEvent<Object, T>> listIterator = multiValueChangeEvents.listIterator(multiValueChangeEvents
.size());
while (listIterator.hasPrevious()) {
final OMultiValueChangeEvent<Object, T> event = listIterator.previous();
switch (event.getChangeType()) {
case ADD:
reverted.remove(event.getKey());
break;
case REMOVE:
reverted.put(event.getKey(), event.getOldValue());
break;
case UPDATE:
reverted.put(event.getKey(), event.getOldValue());
break;
default:
throw new IllegalArgumentException("Invalid change type : " + event.getChangeType());
}
}
return reverted;
}
protected void fireCollectionChangedEvent(final OMultiValueChangeEvent<Object, T> event) {
if (status == STATUS.UNMARSHALLING)
return;
setDirty();
for (final OMultiValueChangeListener<Object, T> changeListener : changeListeners) {
if (changeListener != null)
changeListener.onAfterRecordChanged(event);
}
}
public Class<?> getGenericClass() {
return genericClass;
}
public void setGenericClass(Class<?> genericClass) {
this.genericClass = genericClass;
}
private Object writeReplace() {
return new LinkedHashMap<Object, T>(this);
}
}
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.id;
/**
*
* 192 bit signed presentation of {@link OClusterPosition} instance. With values from -2<sup>192</sup>+1 till 2<sup>192</sup>-1. It
* is based on {@link ONodeId} class so conversion from nodeid to cluster position for autosharded storage is pretty simple task.
*
* @author <NAME>
* @since 12.11.12
*/
public final class OClusterPositionNodeId extends OClusterPosition {
private static final ONodeId INVALID_NODE_ID = ONodeId.valueOf(-1);
private final ONodeId nodeId;
public ONodeId getNodeId() {
return nodeId;
}
public OClusterPositionNodeId(ONodeId nodeId) {
this.nodeId = nodeId;
}
@Override
public OClusterPosition inc() {
return new OClusterPositionNodeId(nodeId.add(ONodeId.ONE));
}
@Override
public OClusterPosition dec() {
return new OClusterPositionNodeId(nodeId.subtract(ONodeId.ONE));
}
@Override
public boolean isValid() {
return !nodeId.equals(INVALID_NODE_ID);
}
@Override
public boolean isPersistent() {
return nodeId.compareTo(INVALID_NODE_ID) > 0;
}
@Override
public boolean isNew() {
return nodeId.compareTo(ONodeId.ZERO) < 0;
}
@Override
public boolean isTemporary() {
return nodeId.compareTo(INVALID_NODE_ID) < 0;
}
@Override
public byte[] toStream() {
return nodeId.toStream();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
OClusterPositionNodeId that = (OClusterPositionNodeId) o;
return nodeId.equals(that.nodeId);
}
@Override
public int hashCode() {
return nodeId.hashCode();
}
@Override
public String toString() {
return nodeId.toString();
}
@Override
public int compareTo(OClusterPosition o) {
final OClusterPositionNodeId clusterPositionNodeId = (OClusterPositionNodeId) o;
return nodeId.compareTo(clusterPositionNodeId.getNodeId());
}
@Override
public int intValue() {
return nodeId.intValue();
}
@Override
public long longValue() {
return nodeId.longValue();
}
@Override
public float floatValue() {
return nodeId.floatValue();
}
@Override
public double doubleValue() {
return nodeId.doubleValue();
}
}
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.test.internal.index;
import com.orientechnologies.common.concur.ONeedRetryException;
import com.orientechnologies.orient.client.db.ODatabaseHelper;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
/**
* @author <NAME>
* @since 03.06.12
*/
class PersonTree {
public ODocument root;
public Map<ORID, ODocument> elements = new HashMap<ORID, ODocument>();
ODocument AddRoot(String name, String identifier) {
root = new ODocument("Person").field("name", name).field("identifier", identifier).field("in", new HashSet<ODocument>())
.field("out", new HashSet<ODocument>());
root.save();
elements.put(root.getIdentity(), root);
return root;
}
void SetRoot(ODocument doc) {
root = doc;
root.save();
elements.put(root.getIdentity(), root);
}
ODocument AddChild(ODocument parent, String name, String identifier) {
ODocument child = new ODocument("Person").field("name", name).field("identifier", identifier)
.field("in", new HashSet<ODocument>()).field("out", new HashSet<ODocument>());
child.save();
elements.put(child.getIdentity(), child);
ODocument edge = new ODocument("OGraphEdge").field("in", parent.getIdentity()).field("out", child.getIdentity());
edge.save();
elements.put(edge.getIdentity(), edge);
child.<Collection<ODocument>> field("in").add(edge);
parent.<Collection<ODocument>> field("out").add(edge);
return child;
}
}
public class IndexConcurrencyTest {
static final int subnodes = 3;
static final int depth = 3;
static final String url = "remote:localhost/demo";
public static boolean checkIndexConsistency(ODatabaseDocumentTx db) {
Map<String, ODocument> persons = new HashMap<String, ODocument>();
Map<String, ORID> indexPersons = new HashMap<String, ORID>();
final List<ODocument> result = db.command(new OCommandSQL("select from cluster:Person")).execute();
for (ODocument d : result) {
persons.put((String) d.field("name"), d);
}
final List<ODocument> indexResult = db.command(new OCommandSQL("select from index:Person.name")).execute();
for (ODocument d : indexResult) {
d.setLazyLoad(false);
indexPersons.put((String) d.field("key"), (ORID) d.field("rid"));
}
System.out.println("PersonCount: " + persons.size() + ", IndexCount: " + indexPersons.size());
boolean missing = false;
for (Map.Entry<String, ODocument> e : persons.entrySet()) {
if (!indexPersons.containsKey(e.getKey())) {
System.out.println("Key found in cluster but not in index: " + e.getValue() + " key: " + e.getKey());
missing = true;
}
}
for (Map.Entry<String, ORID> e : indexPersons.entrySet()) {
if (!persons.containsKey(e.getKey())) {
System.out.println("Key found in index but not in cluster: " + e.getValue() + " key: " + e.getKey());
missing = true;
}
}
return persons.size() == indexPersons.size() && !missing;
}
public static void buildTree(PersonTree tree, ORID rid, String name, int childCount, int level, char startLetter) {
if (level == 0)
return;
for (int i = 0; i < childCount; i++) {
String newName = name;
newName += Character.toString((char) (startLetter + i));
StringBuilder newIdentifier = new StringBuilder(newName);
newIdentifier.setCharAt(0, 'B');
ODocument child = tree.AddChild(tree.elements.get(rid), newName, newIdentifier.toString());
buildTree(tree, child.getIdentity(), newName, childCount, level - 1, startLetter);
}
}
public static void addSubTree(String parentName, char startLetter) {
ODatabaseDocumentTx db = new ODatabaseDocumentTx(url).open("admin", "admin");
for (int i = 0;; ++i) {
try {
ODocument parent;
final List<ODocument> result = db.command(new OCommandSQL("select from Person where name = '" + parentName + "'"))
.execute();
parent = result.get(0);
if (parent == null) {
db.close();
return;
}
String newName = parentName;
newName += Character.toString(startLetter);
StringBuilder newIdentifier = new StringBuilder(newName);
newIdentifier.setCharAt(0, 'B');
db.begin();
PersonTree tree = new PersonTree();
tree.SetRoot(parent);
ODocument child = tree.AddChild(parent, newName, newIdentifier.toString());
buildTree(tree, child.getIdentity(), newName, subnodes, depth - 1, startLetter);
db.commit();
break;
} catch (ONeedRetryException e) {
System.out.println("Concurrency change, retry " + i);
} catch (Exception ex) {
ex.printStackTrace();
}
}
// printPersons("After addSubTree", db);
db.close();
}
public static class AddThread implements Runnable {
String m_name;
char m_startLetter;
Thread t;
AddThread(String name, char startLetter) {
m_name = name;
m_startLetter = startLetter;
t = new Thread(this);
t.start();
}
public void run() {
addSubTree(m_name, m_startLetter);
}
}
public static void deleteSubTree(String parentName) {
ODatabaseDocumentTx db = new ODatabaseDocumentTx(url).open("admin", "admin");
for (int i = 0;; ++i) {
try {
final List<ODocument> result = db.command(new OCommandSQL("select from Person where name = '" + parentName + "'"))
.execute();
ODocument parent = result.get(0);
if (parent == null) {
db.close();
return;
}
db.begin();
Collection<ODocument> out = parent.field("out");
if (out.size() > 0) {
ODocument edge = out.iterator().next();
if (edge != null) {
out.remove(edge);
final List<ODocument> result2 = db.command(new OCommandSQL("traverse out from " + edge.getIdentity())).execute();
for (ODocument d : result2) {
db.delete(d);
}
}
}
parent.save();
db.commit();
break;
} catch (ONeedRetryException e) {
System.out.println("Concurrency change, retry " + i);
} catch (Exception ex) {
ex.printStackTrace();
}
}
db.close();
}
public static class DeleteThread implements Runnable {
String m_name;
Thread t;
DeleteThread(String name) {
m_name = name;
t = new Thread(this);
t.start();
}
public void run() {
deleteSubTree(m_name);
}
}
public static void main(String[] args) {
OGlobalConfiguration.CACHE_LEVEL1_ENABLED.setValue(false);
OGlobalConfiguration.CACHE_LEVEL1_SIZE.setValue(0);
OGlobalConfiguration.CACHE_LEVEL2_ENABLED.setValue(false);
OGlobalConfiguration.CACHE_LEVEL2_SIZE.setValue(0);
int tries = 20;
for (int cnt = 0; cnt < tries; cnt++) {
// SETUP DB
try {
ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
System.out.println("Recreating database");
if (ODatabaseHelper.existsDatabase(db)) {
db.setProperty("security", Boolean.FALSE);
ODatabaseHelper.dropDatabase(db, url);
}
ODatabaseHelper.createDatabase(db, url);
db.close();
} catch (IOException ex) {
System.out.println("Exception: " + ex);
}
// OPEN DB, Create Schema
ODatabaseDocumentTx db = new ODatabaseDocumentTx(url).open("admin", "admin");
OClass vertexClass = db.getMetadata().getSchema().createClass("OGraphVertex");
OClass edgeClass = db.getMetadata().getSchema().createClass("OGraphEdge");
vertexClass.createProperty("in", OType.LINKSET, edgeClass);
vertexClass.createProperty("out", OType.LINKSET, edgeClass);
edgeClass.createProperty("in", OType.LINK, vertexClass);
edgeClass.createProperty("out", OType.LINK, vertexClass);
OClass personClass = db.getMetadata().getSchema().createClass("Person", vertexClass);
personClass.createProperty("name", OType.STRING).createIndex(OClass.INDEX_TYPE.UNIQUE);
personClass.createProperty("identifier", OType.STRING).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
db.getMetadata().getSchema().save();
// POPULATE TREE
db.begin();
PersonTree tree = new PersonTree();
tree.AddRoot("A", "B");
buildTree(tree, tree.root.getIdentity(), "A", subnodes, depth, 'A');
db.commit();
char startLetter = 'A' + subnodes;
try {
AddThread t1 = new AddThread("A", startLetter++);
DeleteThread t2 = new DeleteThread("A");
DeleteThread t3 = new DeleteThread("A");
AddThread t4 = new AddThread("A", startLetter);
t1.t.join();
t2.t.join();
t3.t.join();
t4.t.join();
} catch (InterruptedException ex) {
System.out.println("Interrupted");
}
if (!checkIndexConsistency(db))
cnt = tries;
db.close();
}
}
}
<file_sep>package com.orientechnologies.orient.core.storage.impl.memory.lh;
/**
* @author <NAME> (logart) <EMAIL> Date: 8/28/12 Time: 10:18 AM
*/
class OLinearHashingIndexElement {
byte signature = Byte.MAX_VALUE;
byte displacement = (byte) 255;
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.storage.impl.memory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.orientechnologies.orient.core.id.OClusterPosition;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
import com.orientechnologies.orient.core.version.ORecordVersion;
public class OClusterMemoryArrayList extends OClusterMemory implements OCluster {
private List<OPhysicalPosition> entries = new ArrayList<OPhysicalPosition>();
private List<OPhysicalPosition> removed = new ArrayList<OPhysicalPosition>();
protected void clear() {
entries.clear();
removed.clear();
}
public long getEntries() {
acquireSharedLock();
try {
return entries.size() - removed.size();
} finally {
releaseSharedLock();
}
}
public boolean isRequiresValidPositionBeforeCreation() {
return false;
}
public long getRecordsSize() {
acquireSharedLock();
try {
long size = 0;
for (OPhysicalPosition e : entries)
if (e != null)
size += e.recordSize;
return size;
} finally {
releaseSharedLock();
}
}
@Override
public OClusterPosition getFirstPosition() {
acquireSharedLock();
try {
return OClusterPositionFactory.INSTANCE.valueOf(entries.size() == 0 ? -1 : 0);
} finally {
releaseSharedLock();
}
}
@Override
public OClusterPosition getLastPosition() {
acquireSharedLock();
try {
return OClusterPositionFactory.INSTANCE.valueOf(entries.size() - 1);
} finally {
releaseSharedLock();
}
}
public boolean addPhysicalPosition(final OPhysicalPosition iPPosition) {
acquireExclusiveLock();
try {
if (!removed.isEmpty()) {
final OPhysicalPosition recycledPosition = removed.remove(removed.size() - 1);
// OVERWRITE DATA
iPPosition.clusterPosition = recycledPosition.clusterPosition;
iPPosition.recordVersion = recycledPosition.recordVersion.copy();
if (iPPosition.recordVersion.isTombstone())
iPPosition.recordVersion.revive();
iPPosition.recordVersion.increment();
int positionToStore = recycledPosition.clusterPosition.intValue();
entries.set(positionToStore, iPPosition);
} else {
iPPosition.clusterPosition = allocateRecord(iPPosition);
iPPosition.recordVersion.reset();
entries.add(iPPosition);
}
} finally {
releaseExclusiveLock();
}
return true;
}
protected OClusterPosition allocateRecord(final OPhysicalPosition iPPosition) {
return OClusterPositionFactory.INSTANCE.valueOf(entries.size());
}
public void updateRecordType(final OClusterPosition iPosition, final byte iRecordType) throws IOException {
acquireExclusiveLock();
try {
entries.get(iPosition.intValue()).recordType = iRecordType;
} finally {
releaseExclusiveLock();
}
}
public void updateVersion(OClusterPosition iPosition, ORecordVersion iVersion) throws IOException {
acquireExclusiveLock();
try {
entries.get(iPosition.intValue()).recordVersion = iVersion;
} finally {
releaseExclusiveLock();
}
}
public OPhysicalPosition getPhysicalPosition(final OPhysicalPosition iPPosition) {
acquireSharedLock();
try {
if (iPPosition.clusterPosition.intValue() < 0 || iPPosition.clusterPosition.compareTo(getLastPosition()) > 0)
return null;
return entries.get((int) iPPosition.clusterPosition.intValue());
} finally {
releaseSharedLock();
}
}
public void removePhysicalPosition(final OClusterPosition iPosition) {
acquireExclusiveLock();
try {
int positionToRemove = iPosition.intValue();
final OPhysicalPosition ppos = entries.get(positionToRemove);
// ADD AS HOLE
removed.add(ppos);
entries.set(positionToRemove, null);
} finally {
releaseExclusiveLock();
}
}
public void updateDataSegmentPosition(final OClusterPosition iPosition, final int iDataSegmentId, final long iDataPosition) {
acquireExclusiveLock();
try {
final OPhysicalPosition ppos = entries.get(iPosition.intValue());
ppos.dataSegmentId = iDataSegmentId;
ppos.dataSegmentPos = iDataPosition;
} finally {
releaseExclusiveLock();
}
}
@Override
public OClusterPosition nextRecord(OClusterPosition position) {
int positionInEntries = position.intValue() + 1;
while (positionInEntries < entries.size() && entries.get(positionInEntries) == null) {
positionInEntries++;
}
if (positionInEntries >= 0 && positionInEntries < entries.size()) {
return entries.get(positionInEntries).clusterPosition;
} else {
return OClusterPosition.INVALID_POSITION;
}
}
@Override
public OClusterPosition prevRecord(OClusterPosition position) {
int positionInEntries = position.intValue() - 1;
while (positionInEntries >= 0 && entries.get(positionInEntries) == null) {
positionInEntries--;
}
if (positionInEntries >= 0 && positionInEntries < entries.size()) {
return entries.get(positionInEntries).clusterPosition;
} else {
return OClusterPosition.INVALID_POSITION;
}
}
@Override
public String toString() {
return "OClusterMemory [name=" + getName() + ", id=" + getId() + ", entries=" + entries.size() + ", removed=" + removed + "]";
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.common.serialization.types;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* @author ibershadskiy <a href="mailto:<EMAIL>"><NAME></a>
* @since 18.01.12
*/
public class DoubleSerializerTest {
private static final int FIELD_SIZE = 8;
private static final Double OBJECT = Math.PI;
private ODoubleSerializer doubleSerializer;
byte[] stream = new byte[FIELD_SIZE];
@BeforeClass
public void beforeClass() {
doubleSerializer = new ODoubleSerializer();
}
@Test
public void testFieldSize() {
Assert.assertEquals(doubleSerializer.getObjectSize(null), FIELD_SIZE);
}
@Test
public void testSerialize() {
doubleSerializer.serialize(OBJECT, stream, 0);
Assert.assertEquals(doubleSerializer.deserialize(stream, 0), OBJECT);
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.storage.impl.memory.lh;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import com.orientechnologies.orient.core.id.OClusterPosition;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
/**
* @author <NAME> (<EMAIL>)
*/
class OLinearHashingBucket<K extends OClusterPosition, V extends OPhysicalPosition> {
public static final int BUCKET_MAX_SIZE = 64;
K[] keys = (K[]) new OClusterPosition[BUCKET_MAX_SIZE];
V[] values = (V[]) new OPhysicalPosition[BUCKET_MAX_SIZE];
int size;
public V get(final K key) {
for (int i = 0; i < size; i++) {
if (key.equals(keys[i])) {
return values[i];
}
}
return null;
}
public List<V> getLargestRecords(final byte signature) {
List<V> result = new ArrayList<V>(size / 10);
for (int i = 0; i < size;) {
if (OLinearHashingHashCalculatorFactory.INSTANCE.calculateSignature(keys[i]) == signature) {
result.add(values[i]);
--size;
keys[i] = keys[size];
values[i] = values[size];
keys[size] = null;
values[size] = null;
} else {
++i;
}
}
assert !result.isEmpty();
return result;
}
public Collection<V> getContent() {
return Arrays.asList(values).subList(0, size);
}
public void emptyBucket() {
size = 0;
}
public int deleteKey(OClusterPosition key) {
for (int i = 0; i < size; i++) {
if (key.equals(keys[i])) {
keys[i] = keys[size - 1];
values[i] = values[size - 1];
size--;
return i;
}
}
return -1;
}
public List<V> getSmallestRecords(int maxSizeOfRecordsArray) {
byte signature = 127;
List<V> result = new ArrayList<V>(size / 10);
for (int i = 0; i < size; ++i) {
byte keySignature = OLinearHashingHashCalculatorFactory.INSTANCE.calculateSignature(keys[i]);
if (keySignature < signature) {
signature = keySignature;
result.clear();
result.add(values[i]);
} else if (keySignature == signature) {
result.add(values[i]);
}
}
assert !result.isEmpty();
if (result.size() > maxSizeOfRecordsArray) {
return new ArrayList<V>();
} else {
return result;
}
}
public void add(List<V> smallestRecords) {
if (smallestRecords.size() > (BUCKET_MAX_SIZE - size)) {
throw new IllegalArgumentException("array size should be less than existing free space in bucket");
} else {
for (V smallestRecord : smallestRecords) {
keys[size] = (K) smallestRecord.clusterPosition;
values[size] = smallestRecord;
size++;
}
}
}
}
<file_sep>package com.orientechnologies.orient.core.storage.impl.local;
import java.io.File;
import java.io.IOException;
import com.orientechnologies.orient.core.config.OStorageFileConfiguration;
import com.orientechnologies.orient.core.memory.OMemoryWatchDog;
/**
* @author <NAME>
* @since 03.08.12
*/
public class OClusterLocalLHPEStatistic extends OSingleFileSegment {
public OClusterLocalLHPEStatistic(String iPath, String iType) throws IOException {
super(iPath, iType);
}
public OClusterLocalLHPEStatistic(OStorageLocal iStorage, OStorageFileConfiguration iConfig) throws IOException {
super(iStorage, iConfig);
}
public OClusterLocalLHPEStatistic(OStorageLocal iStorage, OStorageFileConfiguration iConfig, String iType) throws IOException {
super(iStorage, iConfig, iType);
}
public void rename(String iOldName, String iNewName) {
final String osFileName = file.getName();
if (osFileName.startsWith(iOldName)) {
final File newFile = new File(storage.getStoragePath() + '/' + iNewName
+ osFileName.substring(osFileName.lastIndexOf(iOldName) + iOldName.length()));
boolean renamed = file.renameTo(newFile);
while (!renamed) {
OMemoryWatchDog.freeMemory(100);
renamed = file.renameTo(newFile);
}
}
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.command;
import java.util.Collection;
import java.util.Iterator;
/**
* Iterator for commands. Allows to iterate against the resultset of the execution.
*
* @author <NAME>
*
*/
public class OCommandGenericIterator implements Iterator<Object>, Iterable<Object> {
protected OCommandExecutor command;
protected Iterator<Object> resultSet;
protected Object resultOne;
protected boolean executed = false;
public OCommandGenericIterator(OCommandExecutor command) {
this.command = command;
}
public boolean hasNext() {
checkForExecution();
if (resultOne != null)
return true;
else if (resultSet != null)
return resultSet.hasNext();
return false;
}
public Object next() {
checkForExecution();
if (resultOne != null)
return resultOne;
else if (resultSet != null)
return resultSet.next();
return null;
}
public Iterator<Object> iterator() {
return this;
}
public void remove() {
throw new UnsupportedOperationException("remove()");
}
@SuppressWarnings("unchecked")
protected void checkForExecution() {
if (!executed) {
executed = true;
final Object result = command.execute(null);
if (result instanceof Collection)
resultSet = ((Collection<Object>) result).iterator();
else if (result instanceof Object)
resultOne = (Object) result;
}
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.distributed;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import com.orientechnologies.common.concur.resource.OSharedResourceAdaptiveExternal;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.cache.OLevel2RecordCache;
import com.orientechnologies.orient.core.command.OCommandDistributedConditionalReplicateRequest;
import com.orientechnologies.orient.core.command.OCommandDistributedReplicateRequest;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.command.OCommandManager;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.config.OStorageConfiguration;
import com.orientechnologies.orient.core.exception.OStorageException;
import com.orientechnologies.orient.core.id.OClusterPosition;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.ODataSegment;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.ORecordCallback;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.storage.OStorageEmbedded;
import com.orientechnologies.orient.core.storage.OStorageOperationResult;
import com.orientechnologies.orient.core.tx.OTransaction;
import com.orientechnologies.orient.core.version.ORecordVersion;
import com.orientechnologies.orient.server.distributed.ODistributedServerManager.EXECUTION_MODE;
import com.orientechnologies.orient.server.distributed.conflict.OReplicationConflictResolver;
import com.orientechnologies.orient.server.task.OCreateRecordDistributedTask;
import com.orientechnologies.orient.server.task.ODeleteRecordDistributedTask;
import com.orientechnologies.orient.server.task.OReadRecordDistributedTask;
import com.orientechnologies.orient.server.task.OSQLCommandDistributedTask;
import com.orientechnologies.orient.server.task.OUpdateRecordDistributedTask;
/**
* Distributed storage implementation that routes to the owner node the request.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*/
public class ODistributedStorage implements OStorage {
protected final ODistributedServerManager dManager;
protected final OStorageEmbedded wrapped;
protected final OStorageSynchronizer dbSynchronizer;
protected boolean eventuallyConsistent = true;
protected EXECUTION_MODE createRecordMode = EXECUTION_MODE.SYNCHRONOUS;
protected EXECUTION_MODE updateRecordMode = EXECUTION_MODE.SYNCHRONOUS;
protected EXECUTION_MODE deleteRecordMode = EXECUTION_MODE.SYNCHRONOUS;
public ODistributedStorage(final ODistributedServerManager iCluster, final OStorageSynchronizer dbSynchronizer,
final OStorageEmbedded wrapped) {
this.dManager = iCluster;
this.wrapped = wrapped;
this.dbSynchronizer = dbSynchronizer;
}
public Object command(final OCommandRequestText iCommand) {
final OCommandExecutor executor = OCommandManager.instance().getExecutor(iCommand);
executor.setProgressListener(iCommand.getProgressListener());
executor.parse(iCommand);
final boolean distribute;
final OCommandExecutor exec = executor instanceof OCommandExecutorSQLDelegate ? ((OCommandExecutorSQLDelegate) executor)
.getDelegate() : executor;
if (exec instanceof OCommandDistributedConditionalReplicateRequest)
distribute = ((OCommandDistributedConditionalReplicateRequest) exec).isReplicated();
else if (exec instanceof OCommandDistributedReplicateRequest)
distribute = true;
else
distribute = false;
if (distribute)
ODistributedThreadLocal.INSTANCE.distributedExecution = true;
try {
// EXECUTE IT LOCALLY
final Object localResult = wrapped.executeCommand(iCommand, executor);
if (distribute) {
final Map<String, Object> distributedResult = dManager.sendOperation2Nodes(dManager.getRemoteNodeIds(),
new OSQLCommandDistributedTask(dManager.getLocalNodeId(), wrapped.getName(), createRecordMode, iCommand.getText()));
for (Entry<String, Object> entry : distributedResult.entrySet()) {
final Object remoteResult = entry.getValue();
if (localResult != remoteResult
&& (localResult == null && remoteResult != null || localResult != null && remoteResult == null || remoteResult
.equals(localResult))) {
// CONFLICT
final OReplicationConflictResolver resolver = dbSynchronizer.getConflictResolver();
resolver.handleCommandConflict(entry.getKey(), iCommand, localResult, remoteResult);
}
}
}
return localResult;
} finally {
if (distribute)
ODistributedThreadLocal.INSTANCE.distributedExecution = false;
}
}
public OStorageOperationResult<OPhysicalPosition> createRecord(final int iDataSegmentId, final ORecordId iRecordId,
final byte[] iContent, final ORecordVersion iRecordVersion, final byte iRecordType, final int iMode,
final ORecordCallback<OClusterPosition> iCallback) {
if (ODistributedThreadLocal.INSTANCE.distributedExecution)
// ALREADY DISTRIBUTED
return wrapped.createRecord(iDataSegmentId, iRecordId, iContent, iRecordVersion, iRecordType, iMode, iCallback);
Object result = null;
try {
result = dManager.routeOperation2Node(getClusterNameFromRID(iRecordId), iRecordId,
new OCreateRecordDistributedTask(dManager.getLocalNodeId(), wrapped.getName(), createRecordMode, iRecordId, iContent,
iRecordVersion, iRecordType));
iRecordId.clusterPosition = ((OPhysicalPosition) result).clusterPosition;
} catch (ExecutionException e) {
handleDistributedException("Cannot route CREATE_RECORD operation against %s to the distributed node", e, iRecordId);
}
return new OStorageOperationResult<OPhysicalPosition>((OPhysicalPosition) result);
}
public OStorageOperationResult<ORawBuffer> readRecord(final ORecordId iRecordId, final String iFetchPlan,
final boolean iIgnoreCache, final ORecordCallback<ORawBuffer> iCallback) {
if (ODistributedThreadLocal.INSTANCE.distributedExecution)
// ALREADY DISTRIBUTED
return wrapped.readRecord(iRecordId, iFetchPlan, iIgnoreCache, iCallback);
if (eventuallyConsistent || dManager.isLocalNodeMaster(iRecordId))
return wrapped.readRecord(iRecordId, iFetchPlan, iIgnoreCache, iCallback);
try {
return new OStorageOperationResult<ORawBuffer>((ORawBuffer) dManager.routeOperation2Node(getClusterNameFromRID(iRecordId),
iRecordId, new OReadRecordDistributedTask(dManager.getLocalNodeId(), wrapped.getName(), iRecordId)));
} catch (ExecutionException e) {
handleDistributedException("Cannot route READ_RECORD operation against %s to the distributed node", e, iRecordId);
}
return new OStorageOperationResult<ORawBuffer>(null);
}
public OStorageOperationResult<ORecordVersion> updateRecord(final ORecordId iRecordId, final byte[] iContent,
final ORecordVersion iVersion, final byte iRecordType, final int iMode, final ORecordCallback<ORecordVersion> iCallback) {
if (ODistributedThreadLocal.INSTANCE.distributedExecution)
// ALREADY DISTRIBUTED
return wrapped.updateRecord(iRecordId, iContent, iVersion, iRecordType, iMode, iCallback);
Object result = null;
try {
result = dManager.routeOperation2Node(getClusterNameFromRID(iRecordId), iRecordId,
new OUpdateRecordDistributedTask(dManager.getLocalNodeId(), wrapped.getName(), updateRecordMode, iRecordId, iContent,
iVersion, iRecordType));
} catch (ExecutionException e) {
handleDistributedException("Cannot route UPDATE_RECORD operation against %s to the distributed node", e, iRecordId);
}
// UPDATE LOCALLY
return new OStorageOperationResult<ORecordVersion>((ORecordVersion) result);
}
public OStorageOperationResult<Boolean> deleteRecord(final ORecordId iRecordId, final ORecordVersion iVersion, final int iMode,
final ORecordCallback<Boolean> iCallback) {
if (ODistributedThreadLocal.INSTANCE.distributedExecution)
// ALREADY DISTRIBUTED
return wrapped.deleteRecord(iRecordId, iVersion, iMode, iCallback);
Object result = null;
try {
result = dManager.routeOperation2Node(getClusterNameFromRID(iRecordId), iRecordId,
new ODeleteRecordDistributedTask(dManager.getLocalNodeId(), wrapped.getName(), updateRecordMode, iRecordId, iVersion));
} catch (ExecutionException e) {
handleDistributedException("Cannot route DELETE_RECORD operation against %s to the distributed node", e, iRecordId);
}
// DELETE LOCALLY
return new OStorageOperationResult<Boolean>((Boolean) result);
}
@Override
public boolean cleanOutRecord(ORecordId recordId, ORecordVersion recordVersion, int iMode, ORecordCallback<Boolean> callback) {
return wrapped.cleanOutRecord(recordId, recordVersion, iMode, callback);
}
public boolean existsResource(final String iName) {
return wrapped.existsResource(iName);
}
@SuppressWarnings("unchecked")
public <T> T removeResource(final String iName) {
return (T) wrapped.removeResource(iName);
}
public <T> T getResource(final String iName, final Callable<T> iCallback) {
return (T) wrapped.getResource(iName, iCallback);
}
public void open(final String iUserName, final String iUserPassword, final Map<String, Object> iProperties) {
wrapped.open(iUserName, iUserPassword, iProperties);
}
public void create(final Map<String, Object> iProperties) {
wrapped.create(iProperties);
}
public boolean exists() {
return wrapped.exists();
}
public void reload() {
wrapped.reload();
}
public void delete() {
wrapped.delete();
}
public void close() {
wrapped.close();
}
public void close(final boolean iForce) {
wrapped.close(iForce);
}
public boolean isClosed() {
return wrapped.isClosed();
}
public OLevel2RecordCache getLevel2Cache() {
return wrapped.getLevel2Cache();
}
public void commit(final OTransaction iTx) {
throw new ODistributedException("Transactions are not supported in distributed environment");
}
public void rollback(final OTransaction iTx) {
throw new ODistributedException("Transactions are not supported in distributed environment");
}
public OStorageConfiguration getConfiguration() {
return wrapped.getConfiguration();
}
public int getClusters() {
return wrapped.getClusters();
}
public Set<String> getClusterNames() {
return wrapped.getClusterNames();
}
public OCluster getClusterById(int iId) {
return wrapped.getClusterById(iId);
}
public Collection<? extends OCluster> getClusterInstances() {
return wrapped.getClusterInstances();
}
public int addCluster(final String iClusterType, final String iClusterName, final String iLocation,
final String iDataSegmentName, final Object... iParameters) {
return wrapped.addCluster(iClusterType, iClusterName, iLocation, iDataSegmentName, iParameters);
}
public boolean dropCluster(final String iClusterName) {
return wrapped.dropCluster(iClusterName);
}
public boolean dropCluster(final int iId) {
return wrapped.dropCluster(iId);
}
public int addDataSegment(final String iDataSegmentName) {
return wrapped.addDataSegment(iDataSegmentName);
}
public int addDataSegment(final String iSegmentName, final String iDirectory) {
return wrapped.addDataSegment(iSegmentName, iDirectory);
}
public long count(final int iClusterId) {
return wrapped.count(iClusterId);
}
public long count(final int[] iClusterIds) {
return wrapped.count(iClusterIds);
}
public long getSize() {
return wrapped.getSize();
}
public long countRecords() {
return wrapped.countRecords();
}
public int getDefaultClusterId() {
return wrapped.getDefaultClusterId();
}
public void setDefaultClusterId(final int defaultClusterId) {
wrapped.setDefaultClusterId(defaultClusterId);
}
public int getClusterIdByName(String iClusterName) {
return wrapped.getClusterIdByName(iClusterName);
}
public String getClusterTypeByName(final String iClusterName) {
return wrapped.getClusterTypeByName(iClusterName);
}
public String getPhysicalClusterNameById(final int iClusterId) {
return wrapped.getPhysicalClusterNameById(iClusterId);
}
public boolean checkForRecordValidity(final OPhysicalPosition ppos) {
return wrapped.checkForRecordValidity(ppos);
}
public String getName() {
return wrapped.getName();
}
public String getURL() {
return wrapped.getURL();
}
public long getVersion() {
return wrapped.getVersion();
}
public void synch() {
wrapped.synch();
}
public int getUsers() {
return wrapped.getUsers();
}
public int addUser() {
return wrapped.addUser();
}
public int removeUser() {
return wrapped.removeUser();
}
public OClusterPosition[] getClusterDataRange(final int currentClusterId) {
return wrapped.getClusterDataRange(currentClusterId);
}
public <V> V callInLock(final Callable<V> iCallable, final boolean iExclusiveLock) {
return wrapped.callInLock(iCallable, iExclusiveLock);
}
public ODataSegment getDataSegmentById(final int iDataSegmentId) {
return wrapped.getDataSegmentById(iDataSegmentId);
}
public int getDataSegmentIdByName(final String iDataSegmentName) {
return wrapped.getDataSegmentIdByName(iDataSegmentName);
}
public boolean dropDataSegment(final String iName) {
return wrapped.dropDataSegment(iName);
}
public STATUS getStatus() {
return wrapped.getStatus();
}
@Override
public void changeRecordIdentity(ORID originalId, ORID newId) {
wrapped.changeRecordIdentity(originalId, newId);
}
@Override
public void checkForClusterPermissions(final String iClusterName) {
wrapped.checkForClusterPermissions(iClusterName);
}
@Override
public boolean isLHClustersAreUsed() {
return wrapped.isLHClustersAreUsed();
}
@Override
public OClusterPosition getNextClusterPosition(int currentClusterId, OClusterPosition entry) {
return wrapped.getNextClusterPosition(currentClusterId, entry);
}
@Override
public OClusterPosition getPrevClusterPosition(int currentClusterId, OClusterPosition entry) {
return wrapped.getPrevClusterPosition(currentClusterId, entry);
}
@Override
public OSharedResourceAdaptiveExternal getLock() {
return wrapped.getLock();
}
@Override
public String getType() {
return "distributed";
}
protected String getClusterNameFromRID(final ORecordId iRecordId) {
return OStorageSynchronizer.getClusterNameByRID(wrapped, iRecordId);
}
protected void handleDistributedException(final String iMessage, ExecutionException e, Object... iParams) {
OLogManager.instance().error(this, iMessage, e, iParams);
final Throwable t = e.getCause();
if (t instanceof OException)
throw (OException) t;
throw new OStorageException(String.format(iMessage, iParams), e);
}
}
<file_sep>package com.orientechnologies.orient.core.sql;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.orientechnologies.common.listener.OProgressListener;
import com.orientechnologies.common.profiler.OProfiler;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.db.ODatabaseComplex;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexInternal;
import com.orientechnologies.orient.core.index.OIndexNotUnique;
import com.orientechnologies.orient.core.index.OIndexOneValue;
import com.orientechnologies.orient.core.index.OIndexUnique;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.profiler.OJVMProfiler;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemField;
/**
* <p>
* There are some cases when we need to create index for some class by traversed property. Unfortunately, such functionality is not
* supported yet. But we can do that by creating index for each element of {@link OSQLFilterItemField.FieldChain} (which define
* "way" to our property), and then process operations consequently using previously created indexes.
* </p>
* <p>
* This class provides possibility to find optimal chain of indexes and then use it just like it was index for traversed property.
* </p>
* <p>
* IMPORTANT: this class is only for internal usage!
* </p>
*
* @author <NAME>
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class OIndexProxy<T> implements OIndex<T> {
private final OIndex<T> index;
private final List<OIndex<?>> indexChain;
private final OIndex<?> lastIndex;
/**
* Create proxies that support maximum number of different operations. In case when several different indexes which support
* different operations (e.g. indexes of {@code UNIQUE} and {@code FULLTEXT} types) are possible, the creates the only one index
* of each type.
*
* @param index
* - the index which proxies created for
* @param longChain
* - property chain from the query, which should be evaluated
* @param database
* - current database instance
* @return proxies needed to process query.
*/
public static <T> Collection<OIndexProxy<T>> createdProxy(OIndex<T> index, OSQLFilterItemField.FieldChain longChain,
ODatabaseComplex<?> database) {
Collection<OIndexProxy<T>> proxies = new ArrayList<OIndexProxy<T>>();
for (List<OIndex<?>> indexChain : getIndexesForChain(index, longChain, database)) {
proxies.add(new OIndexProxy<T>(index, indexChain));
}
return proxies;
}
private OIndexProxy(OIndex<T> index, List<OIndex<?>> indexChain) {
this.index = index;
this.indexChain = Collections.unmodifiableList(indexChain);
lastIndex = indexChain.get(indexChain.size() - 1);
}
public String getDatabaseName() {
return index.getDatabaseName();
}
/**
* {@inheritDoc}
*/
public T get(Object iKey) {
final Object result = lastIndex.get(iKey);
final Collection<T> resultSet = applyTailIndexes(result, -1);
if (getInternal() instanceof OIndexOneValue && resultSet.size() == 1) {
return resultSet.iterator().next();
} else {
return (T) resultSet;
}
}
public long count(Object iKey) {
return index.count(iKey);
}
/**
* {@inheritDoc}
*/
public Collection<OIdentifiable> getValuesBetween(Object iRangeFrom, Object iRangeTo) {
final Object result = lastIndex.getValuesBetween(iRangeFrom, iRangeTo);
return (Collection<OIdentifiable>) applyTailIndexes(result, -1);
}
/**
* {@inheritDoc}
*/
public Collection<OIdentifiable> getValuesBetween(Object iRangeFrom, boolean iFromInclusive, Object iRangeTo, boolean iToInclusive) {
final Object result = lastIndex.getValuesBetween(iRangeFrom, iFromInclusive, iRangeTo, iToInclusive);
return (Collection<OIdentifiable>) applyTailIndexes(result, -1);
}
/**
* {@inheritDoc}
*/
public Collection<OIdentifiable> getValuesBetween(Object iRangeFrom, boolean iFromInclusive, Object iRangeTo,
boolean iToInclusive, int maxValuesToFetch) {
final Object result = lastIndex.getValuesBetween(iRangeFrom, iFromInclusive, iRangeTo, iToInclusive);
return (Collection<OIdentifiable>) applyTailIndexes(result, maxValuesToFetch);
}
/**
* {@inheritDoc}
*/
public Collection<OIdentifiable> getValuesMajor(Object fromKey, boolean isInclusive) {
final Object result = lastIndex.getValuesMajor(fromKey, isInclusive);
return (Collection<OIdentifiable>) applyTailIndexes(result, -1);
}
/**
* {@inheritDoc}
*/
public Collection<OIdentifiable> getValuesMajor(Object fromKey, boolean isInclusive, int maxValuesToFetch) {
final Object result = lastIndex.getValuesMajor(fromKey, isInclusive);
return (Collection<OIdentifiable>) applyTailIndexes(result, maxValuesToFetch);
}
/**
* {@inheritDoc}
*/
public Collection<OIdentifiable> getValuesMinor(Object toKey, boolean isInclusive) {
final Object result = lastIndex.getValuesMinor(toKey, isInclusive);
return (Collection<OIdentifiable>) applyTailIndexes(result, -1);
}
/**
* {@inheritDoc}
*/
public Collection<OIdentifiable> getValuesMinor(Object toKey, boolean isInclusive, int maxValuesToFetch) {
final Object result = lastIndex.getValuesMinor(toKey, isInclusive);
return (Collection<OIdentifiable>) applyTailIndexes(result, maxValuesToFetch);
}
/**
* {@inheritDoc}
*/
public Collection<OIdentifiable> getValues(Collection<?> iKeys) {
final Object result = lastIndex.getValues(iKeys);
return (Collection<OIdentifiable>) applyTailIndexes(result, -1);
}
/**
* {@inheritDoc}
*/
public Collection<OIdentifiable> getValues(Collection<?> iKeys, int maxValuesToFetch) {
final Object result = lastIndex.getValues(iKeys);
return (Collection<OIdentifiable>) applyTailIndexes(result, maxValuesToFetch);
}
/**
* Returns internal index of last chain index, because proxy applicable to all operations that last index applicable.
*/
public OIndexInternal<T> getInternal() {
return (OIndexInternal<T>) lastIndex.getInternal();
}
/**
* {@inheritDoc}
*/
public OIndexDefinition getDefinition() {
return indexChain.get(indexChain.size() - 1).getDefinition();
}
private Collection<T> applyTailIndexes(final Object result, int maxValuesToFetch) {
final OIndex<?> previousIndex = indexChain.get(indexChain.size() - 2);
Set<Comparable> currentKeys = prepareKeys(previousIndex, result);
for (int j = indexChain.size() - 2; j > 0; j--) {
Set<Comparable> newKeys = new TreeSet<Comparable>();
final OIndex<?> currentIndex = indexChain.get(j);
for (Comparable currentKey : currentKeys) {
final Object currentResult = currentIndex.get(currentKey);
final Set<Comparable> preparedKeys;
preparedKeys = prepareKeys(indexChain.get(j - 1), currentResult);
newKeys.addAll(preparedKeys);
}
updateStatistic(currentIndex);
currentKeys = newKeys;
}
return applyMainIndex(currentKeys, maxValuesToFetch);
}
private Set<Comparable> convertResult(Object result, Class<?> targetType) {
final Set<Comparable> newKeys;
if (result instanceof Set) {
newKeys = new TreeSet<Comparable>();
for (Object o : ((Set) result)) {
newKeys.add((Comparable) OType.convert(o, targetType));
}
return newKeys;
} else {
return Collections.singleton((Comparable) OType.convert(result, targetType));
}
}
/**
* Make type conversion of keys for specific index.
*
* @param index
* - index for which keys prepared for.
* @param keys
* - which should be prepared.
* @return keys converted to necessary type.
*/
private Set<Comparable> prepareKeys(OIndex<?> index, Object keys) {
final Class<?> targetType = index.getKeyTypes()[0].getDefaultJavaType();
return convertResult(keys, targetType);
}
private Collection<T> applyMainIndex(Iterable<Comparable> currentKeys, int maxValuesToFetch) {
Collection<T> resultSet = new TreeSet<T>();
for (Comparable key : currentKeys) {
final T result = index.get(index.getDefinition().createValue(key));
if (result instanceof Set) {
for (T o : (Set<T>) result) {
resultSet.add(o);
if (maxValuesToFetch != -1 && resultSet.size() >= maxValuesToFetch) {
break;
}
}
} else {
resultSet.add(result);
}
if (maxValuesToFetch != -1 && resultSet.size() >= maxValuesToFetch) {
break;
}
}
updateStatistic(index);
return resultSet;
}
private static Iterable<List<OIndex<?>>> getIndexesForChain(OIndex<?> index, OSQLFilterItemField.FieldChain fieldChain,
ODatabaseComplex<?> database) {
List<OIndex<?>> baseIndexes = prepareBaseIndexes(index, fieldChain, database);
Collection<OIndex<?>> lastIndexes = prepareLastIndexVariants(index, fieldChain, database);
Collection<List<OIndex<?>>> result = new ArrayList<List<OIndex<?>>>();
for (OIndex<?> lastIndex : lastIndexes) {
final List<OIndex<?>> indexes = new ArrayList<OIndex<?>>(fieldChain.getItemCount());
indexes.addAll(baseIndexes);
indexes.add(lastIndex);
result.add(indexes);
}
return result;
}
private static Collection<OIndex<?>> prepareLastIndexVariants(OIndex<?> index, OSQLFilterItemField.FieldChain fieldChain,
ODatabaseComplex<?> database) {
OClass oClass = database.getMetadata().getSchema().getClass(index.getDefinition().getClassName());
for (int i = 0; i < fieldChain.getItemCount() - 1; i++) {
oClass = oClass.getProperty(fieldChain.getItemName(i)).getLinkedClass();
}
final Set<OIndex<?>> involvedIndexes = new TreeSet<OIndex<?>>(new Comparator<OIndex<?>>() {
public int compare(OIndex<?> o1, OIndex<?> o2) {
return o1.getDefinition().getParamCount() - o2.getDefinition().getParamCount();
}
});
involvedIndexes.addAll(oClass.getInvolvedIndexes(fieldChain.getItemName(fieldChain.getItemCount() - 1)));
final Collection<Class<? extends OIndex>> indexTypes = new HashSet<Class<? extends OIndex>>(3);
final Collection<OIndex<?>> result = new ArrayList<OIndex<?>>();
for (OIndex<?> involvedIndex : involvedIndexes) {
if (!indexTypes.contains(involvedIndex.getInternal().getClass())) {
result.add(involvedIndex);
indexTypes.add(involvedIndex.getInternal().getClass());
}
}
return result;
}
private static List<OIndex<?>> prepareBaseIndexes(OIndex<?> index, OSQLFilterItemField.FieldChain fieldChain,
ODatabaseComplex<?> database) {
List<OIndex<?>> result = new ArrayList<OIndex<?>>(fieldChain.getItemCount() - 1);
result.add(index);
OClass oClass = database.getMetadata().getSchema().getClass(index.getDefinition().getClassName());
oClass = oClass.getProperty(fieldChain.getItemName(0)).getLinkedClass();
for (int i = 1; i < fieldChain.getItemCount() - 1; i++) {
final Set<OIndex<?>> involvedIndexes = oClass.getInvolvedIndexes(fieldChain.getItemName(i));
final OIndex<?> bestIndex = findBestIndex(involvedIndexes);
result.add(bestIndex);
oClass = oClass.getProperty(fieldChain.getItemName(i)).getLinkedClass();
}
return result;
}
private static OIndex<?> findBestIndex(Iterable<OIndex<?>> involvedIndexes) {
OIndex<?> bestIndex = null;
for (OIndex<?> index : involvedIndexes) {
bestIndex = index;
OIndexInternal<?> bestInternalIndex = index.getInternal();
if (bestInternalIndex instanceof OIndexUnique || bestInternalIndex instanceof OIndexNotUnique) {
return index;
}
}
return bestIndex;
}
/**
* Register statistic information about usage of index in {@link OProfiler}.
*
* @param index
* which usage is registering.
*/
private void updateStatistic(OIndex<?> index) {
final OJVMProfiler profiler = Orient.instance().getProfiler();
if (profiler.isRecording()) {
Orient.instance().getProfiler()
.updateCounter(profiler.getDatabaseMetric(index.getDatabaseName(), "query.indexUsed"), "Used index in query", +1);
final int paramCount = index.getDefinition().getParamCount();
if (paramCount > 1) {
final String profiler_prefix = profiler.getDatabaseMetric(index.getDatabaseName(), "query.compositeIndexUsed");
profiler.updateCounter(profiler_prefix, "Used composite index in query", +1);
profiler.updateCounter(profiler_prefix + "." + paramCount, "Used composite index in query with " + paramCount + " params",
+1);
}
}
}
public void checkEntry(final OIdentifiable iRecord, final Object iKey) {
index.checkEntry(iRecord, iKey);
}
//
// Following methods are not allowed for proxy.
//
public OIndex<T> create(String iName, OIndexDefinition iIndexDefinition, ODatabaseRecord iDatabase, String iClusterIndexName,
int[] iClusterIdsToIndex, OProgressListener iProgressListener) {
throw new UnsupportedOperationException("Not allowed operation");
}
public Collection<ODocument> getEntriesMajor(Object fromKey, boolean isInclusive) {
throw new UnsupportedOperationException("Not allowed operation");
}
public Collection<ODocument> getEntriesMajor(Object fromKey, boolean isInclusive, int maxEntriesToFetch) {
throw new UnsupportedOperationException("Not allowed operation");
}
public Collection<ODocument> getEntriesMinor(Object toKey, boolean isInclusive) {
throw new UnsupportedOperationException("Not allowed operation");
}
public Collection<ODocument> getEntriesMinor(Object toKey, boolean isInclusive, int maxEntriesToFetch) {
throw new UnsupportedOperationException("Not allowed operation");
}
public Collection<ODocument> getEntriesBetween(Object iRangeFrom, Object iRangeTo, boolean iInclusive) {
throw new UnsupportedOperationException("Not allowed operation");
}
public Collection<ODocument> getEntriesBetween(Object iRangeFrom, Object iRangeTo, boolean iInclusive, int maxEntriesToFetch) {
throw new UnsupportedOperationException("Not allowed operation");
}
public Collection<ODocument> getEntriesBetween(Object iRangeFrom, Object iRangeTo) {
throw new UnsupportedOperationException("Not allowed operation");
}
public Collection<ODocument> getEntries(Collection<?> iKeys) {
throw new UnsupportedOperationException("Not allowed operation");
}
public Collection<ODocument> getEntries(Collection<?> iKeys, int maxEntriesToFetch) {
throw new UnsupportedOperationException("Not allowed operation");
}
public boolean contains(Object iKey) {
throw new UnsupportedOperationException("Not allowed operation");
}
public void unload() {
throw new UnsupportedOperationException("Not allowed operation");
}
public OType[] getKeyTypes() {
throw new UnsupportedOperationException("Not allowed operation");
}
public Iterator<Map.Entry<Object, T>> iterator() {
throw new UnsupportedOperationException("Not allowed operation");
}
public Iterator<Map.Entry<Object, T>> inverseIterator() {
throw new UnsupportedOperationException("Not allowed operation");
}
public Iterator<OIdentifiable> valuesIterator() {
throw new UnsupportedOperationException("Not allowed operation");
}
public Iterator<OIdentifiable> valuesInverseIterator() {
throw new UnsupportedOperationException("Not allowed operation");
}
public OIndex<T> put(Object iKey, OIdentifiable iValue) {
throw new UnsupportedOperationException("Not allowed operation");
}
public boolean remove(Object iKey) {
throw new UnsupportedOperationException("Not allowed operation");
}
public boolean remove(Object iKey, OIdentifiable iRID) {
throw new UnsupportedOperationException("Not allowed operation");
}
public int remove(OIdentifiable iRID) {
throw new UnsupportedOperationException("Not allowed operation");
}
public OIndex<T> clear() {
throw new UnsupportedOperationException("Not allowed operation");
}
public Iterable<Object> keys() {
throw new UnsupportedOperationException("Not allowed operation");
}
public long getSize() {
throw new UnsupportedOperationException("Not allowed operation");
}
public long getKeySize() {
throw new UnsupportedOperationException("Not allowed operation");
}
public OIndex<T> lazySave() {
throw new UnsupportedOperationException("Not allowed operation");
}
public OIndex<T> delete() {
throw new UnsupportedOperationException("Not allowed operation");
}
public String getName() {
throw new UnsupportedOperationException("Not allowed operation");
}
public String getType() {
throw new UnsupportedOperationException("Not allowed operation");
}
public boolean isAutomatic() {
throw new UnsupportedOperationException("Not allowed operation");
}
public long rebuild() {
throw new UnsupportedOperationException("Not allowed operation");
}
public long rebuild(OProgressListener iProgressListener) {
throw new UnsupportedOperationException("Not allowed operation");
}
public ODocument getConfiguration() {
throw new UnsupportedOperationException("Not allowed operation");
}
public ORID getIdentity() {
throw new UnsupportedOperationException("Not allowed operation");
}
public void commit(ODocument iDocument) {
throw new UnsupportedOperationException("Not allowed operation");
}
public Set<String> getClusters() {
throw new UnsupportedOperationException("Not allowed operation");
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.index;
import java.util.Collection;
import java.util.Set;
import com.orientechnologies.common.listener.OProgressListener;
import com.orientechnologies.orient.core.dictionary.ODictionary;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* Interface to handle indexes. Implementations works at local or remote level.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*
*/
public interface OIndexManager {
public OIndexManager load();
public void create();
public Collection<? extends OIndex<?>> getIndexes();
public OIndex<?> getIndex(final String iName);
public boolean existsIndex(final String iName);
public OIndex<?> getIndex(final ORID iRID);
public OIndex<?> createIndex(final String iName, final String iType, OIndexDefinition iIndexDefinition,
final int[] iClusterIdsToIndex, final OProgressListener iProgressListener);
public OIndexManager dropIndex(final String iIndexName);
public String getDefaultClusterName();
public void setDefaultClusterName(String defaultClusterName);
public ODictionary<ORecordInternal<?>> getDictionary();
public void flush();
public ODocument getConfiguration();
/**
* Returns list of indexes that contain passed in fields names as their first keys. Order of fields does not matter.
* <p/>
* All indexes sorted by their count of parameters in ascending order. If there are indexes for the given set of fields in super
* class they will be taken into account.
*
*
*
* @param className
* name of class which is indexed.
* @param fields
* Field names.
* @return list of indexes that contain passed in fields names as their first keys.
*/
public Set<OIndex<?>> getClassInvolvedIndexes(String className, Collection<String> fields);
/**
* Returns list of indexes that contain passed in fields names as their first keys. Order of fields does not matter.
* <p/>
* All indexes sorted by their count of parameters in ascending order. If there are indexes for the given set of fields in super
* class they will be taken into account.
*
*
*
* @param className
* name of class which is indexed.
* @param fields
* Field names.
* @return list of indexes that contain passed in fields names as their first keys.
*/
public Set<OIndex<?>> getClassInvolvedIndexes(String className, String... fields);
/**
* Indicates whether given fields are contained as first key fields in class indexes. Order of fields does not matter. If there
* are indexes for the given set of fields in super class they will be taken into account.
*
* @param className
* name of class which contain {@code fields}.
* @param fields
* Field names.
* @return <code>true</code> if given fields are contained as first key fields in class indexes.
*/
public boolean areIndexed(String className, Collection<String> fields);
/**
* @param className
* name of class which contain {@code fields}.
* @param fields
* Field names.
* @return <code>true</code> if given fields are contained as first key fields in class indexes.
* @see #areIndexed(String, java.util.Collection)
*/
public boolean areIndexed(String className, String... fields);
public Set<OIndex<?>> getClassIndexes(String className);
public OIndex<?> getClassIndex(String className, String indexName);
}
<file_sep>/*
* Copyright 2012 Orient Technologies.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.sql.functions;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
import com.orientechnologies.orient.core.sql.functions.coll.OSQLFunctionDifference;
import com.orientechnologies.orient.core.sql.functions.coll.OSQLFunctionDistinct;
import com.orientechnologies.orient.core.sql.functions.coll.OSQLFunctionFirst;
import com.orientechnologies.orient.core.sql.functions.coll.OSQLFunctionIntersect;
import com.orientechnologies.orient.core.sql.functions.coll.OSQLFunctionLast;
import com.orientechnologies.orient.core.sql.functions.coll.OSQLFunctionList;
import com.orientechnologies.orient.core.sql.functions.coll.OSQLFunctionMap;
import com.orientechnologies.orient.core.sql.functions.coll.OSQLFunctionSet;
import com.orientechnologies.orient.core.sql.functions.coll.OSQLFunctionUnion;
import com.orientechnologies.orient.core.sql.functions.geo.OSQLFunctionDistance;
import com.orientechnologies.orient.core.sql.functions.graph.OSQLFunctionDijkstra;
import com.orientechnologies.orient.core.sql.functions.graph.OSQLFunctionShortestPath;
import com.orientechnologies.orient.core.sql.functions.math.OSQLFunctionAverage;
import com.orientechnologies.orient.core.sql.functions.math.OSQLFunctionEval;
import com.orientechnologies.orient.core.sql.functions.math.OSQLFunctionMax;
import com.orientechnologies.orient.core.sql.functions.math.OSQLFunctionMin;
import com.orientechnologies.orient.core.sql.functions.math.OSQLFunctionSum;
import com.orientechnologies.orient.core.sql.functions.misc.OSQLFunctionCoalesce;
import com.orientechnologies.orient.core.sql.functions.misc.OSQLFunctionCount;
import com.orientechnologies.orient.core.sql.functions.misc.OSQLFunctionDate;
import com.orientechnologies.orient.core.sql.functions.misc.OSQLFunctionFormat;
import com.orientechnologies.orient.core.sql.functions.misc.OSQLFunctionIf;
import com.orientechnologies.orient.core.sql.functions.misc.OSQLFunctionIfNull;
import com.orientechnologies.orient.core.sql.functions.misc.OSQLFunctionSysdate;
/**
* Default set of SQL functions.
*
* @author <NAME> (Geomatys)
*/
public final class ODefaultSQLFunctionFactory implements OSQLFunctionFactory {
private static final Map<String, Object> FUNCTIONS = new HashMap<String, Object>();
static {
// MISC FUNCTIONS
FUNCTIONS.put(OSQLFunctionCoalesce.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionCoalesce());
FUNCTIONS.put(OSQLFunctionIf.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionIf());
FUNCTIONS.put(OSQLFunctionIfNull.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionIfNull());
FUNCTIONS.put(OSQLFunctionFormat.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionFormat());
FUNCTIONS.put(OSQLFunctionDate.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionDate.class);
FUNCTIONS.put(OSQLFunctionSysdate.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionSysdate.class);
FUNCTIONS.put(OSQLFunctionCount.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionCount.class);
FUNCTIONS.put(OSQLFunctionDistinct.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionDistinct.class);
FUNCTIONS.put(OSQLFunctionUnion.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionUnion.class);
FUNCTIONS.put(OSQLFunctionIntersect.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionIntersect.class);
FUNCTIONS.put(OSQLFunctionDifference.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionDifference.class);
FUNCTIONS.put(OSQLFunctionFirst.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionFirst.class);
FUNCTIONS.put(OSQLFunctionLast.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionLast.class);
FUNCTIONS.put(OSQLFunctionList.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionList.class);
FUNCTIONS.put(OSQLFunctionSet.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionSet.class);
FUNCTIONS.put(OSQLFunctionMap.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionMap.class);
// MATH FUNCTIONS
FUNCTIONS.put(OSQLFunctionMin.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionMin.class);
FUNCTIONS.put(OSQLFunctionMax.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionMax.class);
FUNCTIONS.put(OSQLFunctionSum.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionSum.class);
FUNCTIONS.put(OSQLFunctionAverage.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionAverage.class);
FUNCTIONS.put(OSQLFunctionEval.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionEval.class);
// GEO FUNCTIONS
FUNCTIONS.put(OSQLFunctionDistance.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionDistance());
// GRAPH FUNCTIONS
FUNCTIONS.put(OSQLFunctionDijkstra.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionDijkstra());
FUNCTIONS.put(OSQLFunctionShortestPath.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionShortestPath());
}
public Set<String> getFunctionNames() {
return FUNCTIONS.keySet();
}
public boolean hasFunction(final String name) {
return FUNCTIONS.containsKey(name);
}
public OSQLFunction createFunction(final String name) {
final Object obj = FUNCTIONS.get(name);
if (obj == null)
throw new OCommandExecutionException("Unknowned function name :" + name);
if (obj instanceof OSQLFunction)
return (OSQLFunction) obj;
else {
// it's a class
final Class<?> clazz = (Class<?>) obj;
try {
return (OSQLFunction) clazz.newInstance();
} catch (Exception e) {
throw new OCommandExecutionException("Error in creation of function " + name
+ "(). Probably there is not an empty constructor or the constructor generates errors", e);
}
}
}
}
<file_sep>package com.orientechnologies.orient.core.storage.impl.memory.lh;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import com.orientechnologies.orient.core.id.OClusterPosition;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
/**
* @author <NAME>
* @since 23.07.12
*/
public class OLinearHashingTable<K extends OClusterPosition, V extends OPhysicalPosition> {
private static final int FILE_SIZE = 4096;
private OLinearHashingIndex primaryIndex;
private OLinearHashingIndex secondaryIndex;
private final int CHAIN_NUMBER;
private int level;
private int next;
private double maxCapacity;
private double minCapacity;
private OGroupOverflowTable groupOverflowTable;
private List<OLinearHashingBucket> file;
private OPageIndicator pageIndicator;
private List<V> recordPool = new ArrayList<V>(100);
private int size;
private static final int MAX_GROUP_SIZE = 128;
public OLinearHashingTable() {
CHAIN_NUMBER = 1;
size = 0;
level = 0;
next = 0;
maxCapacity = 0.8;
minCapacity = 0.7;
primaryIndex = new OLinearHashingIndex();
secondaryIndex = new OLinearHashingIndex();
groupOverflowTable = new OGroupOverflowTable();
pageIndicator = new OPageIndicator();
file = new ArrayList<OLinearHashingBucket>(FILE_SIZE);
file.add(new OLinearHashingBucket());
primaryIndex.addNewPosition();
}
public boolean put(V value) {
int[] hash = calculateHash((K) value.clusterPosition);
final boolean result = tryInsertIntoChain(hash, value);
if (result) {
size++;
}
splitBucketsIfNeeded();
return result;
}
private int[] calculateHash(K key) {
int internalHash = OLinearHashingHashCalculatorFactory.INSTANCE.calculateNaturalOrderedHash(key, level);
final int bucketNumber;
final int currentLevel;
if (internalHash < next) {
bucketNumber = calculateNextHash(key);
currentLevel = level + 1;
} else {
bucketNumber = OLinearHashingHashCalculatorFactory.INSTANCE.calculateBucketNumber(internalHash, level);
currentLevel = level;
}
return new int[] { bucketNumber, currentLevel };
}
private int calculateNextHash(K key) {
int keyHash = OLinearHashingHashCalculatorFactory.INSTANCE.calculateNaturalOrderedHash(key, level + 1);
return OLinearHashingHashCalculatorFactory.INSTANCE.calculateBucketNumber(keyHash, level + 1);
}
private boolean tryInsertIntoChain(final int[] hash, V value) {
int chainDisplacement = primaryIndex.getChainDisplacement(hash[0]);
// try to store record in main bucket
int pageToStore;
final byte keySignature;
if (chainDisplacement > 253) {
return storeRecordInBucket(hash[0], value, true);
} else {
byte chainSignature = primaryIndex.getChainSignature(hash[0]);
keySignature = OLinearHashingHashCalculatorFactory.INSTANCE.calculateSignature(value.clusterPosition);
if (keySignature < chainSignature) {
moveLargestRecordToRecordPool(hash[0], chainSignature);
final boolean result = storeRecordInBucket(hash[0], value, true);
storeRecordFromRecordPool();
return result;
} else if (keySignature == chainSignature) {
recordPool.add(value);
size--;
moveLargestRecordToRecordPool(hash[0], chainSignature);
OLinearHashingBucket bucket = file.get(hash[0]);
primaryIndex.updateSignature(hash[0], bucket.keys, bucket.size);
storeRecordFromRecordPool();
return true;
} else {
if (chainDisplacement == 253) {
// allocate new page
return allocateNewPageAndStore(hash[0], hash[0], value, hash[1], true);
} else {
pageToStore = findNextPageInChain(hash[0], hash[1], chainDisplacement);
}
}
}
// try to store in overflow bucket chain
while (true) {
int realPosInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(pageToStore);
chainDisplacement = secondaryIndex.getChainDisplacement(realPosInSecondaryIndex);
if (chainDisplacement > 253) {
return storeRecordInBucket(pageToStore, value, false);
} else {
int chainSignature = secondaryIndex.getChainSignature(realPosInSecondaryIndex);
if (keySignature < chainSignature) {
moveLargestRecordToRecordPool(pageToStore, (byte) chainSignature);
final boolean result = storeRecordInBucket(pageToStore, value, false);
storeRecordFromRecordPool();
return result;
} else if (keySignature == chainSignature) {
recordPool.add(value);
size--;
moveLargestRecordToRecordPool(pageToStore, (byte) chainSignature);
OLinearHashingBucket bucket = file.get(pageToStore);
secondaryIndex.updateSignature(realPosInSecondaryIndex, bucket.keys, bucket.size);
storeRecordFromRecordPool();
return true;
} else {
if (chainDisplacement == 253) {
// allocate new page
return allocateNewPageAndStore(hash[0], pageToStore, value, hash[1], false);
} else {
pageToStore = findNextPageInChain(hash[0], hash[1], chainDisplacement);
}
}
}
}
}
private void splitBucketsIfNeeded() {
// calculate load factor
double capacity = ((double) size) / (primaryIndex.bucketCount() * OLinearHashingBucket.BUCKET_MAX_SIZE);
if (capacity > maxCapacity) {
int bucketNumberToSplit = OLinearHashingHashCalculatorFactory.INSTANCE.calculateBucketNumber(next, level);
// TODO make this durable by inventing cool record pool
loadChainInPool(bucketNumberToSplit, level);
int pageToStore = next + (int) Math.pow(2, level);
byte groupWithStartingPageLessThan = groupOverflowTable.getGroupWithStartingPageLessThenOrEqual(pageToStore);
if (groupWithStartingPageLessThan != -2) {
int groupSize = groupOverflowTable.getSizeForGroup(groupWithStartingPageLessThan);
boolean needMove = false;
// TODO use group size from group overflow to prevent collisions
for (int i = pageToStore; i < pageToStore + groupSize; ++i) {
if (pageIndicator.get(i)) {
needMove = true;
break;
}
}
if (needMove) {
moveOverflowGroupToNewPosition(pageToStore);
}
}
primaryIndex.addNewPosition(pageToStore);
while (file.size() < pageToStore + 1) {
file.add(null);
}
file.set(pageToStore, new OLinearHashingBucket());
groupOverflowTable.moveDummyGroupIfNeeded(pageToStore, calculateGroupSize(level + 1));
next++;
if (next == (CHAIN_NUMBER * Math.pow(2, level))) {
next = 0;
level++;
}
storeRecordFromRecordPool();
}
}
private void mergeBucketIfNeeded() {
// calculate load factor
double capacity = ((double) size) / (primaryIndex.bucketCount() * OLinearHashingBucket.BUCKET_MAX_SIZE);
if (capacity < minCapacity && level > 0) {
// TODO make this durable by inventing cool record pool
final int naturalOrderKey1;
final int bucketNumberToMerge1;
final int bucketNumberToMerge2;
final int currentLevel;
if (next == 0) {
currentLevel = level;
naturalOrderKey1 = (int) (CHAIN_NUMBER * Math.pow(2, level)) - 2;
bucketNumberToMerge1 = OLinearHashingHashCalculatorFactory.INSTANCE.calculateBucketNumber(naturalOrderKey1, level);
bucketNumberToMerge2 = (int) Math.pow(2, level) - 1;
} else {
currentLevel = level + 1;
naturalOrderKey1 = 2 * (next - 1);
bucketNumberToMerge1 = OLinearHashingHashCalculatorFactory.INSTANCE.calculateBucketNumber(naturalOrderKey1, level + 1);
bucketNumberToMerge2 = next - 1 + (int) Math.pow(2, level);
}
loadChainInPool(bucketNumberToMerge1, currentLevel);
loadChainInPool(bucketNumberToMerge2, currentLevel);
primaryIndex.remove(bucketNumberToMerge2);
file.set(bucketNumberToMerge2, null);
next--;
if (next < 0) {
level--;
next = (int) (CHAIN_NUMBER * Math.pow(2, level) - 1);
}
storeRecordFromRecordPool();
}
}
private void moveOverflowGroupToNewPosition(int page) {
List<OGroupOverflowTable.GroupOverflowInfo> groupsToMove = groupOverflowTable.getOverflowGroupsInfoToMove(page);
for (OGroupOverflowTable.GroupOverflowInfo groupOverflowInfo : groupsToMove) {
int oldPage = groupOverflowInfo.startingPage;
int groupSize = groupOverflowTable.getSizeForGroup(groupOverflowInfo.group);
int newPage = groupOverflowTable.move(groupOverflowInfo.group, groupSize);
moveGroupToNewPosition(oldPage, newPage, groupSize);
}
}
private void moveGroupToNewPosition(int oldPage, int newPage, int groupSize) {
while (file.size() < newPage + groupSize + 1) {
file.add(null);
}
for (int i = oldPage; i < oldPage + groupSize; ++i) {
if (pageIndicator.get(i)) {
OLinearHashingBucket bucket = file.get(i);
file.set(i - oldPage + newPage, bucket);
file.set(i, null);
// move resords in secondary index
int oldPositionInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(i);
pageIndicator.set(i - oldPage + newPage);
pageIndicator.unset(i);
int newPositionInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(i - oldPage + newPage);
secondaryIndex.moveRecord(oldPositionInSecondaryIndex, newPositionInSecondaryIndex);
}
}
}
private void loadChainInPool(final int bucketNumber, final int currentLevel) {
Collection<V> content = file.get(bucketNumber).getContent();
size -= content.size();
recordPool.addAll(content);
file.get(bucketNumber).emptyBucket();
int displacement = primaryIndex.getChainDisplacement(bucketNumber);
int pageToUse;
while (displacement < 253) {
pageToUse = findNextPageInChain(bucketNumber, currentLevel, displacement);
content = file.get(pageToUse).getContent();
size -= content.size();
recordPool.addAll(content);
file.get(pageToUse).emptyBucket();
int realPosInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(pageToUse);
displacement = secondaryIndex.getChainDisplacement(realPosInSecondaryIndex);
// free index
pageIndicator.unset(pageToUse);
secondaryIndex.remove(realPosInSecondaryIndex);
}
groupOverflowTable.removeUnusedGroups(pageIndicator);
primaryIndex.clearChainInfo(bucketNumber);
}
private void storeRecordFromRecordPool() {
while (!recordPool.isEmpty()) {
V key = recordPool.remove(0);
// TODO be sure that key successfully stored
if (!put(key)) {
throw new RuntimeException("error while saving records from pool");
}
}
}
private void moveLargestRecordToRecordPool(int chainNumber, byte signature) {
OLinearHashingBucket bucket = file.get(chainNumber);
List<V> largestRecords = bucket.getLargestRecords(signature);
recordPool.addAll(largestRecords);
size -= largestRecords.size();
}
private int findNextPageInChain(int bucketNumber, int currentLevel, int chainDisplacement) {
byte groupNumber = calculateGroupNumber(bucketNumber, currentLevel);
int startingPage = groupOverflowTable.getPageForGroup(groupNumber);
if (startingPage == -1) {
return -1;
}
return startingPage + chainDisplacement;
}
private boolean allocateNewPageAndStore(int bucketNumber, int pageToStore, V value, int currentLevel, boolean mainChain) {
int groupSize = calculateGroupSize(level);
byte groupNumber = calculateGroupNumber(bucketNumber, currentLevel);
int[] pos = groupOverflowTable.searchForGroupOrCreate(groupNumber, groupSize);
int pageToUse = pageIndicator.getFirstEmptyPage(pos[0], pos[1]);
int actualStartingPage = pos[0];
if (pageToUse == -1) {
if (pos[1] == MAX_GROUP_SIZE) {
throw new OGroupOverflowException("There is no empty page for group size " + groupSize + " because pages "
+ pageIndicator.toString() + " are already allocated." + "Starting page is " + pos[0]);
} else {
groupSize = pos[1] * 2;
int newStartingPage = groupOverflowTable.enlargeGroupSize(groupNumber, groupSize);
moveGroupToNewPosition(pos[0], newStartingPage, pos[1]);
pageToUse = pageIndicator.getFirstEmptyPage(newStartingPage, groupSize);
actualStartingPage = newStartingPage;
}
}
// update displacement of existing index element
if (mainChain) {
primaryIndex.updateDisplacement(pageToStore, (byte) (pageToUse - actualStartingPage));
} else {
int realPosInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(actualStartingPage + pageToStore - pos[0]);
secondaryIndex.updateDisplacement(realPosInSecondaryIndex, (byte) (pageToUse - actualStartingPage));
}
pageIndicator.set(pageToUse);
int realPosInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(pageToUse);
secondaryIndex.addNewPosition(realPosInSecondaryIndex);
OLinearHashingBucket bucket = new OLinearHashingBucket();
while (file.size() < pageToUse + 1) {
file.add(null);
}
file.set(pageToUse, bucket);
return storeRecordInBucket(pageToUse, value, false);
}
private boolean storeRecordInBucket(final int bucketNumber, V value, boolean mainBucket) {
final OLinearHashingBucket bucket = file.get(bucketNumber);
for (int i = 0; i < bucket.size; i++) {
if (value.clusterPosition.equals(bucket.keys[i])) {
return false;
}
}
bucket.keys[bucket.size] = value.clusterPosition;
bucket.values[bucket.size] = value;
bucket.size++;
final int positionInIndex;
final OLinearHashingIndex indexToUse;
if (mainBucket) {
positionInIndex = bucketNumber;
indexToUse = primaryIndex;
} else {
positionInIndex = pageIndicator.getRealPosInSecondaryIndex(bucketNumber);
indexToUse = secondaryIndex;
}
int displacement = indexToUse.incrementChainDisplacement(positionInIndex, bucket.size);
if (bucket.size == OLinearHashingBucket.BUCKET_MAX_SIZE && displacement > 253) {
throw new RuntimeException("this can't be true");
}
byte [] signatures = new byte[bucket.size];
for (int i = 0, keysLength = bucket.size; i < keysLength; i++){
signatures[i] = OLinearHashingHashCalculatorFactory.INSTANCE.calculateSignature(bucket.keys[i]);
}
if (displacement <= 253) {
indexToUse.updateSignature(positionInIndex, bucket.keys, bucket.size);
}
return true;
}
private byte calculateGroupNumber(int bucketNumber, int currentLevel) {
final int groupSize;
groupSize = calculateGroupSize(currentLevel);
int x = (int) (CHAIN_NUMBER * Math.pow(2, currentLevel) + bucketNumber - 1);
int y = x / groupSize;
return (byte) (y % 31);
}
private int calculateGroupSize(final int iLevel) {
int divisor = 0;
byte no = -1;
double nogps;
do {
if (divisor < 128) {
no++;
}
divisor = (int) Math.pow(2, 2 + no);
nogps = (CHAIN_NUMBER * Math.pow(2, iLevel)) / divisor;
} while (!((nogps <= 31) || (divisor == 128)));
return divisor;
}
public boolean contains(K clusterPosition) {
final int[] hash = calculateHash(clusterPosition);
byte keySignature = OLinearHashingHashCalculatorFactory.INSTANCE.calculateSignature(clusterPosition);
byte signature = primaryIndex.getChainSignature(hash[0]);
int pageNumberToUse = hash[0];
int chainDisplacement = primaryIndex.getChainDisplacement(hash[0]);
byte groupNumber = calculateGroupNumber(hash[0], hash[1]);
int pageNumber = groupOverflowTable.getPageForGroup(groupNumber);
while (true) {
if (keySignature > signature) {
if (chainDisplacement >= 253) {
return false;
} else {
pageNumberToUse = pageNumber + chainDisplacement;
int realPosInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(pageNumberToUse);
signature = secondaryIndex.getChainSignature(realPosInSecondaryIndex);
chainDisplacement = secondaryIndex.getChainDisplacement(realPosInSecondaryIndex);
}
} else {
OLinearHashingBucket bucket = file.get(pageNumberToUse);
return bucket != null && bucket.get(clusterPosition) != null;
}
}
}
public boolean delete(K key) {
final int[] hash = calculateHash(key);
byte keySignature = OLinearHashingHashCalculatorFactory.INSTANCE.calculateSignature(key);
byte signature = primaryIndex.getChainSignature(hash[0]);
int pageNumberToUse = hash[0];
int chainDisplacement = primaryIndex.getChainDisplacement(hash[0]);
byte groupNumber = calculateGroupNumber(hash[0], hash[1]);
int pageNumber = groupOverflowTable.getPageForGroup(groupNumber);
int prevPage = hash[0];
while (true) {
if (keySignature > signature) {
if (chainDisplacement >= 253) {
return false;
} else {
prevPage = pageNumberToUse;
pageNumberToUse = pageNumber + chainDisplacement;
int realPosInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(pageNumberToUse);
signature = secondaryIndex.getChainSignature(realPosInSecondaryIndex);
chainDisplacement = secondaryIndex.getChainDisplacement(realPosInSecondaryIndex);
}
} else {
OLinearHashingBucket bucket = file.get(pageNumberToUse);
int position = bucket.deleteKey(key);
if (position >= 0) {
// move record from successor to current bucket
while (chainDisplacement < 253) {
prevPage = pageNumberToUse;
pageNumberToUse = pageNumber + chainDisplacement;
int realPosInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(pageNumberToUse);
chainDisplacement = secondaryIndex.getChainDisplacement(realPosInSecondaryIndex);
OLinearHashingBucket secondBucket = file.get(pageNumberToUse);
List<V> smallestRecords = secondBucket.getSmallestRecords(OLinearHashingBucket.BUCKET_MAX_SIZE - bucket.size);
if (smallestRecords.isEmpty()) {
// do nothing!
} else {
// move this records to predecessor
bucket.add(smallestRecords);
for (V smallestRecord : smallestRecords) {
if (secondBucket.deleteKey(smallestRecord.clusterPosition) < 0) {
throw new IllegalStateException("error while deleting record to move it to predecessor bucket");
}
}
secondaryIndex.updateSignature(realPosInSecondaryIndex, secondBucket.keys, secondBucket.size);
}
// update signatures after removing some records from buckets
if (prevPage == hash[0]) {
if (primaryIndex.getChainDisplacement(hash[0]) > 253) {
primaryIndex.updateSignature(hash[0], Byte.MAX_VALUE);
} else {
primaryIndex.updateSignature(hash[0], bucket.keys, bucket.size);
}
} else {
int indexPosition = pageIndicator.getRealPosInSecondaryIndex(prevPage);
if (primaryIndex.getChainDisplacement(hash[0]) > 253) {
secondaryIndex.updateSignature(indexPosition, Byte.MAX_VALUE);
} else {
secondaryIndex.updateSignature(indexPosition, bucket.keys, bucket.size);
}
}
bucket = secondBucket;
}
// update displacement and signature in last bucket
if (pageNumberToUse == hash[0]) {
// main bucket does not have overflow chain
int displacement = primaryIndex.decrementDisplacement(hash[0], bucket.size);
if (displacement <= 253) {
primaryIndex.updateSignature(hash[0], bucket.keys, bucket.size);
} else {
primaryIndex.updateSignature(hash[0], Byte.MAX_VALUE);
}
} else {
int realPosInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(pageNumberToUse);
if (bucket.size == 0) {
secondaryIndex.remove(realPosInSecondaryIndex);
pageIndicator.unset(pageNumberToUse);
// set prev bucket in chain correct displacement
if (prevPage == hash[0]) {
int displacement = primaryIndex.decrementDisplacement(hash[0], file.get(hash[0]).size, true);
if (displacement > 253) {
primaryIndex.updateSignature(hash[0], Byte.MAX_VALUE);
}
} else {
int prevIndexPosition = pageIndicator.getRealPosInSecondaryIndex(prevPage);
int displacement = secondaryIndex.decrementDisplacement(prevIndexPosition, file.get(prevPage).size, true);
if (displacement > 253) {
secondaryIndex.updateSignature(prevIndexPosition, Byte.MAX_VALUE);
}
}
} else {
int displacement = secondaryIndex.decrementDisplacement(realPosInSecondaryIndex, bucket.size);
if (displacement <= 253) {
secondaryIndex.updateSignature(realPosInSecondaryIndex, bucket.keys, bucket.size);
} else {
secondaryIndex.updateSignature(realPosInSecondaryIndex, Byte.MAX_VALUE);
}
}
}
} else {
return false;
}
size--;
mergeBucketIfNeeded();
return true;
}
}
}
public void clear() {
file.clear();
primaryIndex.clear();
secondaryIndex.clear();
pageIndicator.clear();
groupOverflowTable.clear();
file.add(new OLinearHashingBucket());
primaryIndex.addNewPosition();
}
public long size() {
return size;
}
public V get(K clusterPosition) {
final int[] hash = calculateHash(clusterPosition);
byte keySignature = OLinearHashingHashCalculatorFactory.INSTANCE.calculateSignature(clusterPosition);
byte signature = primaryIndex.getChainSignature(hash[0]);
int pageNumberToUse = hash[0];
int chainDisplacement = primaryIndex.getChainDisplacement(hash[0]);
byte groupNumber = calculateGroupNumber(hash[0], hash[1]);
int pageNumber = groupOverflowTable.getPageForGroup(groupNumber);
while (true) {
if (keySignature > signature) {
if (chainDisplacement >= 253) {
return null;
} else {
pageNumberToUse = pageNumber + chainDisplacement;
int realPosInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(pageNumberToUse);
signature = secondaryIndex.getChainSignature(realPosInSecondaryIndex);
chainDisplacement = secondaryIndex.getChainDisplacement(realPosInSecondaryIndex);
}
} else {
OLinearHashingBucket bucket = file.get(pageNumberToUse);
if (bucket != null) {
return (V) bucket.get(clusterPosition);
}
return null;
}
}
}
public K nextRecord(K currentRecord) {
return nextRecord(currentRecord, false, +1);
}
private K nextRecord(K currentRecord, boolean nextNaturalOrderedKeyShouldBeUsed, int step) {
final K[] result = getKeySet(currentRecord, nextNaturalOrderedKeyShouldBeUsed, step);
if (result.length == 0) {
return null;
}
Arrays.sort(result);
final int recordPosition;
recordPosition = Arrays.binarySearch(result, currentRecord);
if (recordPosition >= 0 || recordPosition < -result.length) {
if (recordPosition == result.length - 1 || recordPosition < -result.length) {
return nextRecord(currentRecord, true, +1);
} else {
return result[recordPosition + 1];
}
} else {
return result[-(recordPosition + 1)];
}
}
public K prevRecord(K currentRecord) {
return prevRecord(currentRecord, false, -1);
}
private K prevRecord(K currentRecord, boolean nextNaturalOrderedKeyShouldBeUsed, int step) {
final K[] result = getKeySet(currentRecord, nextNaturalOrderedKeyShouldBeUsed, step);
if (result.length == 0) {
return null;
}
Arrays.sort(result);
final int recordPosition = Arrays.binarySearch(result, currentRecord);
if (recordPosition >= 0 || recordPosition == -1) {
if (recordPosition == 0 || recordPosition == -1) {
return prevRecord(currentRecord, true, -1);
} else {
return result[recordPosition - 1];
}
} else {
return result[-(recordPosition + 2)];
}
}
private K[] getKeySet(K currentRecord, boolean nextNaturalOrderedKeyShouldBeUsed, int step) {
List<OLinearHashingBucket> chain = new ArrayList<OLinearHashingBucket>();
boolean nextLevel = false;
int naturalOrderedKey = OLinearHashingHashCalculatorFactory.INSTANCE.calculateNaturalOrderedHash(currentRecord, level);
if (naturalOrderedKey < next) {
naturalOrderedKey = OLinearHashingHashCalculatorFactory.INSTANCE.calculateNaturalOrderedHash(currentRecord, level + 1);
nextLevel = true;
}
if (nextNaturalOrderedKeyShouldBeUsed) {
naturalOrderedKey += step;
if (nextLevel && naturalOrderedKey >= 2 * next && step > 0) {
naturalOrderedKey = naturalOrderedKey / 2;
nextLevel = false;
}
if (!nextLevel && naturalOrderedKey < next && step < 0) {
naturalOrderedKey = naturalOrderedKey * 2 + 1;
nextLevel = true;
}
}
int bucketNumber;
if (nextLevel) {
bucketNumber = OLinearHashingHashCalculatorFactory.INSTANCE.calculateBucketNumber(naturalOrderedKey, level + 1);
} else {
bucketNumber = OLinearHashingHashCalculatorFactory.INSTANCE.calculateBucketNumber(naturalOrderedKey, level);
}
int displacement = primaryIndex.getChainDisplacement(bucketNumber);
// load buckets from overflow positions
while (displacement < 253) {
int pageToUse = findNextPageInChain(bucketNumber, nextLevel ? level + 1 : level, displacement);
int realPosInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(pageToUse);
displacement = secondaryIndex.getChainDisplacement(realPosInSecondaryIndex);
OLinearHashingBucket bucket = file.get(pageToUse);
chain.add(bucket);
}
OLinearHashingBucket bucket = file.get(bucketNumber);
final K[] result;
if (chain.size() == 0) {
result = (K[]) new OClusterPosition[bucket.size];
System.arraycopy(bucket.keys, 0, result, 0, bucket.size);
} else {
chain.add(bucket);
int amountOfRecords = 0;
for (OLinearHashingBucket chainElement : chain) {
amountOfRecords += chainElement.size;
}
result = (K[]) new OClusterPosition[amountOfRecords];
int freePositionInArrayPointer = 0;
for (OLinearHashingBucket chainElement : chain) {
System.arraycopy(chainElement.keys, 0, result, freePositionInArrayPointer, chainElement.size);
freePositionInArrayPointer += chainElement.size;
}
}
return result;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.hazelcast.sharding;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import com.orientechnologies.common.concur.resource.OSharedResourceAdaptiveExternal;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.util.MersenneTwister;
import com.orientechnologies.orient.core.cache.OLevel2RecordCache;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.config.OStorageConfiguration;
import com.orientechnologies.orient.core.id.OClusterPosition;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.storage.OAutoshardedStorage;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.ODataSegment;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.ORecordCallback;
import com.orientechnologies.orient.core.storage.ORecordDuplicatedException;
import com.orientechnologies.orient.core.storage.OStorageEmbedded;
import com.orientechnologies.orient.core.storage.OStorageOperationResult;
import com.orientechnologies.orient.core.tx.OTransaction;
import com.orientechnologies.orient.core.version.ORecordVersion;
import com.orientechnologies.orient.server.distributed.ODistributedException;
import com.orientechnologies.orient.server.distributed.ODistributedThreadLocal;
import com.orientechnologies.orient.server.hazelcast.sharding.distributed.ODHTConfiguration;
import com.orientechnologies.orient.server.hazelcast.sharding.distributed.ODHTNode;
import com.orientechnologies.orient.server.hazelcast.sharding.hazelcast.ServerInstance;
/**
* Implementation of the Autosharded storage. This storage is build on Distributed Hash Table principle. Each storage is responsible
* for the part of record ids range (ids are generated by random). In addition storage holds data from other ranges to prevent data
* lose.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @since 8/28/12
*/
public class OAutoshardedStorageImpl implements OAutoshardedStorage {
protected final OStorageEmbedded wrapped;
private final ServerInstance serverInstance;
private final MersenneTwister positionGenerator = new MersenneTwister();
private final Set<Integer> undistributedClusters = new HashSet<Integer>();
/**
* For parallel query execution on different nodes
*/
public OAutoshardedStorageImpl(ServerInstance serverInstance, OStorageEmbedded wrapped, ODHTConfiguration dhtConfiguration) {
this.serverInstance = serverInstance;
this.wrapped = wrapped;
for (String clusterName : dhtConfiguration.getUndistributableClusters()) {
undistributedClusters.add(wrapped.getClusterIdByName(clusterName));
}
}
@Override
public long getStorageId() {
return serverInstance.getLocalNode().getNodeId();
}
@Override
public OStorageOperationResult<OPhysicalPosition> createRecord(int iDataSegmentId, ORecordId iRecordId, byte[] iContent,
ORecordVersion iRecordVersion, byte iRecordType, int iMode, ORecordCallback<OClusterPosition> iCallback) {
if (undistributedClusters.contains(iRecordId.getClusterId())) {
return wrapped.createRecord(iDataSegmentId, iRecordId, iContent, iRecordVersion, iRecordType, iMode, iCallback);
}
OPhysicalPosition result;
int retryCount = 0;
while (true) {
try {
if (iRecordId.isNew())
iRecordId.clusterPosition = OClusterPositionFactory.INSTANCE.valueOf(Math.abs(positionGenerator.nextLong()));
final ODHTNode node = serverInstance.findSuccessor(iRecordId.clusterPosition.longValue());
if (node.isLocal()) {
OLogManager.instance().info(this, "Record " + iRecordId.toString() + " has been distributed to this node.");
return wrapped.createRecord(iDataSegmentId, iRecordId, iContent, iRecordVersion, iRecordType, iMode, iCallback);
} else
result = node.createRecord(wrapped.getName(), iRecordId, iContent, iRecordVersion, iRecordType);
break;
} catch (ORecordDuplicatedException e) {
if (retryCount > 10) {
throw e;
}
retryCount++;
}
}
iRecordId.clusterPosition = result.clusterPosition;
return new OStorageOperationResult<OPhysicalPosition>(result, true);
}
@Override
public OStorageOperationResult<ORawBuffer> readRecord(ORecordId iRid, String iFetchPlan, boolean iIgnoreCache,
ORecordCallback<ORawBuffer> iCallback) {
if (undistributedClusters.contains(iRid.getClusterId())) {
return wrapped.readRecord(iRid, iFetchPlan, iIgnoreCache, iCallback);
}
final ODHTNode node = serverInstance.findSuccessor(iRid.clusterPosition.longValue());
if (node.isLocal())
return wrapped.readRecord(iRid, iFetchPlan, iIgnoreCache, iCallback);
else
return new OStorageOperationResult<ORawBuffer>(node.readRecord(wrapped.getName(), iRid), true);
}
@Override
public OStorageOperationResult<ORecordVersion> updateRecord(ORecordId iRecordId, byte[] iContent, ORecordVersion iVersion,
byte iRecordType, int iMode, ORecordCallback<ORecordVersion> iCallback) {
if (undistributedClusters.contains(iRecordId.getClusterId())) {
return wrapped.updateRecord(iRecordId, iContent, iVersion, iRecordType, iMode, iCallback);
}
final ODHTNode node = serverInstance.findSuccessor(iRecordId.clusterPosition.longValue());
if (node.isLocal())
return wrapped.updateRecord(iRecordId, iContent, iVersion, iRecordType, iMode, iCallback);
else
return new OStorageOperationResult<ORecordVersion>(node.updateRecord(wrapped.getName(), iRecordId, iContent, iVersion,
iRecordType), true);
}
@Override
public OStorageOperationResult<Boolean> deleteRecord(ORecordId iRecordId, ORecordVersion iVersion, int iMode,
ORecordCallback<Boolean> iCallback) {
if (ODistributedThreadLocal.INSTANCE.distributedExecution || undistributedClusters.contains(iRecordId.getClusterId())) {
return wrapped.deleteRecord(iRecordId, iVersion, iMode, iCallback);
}
final ODHTNode node = serverInstance.findSuccessor(iRecordId.clusterPosition.longValue());
if (node.isLocal())
return wrapped.deleteRecord(iRecordId, iVersion, iMode, iCallback);
else
return new OStorageOperationResult<Boolean>(node.deleteRecord(wrapped.getName(), iRecordId, iVersion), true);
}
@Override
public boolean cleanOutRecord(ORecordId recordId, ORecordVersion recordVersion, int iMode, ORecordCallback<Boolean> callback) {
return wrapped.cleanOutRecord(recordId, recordVersion, iMode, callback);
}
@Override
public Object command(OCommandRequestText iCommand) {
return OQueryExecutorsFactory.INSTANCE.getExecutor(iCommand, wrapped, serverInstance, undistributedClusters).execute();
}
public boolean existsResource(final String iName) {
return wrapped.existsResource(iName);
}
public <T> T removeResource(final String iName) {
return wrapped.removeResource(iName);
}
public <T> T getResource(final String iName, final Callable<T> iCallback) {
return wrapped.getResource(iName, iCallback);
}
public void open(final String iUserName, final String iUserPassword, final Map<String, Object> iProperties) {
wrapped.open(iUserName, iUserPassword, iProperties);
}
public void create(final Map<String, Object> iProperties) {
wrapped.create(iProperties);
}
public boolean exists() {
return wrapped.exists();
}
public void reload() {
wrapped.reload();
}
public void delete() {
wrapped.delete();
}
public void close() {
wrapped.close();
}
public void close(final boolean iForce) {
wrapped.close(iForce);
}
public boolean isClosed() {
return wrapped.isClosed();
}
public OLevel2RecordCache getLevel2Cache() {
return wrapped.getLevel2Cache();
}
public void commit(final OTransaction iTx) {
throw new ODistributedException("Transactions are not supported in distributed environment");
}
public void rollback(final OTransaction iTx) {
throw new ODistributedException("Transactions are not supported in distributed environment");
}
public OStorageConfiguration getConfiguration() {
return wrapped.getConfiguration();
}
public int getClusters() {
return wrapped.getClusters();
}
public Set<String> getClusterNames() {
return wrapped.getClusterNames();
}
public OCluster getClusterById(int iId) {
return wrapped.getClusterById(iId);
}
public Collection<? extends OCluster> getClusterInstances() {
return wrapped.getClusterInstances();
}
public int addCluster(final String iClusterType, final String iClusterName, final String iLocation,
final String iDataSegmentName, final Object... iParameters) {
return wrapped.addCluster(iClusterType, iClusterName, iLocation, iDataSegmentName, iParameters);
}
public boolean dropCluster(final String iClusterName) {
return wrapped.dropCluster(iClusterName);
}
public boolean dropCluster(final int iId) {
return wrapped.dropCluster(iId);
}
public int addDataSegment(final String iDataSegmentName) {
return wrapped.addDataSegment(iDataSegmentName);
}
public int addDataSegment(final String iSegmentName, final String iDirectory) {
return wrapped.addDataSegment(iSegmentName, iDirectory);
}
public long count(final int iClusterId) {
return wrapped.count(iClusterId);
}
public long count(final int[] iClusterIds) {
return wrapped.count(iClusterIds);
}
public long getSize() {
return wrapped.getSize();
}
public long countRecords() {
return wrapped.countRecords();
}
public int getDefaultClusterId() {
return wrapped.getDefaultClusterId();
}
public void setDefaultClusterId(final int defaultClusterId) {
wrapped.setDefaultClusterId(defaultClusterId);
}
public int getClusterIdByName(String iClusterName) {
return wrapped.getClusterIdByName(iClusterName);
}
public String getClusterTypeByName(final String iClusterName) {
return wrapped.getClusterTypeByName(iClusterName);
}
public String getPhysicalClusterNameById(final int iClusterId) {
return wrapped.getPhysicalClusterNameById(iClusterId);
}
public boolean checkForRecordValidity(final OPhysicalPosition ppos) {
return wrapped.checkForRecordValidity(ppos);
}
public String getName() {
return wrapped.getName();
}
public String getURL() {
return wrapped.getURL();
}
public long getVersion() {
return wrapped.getVersion();
}
public void synch() {
wrapped.synch();
}
public int getUsers() {
return wrapped.getUsers();
}
public int addUser() {
return wrapped.addUser();
}
public int removeUser() {
return wrapped.removeUser();
}
public OClusterPosition[] getClusterDataRange(final int currentClusterId) {
return wrapped.getClusterDataRange(currentClusterId);
}
public <V> V callInLock(final Callable<V> iCallable, final boolean iExclusiveLock) {
return wrapped.callInLock(iCallable, iExclusiveLock);
}
public ODataSegment getDataSegmentById(final int iDataSegmentId) {
return wrapped.getDataSegmentById(iDataSegmentId);
}
public int getDataSegmentIdByName(final String iDataSegmentName) {
return wrapped.getDataSegmentIdByName(iDataSegmentName);
}
public boolean dropDataSegment(final String iName) {
return wrapped.dropDataSegment(iName);
}
public STATUS getStatus() {
return wrapped.getStatus();
}
@Override
public void changeRecordIdentity(ORID originalId, ORID newId) {
wrapped.changeRecordIdentity(originalId, newId);
}
@Override
public boolean isLHClustersAreUsed() {
return wrapped.isLHClustersAreUsed();
}
@Override
public OClusterPosition getNextClusterPosition(int currentClusterId, OClusterPosition clusterPosition) {
return wrapped.getNextClusterPosition(currentClusterId, clusterPosition);
}
@Override
public OClusterPosition getPrevClusterPosition(int currentClusterId, OClusterPosition clusterPosition) {
return wrapped.getPrevClusterPosition(currentClusterId, clusterPosition);
}
@Override
public OSharedResourceAdaptiveExternal getLock() {
return wrapped.getLock();
}
@Override
public String getType() {
return "autoshareded";
}
@Override
public void checkForClusterPermissions(final String iClusterName) {
wrapped.checkForClusterPermissions(iClusterName);
}
}
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.test.java.collection;
import com.orientechnologies.common.directmemory.OBuddyMemory;
import com.orientechnologies.common.directmemory.collections.ODirectMemoryList;
import com.orientechnologies.common.serialization.types.OStringSerializer;
/**
* @author <NAME>
* @since 12.08.12
*/
public class DirectMemoryListSpeedTest extends CollectionBaseAbstractSpeedTest {
private ODirectMemoryList<String> arrayList;
public DirectMemoryListSpeedTest() {
super(10000000);
}
@Override
public void cycle() {
for (String item : arrayList) {
if (item.equals(searchedValue))
break;
}
}
@Override
public void init() {
arrayList = new ODirectMemoryList<String>(new OBuddyMemory(100 * 1024 * 1024, 32), OStringSerializer.INSTANCE);
for (int i = 0; i < collectionSize; ++i) {
arrayList.add(String.valueOf(i));
}
}
public void deInit() {
arrayList.clear();
arrayList = null;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.metadata.function;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.hook.ODocumentHookAbstract;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* Update the in-memory function library.
*
* @author <NAME>
*/
public class OFunctionTrigger extends ODocumentHookAbstract {
public OFunctionTrigger() {
setIncludeClasses("OFunction");
}
@Override
public void onRecordAfterCreate(final ODocument iDocument) {
reloadLibrary();
}
@Override
public void onRecordAfterUpdate(final ODocument iDocument) {
reloadLibrary();
}
@Override
public void onRecordAfterDelete(final ODocument iDocument) {
reloadLibrary();
}
protected void reloadLibrary() {
final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.get();
db.getMetadata().getFunctionLibrary().load();
}
}
<file_sep>/*
*
* Copyright 2012 <NAME> (molino.luca--AT--gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.test.domain.base;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.Id;
import javax.persistence.Transient;
import javax.persistence.Version;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.test.domain.business.Child;
/**
* @author luca.molino
*
*/
public class JavaAttachDetachTestClass {
public static final String testStatic = "10";
@Transient
public String testTransient;
@Id
public Object id;
@Version
public Object version;
public ODocument embeddedDocument;
public ODocument document;
public ORecordBytes byteArray;
public String name;
public Map<String, Child> children = new HashMap<String, Child>();
public List<EnumTest> enumList = new ArrayList<EnumTest>();
public Set<EnumTest> enumSet = new HashSet<EnumTest>();
public Map<String, EnumTest> enumMap = new HashMap<String, EnumTest>();
public String text = "initTest";
public EnumTest enumeration;
public int numberSimple = 0;
public long longSimple = 0l;
public double doubleSimple = 0d;
public float floatSimple = 0f;
public byte byteSimple = 0;
public boolean flagSimple = false;
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.version;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.serialization.OBinaryProtocol;
import com.orientechnologies.orient.core.util.OHostInfo;
/**
*
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @since 10/25/12
*/
public class OVersionFactory {
private static final OVersionFactory instance = new OVersionFactory();
private static final boolean useDistributed = OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean();
private static final long macAddress = convertMacToLong(OHostInfo.getMac());
private static long convertMacToLong(byte[] mac) {
long result = 0;
for (int i = mac.length - 1; i >= 0; i--) {
result = (result << 8) | (mac[i] & 0xFF);
}
return result;
}
public ORecordVersion createVersion() {
if (useDistributed) {
return new ODistributedVersion(0);
} else {
return new OSimpleVersion();
}
}
public ORecordVersion createTombstone() {
if (useDistributed) {
return new ODistributedVersion(-1);
} else {
return new OSimpleVersion(-1);
}
}
public ORecordVersion createUntrackedVersion() {
if (useDistributed) {
return new ODistributedVersion(-1);
} else {
return new OSimpleVersion(-1);
}
}
public static OVersionFactory instance() {
return instance;
}
long getMacAddress() {
return macAddress;
}
public boolean isDistributed() {
return useDistributed;
}
public int getVersionSize() {
if (useDistributed)
return OBinaryProtocol.SIZE_INT + 2 * OBinaryProtocol.SIZE_LONG;
else
return OBinaryProtocol.SIZE_INT;
}
public ODistributedVersion createDistributedVersion(int recordVersion, long timestamp, long macAddress) {
return new ODistributedVersion(recordVersion, timestamp, macAddress);
}
}
<file_sep>package com.orientechnologies.orient.core.id;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author <NAME>
* @since 16.11.12
*/
@Test
public class NodeIdTest {
public void testOneOneAddValues() {
ONodeId one = ONodeId.valueOf(1);
ONodeId two = one.add(one);
String result = two.toHexString();
Assert.assertEquals(result, "000000000000000000000000000000000000000000000002");
}
public void testAddOverflowValue() {
ONodeId one = ONodeId.valueOf(0xFFFFFFFFFL);
ONodeId two = one.add(ONodeId.ONE);
String result = two.toHexString();
Assert.assertEquals(result, "000000000000000000000000000000000000001000000000");
}
public void testAddOverflowValues() {
ONodeId one = ONodeId.valueOf(0xFFFFFFFFFL);
ONodeId two = one.add(ONodeId.valueOf(0xFFFFFFFFFL));
String result = two.toHexString();
Assert.assertEquals(result, "000000000000000000000000000000000000001ffffffffe");
}
public void testAddOverflow() {
ONodeId one = ONodeId.MAX_VALUE;
ONodeId two = one.add(ONodeId.ONE);
String result = two.toHexString();
Assert.assertEquals(result, "000000000000000000000000000000000000000000000000");
}
public void testAddSamePositiveAndNegativeNumbers() {
ONodeId one = ONodeId.parseString("1234567895623");
ONodeId two = ONodeId.parseString("-1234567895623");
ONodeId result = one.add(two);
Assert.assertEquals(result, ONodeId.ZERO);
}
public void testAddPositiveMoreNegativeNumbers() {
ONodeId one = ONodeId.parseString("12358971234567895622");
ONodeId two = ONodeId.parseString("-1234567895623");
ONodeId result = one.add(two);
Assert.assertEquals(result, ONodeId.parseString("12358969999999999999"));
}
public void testAddPositiveLessNegativeNumbers() {
ONodeId one = ONodeId.parseString("1234567895623");
ONodeId two = ONodeId.parseString("-12358971234567895622");
ONodeId result = one.add(two);
Assert.assertEquals(result, ONodeId.parseString("-12358969999999999999"));
}
public void testAddToZeroPositive() {
ONodeId one = ONodeId.parseString("1234567895623");
ONodeId two = ONodeId.parseString("0");
ONodeId result = one.add(two);
Assert.assertEquals(result, ONodeId.parseString("1234567895623"));
}
public void testAddToZeroNegative() {
ONodeId one = ONodeId.parseString("-1234567895623");
ONodeId two = ONodeId.parseString("0");
ONodeId result = one.add(two);
Assert.assertEquals(result, ONodeId.parseString("-1234567895623"));
}
public void testAddZeroToPositive() {
ONodeId two = ONodeId.ZERO.add(ONodeId.parseString("1234567895623"));
Assert.assertEquals(two, ONodeId.parseString("1234567895623"));
}
public void testAddZeroToNegative() {
ONodeId two = ONodeId.ZERO.add(ONodeId.parseString("-1234567895623"));
Assert.assertEquals(two, ONodeId.parseString("-1234567895623"));
}
public void testSubtractTwoMinusOne() {
ONodeId one = ONodeId.valueOf(2);
ONodeId two = one.subtract(ONodeId.ONE);
String result = two.toHexString();
Assert.assertEquals(result, "000000000000000000000000000000000000000000000001");
}
public void testSubtractOverflowValue() {
ONodeId one = ONodeId.valueOf(0xF0000000L);
ONodeId two = one.subtract(ONodeId.ONE);
String result = two.toHexString();
Assert.assertEquals(result, "0000000000000000000000000000000000000000efffffff");
}
public void testSubtractOverflowValueTwo() {
ONodeId one = ONodeId.valueOf(0xF0000000L);
ONodeId two = ONodeId.ONE.subtract(one);
String result = two.toHexString();
Assert.assertEquals(result, "-0000000000000000000000000000000000000000efffffff");
}
public void testSubtractToNegativeResult() {
ONodeId one = ONodeId.ZERO;
ONodeId two = one.subtract(ONodeId.ONE);
String result = two.toHexString();
Assert.assertEquals(result, "-000000000000000000000000000000000000000000000001");
}
public void testSubtractZero() {
ONodeId one = ONodeId.parseString("451234567894123456987465");
ONodeId two = one.subtract(ONodeId.ZERO);
Assert.assertEquals(two, ONodeId.parseString("451234567894123456987465"));
}
public void testSubtractFromZeroPositive() {
ONodeId one = ONodeId.parseString("451234567894123456987465");
ONodeId two = ONodeId.ZERO.subtract(one);
Assert.assertEquals(two, ONodeId.parseString("-451234567894123456987465"));
}
public void testSubtractFromZeroNegative() {
ONodeId one = ONodeId.parseString("-451234567894123456987465");
ONodeId two = ONodeId.ZERO.subtract(one);
Assert.assertEquals(two, ONodeId.parseString("451234567894123456987465"));
}
public void testSubtractZeroFromZero() {
ONodeId two = ONodeId.ZERO.subtract(ONodeId.ZERO);
Assert.assertEquals(two, ONodeId.ZERO);
}
public void testSubtractFromNegativePositive() {
ONodeId one = ONodeId.parseString("-99999999999999");
ONodeId two = ONodeId.parseString("10");
ONodeId result = one.subtract(two);
Assert.assertEquals(result, ONodeId.parseString("-100000000000009"));
}
public void testSubtractFromPositiveNegative() {
ONodeId one = ONodeId.parseString("99999999999999");
ONodeId two = ONodeId.parseString("-10");
ONodeId result = one.subtract(two);
Assert.assertEquals(result, ONodeId.parseString("100000000000009"));
}
public void testSubtractSamePositiveNumbers() {
ONodeId one = ONodeId.parseString("1245796317821536854785");
ONodeId two = ONodeId.parseString("1245796317821536854785");
ONodeId result = one.subtract(two);
Assert.assertEquals(result, ONodeId.ZERO);
}
public void testSubtractSameNegativeNumbers() {
ONodeId one = ONodeId.parseString("-1245796317821536854785");
ONodeId two = ONodeId.parseString("-1245796317821536854785");
ONodeId result = one.subtract(two);
Assert.assertEquals(result, ONodeId.ZERO);
}
public void testSubtractFromMaxNegativeOnePositive() {
ONodeId result = ONodeId.MIN_VALUE.subtract(ONodeId.ONE);
Assert.assertEquals(result, ONodeId.ZERO);
}
public void testSubtractFromMaxPositiveOneNegative() {
ONodeId result = ONodeId.MAX_VALUE.subtract(ONodeId.parseString("-1"));
Assert.assertEquals(result, ONodeId.ZERO);
}
public void testMultiplyTwoAndFive() {
ONodeId one = ONodeId.valueOf(2);
ONodeId two = one.multiply(5);
String result = two.toHexString();
Assert.assertEquals(result, "00000000000000000000000000000000000000000000000a");
}
public void testMultiplyOnZero() {
ONodeId one = ONodeId.valueOf(2);
ONodeId two = one.multiply(0);
Assert.assertEquals(two, ONodeId.ZERO);
}
public void testMultiplyOverflowNumbers() {
ONodeId one = ONodeId.valueOf(0xFFFFFFFFFL);
ONodeId two = one.multiply(26);
String result = two.toHexString();
Assert.assertEquals(result, "000000000000000000000000000000000000019fffffffe6");
}
public void testLeftShift2Bits() {
ONodeId nodeOne = ONodeId.valueOf(0xFFFFFFFFDL);
ONodeId two = nodeOne.shiftLeft(2);
String result = two.toHexString();
Assert.assertEquals(result, "000000000000000000000000000000000000003ffffffff4");
}
public void testLeftShift32Bits() {
ONodeId nodeOne = ONodeId.valueOf(0xFFFFFFFFDL);
ONodeId two = nodeOne.shiftLeft(32);
String result = two.toHexString();
Assert.assertEquals(result, "0000000000000000000000000000000ffffffffd00000000");
}
public void testLeftShift34Bits() {
ONodeId nodeOne = ONodeId.valueOf(0xFFFFFFFFDL);
ONodeId two = nodeOne.shiftLeft(34);
String result = two.toHexString();
Assert.assertEquals(result, "0000000000000000000000000000003ffffffff400000000");
}
public void testLeftShiftTillZero() {
ONodeId nodeOne = ONodeId.valueOf(0xFFFFFFFFDL);
ONodeId two = nodeOne.shiftLeft(192);
Assert.assertEquals(two, ONodeId.ZERO);
}
public void testLeftShiftTillZeroTwo() {
ONodeId nodeOne = ONodeId.parseHexSting("0000000000000000000000000000003ffffffff400000000");
ONodeId two = nodeOne.shiftLeft(160);
Assert.assertEquals(two, ONodeId.ZERO);
}
public void testRightShift2Bits() {
ONodeId nodeOne = ONodeId.valueOf(0xAAAFFFFFFFFDL);
ONodeId two = nodeOne.shiftRight(2);
String result = two.toHexString();
Assert.assertEquals(result, "0000000000000000000000000000000000002aabffffffff");
}
public void testRightShift32Bits() {
ONodeId nodeOne = ONodeId.valueOf(0xAAAFFFFFFFFDL);
ONodeId two = nodeOne.shiftRight(32);
String result = two.toHexString();
Assert.assertEquals(result, "00000000000000000000000000000000000000000000aaaf");
}
public void testRightShift34Bits() {
ONodeId nodeOne = ONodeId.valueOf(0xAAAFFFFFFFFDL);
ONodeId two = nodeOne.shiftRight(34);
String result = two.toHexString();
Assert.assertEquals(result, "000000000000000000000000000000000000000000002aab");
}
public void testRightShiftTillZero() {
ONodeId nodeOne = ONodeId.valueOf(0xFFFFFFFFDL);
ONodeId two = nodeOne.shiftRight(192);
Assert.assertEquals(two, ONodeId.ZERO);
}
public void testRightShiftTillZeroTwo() {
ONodeId nodeOne = ONodeId.parseHexSting("0000000000000000000000000000003ffffffff400000000");
ONodeId two = nodeOne.shiftRight(72);
Assert.assertEquals(two, ONodeId.ZERO);
}
public void testIntValue() {
final ONodeId nodeId = ONodeId.valueOf(0xAAAFFFFFFFFDL);
Assert.assertEquals(0xFFFFFFFD, nodeId.intValue());
}
public void testToValueOfFromString() {
final ONodeId nodeId = ONodeId.parseHexSting("00<KEY>000000123000000000000002aab");
Assert.assertEquals(nodeId.toHexString(), "001<KEY>0000000000123000000000000002aab");
}
public void testToStream() {
final ONodeId nodeId = ONodeId.parseHexSting("00<KEY>0000000000123000000000000002aab");
byte[] expectedResult = new byte[25];
expectedResult[0] = 0;
expectedResult[1] = 0x12;
expectedResult[2] = 0x34;
expectedResult[3] = 0x56;
expectedResult[4] = 0x78;
expectedResult[5] = (byte) 0x9A;
expectedResult[6] = (byte) 0xBC;
expectedResult[7] = (byte) 0xDE;
expectedResult[8] = (byte) 0xF0;
expectedResult[9] = (byte) 0x00;
expectedResult[10] = (byte) 0x00;
expectedResult[11] = (byte) 0x00;
expectedResult[12] = (byte) 0x00;
expectedResult[13] = (byte) 0x01;
expectedResult[14] = (byte) 0x23;
expectedResult[15] = (byte) 0x00;
expectedResult[16] = (byte) 0x00;
expectedResult[17] = (byte) 0x00;
expectedResult[18] = (byte) 0x00;
expectedResult[19] = (byte) 0x00;
expectedResult[20] = (byte) 0x00;
expectedResult[21] = (byte) 0x00;
expectedResult[22] = (byte) 0x2a;
expectedResult[23] = (byte) 0xab;
expectedResult[24] = (byte) 1;
Assert.assertEquals(nodeId.toStream(), expectedResult);
}
public void testChunksToByteArray() {
final ONodeId nodeId = ONodeId.parseHexSting("00123456789abcdef0000000000123000000000000002aab");
byte[] expectedResult = new byte[24];
expectedResult[0] = 0;
expectedResult[1] = 0x12;
expectedResult[2] = 0x34;
expectedResult[3] = 0x56;
expectedResult[4] = 0x78;
expectedResult[5] = (byte) 0x9A;
expectedResult[6] = (byte) 0xBC;
expectedResult[7] = (byte) 0xDE;
expectedResult[8] = (byte) 0xF0;
expectedResult[9] = (byte) 0x00;
expectedResult[10] = (byte) 0x00;
expectedResult[11] = (byte) 0x00;
expectedResult[12] = (byte) 0x00;
expectedResult[13] = (byte) 0x01;
expectedResult[14] = (byte) 0x23;
expectedResult[15] = (byte) 0x00;
expectedResult[16] = (byte) 0x00;
expectedResult[17] = (byte) 0x00;
expectedResult[18] = (byte) 0x00;
expectedResult[19] = (byte) 0x00;
expectedResult[20] = (byte) 0x00;
expectedResult[21] = (byte) 0x00;
expectedResult[22] = (byte) 0x2a;
expectedResult[23] = (byte) 0xab;
Assert.assertEquals(nodeId.chunksToByteArray(), expectedResult);
}
public void testLongValuePositive() {
final ONodeId nodeId = ONodeId.parseHexSting("00123456789abcdef000000000012300ecffaabb12342aab");
Assert.assertEquals(nodeId.longValue(), 0x6cffaabb12342aabL);
}
public void testLongValueNegative() {
final ONodeId nodeId = ONodeId.parseHexSting("-00123456789abcdef000000000012300ecffaabb12342aab");
Assert.assertEquals(nodeId.longValue(), -0x6cffaabb12342aabL);
}
public void testIntValuePositive() {
final ONodeId nodeId = ONodeId.parseHexSting("00123456789abcdef000000000012300ecffaabb12342aab");
Assert.assertEquals(nodeId.intValue(), 0x12342aab);
}
public void testIntValueNegative() {
final ONodeId nodeId = ONodeId.parseHexSting("-00123456789abcdef000000000012300ecffaabb12342aab");
Assert.assertEquals(nodeId.intValue(), -0x12342aab);
}
public void testFromStreamPositive() {
final ONodeId nodeId = ONodeId.parseString("1343412555467812");
final byte[] content = nodeId.toStream();
final ONodeId deserializedNodeId = ONodeId.fromStream(content, 0);
Assert.assertEquals(nodeId, deserializedNodeId);
}
public void testFromStreamNegative() {
final ONodeId nodeId = ONodeId.parseString("-1343412555467812");
final byte[] content = nodeId.toStream();
final ONodeId deserializedNodeId = ONodeId.fromStream(content, 0);
Assert.assertEquals(nodeId, deserializedNodeId);
}
public void testFromStreamZero() {
final ONodeId nodeId = ONodeId.parseString("0");
final byte[] content = nodeId.toStream();
final ONodeId deserializedNodeId = ONodeId.fromStream(content, 0);
Assert.assertEquals(nodeId, deserializedNodeId);
}
public void testFromStreamPositiveWithOffset() {
final ONodeId nodeId = ONodeId.parseString("1343412555467812");
final byte[] content = nodeId.toStream();
final byte[] contentWithOffset = new byte[content.length + 10];
System.arraycopy(content, 0, contentWithOffset, 5, content.length);
final ONodeId deserializedNodeId = ONodeId.fromStream(contentWithOffset, 5);
Assert.assertEquals(nodeId, deserializedNodeId);
}
public void testFromStreamNegativeWithOffset() {
final ONodeId nodeId = ONodeId.parseString("-1343412555467812");
final byte[] content = nodeId.toStream();
final byte[] contentWithOffset = new byte[content.length + 10];
System.arraycopy(content, 0, contentWithOffset, 5, content.length);
final ONodeId deserializedNodeId = ONodeId.fromStream(contentWithOffset, 5);
Assert.assertEquals(nodeId, deserializedNodeId);
}
public void testFromStreamZeroWithOffset() {
final ONodeId nodeId = ONodeId.parseString("0");
final byte[] content = nodeId.toStream();
final byte[] contentWithOffset = new byte[content.length + 10];
System.arraycopy(content, 0, contentWithOffset, 5, content.length);
final ONodeId deserializedNodeId = ONodeId.fromStream(contentWithOffset, 5);
Assert.assertEquals(nodeId, deserializedNodeId);
}
public void testCompareToRIDNodeIdCompatibility() {
final TreeSet<ONodeId> nodeIds = new TreeSet<ONodeId>();
final TreeSet<ORecordId> recordIds = new TreeSet<ORecordId>();
for (int i = 0; i < 10000; i++) {
final ONodeId nodeId = ONodeId.generateUniqueId();
nodeIds.add(nodeId);
recordIds.add(new ORecordId(1, new OClusterPositionNodeId(nodeId)));
}
final Iterator<ORecordId> recordIdIterator = recordIds.iterator();
for (final ONodeId nodeId : nodeIds) {
final ORecordId recordId = recordIdIterator.next();
Assert.assertEquals(recordId, new ORecordId(1, new OClusterPositionNodeId(nodeId)));
}
Assert.assertFalse(recordIdIterator.hasNext());
}
public void testNodeIdSerializaion() throws Exception {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
final List<ONodeId> serializedNodes = new ArrayList<ONodeId>();
for (int i = 0; i < 10000; i++) {
final ONodeId nodeId = ONodeId.generateUniqueId();
objectOutputStream.writeObject(nodeId);
serializedNodes.add(nodeId);
}
objectOutputStream.close();
byte[] serializedContent = out.toByteArray();
final ByteArrayInputStream in = new ByteArrayInputStream(serializedContent);
final ObjectInputStream objectInputStream = new ObjectInputStream(in);
for (ONodeId nodeId : serializedNodes) {
final ONodeId deserializedNodeId = (ONodeId) objectInputStream.readObject();
Assert.assertEquals(deserializedNodeId, nodeId);
}
Assert.assertEquals(objectInputStream.available(), 0);
}
}
<file_sep>package com.orientechnologies.orient.graph.gremlin;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.orientechnologies.orient.core.db.graph.OGraphDatabase;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/**
* If some of the tests start to fail then check cluster number in queries, e.g #7:1. It can be because the order of clusters could
* be affected due to adding or removing cluster from storage.
*/
public class LocalGremlinTest {
public static void main(String[] args) {
LocalGremlinTest instance = new LocalGremlinTest();
long start = System.currentTimeMillis();
instance.function();
System.out.println("function: " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
instance.command();
System.out.println("command: " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
instance.testMultipleExpressions();
System.out.println("testMultipleExpressions: " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
instance.testMultipleExpressionsSideEffects();
System.out.println("testMultipleExpressionsSideEffects: " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
instance.testGremlinAgainstBlueprints();
System.out.println("testGremlinAgainstBlueprints: " + (System.currentTimeMillis() - start));
}
public LocalGremlinTest() {
OGremlinHelper.global().create();
}
@Test
public void function() {
OGraphDatabase db = new OGraphDatabase("local:target/databases/tinkerpop");
db.open("admin", "admin");
ODocument vertex1 = (ODocument) db.createVertex().field("label", "car").save();
ODocument vertex2 = (ODocument) db.createVertex().field("label", "pilot").save();
db.createEdge(vertex1, vertex2).field("label", "drives").save();
List<?> result = db.query(new OSQLSynchQuery<Object>(
"select gremlin('current.out.in') as value from V where out.size() > 0 limit 3"));
System.out.println("Query result: " + result);
result = db.query(new OSQLSynchQuery<Object>("select gremlin('current.out') as value from V"));
System.out.println("Query result: " + result);
int clusterId = db.getVertexBaseClass().getDefaultClusterId();
result = db.query(new OSQLSynchQuery<Object>("select gremlin('current.out.in') as value from " + clusterId + ":1"));
System.out.println("Query result: " + result);
result = db.query(new OSQLSynchQuery<Object>("select gremlin('current.out(\"drives\").count()') as value from V"));
System.out.println("Query result: " + result);
result = db.query(new OSQLSynchQuery<Object>("select gremlin('current.out') as value from V order by label"));
System.out.println("Query result: " + result);
db.close();
}
@Test
public void command() {
OGraphDatabase db = new OGraphDatabase("local:target/databases/tinkerpop");
db.open("admin", "admin");
List<OIdentifiable> result = db.command(new OCommandGremlin("g.V[0..10]")).execute();
if (result != null) {
for (OIdentifiable doc : result) {
System.out.println(doc.getRecord().toJSON());
}
}
Map<String, Object> params = new HashMap<String, Object>();
params.put("par1", 100);
result = db.command(new OCommandSQL("select gremlin('current.out.filter{ it.performances > par1 }') from V")).execute(params);
System.out.println("Command result: " + result);
db.close();
}
@Test
public void testMultipleExpressions() {
OGraphDatabase db = new OGraphDatabase("local:target/databases/tinkerpop");
db.open("admin", "admin");
int clusterId = db.getVertexBaseClass().getDefaultClusterId();
List<OIdentifiable> result = db.command(new OCommandSQL("SELECT gremlin('m = []; m << 1; m;') FROM #" + clusterId + ":1"))
.execute();
Assert.assertEquals(1, result.size());
Assert.assertEquals(1, ((Collection<?>) ((ODocument) result.get(0)).field("gremlin")).iterator().next());
db.close();
}
@Test
public void testMultipleExpressionsSideEffects() {
OGraphDatabase db = new OGraphDatabase("local:target/databases/tinkerpop");
db.open("admin", "admin");
int clusterId = db.getVertexBaseClass().getDefaultClusterId();
List<OIdentifiable> result = db.command(
new OCommandSQL(
"SELECT gremlin('m = []; current.out.sideEffect({ m << it.id }).out.out.sideEffect({ m << it.id })') FROM #"
+ clusterId + ":1")).execute();
Assert.assertEquals(1, result.size());
System.out.println("Query result: " + result);
db.close();
}
@Test
public void testGremlinAgainstBlueprints() {
OGremlinHelper.global().create();
OrientGraph graph = new OrientGraph("local:target/databases/tinkerpop");
final int NUM_ITERS = 1000;
long start = System.currentTimeMillis();
try {
for (int i = NUM_ITERS; i > 0; i--) {
List<Vertex> r = graph.getRawGraph().command(new OCommandGremlin("g.V[1].out.out.in")).execute();
System.out.println(i + " = found: " + r.size() + " items");
}
System.out.println("Total: " + (System.currentTimeMillis() - start) + " ms AVG: "
+ ((System.currentTimeMillis() - start) / (float) NUM_ITERS));
} catch (Exception x) {
x.printStackTrace();
System.out.println(graph.getRawGraph().isClosed());
}
}
}
<file_sep>package com.orientechnologies.orient.core.storage;
/**
* This class represent CRUD operation result RET is the actual result Stores addition information about command execution process
* Flag {@code isMoved == true} indicates that operation has been executed on local OrientDB server node, {@code isMoved == false}
* indicates that operation has been executed on remote OrientDB node. This information will help to maintain local indexes and
* caches in consistent state
*
* @author edegtyarenko
* @since 28.09.12 13:47
*/
public class OStorageOperationResult<RET> {
private final RET result;
private final boolean isMoved;
public OStorageOperationResult(RET result) {
this(result, false);
}
public OStorageOperationResult(RET result, boolean moved) {
this.result = result;
isMoved = moved;
}
public boolean isMoved() {
return isMoved;
}
public RET getResult() {
return result;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.command.traverse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.orientechnologies.orient.core.command.OBasicCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.record.impl.ODocumentHelper;
public class OTraverseContext extends OBasicCommandContext {
private Set<ORID> history = new HashSet<ORID>();
private List<OTraverseAbstractProcess<?>> stack = new ArrayList<OTraverseAbstractProcess<?>>();
private int depth = -1;
public void push(final OTraverseAbstractProcess<?> iProcess) {
stack.add(iProcess);
}
public Map<String, Object> getVariables() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("depth", depth);
map.put("path", getPath());
map.put("stack", stack);
// DELEGATE
map.putAll(super.getVariables());
return map;
}
public Object getVariable(final String iName) {
final String name = iName.trim().toUpperCase();
if ("DEPTH".startsWith(name))
return depth;
else if (name.startsWith("PATH"))
return ODocumentHelper.getFieldValue(getPath(), iName.substring("PATH".length()));
else if (name.startsWith("STACK"))
return ODocumentHelper.getFieldValue(stack, iName.substring("STACK".length()));
else if (name.startsWith("HISTORY"))
return ODocumentHelper.getFieldValue(history, iName.substring("HISTORY".length()));
else
// DELEGATE
return super.getVariable(iName);
}
public OTraverseAbstractProcess<?> pop() {
if (stack.isEmpty())
throw new IllegalStateException("Traverse stack is empty");
return stack.remove(stack.size() - 1);
}
public OTraverseAbstractProcess<?> peek() {
return stack.isEmpty() ? null : stack.get(stack.size() - 1);
}
public OTraverseAbstractProcess<?> peek(final int iFromLast) {
return stack.size() + iFromLast < 0 ? null : stack.get(stack.size() + iFromLast);
}
public void reset() {
stack.clear();
}
public boolean isAlreadyTraversed(final OIdentifiable identity) {
return history.contains(identity.getIdentity());
}
public void addTraversed(final OIdentifiable identity) {
history.add(identity.getIdentity());
}
public int incrementDepth() {
return ++depth;
}
public int decrementDepth() {
return --depth;
}
public String getPath() {
final StringBuilder buffer = new StringBuilder();
for (OTraverseAbstractProcess<?> process : stack) {
final String status = process.getStatus();
if (status != null) {
if (buffer.length() > 0)
buffer.append('.');
buffer.append(status);
}
}
return buffer.toString();
}
}<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.memory;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.Map;
import com.orientechnologies.common.io.OFileUtils;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.profiler.OProfiler.METRIC_TYPE;
import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue;
import com.orientechnologies.orient.core.Orient;
/**
* This memory warning system will call the listener when we exceed the percentage of available memory specified. There should only
* be one instance of this object created, since the usage threshold can only be set to one number.
*/
public class OMemoryWatchDog extends Thread {
private final Map<Listener, Object> listeners = new IdentityHashMap<Listener, Object>(128);
private int alertTimes = 0;
protected ReferenceQueue<Object> monitorQueue = new ReferenceQueue<Object>();
protected SoftReference<Object> monitorRef = new SoftReference<Object>(new Object(), monitorQueue);
public static interface Listener {
/**
* Execute a soft free of memory resources.
*
* @param iType
* OS or JVM
* @param iFreeMemory
* Current used memory
* @param iFreeMemoryPercentage
* Max memory
*/
public void memoryUsageLow(long iFreeMemory, long iFreeMemoryPercentage);
}
/**
* Create the memory watch dog with the default memory threshold.
*
* @param iThreshold
*/
public OMemoryWatchDog() {
super("OrientDB MemoryWatchDog");
setDaemon(true);
start();
}
public void run() {
Orient
.instance()
.getProfiler()
.registerHookValue("system.memory.alerts", "Number of alerts received by JVM to free memory resources",
METRIC_TYPE.COUNTER, new OProfilerHookValue() {
public Object getValue() {
return alertTimes;
}
});
while (true) {
try {
// WAITS FOR THE GC FREE
monitorQueue.remove();
// GC is freeing memory!
alertTimes++;
long maxMemory = Runtime.getRuntime().maxMemory();
long freeMemory = Runtime.getRuntime().freeMemory();
int freeMemoryPer = (int) (freeMemory * 100 / maxMemory);
if (OLogManager.instance().isDebugEnabled())
OLogManager.instance().debug(this, "Free memory is low %s of %s (%d%%), calling listeners to free memory...",
OFileUtils.getSizeAsString(freeMemory), OFileUtils.getSizeAsString(maxMemory), freeMemoryPer);
final long timer = Orient.instance().getProfiler().startChrono();
synchronized (listeners) {
for (Listener listener : listeners.keySet()) {
try {
listener.memoryUsageLow(freeMemory, freeMemoryPer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Orient.instance().getProfiler().stopChrono("OMemoryWatchDog.freeResources", "WatchDog free resources", timer);
} catch (Exception e) {
} finally {
// RE-INSTANTIATE THE MONITOR REF
monitorRef = new SoftReference<Object>(new Object(), monitorQueue);
}
}
}
public Collection<Listener> getListeners() {
synchronized (listeners) {
return listeners.keySet();
}
}
public Listener addListener(final Listener listener) {
synchronized (listeners) {
listeners.put(listener, listener);
}
return listener;
}
public boolean removeListener(final Listener listener) {
synchronized (listeners) {
return listeners.remove(listener) != null;
}
}
public static void freeMemory(final long iDelayTime) {
// INVOKE GC AND WAIT A BIT
System.gc();
if (iDelayTime > 0)
try {
Thread.sleep(iDelayTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.test.database.auto;
import java.util.List;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.orientechnologies.common.concur.ONeedRetryException;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.OCommandSQL;
@Test
public class ConcurrentQueriesTest {
private final static int THREADS = 10;
protected String url;
static class CommandExecutor implements Runnable {
String url;
String threadName;
public CommandExecutor(String url, String iThreadName) {
super();
this.url = url;
threadName = iThreadName;
}
public void run() {
try {
for (int i = 0; i < 50; i++) {
ODatabaseDocumentTx db = new ODatabaseDocumentTx(url).open("admin", "admin");
try {
while (true) {
try {
List<ODocument> result = db.command(new OCommandSQL("select from Concurrent")).execute();
System.out.println("Thread " + threadName + ", step " + i + ", result = " + result.size());
break;
} catch (ONeedRetryException e) {
// e.printStackTrace();
System.out.println("Retry...");
}
}
} finally {
db.close();
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
@Parameters(value = "url")
public ConcurrentQueriesTest(@Optional(value = "memory:test") String iURL) {
url = iURL;
}
@BeforeClass
public void init() {
if ("memory:test".equals(url))
new ODatabaseDocumentTx(url).create().close();
ODatabaseDocumentTx db = new ODatabaseDocumentTx(url).open("admin", "admin");
db.getMetadata().getSchema().createClass("Concurrent");
for (int i = 0; i < 1000; ++i) {
db.newInstance("Concurrent").field("test", i).save();
}
}
@Test
public void concurrentCommands() throws Exception {
Thread[] threads = new Thread[THREADS];
System.out.println("Spanning " + THREADS + " threads...");
for (int i = 0; i < THREADS; ++i) {
threads[i] = new Thread(new CommandExecutor(url, "thread" + i), "ConcurrentTest1");
}
System.out.println("Starting " + THREADS + " threads...");
for (int i = 0; i < THREADS; ++i) {
threads[i].start();
}
System.out.println("Waiting for " + THREADS + " threads...");
for (int i = 0; i < THREADS; ++i) {
threads[i].join();
}
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.command.script;
import java.util.Map;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.command.OCommandExecutorAbstract;
import com.orientechnologies.orient.core.command.OCommandRequest;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.db.record.ODatabaseRecordTx;
/**
* Executes Script Commands.
*
* @see OCommandScript
* @author <NAME>
*
*/
public class OCommandExecutorScript extends OCommandExecutorAbstract {
protected OCommandScript request;
public OCommandExecutorScript() {
}
@SuppressWarnings("unchecked")
public OCommandExecutorScript parse(final OCommandRequest iRequest) {
request = (OCommandScript) iRequest;
return this;
}
public Object execute(final Map<Object, Object> iArgs) {
return executeInContext(null, iArgs);
}
public Object executeInContext(final OCommandContext iContext, final Map<Object, Object> iArgs) {
final String language = request.getLanguage();
parserText = request.getText();
ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
if (db != null && !(db instanceof ODatabaseRecordTx))
db = db.getUnderlying();
final OScriptManager scriptManager = Orient.instance().getScriptManager();
final ScriptEngine scriptEngine = scriptManager.getEngine(language);
final Bindings binding = scriptManager.bind(scriptEngine, (ODatabaseRecordTx) db, iContext, iArgs);
try {
// COMPILE FUNCTION LIBRARY
String lib = scriptManager.getLibrary(db, language);
if (lib == null)
lib = "";
parserText = lib + parserText;
return scriptEngine.eval(parserText, binding);
} catch (ScriptException e) {
throw new OCommandScriptException("Error on execution of the script", request.getText(), e.getColumnNumber(), e);
} finally {
scriptManager.unbind(binding);
}
}
public boolean isIdempotent() {
return false;
}
@Override
protected void throwSyntaxErrorException(String iText) {
throw new OCommandScriptException("Error on execution of the script: " + iText, request.getText(), 0);
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.query.nativ;
import java.util.ArrayList;
import java.util.List;
import com.orientechnologies.orient.core.command.OCommandResultListener;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
@SuppressWarnings("serial")
public abstract class ONativeSynchQuery<CTX extends OQueryContextNative> extends ONativeAsynchQuery<CTX> implements
OCommandResultListener {
protected final List<ODocument> result = new ArrayList<ODocument>();
public ONativeSynchQuery(final ODatabaseRecord iDatabase, final String iCluster, final CTX iQueryRecordImpl) {
super(iCluster, iQueryRecordImpl, null);
resultListener = this;
}
public boolean result(final Object iRecord) {
result.add((ODocument) iRecord);
return true;
}
@Override
public List<ODocument> run(final Object... iArgs) {
result.clear();
super.run();
return result;
}
@Override
public ODocument runFirst(final Object... iArgs) {
super.run();
return result != null && !result.isEmpty() ? result.get(0) : null;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.storage;
import java.util.Arrays;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.config.OStorageClusterConfiguration;
import com.orientechnologies.orient.core.config.OStorageMemoryClusterConfiguration;
import com.orientechnologies.orient.core.config.OStorageMemoryLinearHashingClusterConfiguration;
import com.orientechnologies.orient.core.config.OStoragePhysicalClusterConfigurationLocal;
import com.orientechnologies.orient.core.config.OStoragePhysicalClusterLHPEPSConfiguration;
import com.orientechnologies.orient.core.exception.OStorageException;
import com.orientechnologies.orient.core.storage.impl.local.OClusterLocal;
import com.orientechnologies.orient.core.storage.impl.local.OClusterLocalLHPEPS;
import com.orientechnologies.orient.core.storage.impl.memory.OClusterMemory;
import com.orientechnologies.orient.core.storage.impl.memory.OClusterMemoryArrayList;
import com.orientechnologies.orient.core.storage.impl.memory.lh.OClusterMemoryLinearHashing;
public class ODefaultClusterFactory implements OClusterFactory {
protected static final String[] TYPES = { OClusterLocal.TYPE, OClusterMemory.TYPE };
public OCluster createCluster(final String iType) {
if (iType.equalsIgnoreCase(OClusterLocal.TYPE))
return OGlobalConfiguration.USE_LHPEPS_CLUSTER.getValueAsBoolean() ? new OClusterLocalLHPEPS() : new OClusterLocal();
else if (iType.equalsIgnoreCase(OClusterMemory.TYPE))
return OGlobalConfiguration.USE_LHPEPS_MEMORY_CLUSTER.getValueAsBoolean() ? new OClusterMemoryLinearHashing()
: new OClusterMemoryArrayList();
else
OLogManager.instance().exception(
"Cluster type '" + iType + "' is not supported. Supported types are: " + Arrays.toString(TYPES), null,
OStorageException.class);
return null;
}
public OCluster createCluster(final OStorageClusterConfiguration iConfig) {
if (iConfig instanceof OStoragePhysicalClusterConfigurationLocal)
return new OClusterLocal();
else if (iConfig instanceof OStoragePhysicalClusterLHPEPSConfiguration)
return new OClusterLocalLHPEPS();
else if (iConfig instanceof OStorageMemoryClusterConfiguration)
return new OClusterMemoryArrayList();
else if (iConfig instanceof OStorageMemoryLinearHashingClusterConfiguration)
return new OClusterMemoryLinearHashing();
else
OLogManager.instance().exception(
"Cluster type '" + iConfig + "' is not supported. Supported types are: " + Arrays.toString(TYPES), null,
OStorageException.class);
return null;
}
public String[] getSupported() {
return TYPES;
}
@Override
public boolean isSupported(final String iClusterType) {
for (String type : TYPES)
if (type.equalsIgnoreCase(iClusterType))
return true;
return false;
}
}
<file_sep>package com.orientechnologies.orient.graph.handler;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.graph.gremlin.OGremlinHelper;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.config.OServerParameterConfiguration;
import com.orientechnologies.orient.server.handler.OServerHandlerAbstract;
public class OGraphServerHandler extends OServerHandlerAbstract {
@Override
public void config(OServer oServer, OServerParameterConfiguration[] iParams) {
OLogManager.instance().info(this, "Installing GREMLIN language v.%s", OGremlinHelper.getEngineVersion());
}
@Override
public String getName() {
return "graph";
}
@Override
public void startup() {
OGremlinHelper.global().create();
}
@Override
public void shutdown() {
OGremlinHelper.global().destroy();
}
}
<file_sep>package com.orientechnologies.common.util;
import java.util.Iterator;
import javax.imageio.spi.ServiceRegistry;
public class OClassLoaderHelper {
/**
* Switch to the OrientDb classloader before lookups on ServiceRegistry for
* implementation of the given Class. Useful under OSGI and generally under
* applications where jars are loaded by another class loader
*
* @param clazz
* the class to lookup foor
* @return an Iterator on the class implementation
*/
public static synchronized <T extends Object> Iterator<T> lookupProviderWithOrientClassLoader(Class<T> clazz) {
return lookupProviderWithOrientClassLoader(clazz,OClassLoaderHelper.class.getClassLoader());
}
public static synchronized <T extends Object> Iterator<T> lookupProviderWithOrientClassLoader(Class<T> clazz,ClassLoader orientClassLoader) {
ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(orientClassLoader);
Iterator<T> lookupProviders = ServiceRegistry.lookupProviders(clazz);
Thread.currentThread().setContextClassLoader(origClassLoader);
return lookupProviders;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.hazelcast.sharding.hazelcast;
import java.io.IOException;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ITopic;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.command.OCommandResultListener;
import com.orientechnologies.orient.server.hazelcast.sharding.OCommandResultSerializationHelper;
import com.orientechnologies.orient.server.hazelcast.sharding.ODistributedSelectQueryExecutor;
/**
* This class provides functionality to async aggregation of result sets from different nodes to one that initiated query
*
* @author edegtyarenko
* @since 22.10.12 11:53
*/
public class OHazelcastResultListener implements OCommandResultListener {
public static final class EndOfResult {
private final long nodeId;
public EndOfResult(long nodeId) {
this.nodeId = nodeId;
}
public long getNodeId() {
return nodeId;
}
}
private final long storageId;
private final long selectId;
private final ITopic<byte[]> topic;
public OHazelcastResultListener(HazelcastInstance hazelcast, long storageId, long selectId) {
this.storageId = storageId;
this.selectId = selectId;
this.topic = hazelcast.getTopic(ODistributedSelectQueryExecutor.getResultTopicName(storageId, selectId));
}
@Override
public boolean result(Object iRecord) {
try {
topic.publish(OCommandResultSerializationHelper.writeToStream(iRecord));
return true;
} catch (IOException e) {
OLogManager.instance().error(this, "Error serializing record", e);
return false;
}
}
public long getStorageId() {
return storageId;
}
public long getSelectId() {
return selectId;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.hazelcast.sharding;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import com.hazelcast.core.ITopic;
import com.hazelcast.core.Message;
import com.hazelcast.core.MessageListener;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.util.OPair;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.command.OCommandResultListener;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.query.OQueryAbstract;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ODocumentHelper;
import com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect;
import com.orientechnologies.orient.core.sql.functions.OSQLFunction;
import com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime;
import com.orientechnologies.orient.core.sql.functions.coll.OSQLFunctionDistinct;
import com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.core.storage.OStorageEmbedded;
import com.orientechnologies.orient.server.hazelcast.sharding.hazelcast.OHazelcastResultListener;
import com.orientechnologies.orient.server.hazelcast.sharding.hazelcast.ServerInstance;
/**
* Executor for distributed select command and its result merge
*
* @author edegtyarenko
* @since 25.10.12 8:12
*/
public class ODistributedSelectQueryExecutor extends OAbstractDistributedQueryExecutor implements MessageListener<byte[]> {
private static final int QUEUE_SIZE = 100;
private static final AtomicLong SELECT_ID_GENERATOR = new AtomicLong(0);
private final long storageId;
private final long selectId;
private final boolean anyFunctionAggregate;
private final List<OPair<String, OSQLFunction>> mergers = new ArrayList<OPair<String, OSQLFunction>>();
private OPair<String, OSQLFunctionDistinct> distinct = null;
private List<OPair<String, String>> order = null;
private final int limit;
private final boolean async;
private final OCommandResultListener resultListener;
private final BlockingQueue<byte[]> plainResult = new ArrayBlockingQueue<byte[]>(QUEUE_SIZE);
private final ITopic<byte[]> resultTopic;
public ODistributedSelectQueryExecutor(OCommandRequestText iCommand, OCommandExecutorSQLSelect executor,
OStorageEmbedded wrapped, ServerInstance serverInstance) {
super(iCommand, wrapped, serverInstance);
this.selectId = SELECT_ID_GENERATOR.incrementAndGet();
this.storageId = serverInstance.getLocalNode().getNodeId();
this.anyFunctionAggregate = executor.isAnyFunctionAggregates();
if (executor.getProjections() != null) {
for (Map.Entry<String, Object> projection : executor.getProjections().entrySet()) {
if (projection.getValue() instanceof OSQLFunctionRuntime) {
final OSQLFunctionRuntime fr = (OSQLFunctionRuntime) projection.getValue();
if (fr.getFunction().shouldMergeDistributedResult()) {
mergers.add(new OPair<String, OSQLFunction>(projection.getKey(), fr.getFunction()));
} else if (fr.getFunction() instanceof OSQLFunctionDistinct) {
distinct = new OPair<String, OSQLFunctionDistinct>(projection.getKey(), (OSQLFunctionDistinct) fr.getFunction());
}
}
}
}
this.order = executor.getOrderedFields();
this.limit = executor.getLimit();
this.resultListener = (iCommand.getResultListener() != null && !(iCommand.getResultListener() instanceof OSQLSynchQuery)) ? iCommand
.getResultListener() : null;
this.async = resultListener != null && !anyFunctionAggregate && distinct == null && mergers.isEmpty() && order == null;
this.resultTopic = ServerInstance.getHazelcast().getTopic(getResultTopicName(storageId, selectId));
this.resultTopic.addMessageListener(this);
}
@Override
protected void addResult(Object result) {
// hear result is always null, no actions needed
}
@Override
public void onMessage(Message<byte[]> message) {
try {
plainResult.put(message.getMessageObject());
} catch (InterruptedException e) {
OLogManager.instance().warn(this, "Failed to put message into queue");
}
}
@Override
public Object execute() {
if (iCommand.getParameters().size() == 1) {
final Map.Entry<Object, Object> entry = iCommand.getParameters().entrySet().iterator().next();
if (entry.getKey().equals(Integer.valueOf(0)) && entry.getValue() == null) {
iCommand.getParameters().clear();
}
}
int remainingExecutors = runCommandOnAllNodes(new OSQLAsynchQuery(iCommand.getText(), iCommand.getLimit(),
iCommand instanceof OQueryAbstract ? ((OQueryAbstract) iCommand).getFetchPlan() : null, iCommand.getParameters(),
new OHazelcastResultListener(ServerInstance.getHazelcast(), storageId, selectId)));
int processed = 0;
final List<OIdentifiable> result = new ArrayList<OIdentifiable>();
while (true) {
try {
final byte[] plainItem = plainResult.take();
final Object item = OCommandResultSerializationHelper.readFromStream(plainItem);
if (item instanceof OIdentifiable) {
if (async) {
resultListener.result(item);
} else {
result.add((OIdentifiable) item);
}
processed++;
} else if (item instanceof OHazelcastResultListener.EndOfResult) {
remainingExecutors--;
} else {
throw new IllegalArgumentException("Invalid type provided");
}
} catch (InterruptedException e) {
OLogManager.instance().warn(this, "Failed to take message from queue");
} catch (IOException e) {
OLogManager.instance().warn(this, "Error deserializing result");
}
if (remainingExecutors <= failedNodes.get() || (async && limit != -1 && processed >= limit)) {
break;
}
}
resultTopic.destroy();
if (async) {
return null;
} else {
return processResult(result);
}
}
private List<OIdentifiable> processResult(List<OIdentifiable> result) {
final Map<String, Object> values = new HashMap<String, Object>();
for (OPair<String, OSQLFunction> merger : mergers) {
final List<Object> dataToMerge = new ArrayList<Object>();
for (OIdentifiable o : result) {
dataToMerge.add(((ODocument) o).field(merger.getKey()));
}
values.put(merger.getKey(), merger.getValue().mergeDistributedResult(dataToMerge));
}
if (distinct != null) {
final List<OIdentifiable> resultToMerge = new ArrayList<OIdentifiable>(result);
result.clear();
for (OIdentifiable record : resultToMerge) {
Object ret = distinct.getValue()
.execute(record, null, new Object[] { ((ODocument) record).field(distinct.getKey()) }, null);
if (ret != null) {
final ODocument resultItem = new ODocument().setOrdered(true); // ASSIGN A TEMPORARY RID TO ALLOW PAGINATION IF ANY
((ORecordId) resultItem.getIdentity()).clusterId = -2;
resultItem.field(distinct.getKey(), ret);
result.add(resultItem);
}
}
}
if (anyFunctionAggregate && !result.isEmpty()) {
// left only one result
final OIdentifiable doc = result.get(0);
result.clear();
result.add(doc);
}
// inject values
if (!values.isEmpty()) {
for (Map.Entry<String, Object> entry : values.entrySet()) {
for (OIdentifiable item : result) {
((ODocument) item).field(entry.getKey(), entry.getValue());
}
}
}
if (order != null) {
ODocumentHelper.sort(result, order);
}
if (limit != -1 && result.size() > limit) {
do {
result.remove(result.size() - 1);
} while (result.size() > limit);
}
if (!result.isEmpty() && result.get(0).getIdentity().getClusterId() == -2) {
long position = 0;
for (OIdentifiable id : result) {
((ORecordId) id.getIdentity()).clusterPosition = OClusterPositionFactory.INSTANCE.valueOf(position);
}
}
if (resultListener != null) {
for (Object o : result) {
resultListener.result(o);
}
}
return result;
}
public static String getResultTopicName(long storageId, long selectId) {
return new StringBuilder("query-").append(storageId).append("-").append(selectId).toString();
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.storage.impl.local;
import java.io.File;
import java.io.IOException;
import com.orientechnologies.common.concur.resource.OSharedResourceAdaptive;
import com.orientechnologies.common.io.OFileUtils;
import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.config.OStorageClusterConfiguration;
import com.orientechnologies.orient.core.config.OStorageClusterHoleConfiguration;
import com.orientechnologies.orient.core.config.OStorageFileConfiguration;
import com.orientechnologies.orient.core.config.OStoragePhysicalClusterConfiguration;
import com.orientechnologies.orient.core.config.OStoragePhysicalClusterConfigurationLocal;
import com.orientechnologies.orient.core.id.OClusterPosition;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.memory.OMemoryWatchDog;
import com.orientechnologies.orient.core.serialization.OBinaryProtocol;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OClusterEntryIterator;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.storage.fs.OFile;
import com.orientechnologies.orient.core.version.ORecordVersion;
import com.orientechnologies.orient.core.version.OVersionFactory;
/**
* Handles the table to resolve logical address to physical address. Deleted records have negative versions. <br/>
* <br/>
* Record structure:<br/>
* <code>
* +----------------------+----------------------+-------------+----------------------+<br/>
* | DATA SEGMENT........ | DATA OFFSET......... | RECORD TYPE | VERSION............. |<br/>
* | 2 bytes = max 2^15-1 | 8 bytes = max 2^63-1 | 1 byte..... | 4 bytes = max 2^31-1 |<br/>
* +----------------------+----------------------+-------------+----------------------+<br/>
* = 15 bytes
* </code><br/>
*/
public class OClusterLocal extends OSharedResourceAdaptive implements OCluster {
public static final int RECORD_SIZE = 11 + OVersionFactory.instance().getVersionSize();
public static final String TYPE = "PHYSICAL";
private static final int RECORD_TYPE_OFFSET = 10;
private static final String DEF_EXTENSION = ".ocl";
private static final int DEF_SIZE = 1000000;
private static final byte RECORD_WAS_DELETED = (byte) -1;
private OMultiFileSegment fileSegment;
private int id;
private long beginOffsetData = -1;
private long endOffsetData = -1; // end of
// data
// offset.
// -1 =
// latest
protected OClusterLocalHole holeSegment;
private OStoragePhysicalClusterConfigurationLocal config;
private OStorageLocal storage;
private String name;
public OClusterLocal() {
super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean());
}
public void configure(final OStorage iStorage, OStorageClusterConfiguration iConfig) throws IOException {
config = (OStoragePhysicalClusterConfigurationLocal) iConfig;
init(iStorage, config.getId(), config.getName(), config.getLocation(), config.getDataSegmentId());
}
public void configure(final OStorage iStorage, final int iId, final String iClusterName, final String iLocation,
final int iDataSegmentId, final Object... iParameters) throws IOException {
config = new OStoragePhysicalClusterConfigurationLocal(iStorage.getConfiguration(), iId, iDataSegmentId);
config.name = iClusterName;
init(iStorage, iId, iClusterName, iLocation, iDataSegmentId);
}
public void create(int iStartSize) throws IOException {
acquireExclusiveLock();
try {
if (iStartSize == -1)
iStartSize = DEF_SIZE;
if (config.root.clusters.size() <= config.id)
config.root.clusters.add(config);
else
config.root.clusters.set(config.id, config);
fileSegment.create(iStartSize);
holeSegment.create();
fileSegment.files[0].writeHeaderLong(0, beginOffsetData);
fileSegment.files[0].writeHeaderLong(OBinaryProtocol.SIZE_LONG, beginOffsetData);
fileSegment.files[0].writeHeaderLong(2 * OBinaryProtocol.SIZE_LONG, 1);
} finally {
releaseExclusiveLock();
}
}
public void open() throws IOException {
acquireExclusiveLock();
try {
fileSegment.open();
holeSegment.open();
beginOffsetData = fileSegment.files[0].readHeaderLong(0);
endOffsetData = fileSegment.files[0].readHeaderLong(OBinaryProtocol.SIZE_LONG);
final long version = fileSegment.files[0].readHeaderLong(2 * OBinaryProtocol.SIZE_LONG);
if (version < 1)
convertDeletedRecords();
} finally {
releaseExclusiveLock();
}
}
private void convertDeletedRecords() throws IOException {
int holesCount = holeSegment.getHoles();
OLogManager.instance().info(this, "Please wait till %d holes will be converted to new format in cluster %s.", holesCount, name);
for (int i = 0; i < holesCount; i++) {
long relativeHolePosition = holeSegment.getEntryPosition(i);
if (relativeHolePosition > -1) {
final long[] pos = fileSegment.getRelativePosition(relativeHolePosition);
final OFile f = fileSegment.files[(int) pos[0]];
final long p = pos[1] + RECORD_TYPE_OFFSET;
f.writeByte(p, RECORD_WAS_DELETED);
}
if (i % 1000 == 0)
OLogManager.instance().info(this, "%d holes were converted in cluster %s ...", i, name);
}
OLogManager.instance().info(this, "Conversion of holes to new format was finished for cluster %s.", holesCount, name);
}
public void close() throws IOException {
acquireExclusiveLock();
try {
fileSegment.close();
holeSegment.close();
} finally {
releaseExclusiveLock();
}
}
public void delete() throws IOException {
acquireExclusiveLock();
try {
truncate();
for (OFile f : fileSegment.files)
f.delete();
fileSegment.files = null;
holeSegment.delete();
} finally {
releaseExclusiveLock();
}
}
public void truncate() throws IOException {
storage.checkForClusterPermissions(getName());
acquireExclusiveLock();
try {
// REMOVE ALL DATA BLOCKS
final OClusterPosition begin = getFirstPosition();
if (begin.isPersistent()) {
final OClusterPosition end = getLastPosition();
final OPhysicalPosition ppos = new OPhysicalPosition();
for (ppos.clusterPosition = begin; ppos.clusterPosition.compareTo(end) <= 0; ppos.clusterPosition = ppos.clusterPosition
.inc()) {
final OPhysicalPosition pposToDelete = getPhysicalPosition(ppos);
if (pposToDelete != null && storage.checkForRecordValidity(pposToDelete))
storage.getDataSegmentById(pposToDelete.dataSegmentId).deleteRecord(pposToDelete.dataSegmentPos);
}
}
fileSegment.truncate();
holeSegment.truncate();
} finally {
releaseExclusiveLock();
}
}
public void set(ATTRIBUTES iAttribute, Object iValue) throws IOException {
if (iAttribute == null)
throw new IllegalArgumentException("attribute is null");
final String stringValue = iValue != null ? iValue.toString() : null;
acquireExclusiveLock();
try {
switch (iAttribute) {
case NAME:
setNameInternal(stringValue);
break;
case DATASEGMENT:
setDataSegmentInternal(stringValue);
break;
}
} finally {
releaseExclusiveLock();
}
}
/**
* Fills and return the PhysicalPosition object received as parameter with the physical position of logical record iPosition
*
* @throws IOException
*/
public OPhysicalPosition getPhysicalPosition(final OPhysicalPosition iPPosition) throws IOException {
final OClusterPosition position = iPPosition.clusterPosition;
final long filePosition = position.longValue() * RECORD_SIZE;
acquireSharedLock();
try {
if (position.isNew() || position.compareTo(getLastPosition()) > 0)
return null;
final long[] pos = fileSegment.getRelativePosition(filePosition);
final OFile f = fileSegment.files[(int) pos[0]];
long p = pos[1];
iPPosition.dataSegmentId = f.readShort(p);
iPPosition.dataSegmentPos = f.readLong(p += OBinaryProtocol.SIZE_SHORT);
iPPosition.recordType = f.readByte(p += OBinaryProtocol.SIZE_LONG);
if (iPPosition.recordType == RECORD_WAS_DELETED)
return null;
p += OBinaryProtocol.SIZE_BYTE;
iPPosition.recordVersion.getSerializer().readFrom(f, p, iPPosition.recordVersion);
return iPPosition;
} finally {
releaseSharedLock();
}
}
/**
* Update position in data segment (usually on defrag)
*
* @throws IOException
*/
public void updateDataSegmentPosition(OClusterPosition iPosition, final int iDataSegmentId, final long iDataSegmentPosition)
throws IOException {
long position = iPosition.longValue();
position = position * RECORD_SIZE;
acquireExclusiveLock();
try {
final long[] pos = fileSegment.getRelativePosition(position);
final OFile f = fileSegment.files[(int) pos[0]];
long p = pos[1];
f.writeShort(p, (short) iDataSegmentId);
f.writeLong(p += OBinaryProtocol.SIZE_SHORT, iDataSegmentPosition);
} finally {
releaseExclusiveLock();
}
}
public void updateVersion(OClusterPosition iPosition, final ORecordVersion iVersion) throws IOException {
long position = iPosition.longValue();
position = position * RECORD_SIZE;
acquireExclusiveLock();
try {
final long[] pos = fileSegment.getRelativePosition(position);
iVersion.getSerializer().writeTo(fileSegment.files[(int) pos[0]],
pos[1] + OBinaryProtocol.SIZE_SHORT + OBinaryProtocol.SIZE_LONG + OBinaryProtocol.SIZE_BYTE, iVersion);
} finally {
releaseExclusiveLock();
}
}
public void updateRecordType(OClusterPosition iPosition, final byte iRecordType) throws IOException {
long position = iPosition.longValue();
position = position * RECORD_SIZE;
acquireExclusiveLock();
try {
final long[] pos = fileSegment.getRelativePosition(position);
fileSegment.files[(int) pos[0]].writeByte(pos[1] + OBinaryProtocol.SIZE_SHORT + OBinaryProtocol.SIZE_LONG, iRecordType);
} finally {
releaseExclusiveLock();
}
}
/**
* Removes the Logical position entry. Add to the hole segment and add the minus to the version.
*
* @throws IOException
*/
public void removePhysicalPosition(final OClusterPosition iPosition) throws IOException {
final long position = iPosition.longValue() * RECORD_SIZE;
acquireExclusiveLock();
try {
final long[] pos = fileSegment.getRelativePosition(position);
final OFile file = fileSegment.files[(int) pos[0]];
final long p = pos[1] + RECORD_TYPE_OFFSET;
holeSegment.pushPosition(position);
file.writeByte(p, RECORD_WAS_DELETED);
updateBoundsAfterDeletion(iPosition.longValue());
} finally {
releaseExclusiveLock();
}
}
public boolean removeHole(final long iPosition) throws IOException {
acquireExclusiveLock();
try {
return holeSegment.removeEntryWithPosition(iPosition * RECORD_SIZE);
} finally {
releaseExclusiveLock();
}
}
public int getDataSegmentId() {
acquireSharedLock();
try {
return config.getDataSegmentId();
} finally {
releaseSharedLock();
}
}
/**
* Adds a new entry.
*
* @throws IOException
*/
public boolean addPhysicalPosition(final OPhysicalPosition iPPosition) throws IOException {
final long[] pos;
long offset;
acquireExclusiveLock();
try {
offset = holeSegment.popLastEntryPosition();
boolean recycled;
if (offset > -1) {
// REUSE THE HOLE
pos = fileSegment.getRelativePosition(offset);
recycled = true;
} else {
// NO HOLES FOUND: ALLOCATE MORE SPACE
pos = allocateRecord();
offset = fileSegment.getAbsolutePosition(pos);
recycled = false;
}
final OFile file = fileSegment.files[(int) pos[0]];
long p = pos[1];
file.writeShort(p, (short) iPPosition.dataSegmentId);
file.writeLong(p += OBinaryProtocol.SIZE_SHORT, iPPosition.dataSegmentPos);
file.writeByte(p += OBinaryProtocol.SIZE_LONG, iPPosition.recordType);
if (recycled) {
// GET LAST VERSION
iPPosition.recordVersion.getSerializer().readFrom(file, p + OBinaryProtocol.SIZE_BYTE, iPPosition.recordVersion);
if (iPPosition.recordVersion.isTombstone())
iPPosition.recordVersion.revive();
iPPosition.recordVersion.increment();
} else
iPPosition.recordVersion.reset();
iPPosition.recordVersion.getSerializer().writeTo(file, p + OBinaryProtocol.SIZE_BYTE, iPPosition.recordVersion);
iPPosition.clusterPosition = OClusterPositionFactory.INSTANCE.valueOf(offset / RECORD_SIZE);
updateBoundsAfterInsertion(iPPosition.clusterPosition.longValue());
} finally {
releaseExclusiveLock();
}
return true;
}
/**
* Allocates space to store a new record.
*/
protected long[] allocateRecord() throws IOException {
return fileSegment.allocateSpace(RECORD_SIZE);
}
@Override
public OClusterPosition getFirstPosition() {
acquireSharedLock();
try {
return OClusterPositionFactory.INSTANCE.valueOf(beginOffsetData);
} finally {
releaseSharedLock();
}
}
/**
* Returns the endOffsetData value if it's not equals to the last one, otherwise the total entries.
*/
@Override
public OClusterPosition getLastPosition() {
acquireSharedLock();
try {
return OClusterPositionFactory.INSTANCE.valueOf(endOffsetData > -1 ? endOffsetData : fileSegment.getFilledUpTo()
/ RECORD_SIZE - 1);
} finally {
releaseSharedLock();
}
}
public long getEntries() {
acquireSharedLock();
try {
return fileSegment.getFilledUpTo() / RECORD_SIZE - holeSegment.getHoles();
} finally {
releaseSharedLock();
}
}
public int getId() {
return id;
}
public OClusterEntryIterator absoluteIterator() {
return new OClusterEntryIterator(this);
}
public long getSize() {
acquireSharedLock();
try {
return fileSegment.getSize();
} finally {
releaseSharedLock();
}
}
public long getFilledUpTo() {
acquireSharedLock();
try {
return fileSegment.getFilledUpTo();
} finally {
releaseSharedLock();
}
}
@Override
public String toString() {
return name + " (id=" + id + ")";
}
public void lock() {
acquireSharedLock();
}
public void unlock() {
releaseSharedLock();
}
public String getType() {
return TYPE;
}
public boolean isRequiresValidPositionBeforeCreation() {
return false;
}
public long getRecordsSize() {
acquireSharedLock();
try {
long size = fileSegment.getFilledUpTo();
final OClusterEntryIterator it = absoluteIterator();
while (it.hasNext()) {
final OPhysicalPosition pos = it.next();
if (pos.dataSegmentPos > -1 && !pos.recordVersion.isTombstone())
size += storage.getDataSegmentById(pos.dataSegmentId).getRecordSize(pos.dataSegmentPos);
}
return size;
} catch (IOException e) {
throw new OIOException("Error on calculating cluster size for: " + getName(), e);
} finally {
releaseSharedLock();
}
}
public void synch() throws IOException {
acquireSharedLock();
try {
fileSegment.synch();
holeSegment.synch();
} finally {
releaseSharedLock();
}
}
public void setSoftlyClosed(boolean softlyClosed) throws IOException {
acquireExclusiveLock();
try {
fileSegment.setSoftlyClosed(softlyClosed);
holeSegment.setSoftlyClosed(softlyClosed);
} finally {
releaseExclusiveLock();
}
}
public String getName() {
return name;
}
public OStoragePhysicalClusterConfiguration getConfig() {
return config;
}
private void setNameInternal(final String iNewName) {
if (storage.getClusterIdByName(iNewName) > -1)
throw new IllegalArgumentException("Cluster with name '" + iNewName + "' already exists");
for (int i = 0; i < fileSegment.files.length; i++) {
final String osFileName = fileSegment.files[i].getName();
if (osFileName.startsWith(name)) {
final File newFile = new File(storage.getStoragePath() + "/" + iNewName
+ osFileName.substring(osFileName.lastIndexOf(name) + name.length()));
for (OStorageFileConfiguration conf : config.infoFiles) {
if (conf.parent.name.equals(name))
conf.parent.name = iNewName;
if (conf.path.endsWith(osFileName))
conf.path = new String(conf.path.replace(osFileName, newFile.getName()));
}
boolean renamed = fileSegment.files[i].renameTo(newFile);
while (!renamed) {
OMemoryWatchDog.freeMemory(100);
renamed = fileSegment.files[i].renameTo(newFile);
}
}
}
config.name = iNewName;
holeSegment.rename(name, iNewName);
storage.renameCluster(name, iNewName);
name = iNewName;
storage.getConfiguration().update();
}
/**
* Assigns a different data-segment id.
*
* @param iName
* Data-segment's name
*/
private void setDataSegmentInternal(final String iName) {
final int dataId = storage.getDataSegmentIdByName(iName);
config.setDataSegmentId(dataId);
storage.getConfiguration().update();
}
protected void updateBoundsAfterInsertion(final long iPosition) throws IOException {
if (iPosition < beginOffsetData || beginOffsetData == -1) {
// UPDATE END OF DATA
beginOffsetData = iPosition;
fileSegment.files[0].writeHeaderLong(0, beginOffsetData);
}
if (endOffsetData > -1 && iPosition > endOffsetData) {
// UPDATE END OF DATA
endOffsetData = iPosition;
fileSegment.files[0].writeHeaderLong(OBinaryProtocol.SIZE_LONG, endOffsetData);
}
}
protected void updateBoundsAfterDeletion(final long iPosition) throws IOException {
final long position = iPosition * RECORD_SIZE;
if (iPosition == beginOffsetData) {
if (getEntries() == 0)
beginOffsetData = -1;
else {
// DISCOVER THE BEGIN OF DATA
beginOffsetData++;
long[] fetchPos;
for (long currentPos = position + RECORD_SIZE; currentPos < fileSegment.getFilledUpTo(); currentPos += RECORD_SIZE) {
fetchPos = fileSegment.getRelativePosition(currentPos);
if (fileSegment.files[(int) fetchPos[0]].readByte(fetchPos[1] + RECORD_TYPE_OFFSET) != RECORD_WAS_DELETED)
// GOOD RECORD: SET IT AS BEGIN
break;
beginOffsetData++;
}
}
fileSegment.files[0].writeHeaderLong(0, beginOffsetData);
}
if (iPosition == endOffsetData) {
if (getEntries() == 0)
endOffsetData = -1;
else {
// DISCOVER THE END OF DATA
endOffsetData--;
long[] fetchPos;
for (long currentPos = position - RECORD_SIZE; currentPos >= beginOffsetData; currentPos -= RECORD_SIZE) {
fetchPos = fileSegment.getRelativePosition(currentPos);
if (fileSegment.files[(int) fetchPos[0]].readByte(fetchPos[1] + RECORD_TYPE_OFFSET) != RECORD_WAS_DELETED)
// GOOD RECORD: SET IT AS BEGIN
break;
endOffsetData--;
}
}
fileSegment.files[0].writeHeaderLong(OBinaryProtocol.SIZE_LONG, endOffsetData);
}
}
protected void init(final OStorage iStorage, final int iId, final String iClusterName, final String iLocation,
final int iDataSegmentId, final Object... iParameters) throws IOException {
OFileUtils.checkValidName(iClusterName);
storage = (OStorageLocal) iStorage;
config.setDataSegmentId(iDataSegmentId);
config.id = iId;
config.name = iClusterName;
name = iClusterName;
id = iId;
if (fileSegment == null) {
fileSegment = new OMultiFileSegment(storage, config, DEF_EXTENSION, RECORD_SIZE);
config.setHoleFile(new OStorageClusterHoleConfiguration(config, OStorageVariableParser.DB_PATH_VARIABLE + "/" + config.name,
config.fileType, config.fileMaxSize));
holeSegment = new OClusterLocalHole(this, storage, config.getHoleFile());
}
}
public boolean isSoftlyClosed() {
// Look over files of the cluster
if (!fileSegment.wasSoftlyClosedAtPreviousTime())
return false;
// Look over the hole segment
if (!holeSegment.wasSoftlyClosedAtPreviousTime())
return false;
// Look over files of the corresponding data segment
final ODataLocal dataSegment = storage.getDataSegmentById(config.getDataSegmentId());
if (!dataSegment.wasSoftlyClosedAtPreviousTime())
return false;
// Look over the hole segment
if (!dataSegment.holeSegment.wasSoftlyClosedAtPreviousTime())
return false;
return true;
}
@Override
public OClusterPosition nextRecord(OClusterPosition position) throws IOException {
long filePosition = position.longValue() * RECORD_SIZE;
acquireSharedLock();
try {
if (position.compareTo(getLastPosition()) >= 0)
return OClusterPosition.INVALID_POSITION;
long lastFilePosition = getLastPosition().longValue() * RECORD_SIZE;
byte recordType;
do {
filePosition += RECORD_SIZE;
final long[] pos = fileSegment.getRelativePosition(filePosition);
final OFile f = fileSegment.files[(int) pos[0]];
long p = pos[1] + RECORD_TYPE_OFFSET;
recordType = f.readByte(p);
} while (recordType == RECORD_WAS_DELETED && filePosition < lastFilePosition);
if (recordType == RECORD_WAS_DELETED) {
return OClusterPosition.INVALID_POSITION;
} else {
return OClusterPositionFactory.INSTANCE.valueOf(filePosition / RECORD_SIZE);
}
} finally {
releaseSharedLock();
}
}
@Override
public OClusterPosition prevRecord(OClusterPosition position) throws IOException {
long filePosition = position.longValue() * RECORD_SIZE;
acquireSharedLock();
try {
if (position.compareTo(getLastPosition()) > 0)
return OClusterPosition.INVALID_POSITION;
byte recordType;
do {
filePosition -= RECORD_SIZE;
final long[] pos = fileSegment.getRelativePosition(filePosition);
final OFile f = fileSegment.files[(int) pos[0]];
long p = pos[1] + RECORD_TYPE_OFFSET;
recordType = f.readByte(p);
} while (recordType == RECORD_WAS_DELETED && position.compareTo(getFirstPosition()) >= 0);
if (recordType == RECORD_WAS_DELETED) {
return OClusterPosition.INVALID_POSITION;
} else {
return OClusterPositionFactory.INSTANCE.valueOf(filePosition / RECORD_SIZE);
}
} finally {
releaseSharedLock();
}
}
}
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.common.directmemory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author <NAME>
* @since 12.08.12
*/
public class BuddyMemoryTest {
@Test
public void testCapacityUpperBoundary() throws Exception {
OBuddyMemory memory = new OBuddyMemory(191, 64);
Assert.assertEquals(memory.capacity(), 128);
}
@Test
public void testCapacityLowerBoundary() throws Exception {
OBuddyMemory memory = new OBuddyMemory(129, 64);
Assert.assertEquals(memory.capacity(), 128);
}
@Test
public void testCapacity() throws Exception {
OBuddyMemory memory = new OBuddyMemory(128, 64);
Assert.assertEquals(memory.capacity(), 128);
}
@Test
public void testAllocateInt() {
OBuddyMemory memory = new OBuddyMemory(128, 64);
int pointer1 = memory.allocate(64 - OBuddyMemory.SYSTEM_INFO_SIZE);
int pointer2 = memory.allocate(64 - OBuddyMemory.SYSTEM_INFO_SIZE);
int pointer3 = memory.allocate(64 - OBuddyMemory.SYSTEM_INFO_SIZE);
Assert.assertEquals(pointer1, 64);
Assert.assertEquals(pointer2, 0);
Assert.assertEquals(pointer3, ODirectMemory.NULL_POINTER);
}
@Test
public void testAllocateTooMuch() {
OBuddyMemory memory = new OBuddyMemory(128, 64);
int pointer = memory.allocate(129);
Assert.assertEquals(pointer, ODirectMemory.NULL_POINTER);
}
@Test
public void testFreeSpace() throws Exception {
OBuddyMemory memory = new OBuddyMemory(128, 64);
int freeSpaceInEmptyMemmory = memory.freeSpace();
Assert.assertEquals(freeSpaceInEmptyMemmory, 128);
int pointer1 = memory.allocate(1);
int freeSpaceAfterAllocation1 = memory.freeSpace();
Assert.assertEquals(freeSpaceAfterAllocation1, 64);
int pointer2 = memory.allocate(1);
int freeSpaceAfterAllocation2 = memory.freeSpace();
Assert.assertEquals(freeSpaceAfterAllocation2, 0);
memory.free(pointer2);
int freeSpaceAfterFree1 = memory.freeSpace();
Assert.assertEquals(freeSpaceAfterFree1, 64);
memory.free(pointer1);
int freeSpaceAfterFree2 = memory.freeSpace();
Assert.assertEquals(freeSpaceAfterFree2, 128);
}
@Test
public void test960BytesMapping() throws Exception {
final int expectedSize = 960;
final OBuddyMemory memory = new OBuddyMemory(expectedSize, 64);
Assert.assertEquals(memory.freeSpace(), expectedSize);
final int chunkCount = expectedSize / 64;
final List<Integer> pointers = new ArrayList<Integer>(chunkCount);
for (int i = 0; i < chunkCount; i++) {
int pointer = memory.allocate(64 - OBuddyMemory.SYSTEM_INFO_SIZE);
Assert.assertTrue(pointer != ODirectMemory.NULL_POINTER);
pointers.add(pointer);
}
int nullPointer = memory.allocate(64 - OBuddyMemory.SYSTEM_INFO_SIZE);
Assert.assertTrue(nullPointer == ODirectMemory.NULL_POINTER);
for (Integer pointer : pointers) {
memory.free(pointer);
}
Assert.assertEquals(memory.freeSpace(), expectedSize);
}
@Test
public void test704BytesMapping() throws Exception {
final int expectedSize = 704;
final OBuddyMemory memory = new OBuddyMemory(expectedSize, 64);
Assert.assertEquals(memory.freeSpace(), expectedSize);
final int chunkCount = expectedSize / 64;
final List<Integer> pointers = new ArrayList<Integer>(chunkCount);
for (int i = 0; i < chunkCount; i++) {
int pointer = memory.allocate(64 - OBuddyMemory.SYSTEM_INFO_SIZE);
Assert.assertTrue(pointer != ODirectMemory.NULL_POINTER);
pointers.add(pointer);
}
int nullPointer = memory.allocate(64 - OBuddyMemory.SYSTEM_INFO_SIZE);
Assert.assertTrue(nullPointer == ODirectMemory.NULL_POINTER);
for (Integer pointer : pointers) {
memory.free(pointer);
}
Assert.assertEquals(memory.freeSpace(), expectedSize);
}
@Test
public void testWrites() throws Exception {
final Random r = new Random();
final int initialSize = 8192;
final OBuddyMemory memory = new OBuddyMemory(initialSize, 64);
int expectedSize = initialSize;
Assert.assertEquals(memory.freeSpace(), expectedSize);
final Map<Integer, byte[]> pointers = new HashMap<Integer, byte[]>();
while (expectedSize > 256) {
int arrayLen = 50 + r.nextInt(250);
byte[] bytes = new byte[arrayLen];
r.nextBytes(bytes);
int pointer = memory.allocate(bytes);
if (pointer == ODirectMemory.NULL_POINTER)
continue;
byte[] readBytes = memory.get(pointer, 0, arrayLen);
Assert.assertEquals(readBytes, bytes);
expectedSize -= memory.getActualSpace(pointer);
Assert.assertEquals(memory.freeSpace(), expectedSize);
if (r.nextDouble() < .8) {
int actualSpace = memory.getActualSpace(pointer);
memory.free(pointer);
expectedSize += actualSpace;
Assert.assertEquals(memory.freeSpace(), expectedSize);
} else {
pointers.put(pointer, bytes);
}
}
for (Map.Entry<Integer, byte[]> entry : pointers.entrySet()) {
final Integer pointer = entry.getKey();
final byte[] expected = entry.getValue();
final byte[] read = Arrays.copyOf(memory.get(pointer, 0, -1), expected.length);
Assert.assertEquals(read, expected);
final int actualSpace = memory.getActualSpace(pointer);
memory.free(pointer);
expectedSize += actualSpace;
Assert.assertEquals(memory.freeSpace(), expectedSize);
}
Assert.assertEquals(memory.freeSpace(), initialSize);
}
}
<file_sep>package com.orientechnologies.orient.core.cache;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import java.util.Collection;
import org.testng.annotations.Test;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODocument;
@Test
public class ODefaultCacheTest {
public void enabledAfterStartup() {
// Given cache created
// And not started
// And not enabled
OCache sut = newCache();
// When started
sut.startup();
// Then it should be enabled
assertTrue(sut.isEnabled());
}
public void disabledAfterShutdown() {
// Given running cache
OCache sut = runningCache();
// When started
sut.shutdown();
// Then it should be disabled
assertFalse(sut.isEnabled());
}
public void disablesOnlyIfWasEnabled() {
// Given enabled cache
OCache sut = enabledCache();
// When disabled more than once
boolean disableConfirmed = sut.disable();
boolean disableNotConfirmed = sut.disable();
// Then should return confirmation of switching from enabled to disabled state for first time
// And no confirmation on subsequent disables
assertTrue(disableConfirmed);
assertFalse(disableNotConfirmed);
}
public void enablesOnlyIfWasDisabled() {
// Given disabled cache
OCache sut = newCache();
// When enabled more than once
boolean enableConfirmed = sut.enable();
boolean enableNotConfirmed = sut.enable();
// Then should return confirmation of switching from disabled to enabled state for first time
// And no confirmation on subsequent enables
assertTrue(enableConfirmed);
assertFalse(enableNotConfirmed);
}
public void doesNothingWhileDisabled() {
// Given cache created
// And not started
// And not enabled
OCache sut = new ODefaultCache(null, 1);
// When any operation called on it
ODocument record = new ODocument();
ORID recordId = record.getIdentity();
sut.put(record);
ORecordInternal<?> recordGot = sut.get(recordId);
int cacheSizeAfterPut = sut.size();
ORecordInternal<?> recordRemoved = sut.remove(recordId);
int cacheSizeAfterRemove = sut.size();
// Then it has no effect on cache's state
assertEquals(sut.isEnabled(), false, "Cache should be disabled at creation");
assertEquals(recordGot, null, "Cache should return empty records while disabled");
assertEquals(recordRemoved, null, "Cache should return empty records while disabled");
assertEquals(cacheSizeAfterPut, 0, "Cache should ignore insert while disabled");
assertEquals(cacheSizeAfterRemove, cacheSizeAfterPut, "Cache should ignore remove while disabled");
}
public void hasZeroSizeAfterClear() {
// Given enabled non-empty cache
OCache sut = enabledNonEmptyCache();
// When cleared
sut.clear();
// Then size of cache should be zero
assertEquals(sut.size(), 0, "Cache was not cleaned up");
}
public void providesAccessToAllKeysInCache() {
// Given enabled non-empty cache
OCache sut = enabledNonEmptyCache();
// When asked for keys
Collection<ORID> keys = sut.keys();
// Then keys count should be same as size of cache
// And records available for keys
assertEquals(keys.size(), sut.size(), "Cache provided not all keys?");
for (ORID key : keys) {
assertNotNull(sut.get(key));
}
}
public void storesRecordsUsingTheirIdentity() {
// Given an enabled cache
OCache sut = enabledCache();
// When new record put into
ORecordId id = new ORecordId(1, OClusterPositionFactory.INSTANCE.valueOf(1));
ODocument record = new ODocument(id);
sut.put(record);
// Then it can be retrieved later by it's id
assertEquals(sut.get(id), record);
}
public void storesRecordsOnlyOnceForEveryIdentity() {
// Given an enabled cache
OCache sut = enabledCache();
final int initialSize = sut.size();
// When some records with same identity put in several times
ODocument first = new ODocument(new ORecordId(1, OClusterPositionFactory.INSTANCE.valueOf(1)));
ODocument last = new ODocument(new ORecordId(1, OClusterPositionFactory.INSTANCE.valueOf(1)));
sut.put(first);
sut.put(last);
// Then cache ends up storing only one item
assertEquals(sut.size(), initialSize + 1);
}
public void removesOnlyOnce() {
// Given an enabled cache with records in it
OCache sut = enabledCache();
ORecordId id = new ORecordId(1, OClusterPositionFactory.INSTANCE.valueOf(1));
ODocument record = new ODocument(id);
sut.put(record);
sut.remove(id);
// When removing already removed record
ORecordInternal<?> removedSecond = sut.remove(id);
// Then empty result returned
assertNull(removedSecond);
}
public void storesNoMoreElementsThanSpecifiedLimit() {
// Given an enabled cache
OCache sut = enabledCache();
// When stored more distinct elements than cache limit allows
for (int i = sut.limit() + 2; i > 0; i--)
sut.put(new ODocument(new ORecordId(i, OClusterPositionFactory.INSTANCE.valueOf(i))));
// Then size of cache should be exactly as it's limit
assertEquals(sut.size(), sut.limit(), "Cache doesn't meet limit requirements");
}
private ODefaultCache newCache() {
return new ODefaultCache(null, 5);
}
private OCache enabledCache() {
ODefaultCache cache = newCache();
cache.enable();
return cache;
}
private OCache enabledNonEmptyCache() {
OCache cache = enabledCache();
cache.put(new ODocument(new ORecordId(1, OClusterPositionFactory.INSTANCE.valueOf(1))));
cache.put(new ODocument(new ORecordId(2, OClusterPositionFactory.INSTANCE.valueOf(2))));
return cache;
}
private OCache runningCache() {
ODefaultCache cache = newCache();
cache.startup();
return cache;
}
}
<file_sep>package com.orientechnologies.orient.server.hazelcast.sharding;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.storage.OStorageEmbedded;
/**
* Executor for undistributable commands such as insert/update/delete (distribution will be performed by storage CRUD operations)
*
* @author edegtyarenko
* @since 25.10.12 8:10
*/
public class OLocalQueryExecutor extends OQueryExecutor {
public OLocalQueryExecutor(OCommandRequestText iCommand, OStorageEmbedded wrapped) {
super(iCommand, wrapped);
}
@Override
public Object execute() {
return wrapped.command(iCommand);
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.db.record;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.WeakHashMap;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.record.ORecord;
/**
* Implementation of ArrayList bound to a source ORecord object to keep track of changes for literal types. This avoid to call the
* makeDirty() by hand when the list is changed.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*
*/
@SuppressWarnings({ "serial" })
public class OTrackedList<T> extends ArrayList<T> implements ORecordElement, OTrackedMultiValue<Integer, T>, Serializable {
protected final ORecord<?> sourceRecord;
private STATUS status = STATUS.NOT_LOADED;
protected Set<OMultiValueChangeListener<Integer, T>> changeListeners = Collections
.newSetFromMap(new WeakHashMap<OMultiValueChangeListener<Integer, T>, Boolean>());
protected Class<?> genericClass;
public OTrackedList(final ORecord<?> iRecord, final Collection<? extends T> iOrigin, final Class<?> iGenericClass) {
this(iRecord);
genericClass = iGenericClass;
if (iOrigin != null && !iOrigin.isEmpty())
addAll(iOrigin);
}
public OTrackedList(final ORecord<?> iSourceRecord) {
this.sourceRecord = iSourceRecord;
}
@Override
public boolean add(T element) {
final boolean result = super.add(element);
if (result)
fireCollectionChangedEvent(new OMultiValueChangeEvent<Integer, T>(OMultiValueChangeEvent.OChangeType.ADD, super.size() - 1,
element));
return result;
}
@Override
public boolean addAll(final Collection<? extends T> c) {
for (T o : c) {
add(o);
}
return true;
}
@Override
public void add(int index, T element) {
super.add(index, element);
fireCollectionChangedEvent(new OMultiValueChangeEvent<Integer, T>(OMultiValueChangeEvent.OChangeType.ADD, index, element));
}
@Override
public T set(int index, T element) {
final T oldValue = super.set(index, element);
if (!oldValue.equals(element))
fireCollectionChangedEvent(new OMultiValueChangeEvent<Integer, T>(OMultiValueChangeEvent.OChangeType.UPDATE, index, element,
oldValue));
return oldValue;
}
@Override
public T remove(int index) {
final T oldValue = super.remove(index);
fireCollectionChangedEvent(new OMultiValueChangeEvent<Integer, T>(OMultiValueChangeEvent.OChangeType.REMOVE, index, null,
oldValue));
return oldValue;
}
@Override
public boolean remove(Object o) {
final int index = indexOf(o);
if (index >= 0) {
remove(index);
return true;
}
return false;
}
@Override
public void clear() {
final List<T> origValues;
if (changeListeners.isEmpty())
origValues = null;
else
origValues = new ArrayList<T>(this);
super.clear();
if (origValues != null)
for (int i = origValues.size() - 1; i >= 0; i--) {
fireCollectionChangedEvent(new OMultiValueChangeEvent<Integer, T>(OMultiValueChangeEvent.OChangeType.REMOVE, i, null,
origValues.get(i)));
}
else
setDirty();
}
public void reset() {
super.clear();
}
@SuppressWarnings("unchecked")
public <RET> RET setDirty() {
if (status != STATUS.UNMARSHALLING && sourceRecord != null && !sourceRecord.isDirty())
sourceRecord.setDirty();
return (RET) this;
}
public void onBeforeIdentityChanged(ORID iRID) {
}
public void onAfterIdentityChanged(ORecord<?> iRecord) {
}
public void addChangeListener(final OMultiValueChangeListener<Integer, T> changeListener) {
changeListeners.add(changeListener);
}
public void removeRecordChangeListener(final OMultiValueChangeListener<Integer, T> changeListener) {
changeListeners.remove(changeListener);
}
public List<T> returnOriginalState(final List<OMultiValueChangeEvent<Integer, T>> multiValueChangeEvents) {
final List<T> reverted = new ArrayList<T>(this);
final ListIterator<OMultiValueChangeEvent<Integer, T>> listIterator = multiValueChangeEvents
.listIterator(multiValueChangeEvents.size());
while (listIterator.hasPrevious()) {
final OMultiValueChangeEvent<Integer, T> event = listIterator.previous();
switch (event.getChangeType()) {
case ADD:
reverted.remove(event.getKey().intValue());
break;
case REMOVE:
reverted.add(event.getKey(), event.getOldValue());
break;
case UPDATE:
reverted.set(event.getKey(), event.getOldValue());
break;
default:
throw new IllegalArgumentException("Invalid change type : " + event.getChangeType());
}
}
return reverted;
}
protected void fireCollectionChangedEvent(final OMultiValueChangeEvent<Integer, T> event) {
if (status == STATUS.UNMARSHALLING)
return;
setDirty();
for (final OMultiValueChangeListener<Integer, T> changeListener : changeListeners) {
if (changeListener != null)
changeListener.onAfterRecordChanged(event);
}
}
public STATUS getInternalStatus() {
return status;
}
public void setInternalStatus(final STATUS iStatus) {
status = iStatus;
}
public Class<?> getGenericClass() {
return genericClass;
}
public void setGenericClass(Class<?> genericClass) {
this.genericClass = genericClass;
}
private Object writeReplace() {
return new ArrayList<T>(this);
}
}
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* 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.
*/
/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.common.util;
import java.nio.ByteBuffer;
/**
* This class is utility class for split primitive types to separate byte buffers and vice versa. This class is used because we use
* many byte buffers for mmap and there is situation when we need to write value on border of two buffers.
*
* @author <NAME> (logart) <EMAIL> Date: 5/25/12 Time: 6:37 AM
*/
public class OByteBufferUtils {
public static final int SIZE_OF_SHORT = 2;
public static final int SIZE_OF_INT = 4;
public static final int SIZE_OF_LONG = 8;
private static final int SIZE_OF_BYTE_IN_BITS = 8;
private static final int MASK = 0x000000FF;
/**
* Merge short value from two byte buffer. First byte of short will be extracted from first byte buffer and second from second
* one.
*
* @param buffer
* to read first part of value
* @param buffer1
* to read second part of value
* @return merged value
*/
public static short mergeShortFromBuffers(final ByteBuffer buffer, final ByteBuffer buffer1) {
short result = 0;
result = (short) (result | (buffer.get() & MASK));
result = (short) (result << SIZE_OF_BYTE_IN_BITS);
result = (short) (result | (buffer1.get() & MASK));
return result;
}
/**
* Merge int value from two byte buffer. First bytes of int will be extracted from first byte buffer and second from second one.
* How many bytes will be read from first buffer determines based on <code>buffer.remaining()</code> value
*
* @param buffer
* to read first part of value
* @param buffer1
* to read second part of value
* @return merged value
*/
public static int mergeIntFromBuffers(final ByteBuffer buffer, final ByteBuffer buffer1) {
int result = 0;
final int remaining = buffer.remaining();
for (int i = 0; i < remaining; ++i) {
result = result | (buffer.get() & MASK);
result = result << SIZE_OF_BYTE_IN_BITS;
}
for (int i = 0; i < SIZE_OF_INT - remaining - 1; ++i) {
result = result | (buffer1.get() & MASK);
result = result << SIZE_OF_BYTE_IN_BITS;
}
result = result | (buffer1.get() & MASK);
return result;
}
/**
* Merge long value from two byte buffer. First bytes of long will be extracted from first byte buffer and second from second one.
* How many bytes will be read from first buffer determines based on <code>buffer.remaining()</code> value
*
* @param buffer
* to read first part of value
* @param buffer1
* to read second part of value
* @return merged value
*/
public static long mergeLongFromBuffers(final ByteBuffer buffer, final ByteBuffer buffer1) {
long result = 0;
final int remaining = buffer.remaining();
for (int i = 0; i < remaining; ++i) {
result = result | (MASK & buffer.get());
result = result << SIZE_OF_BYTE_IN_BITS;
}
for (int i = 0; i < SIZE_OF_LONG - remaining - 1; ++i) {
result = result | (MASK & buffer1.get());
result = result << SIZE_OF_BYTE_IN_BITS;
}
result = result | (MASK & buffer1.get());
return result;
}
/**
* Split short value into two byte buffer. First byte of short will be written to first byte buffer and second to second one.
*
* @param buffer
* to write first part of value
* @param buffer1
* to write second part of value
*/
public static void splitShortToBuffers(final ByteBuffer buffer, final ByteBuffer buffer1, final short iValue) {
buffer.put((byte) (MASK & (iValue >>> SIZE_OF_BYTE_IN_BITS)));
buffer1.put((byte) (MASK & iValue));
}
/**
* Split int value into two byte buffer. First byte of int will be written to first byte buffer and second to second one. How many
* bytes will be written to first buffer determines based on <code>buffer.remaining()</code> value
*
* @param buffer
* to write first part of value
* @param buffer1
* to write second part of value
*/
public static void splitIntToBuffers(final ByteBuffer buffer, final ByteBuffer buffer1, final int iValue) {
final int remaining = buffer.remaining();
int i;
for (i = 0; i < remaining; ++i) {
buffer.put((byte) (MASK & (iValue >>> SIZE_OF_BYTE_IN_BITS * (SIZE_OF_INT - i - 1))));
}
for (int j = 0; j < SIZE_OF_INT - remaining; ++j) {
buffer1.put((byte) (MASK & (iValue >>> SIZE_OF_BYTE_IN_BITS * (SIZE_OF_INT - i - j - 1))));
}
}
/**
* Split long value into two byte buffer. First byte of long will be written to first byte buffer and second to second one. How
* many bytes will be written to first buffer determines based on <code>buffer.remaining()</code> value
*
* @param buffer
* to write first part of value
* @param buffer1
* to write second part of value
*/
public static void splitLongToBuffers(final ByteBuffer buffer, final ByteBuffer buffer1, final long iValue) {
final int remaining = buffer.remaining();
int i;
for (i = 0; i < remaining; ++i) {
buffer.put((byte) (iValue >> SIZE_OF_BYTE_IN_BITS * (SIZE_OF_LONG - i - 1)));
}
for (int j = 0; j < SIZE_OF_LONG - remaining; ++j) {
buffer1.put((byte) (iValue >> SIZE_OF_BYTE_IN_BITS * (SIZE_OF_LONG - i - j - 1)));
}
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.engine.local;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.engine.OEngineAbstract;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.exception.OMemoryLockException;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.storage.impl.local.OStorageLocal;
public class OEngineLocal extends OEngineAbstract {
public static final String NAME = "local";
private static final AtomicBoolean memoryLocked = new AtomicBoolean(false);
public OStorage createStorage(final String iDbName, final Map<String, String> iConfiguration) {
if (memoryLocked.compareAndSet(false, true)) {
lockMemory();
}
try {
// GET THE STORAGE
return new OStorageLocal(iDbName, iDbName, getMode(iConfiguration));
} catch (Throwable t) {
OLogManager.instance().error(this,
"Error on opening database: " + iDbName + ". Current location is: " + new java.io.File(".").getAbsolutePath(), t,
ODatabaseException.class);
}
return null;
}
private void lockMemory() {
if (!OGlobalConfiguration.FILE_MMAP_USE_OLD_MANAGER.getValueAsBoolean()
&& OGlobalConfiguration.FILE_MMAP_LOCK_MEMORY.getValueAsBoolean()) {
// lock memory
try {
Class<?> MemoryLocker = ClassLoader.getSystemClassLoader().loadClass("com.orientechnologies.nio.MemoryLocker");
Method lockMemory = MemoryLocker.getMethod("lockMemory", boolean.class);
lockMemory.invoke(null, OGlobalConfiguration.JNA_DISABLE_USE_SYSTEM_LIBRARY.getValueAsBoolean());
} catch (ClassNotFoundException e) {
OLogManager
.instance()
.config(
null,
"[OEngineLocal.createStorage] Cannot lock virtual memory, the orientdb-nativeos.jar is not in classpath or there is not a native implementation for the current OS: "
+ System.getProperty("os.name") + " v." + System.getProperty("os.name"));
} catch (NoSuchMethodException e) {
throw new OMemoryLockException("Error while locking memory", e);
} catch (InvocationTargetException e) {
throw new OMemoryLockException("Error while locking memory", e);
} catch (IllegalAccessException e) {
throw new OMemoryLockException("Error while locking memory", e);
}
}
}
public String getName() {
return NAME;
}
public boolean isShared() {
return true;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.journal;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.orientechnologies.common.concur.resource.OSharedResourceAdaptiveExternal;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.serialization.OBinaryProtocol;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.storage.fs.OFile;
import com.orientechnologies.orient.core.storage.fs.OFileFactory;
import com.orientechnologies.orient.core.version.ORecordVersion;
import com.orientechnologies.orient.core.version.OVersionFactory;
import com.orientechnologies.orient.server.task.OAbstractDistributedTask;
import com.orientechnologies.orient.server.task.OAbstractDistributedTask.STATUS;
import com.orientechnologies.orient.server.task.OAbstractRecordDistributedTask;
import com.orientechnologies.orient.server.task.OCreateRecordDistributedTask;
import com.orientechnologies.orient.server.task.ODeleteRecordDistributedTask;
import com.orientechnologies.orient.server.task.OSQLCommandDistributedTask;
import com.orientechnologies.orient.server.task.OUpdateRecordDistributedTask;
/**
* Writes all the non-idempotent operations against a database. Uses the classic IO API and NOT the MMAP to avoid the buffer is not
* buffered by OS. The record is at variable size.<br/>
* <br/>
* Record structure:<br/>
* <code>
* +--------+--------+---------------+---------+---------+-----------+<br/>
* | STATUS | OPERAT | VARIABLE DATA | SIZE .. | RUN ID .| OPERAT ID |<br/>
* | 1 byte | 1 byte | <SIZE> bytes. | 4 bytes | 8 bytes | 8 bytes . |<br/>
* +--------+--------+---------------+---------+---------+-----------+<br/>
* FIXED SIZE = 22 <br/>
* <br/>
* Where:
* <ul>
* <li> <b>STATUS</b> = [ 0 = doing, 1 = done ] </li>
* <li> <b>OPERAT</b> = [ 1 = update, 2 = delete, 3 = create, 4 = sql command ] </li>
* <li> <b>RUN ID</b> = is the running id. It's the timestamp the server is started, or inside a cluster is the timestamp when the cluster is started</li>
* <li> <b>OPERAT ID</b> = is the unique id of the operation. First operation is 0</li>
* </ul>
* </code><br/>
*/
public class ODatabaseJournal {
public enum OPERATION_TYPES {
RECORD_CREATE, RECORD_UPDATE, RECORD_DELETE, SQL_COMMAND
}
public static final String DIRECTORY = "log";
public static final String FILENAME = "journal.olj";
private static final int DEF_START_SIZE = 262144;
private static final int OFFSET_STATUS = 0;
private static final int OFFSET_OPERATION_TYPE = OFFSET_STATUS + OBinaryProtocol.SIZE_BYTE;
private static final int OFFSET_VARDATA = OFFSET_OPERATION_TYPE + OBinaryProtocol.SIZE_BYTE;
private static final int OFFSET_BACK_OPERATID = OBinaryProtocol.SIZE_LONG;
private static final int OFFSET_BACK_RUNID = OFFSET_BACK_OPERATID + OBinaryProtocol.SIZE_LONG;
private static final int OFFSET_BACK_SIZE = OFFSET_BACK_RUNID + OBinaryProtocol.SIZE_INT;
private static final int FIXED_SIZE = 22;
private OSharedResourceAdaptiveExternal lock = new OSharedResourceAdaptiveExternal(
OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean(),
0, true);
private OStorage storage;
private OFile file;
private boolean synchEnabled = false;
public ODatabaseJournal(final OStorage iStorage, final String iStartingDirectory) throws IOException {
storage = iStorage;
File osFile = new File(iStartingDirectory + "/" + DIRECTORY);
if (!osFile.exists())
osFile.mkdirs();
osFile = new File(iStartingDirectory + "/" + DIRECTORY + "/" + FILENAME);
file = OFileFactory.instance().create("classic", osFile.getAbsolutePath(), "rw");
if (file.exists())
file.open();
else
file.create(DEF_START_SIZE);
}
/**
* Returns the last operation id.
*/
public long[] getLastOperationId() throws IOException {
return getOperationId(file.getFilledUpTo());
}
/**
* Returns the last operation id.
*/
public long[] getOperationId(final long iOffset) throws IOException {
final int filled = file.getFilledUpTo();
if (filled == 0 || iOffset <= 0 || iOffset > filled)
return new long[] { -1, -1 };
lock.acquireExclusiveLock();
try {
final long[] ids = new long[2];
ids[0] = file.readLong(iOffset - OFFSET_BACK_RUNID);
ids[1] = file.readLong(iOffset - OFFSET_BACK_OPERATID);
return ids;
} finally {
lock.releaseExclusiveLock();
}
}
/**
* Moves backward from the end of the file until the record id is major than the remote one collecting the positions
*
* @param iRemoteLastOperationId
* @return
* @throws IOException
*/
public Iterator<Long> browse(final long[] iRemoteLastOperationId) throws IOException {
final LinkedList<Long> result = new LinkedList<Long>();
lock.acquireExclusiveLock();
try {
long fileOffset = file.getFilledUpTo();
long[] localOperationId = getOperationId(fileOffset);
while ((localOperationId[0] > iRemoteLastOperationId[0])
|| (localOperationId[0] == iRemoteLastOperationId[0] && localOperationId[1] > iRemoteLastOperationId[1])) {
// COLLECT CURRENT POSITION AS GOOD
result.add(fileOffset);
final long prevOffset = getPreviousOperation(fileOffset);
localOperationId = getOperationId(prevOffset);
fileOffset = prevOffset;
}
return result.descendingIterator();
} finally {
lock.releaseExclusiveLock();
}
}
public List<ORecordId> getUncommittedOperations() throws IOException {
final List<ORecordId> uncommittedRecords = new ArrayList<ORecordId>();
// FIND LAST COMMITTED OPERATION
long fileOffset = file.getFilledUpTo();
while (fileOffset > 0) {
if (getOperationStatus(fileOffset))
break;
final OAbstractDistributedTask<?> op = getOperation(fileOffset);
OLogManager.instance().warn(this, "DISTRIBUTED Found uncommitted operation %s", op);
if (op instanceof OAbstractRecordDistributedTask<?>)
// COLLECT THE RECORD TO BE RETRIEVED FROM OTHER SERVERS
uncommittedRecords.add(((OAbstractRecordDistributedTask<?>) op).getRid());
fileOffset = getPreviousOperation(fileOffset);
}
return uncommittedRecords;
}
/**
* Changes the status of an operation
*/
public void changeOperationStatus(final long iOffsetEndOperation, final ORecordId iRid) throws IOException {
lock.acquireExclusiveLock();
try {
final int varSize = file.readInt(iOffsetEndOperation - OFFSET_BACK_SIZE);
final long offset = iOffsetEndOperation - OFFSET_BACK_SIZE - varSize - OFFSET_VARDATA;
OLogManager.instance().warn(this, "Updating status operation #%d.%d rid %s",
file.readLong(iOffsetEndOperation - OFFSET_BACK_RUNID), file.readLong(iOffsetEndOperation - OFFSET_BACK_OPERATID), iRid);
file.write(offset + OFFSET_STATUS, new byte[] { 1 });
if (iRid != null)
// UPDATE THE CLUSTER POSITION: THIS IS THE CASE OF CREATE RECORD
file.writeLong(offset + OFFSET_VARDATA + OBinaryProtocol.SIZE_SHORT, iRid.clusterPosition.longValue());
file.synch();
} finally {
lock.releaseExclusiveLock();
}
}
/**
* Return the operation status.
*
* @return true if the operation has been committed, otherwise false
*/
public boolean getOperationStatus(final long iOffsetEndOperation) throws IOException {
lock.acquireExclusiveLock();
try {
final int varSize = file.readInt(iOffsetEndOperation - OFFSET_BACK_SIZE);
final long offset = iOffsetEndOperation - OFFSET_BACK_SIZE - varSize - OFFSET_VARDATA;
return file.readByte(offset + OFFSET_STATUS) == 1;
} finally {
lock.releaseExclusiveLock();
}
}
/**
* Appends a log entry about a command with status = 0 (doing).
*
* @return The end of the record stored for this operation.
*/
public long journalOperation(final long iRunId, final long iOperationId, final OPERATION_TYPES iOperationType,
final Object iVarData) throws IOException {
lock.acquireExclusiveLock();
try {
long offset = 0;
int varSize = 0;
switch (iOperationType) {
case RECORD_CREATE:
case RECORD_UPDATE:
case RECORD_DELETE: {
final OAbstractRecordDistributedTask<?> task = (OAbstractRecordDistributedTask<?>) iVarData;
varSize = ORecordId.PERSISTENT_SIZE;
final ORecordId rid = task.getRid();
if (OLogManager.instance().isDebugEnabled())
OLogManager.instance().warn(this, "Journaled operation %s %s as #%d.%d", iOperationType.toString(), rid, iRunId,
iOperationId);
offset = writeOperationLogHeader(iOperationType, varSize);
file.writeShort(offset + OFFSET_VARDATA, (short) rid.clusterId);
file.writeLong(offset + OFFSET_VARDATA + OBinaryProtocol.SIZE_SHORT, rid.clusterPosition.longValue());
break;
}
case SQL_COMMAND: {
final OCommandSQL cmd = (OCommandSQL) iVarData;
final String cmdText = cmd.getText();
final byte[] cmdBinary = cmdText.getBytes();
varSize = cmdBinary.length;
if (OLogManager.instance().isDebugEnabled())
OLogManager.instance().warn(this, "Journaled operation %s '%s' as #%d.%d", iOperationType.toString(), cmdText, iRunId,
iOperationId);
offset = writeOperationLogHeader(iOperationType, varSize);
file.write(offset + OFFSET_VARDATA, cmdText.getBytes());
break;
}
}
file.writeLong(offset + OFFSET_VARDATA + varSize + OBinaryProtocol.SIZE_INT, iRunId);
file.writeLong(offset + OFFSET_VARDATA + varSize + OBinaryProtocol.SIZE_INT + OBinaryProtocol.SIZE_LONG, iOperationId);
if (synchEnabled)
file.synch();
return offset + OFFSET_VARDATA + varSize + OBinaryProtocol.SIZE_INT + OBinaryProtocol.SIZE_LONG + OBinaryProtocol.SIZE_LONG;
} finally {
lock.releaseExclusiveLock();
}
}
protected long writeOperationLogHeader(final OPERATION_TYPES iOperationType, final int varSize) throws IOException {
final long offset = file.allocateSpace(FIXED_SIZE + varSize);
file.writeByte(offset + OFFSET_STATUS, (byte) 0);
file.writeByte(offset + OFFSET_OPERATION_TYPE, (byte) iOperationType.ordinal());
file.writeInt(offset + OFFSET_VARDATA + varSize, varSize);
return offset;
}
public OAbstractDistributedTask<?> getOperation(final long iOffsetEndOperation) throws IOException {
OAbstractDistributedTask<?> task = null;
lock.acquireExclusiveLock();
try {
final long runId = file.readLong(iOffsetEndOperation - OFFSET_BACK_RUNID);
final long operationId = file.readLong(iOffsetEndOperation - OFFSET_BACK_OPERATID);
final int varSize = file.readInt(iOffsetEndOperation - OFFSET_BACK_SIZE);
final long offset = iOffsetEndOperation - OFFSET_BACK_SIZE - varSize - OFFSET_VARDATA;
final OPERATION_TYPES operationType = OPERATION_TYPES.values()[file.readByte(offset + OFFSET_OPERATION_TYPE)];
switch (operationType) {
case RECORD_CREATE: {
final ORecordId rid = new ORecordId(file.readShort(offset + OFFSET_VARDATA), OClusterPositionFactory.INSTANCE.valueOf(file
.readLong(offset + OFFSET_VARDATA + OBinaryProtocol.SIZE_SHORT)));
if (rid.isNew())
// GET LAST RID
rid.clusterPosition = storage.getClusterDataRange(rid.clusterId)[1];
final ORawBuffer record = storage.readRecord(rid, null, false, null).getResult();
if (record != null)
task = new OCreateRecordDistributedTask(runId, operationId, rid, record.buffer, record.version, record.recordType);
break;
}
case RECORD_UPDATE: {
final ORecordId rid = new ORecordId(file.readShort(offset + OFFSET_VARDATA), OClusterPositionFactory.INSTANCE.valueOf(file
.readLong(offset + OFFSET_VARDATA + OBinaryProtocol.SIZE_SHORT)));
final ORawBuffer record = storage.readRecord(rid, null, false, null).getResult();
if (record != null) {
final ORecordVersion version = record.version.copy();
version.decrement();
task = new OUpdateRecordDistributedTask(runId, operationId, rid, record.buffer, version, record.recordType);
}
break;
}
case RECORD_DELETE: {
final ORecordId rid = new ORecordId(file.readShort(offset + OFFSET_VARDATA), OClusterPositionFactory.INSTANCE.valueOf(file
.readLong(offset + OFFSET_VARDATA + OBinaryProtocol.SIZE_SHORT)));
final ORawBuffer record = storage.readRecord(rid, null, false, null).getResult();
task = new ODeleteRecordDistributedTask(runId, operationId, rid, record != null ? record.version : OVersionFactory
.instance().createUntrackedVersion());
break;
}
case SQL_COMMAND: {
final byte[] buffer = new byte[varSize];
file.read(offset + OFFSET_VARDATA, buffer, buffer.length);
task = new OSQLCommandDistributedTask(runId, operationId, new String(buffer));
break;
}
}
if (task != null)
task.setStatus(STATUS.ALIGN);
} finally {
lock.releaseExclusiveLock();
}
return task;
}
public long getPreviousOperation(final long iPosition) throws IOException {
lock.acquireExclusiveLock();
try {
final int size = file.readInt(iPosition - OFFSET_BACK_SIZE);
return iPosition - OFFSET_BACK_SIZE - size - OFFSET_VARDATA;
} finally {
lock.releaseExclusiveLock();
}
}
}
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.storage.fs;
import java.util.concurrent.atomic.AtomicReference;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
/**
* This class is mmap manager singleton factory. It used for getting mmap manager instance from any part of the system. This locator
* know how to create mmap manager. If mmap manager already exist returns it.
*
* @author <NAME> (logart) <EMAIL>
*
*/
public class OMMapManagerLocator {
private static final AtomicReference<OMMapManager> instanceRef = new AtomicReference<OMMapManager>(null);
/**
* This method returns instance of mmap manager.
*
* @return mmap manager instance. If it is not exist create new one.
*/
public static OMMapManager getInstance() {
if (instanceRef.get() == null) {
synchronized (instanceRef) {
if (instanceRef.compareAndSet(null, createInstance())) {
instanceRef.get().init();
}
}
}
return instanceRef.get();
}
/**
* This method called from com.orientechnologies.orient.core.storage.fs.OMMapManagerLocator#getInstance() to create new mmap
* manager and init it.
*
* @return mmap manager instance.
*/
private static OMMapManager createInstance() {
final OMMapManager localInstance;
if (OGlobalConfiguration.FILE_MMAP_USE_OLD_MANAGER.getValueAsBoolean()) {
OLogManager.instance().config(null, "[OMMapManagerLocator.createInstance] Using old mmap manager!");
localInstance = new OMMapManagerOld();
} else {
OLogManager.instance().config(null, "[OMMapManagerLocator.createInstance] Using new mmap manager!");
localInstance = new OMMapManagerNew();
}
return localInstance;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.storage;
import java.io.IOException;
import com.orientechnologies.common.concur.lock.OLockManager.LOCK;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.command.OCommandManager;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
import com.orientechnologies.orient.core.exception.OStorageException;
import com.orientechnologies.orient.core.id.OClusterPosition;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.record.ORecordInternal;
/**
* Interface for embedded storage.
*
* @author <NAME>
* @see com.orientechnologies.orient.core.storage.impl.local.OStorageLocal, OStorageMemory
*/
public abstract class OStorageEmbedded extends OStorageAbstract {
protected final ORecordLockManager lockManager;
protected final String PROFILER_CREATE_RECORD;
protected final String PROFILER_READ_RECORD;
protected final String PROFILER_UPDATE_RECORD;
protected final String PROFILER_DELETE_RECORD;
public OStorageEmbedded(final String iName, final String iFilePath, final String iMode) {
super(iName, iFilePath, iMode);
lockManager = new ORecordLockManager(OGlobalConfiguration.STORAGE_RECORD_LOCK_TIMEOUT.getValueAsInteger());
PROFILER_CREATE_RECORD = "db." + name + ".createRecord";
PROFILER_READ_RECORD = "db." + name + ".readRecord";
PROFILER_UPDATE_RECORD = "db." + name + ".updateRecord";
PROFILER_DELETE_RECORD = "db." + name + ".deleteRecord";
}
public abstract OCluster getClusterByName(final String iClusterName);
protected abstract ORawBuffer readRecord(final OCluster iClusterSegment, final ORecordId iRid, boolean iAtomicLock);
/**
* Closes the storage freeing the lock manager first.
*/
@Override
public void close(final boolean iForce) {
if (checkForClose(iForce))
lockManager.clear();
super.close(iForce);
}
/**
* Executes the command request and return the result back.
*/
public Object command(final OCommandRequestText iCommand) {
final OCommandExecutor executor = OCommandManager.instance().getExecutor(iCommand);
executor.setProgressListener(iCommand.getProgressListener());
executor.parse(iCommand);
return executeCommand(iCommand, executor);
}
public Object executeCommand(final OCommandRequestText iCommand, final OCommandExecutor executor) {
if (iCommand.isIdempotent() && !executor.isIdempotent())
throw new OCommandExecutionException("Cannot execute non idempotent command");
long beginTime = Orient.instance().getProfiler().startChrono();
try {
iCommand.getContext().setChild(executor.getContext());
final Object result = executor.execute(iCommand.getParameters());
iCommand.getContext().setChild(null);
return result;
} catch (OException e) {
// PASS THROUGHT
throw e;
} catch (Exception e) {
throw new OCommandExecutionException("Error on execution of command: " + iCommand, e);
} finally {
Orient
.instance()
.getProfiler()
.stopChrono("db." + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + ".command." + iCommand.getText(),
"Command executed against the database", beginTime, "db.*.command.*");
}
}
@Override
public OClusterPosition getNextClusterPosition(int currentClusterId, OClusterPosition clusterPosition) {
if (currentClusterId == -1)
return null;
checkOpeness();
lock.acquireSharedLock();
try {
final OCluster cluster = getClusterById(currentClusterId);
final OClusterPosition nextClusterPosition = cluster.nextRecord(clusterPosition);
return nextClusterPosition;
} catch (IOException ioe) {
throw new OStorageException("Cluster Id " + currentClusterId + " is invalid in storage '" + name + '\'', ioe);
} finally {
lock.releaseSharedLock();
}
}
@Override
public OClusterPosition getPrevClusterPosition(int currentClusterId, OClusterPosition clusterPosition) {
if (currentClusterId == -1)
return null;
checkOpeness();
lock.acquireSharedLock();
try {
final OCluster cluster = getClusterById(currentClusterId);
final OClusterPosition prevClusterPosition = cluster.prevRecord(clusterPosition);
return prevClusterPosition;
} catch (IOException ioe) {
throw new OStorageException("Cluster Id " + currentClusterId + " is invalid in storage '" + name + '\'', ioe);
} finally {
lock.releaseSharedLock();
}
}
public void acquireWriteLock(final ORID iRid) {
lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE);
}
public void releaseWriteLock(final ORID iRid) {
lockManager.releaseLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE);
}
public void acquireReadLock(final ORID iRid) {
lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.SHARED);
}
public void releaseReadLock(final ORID iRid) {
lockManager.releaseLock(Thread.currentThread(), iRid, LOCK.SHARED);
}
protected OPhysicalPosition moveRecord(ORID originalId, ORID newId) throws IOException {
final OCluster originalCluster = getClusterById(originalId.getClusterId());
final OCluster destinationCluster = getClusterById(newId.getClusterId());
if (destinationCluster.getDataSegmentId() != originalCluster.getDataSegmentId())
throw new OStorageException("Original and destination clusters use different data segment ids "
+ originalCluster.getDataSegmentId() + "<->" + destinationCluster.getDataSegmentId());
if (!destinationCluster.isRequiresValidPositionBeforeCreation()) {
if (originalId.getClusterId() == newId.getClusterId())
throw new OStorageException("Record identity can not be moved inside of the same non LH based cluster.");
if (newId.getClusterPosition().compareTo(destinationCluster.getLastPosition()) <= 0)
throw new OStorageException("New position " + newId.getClusterPosition() + " of " + originalId + " record inside of "
+ destinationCluster.getName() + " cluster and can not be used as destination");
if (OGlobalConfiguration.USE_LHPEPS_CLUSTER.getValueAsBoolean()
|| OGlobalConfiguration.USE_LHPEPS_MEMORY_CLUSTER.getValueAsBoolean()) {
if (destinationCluster.getFirstPosition().longValue() != 0
|| destinationCluster.getEntries() != destinationCluster.getLastPosition().longValue() + 1)
throw new OStorageException("Cluster " + destinationCluster.getName()
+ " contains holes and can not be used as destination for " + originalId + " record.");
}
}
final OPhysicalPosition ppos = originalCluster.getPhysicalPosition(new OPhysicalPosition(originalId.getClusterPosition()));
if (ppos == null)
throw new OStorageException("Record with id " + originalId + " does not exist");
ppos.clusterPosition = newId.getClusterPosition();
if (destinationCluster.isRequiresValidPositionBeforeCreation()) {
if (!destinationCluster.addPhysicalPosition(ppos))
throw new OStorageException("Record with id " + newId + " has already exists in cluster " + destinationCluster.getName());
} else {
final int diff = (int) (newId.getClusterPosition().longValue() - destinationCluster.getLastPosition().longValue() - 1);
final OClusterPosition startPos = OClusterPositionFactory.INSTANCE
.valueOf(destinationCluster.getLastPosition().longValue() + 1);
OClusterPosition pos = startPos;
final OPhysicalPosition physicalPosition = new OPhysicalPosition(pos);
for (int i = 0; i < diff; i++) {
physicalPosition.clusterPosition = pos;
destinationCluster.addPhysicalPosition(physicalPosition);
pos = pos.inc();
}
destinationCluster.addPhysicalPosition(ppos);
pos = startPos;
for (int i = 0; i < diff; i++) {
destinationCluster.removePhysicalPosition(pos);
pos = pos.inc();
}
}
originalCluster.removePhysicalPosition(originalId.getClusterPosition());
ORecordInternal<?> recordInternal = getLevel2Cache().freeRecord(originalId);
if (recordInternal != null) {
recordInternal.setIdentity(newId.getClusterId(), newId.getClusterPosition());
getLevel2Cache().updateRecord(recordInternal);
}
return ppos;
}
/**
* Checks if the storage is open. If it's closed an exception is raised.
*/
protected void checkOpeness() {
if (status != STATUS.OPEN)
throw new OStorageException("Storage " + name + " is not opened.");
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.test.database.auto;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.orientechnologies.common.concur.ONeedRetryException;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE;
@Test
public class ConcurrentUpdatesTest {
protected String url;
private boolean level1CacheEnabled;
private boolean level2CacheEnabled;
private boolean mvccEnabled;
static class UpdateField implements Runnable {
ODatabaseDocumentTx db;
ORID rid1;
ORID rid2;
String fieldValue = null;
String threadName;
public UpdateField(ODatabaseDocumentTx iDb, ORID iRid1, ORID iRid2, String iThreadName) {
super();
db = iDb;
rid1 = iRid1;
rid2 = iRid2;
threadName = iThreadName;
}
public void run() {
try {
for (int i = 0; i < 50; i++) {
while (true) {
try {
db.begin(TXTYPE.OPTIMISTIC);
ODocument vDoc1 = db.load(rid1, null, true);
vDoc1.field(threadName, vDoc1.field(threadName) + ";" + i);
vDoc1.save();
ODocument vDoc2 = db.load(rid2, null, true);
vDoc2.field(threadName, vDoc2.field(threadName) + ";" + i);
vDoc2.save();
db.commit();
break;
} catch (ONeedRetryException e) {
System.out.println("Retry... " + Thread.currentThread().getName() + " " + i);
}
}
fieldValue += ";" + i;
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
@Parameters(value = "url")
public ConcurrentUpdatesTest(@Optional(value = "memory:test") String iURL) {
url = iURL;
}
@BeforeClass
public void init() {
level1CacheEnabled = OGlobalConfiguration.CACHE_LEVEL1_ENABLED.getValueAsBoolean();
level2CacheEnabled = OGlobalConfiguration.CACHE_LEVEL2_ENABLED.getValueAsBoolean();
mvccEnabled = OGlobalConfiguration.DB_MVCC.getValueAsBoolean();
if (level1CacheEnabled)
OGlobalConfiguration.CACHE_LEVEL1_ENABLED.setValue(false);
if (level2CacheEnabled)
OGlobalConfiguration.CACHE_LEVEL2_ENABLED.setValue(false);
if (!mvccEnabled)
OGlobalConfiguration.DB_MVCC.setValue(true);
if ("memory:test".equals(url))
new ODatabaseDocumentTx(url).create().close();
}
@AfterClass
public void deinit() {
OGlobalConfiguration.CACHE_LEVEL1_ENABLED.setValue(level1CacheEnabled);
OGlobalConfiguration.CACHE_LEVEL2_ENABLED.setValue(level2CacheEnabled);
OGlobalConfiguration.DB_MVCC.setValue(mvccEnabled);
}
// public ConcurrentTest() throws Exception {
// url = "local:C:\\tmp\\tests\\concurrAccess";
// OGlobalConfiguration.CACHE_LEVEL1_ENABLED.setValue(false);
// OGlobalConfiguration.CACHE_LEVEL2_ENABLED.setValue(false);
// OGlobalConfiguration.DB_MVCC.setValue(true);
// ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
// if (db.exists()) {
// db.delete();
// }
// db.create();
// db.close();
// }
/**
*
*/
@Test
public void concurrentUpdates() throws Exception {
ODatabaseDocumentTx database1 = new ODatabaseDocumentTx(url).open("admin", "admin");
ODatabaseDocumentTx database2 = new ODatabaseDocumentTx(url).open("admin", "admin");
ODatabaseDocumentTx database3 = new ODatabaseDocumentTx(url).open("admin", "admin");
ODocument doc1 = database1.newInstance();
doc1.field("INIT", "ok");
database1.save(doc1);
ORID rid1 = doc1.getIdentity();
ODocument doc2 = database1.newInstance();
doc2.field("INIT", "ok");
database1.save(doc2);
ORID rid2 = doc2.getIdentity();
UpdateField vUpdate1 = new UpdateField(database1, rid1, rid2, "thread1");
UpdateField vUpdate2 = new UpdateField(database2, rid2, rid1, "thread2");
UpdateField vUpdate3 = new UpdateField(database3, rid2, rid1, "thread3");
Thread vThread1 = new Thread(vUpdate1, "ConcurrentTest1");
Thread vThread2 = new Thread(vUpdate2, "ConcurrentTest2");
Thread vThread3 = new Thread(vUpdate3, "ConcurrentTest3");
vThread1.start();
vThread2.start();
vThread3.start();
vThread1.join();
vThread2.join();
vThread3.join();
doc1 = database1.load(rid1, null, true);
Assert.assertEquals(doc1.field(vUpdate1.threadName), vUpdate1.fieldValue, vUpdate1.threadName);
Assert.assertEquals(doc1.field(vUpdate2.threadName), vUpdate2.fieldValue, vUpdate2.threadName);
Assert.assertEquals(doc1.field(vUpdate3.threadName), vUpdate3.fieldValue, vUpdate3.threadName);
System.out.println("RESULT doc 1:");
System.out.println(doc1.toJSON());
doc2 = database1.load(rid2, null, true);
Assert.assertEquals(doc2.field(vUpdate1.threadName), vUpdate1.fieldValue, vUpdate1.threadName);
Assert.assertEquals(doc2.field(vUpdate2.threadName), vUpdate2.fieldValue, vUpdate2.threadName);
Assert.assertEquals(doc2.field(vUpdate3.threadName), vUpdate3.fieldValue, vUpdate3.threadName);
System.out.println("RESULT doc 2:");
System.out.println(doc2.toJSON());
database1.close();
database2.close();
}
}
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.common.directmemory.collections;
import java.util.AbstractList;
import java.util.List;
import java.util.RandomAccess;
import com.orientechnologies.common.directmemory.ODirectMemory;
import com.orientechnologies.common.serialization.types.OBinarySerializer;
/**
* Implementation of list which uses {@link ODirectMemory} to store data.
*
*
* @author <NAME>
* @since 12.08.12
*/
public class ODirectMemoryList<E> extends AbstractList<E> implements List<E>, RandomAccess {
private final ODirectMemory memory;
private final OBinarySerializer<E> serializer;
private int size;
private int elementData;
public ODirectMemoryList(int initialCapacity, ODirectMemory memory, OBinarySerializer<E> serializer) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
this.memory = memory;
this.serializer = serializer;
this.elementData = allocateSpace(initialCapacity);
}
public ODirectMemoryList(ODirectMemory memory, OBinarySerializer<E> serializer) {
this(16, memory, serializer);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (getData(elementData, i) == null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(getData(elementData, i)))
return i;
}
return -1;
}
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size - 1; i >= 0; i--)
if (getData(elementData, i) == null)
return i;
} else {
for (int i = size - 1; i >= 0; i--)
if (o.equals(getData(elementData, i)))
return i;
}
return -1;
}
public E get(int index) {
rangeCheck(index);
return getData(elementData, index);
}
public E set(int index, E element) {
rangeCheck(index);
E oldValue = getData(elementData, index);
setData(elementData, index, element);
return oldValue;
}
public boolean add(E e) {
ensureCapacity(size + 1);
setData(elementData, size++, e);
return true;
}
public E remove(int index) {
if (size == 0)
return null;
rangeCheck(index);
E oldValue = getData(elementData, index);
doRemove(index);
return oldValue;
}
private void doRemove(int index) {
modCount++;
setData(elementData, index, null);
int numMoved = size - index - 1;
if (numMoved > 0)
copyData(elementData, index + 1, index, numMoved);
size--;
clearData(elementData, size);
}
public boolean remove(Object o) {
if (size == 0)
return false;
if (o == null) {
for (int index = 0; index < size; index++)
if (getData(elementData, index) == null) {
doRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(getData(elementData, index))) {
doRemove(index);
return true;
}
}
return false;
}
public void clear() {
modCount++;
for (int i = 0; i < size; i++)
setData(elementData, i, null);
size = 0;
}
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
for (int i = fromIndex; i < toIndex; i++)
setData(elementData, i, null);
copyData(elementData, fromIndex, toIndex, numMoved);
int newSize = size - (toIndex - fromIndex);
while (size != newSize)
clearData(elementData, --size);
}
private void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = memory.getInt(elementData, 0);
if (minCapacity > oldCapacity) {
int oldData = elementData;
int newCapacity = (oldCapacity * 3) / 2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
elementData = allocateSpace(newCapacity);
copyData(oldData, 0, elementData, 0, oldCapacity);
}
}
private void copyData(int ptr, int fromIndex, int toIndex, int len) {
final int fromOffset = fromIndex * 4 + 4;
final int toOffset = toIndex * 4 + 4;
memory.copyData(ptr, fromOffset, ptr, toOffset, len * 4);
}
private void copyData(int fromPtr, int fromIndex, int toPtr, int toIndex, int len) {
final int fromOffset = fromIndex * 4 + 4;
final int toOffset = toIndex * 4 + 4;
memory.copyData(fromPtr, fromOffset, toPtr, toOffset, len * 4);
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
private E getData(int ptr, int index) {
final int offset = index * 4 + 4;
final int dataPtr = memory.getInt(ptr, offset);
if (dataPtr == ODirectMemory.NULL_POINTER)
return null;
return memory.get(dataPtr, 0, serializer);
}
private void setData(int ptr, int index, E data) {
final int dataPtr;
if (data != null) {
dataPtr = memory.allocate(serializer.getObjectSize(data));
if (dataPtr == ODirectMemory.NULL_POINTER)
throw new IllegalStateException("There is no enough memory to allocate for item " + data);
memory.set(dataPtr, 0, data, serializer);
} else
dataPtr = ODirectMemory.NULL_POINTER;
final int offset = index * 4 + 4;
final int oldPtr = memory.getInt(ptr, offset);
if (oldPtr != ODirectMemory.NULL_POINTER)
memory.free(oldPtr);
memory.setInt(ptr, offset, dataPtr);
}
private void clearData(int ptr, int index) {
final int offset = index * 4 + 4;
memory.setInt(ptr, offset, ODirectMemory.NULL_POINTER);
}
private int allocateSpace(int capacity) {
final int size = capacity * 4 + 4;
final int ptr = memory.allocate(size);
if (ptr == ODirectMemory.NULL_POINTER)
throw new IllegalStateException("There is no enough memory to allocate for capacity = " + capacity);
int pos = 4;
for (int i = 0; i < capacity; i++) {
memory.setInt(ptr, pos, ODirectMemory.NULL_POINTER);
pos += 4;
}
memory.setInt(ptr, 0, capacity);
return ptr;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
clear();
memory.free(elementData);
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.distributed;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.parser.OSystemVariableResolver;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.version.OVersionFactory;
import com.orientechnologies.orient.server.OServerMain;
import com.orientechnologies.orient.server.distributed.conflict.OReplicationConflictResolver;
import com.orientechnologies.orient.server.journal.ODatabaseJournal;
import com.orientechnologies.orient.server.task.OAbstractDistributedTask;
import com.orientechnologies.orient.server.task.OAbstractDistributedTask.STATUS;
import com.orientechnologies.orient.server.task.OReadRecordDistributedTask;
/**
* Manages replication across clustered nodes.
*
* @author <NAME> (l.garulli--at--orient<EMAIL>)
*
*/
public class OStorageSynchronizer {
private ODistributedServerManager cluster;
private String storageName;
private ODatabaseJournal log;
private OReplicationConflictResolver resolver;
public OStorageSynchronizer(final ODistributedServerManager iCluster, final String storageName) throws IOException {
cluster = iCluster;
final OStorage storage = openStorage(storageName);
try {
resolver = iCluster.getConfictResolverClass().newInstance();
resolver.startup(iCluster, storageName);
} catch (Exception e) {
OLogManager.instance().error(this, "Cannot create the conflict resolver instance of class '%s'",
iCluster.getConfictResolverClass(), e);
}
final String logDirectory = OSystemVariableResolver.resolveSystemVariables(OServerMain.server().getDatabaseDirectory() + "/"
+ storageName);
log = new ODatabaseJournal(storage, logDirectory);
// RECOVER ALL THE UNCOMMITTED RECORDS ASKING TO THE CURRENT SERVERS FOR THEM
for (ORecordId rid : log.getUncommittedOperations()) {
try {
if (getConflictResolver().existConflictsForRecord(rid))
continue;
final ORawBuffer record = (ORawBuffer) iCluster.routeOperation2Node(getClusterNameByRID(storage, rid), rid,
new OReadRecordDistributedTask(iCluster.getLocalNodeId(), storageName, rid));
if (record == null)
// DELETE IT
storage.deleteRecord(rid, OVersionFactory.instance().createUntrackedVersion(), 0, null);
else
// UPDATE IT
storage.updateRecord(rid, record.buffer, record.version, record.recordType, 0, null);
} catch (ExecutionException e) {
OLogManager
.instance()
.warn(
this,
"DISTRIBUTED Error on acquiring uncommitted record %s from other servers. The database could be unaligned with others!",
e, rid);
}
}
}
public Map<String, Object> distributeOperation(final byte operation, final ORecordId rid, final OAbstractDistributedTask<?> iTask) {
final Set<String> targetNodes = cluster.getRemoteNodeIdsBut(iTask.getNodeSource());
if (!targetNodes.isEmpty()) {
// RESET THE SOURCE TO AVOID LOOPS
iTask.setNodeSource(cluster.getLocalNodeId());
iTask.setStatus(STATUS.REMOTE_EXEC);
return cluster.sendOperation2Nodes(targetNodes, iTask);
}
return null;
}
/**
* Returns the conflict resolver implementation
*
* @return
*/
public OReplicationConflictResolver getConflictResolver() {
return resolver;
}
public ODatabaseJournal getLog() {
return log;
}
@Override
public String toString() {
return storageName;
}
public static String getClusterNameByRID(final OStorage iStorage, final ORecordId iRid) {
final OCluster cluster = iStorage.getClusterById(iRid.clusterId);
return cluster != null ? cluster.getName() : "*";
}
protected OStorage openStorage(final String iName) {
OStorage stg = Orient.instance().getStorage(iName);
if (stg == null) {
// NOT YET OPEN: OPEN IT NOW
OLogManager.instance().warn(this, "DISTRIBUTED Initializing storage '%s'", iName);
final String url = OServerMain.server().getStorageURL(iName);
if (url == null)
throw new IllegalArgumentException("Database '" + iName + "' is not configured on local server");
stg = Orient.instance().loadStorage(url);
stg.open(null, null, null);
}
return stg;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.storage.impl.local;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.orientechnologies.common.concur.resource.OSharedResourceAdaptiveExternal;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.config.OStorageTxConfiguration;
import com.orientechnologies.orient.core.id.OClusterPosition;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.serialization.OBinaryProtocol;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.tx.OTransaction;
import com.orientechnologies.orient.core.version.ORecordVersion;
import com.orientechnologies.orient.core.version.OVersionFactory;
/**
* Handles the records that wait to be committed. This class is not synchronized because the caller is responsible of it.<br/>
* Uses the classic IO API and NOT the MMAP to avoid the buffer is not buffered by OS.<br/>
* <br/>
* Record structure:<br/>
* <code>
* +-----------------------------------------------------------------------------------------+--------------------+<br/>
* | .................... FIXED SIZE AREA = 24 or 208 bytes ................................ | VARIABLE SIZE AREA |<br/>
* +--------+--------+---------+------------+----------------+--------+--------+-------------+--------------------+<br/>
* | STATUS | OPERAT | TX ID . | CLUSTER ID | CLUSTER OFFSET | TYPE . |VERSION | RECORD SIZE | RECORD CONTENT ... |<br/>
* | 1 byte | 1 byte | 4 bytes | 2 bytes .. | 8 or 192 bytes | 1 byte |4 bytes | 4 bytes ... | ? bytes .......... |<br/>
* +--------+--------|---------+------------+----------------+--------+--------+-------------+--------------------+<br/>
* > 25 bytes
* </code><br/>
* At commit time all the changes are written in the TX log file with status = STATUS_COMMITTING. Once all records have been
* written, then the status of all the records is changed in STATUS_FREE. If a transactions has at least a STATUS_FREE means that
* has been successfully committed. This is the reason why on startup all the pending transactions will be recovered, but those with
* at least one record with status = STATUS_FREE.
*/
public class OTxSegment extends OSingleFileSegment {
public static final byte STATUS_FREE = 0;
public static final byte STATUS_COMMITTING = 1;
public static final byte OPERATION_CREATE = 0;
public static final byte OPERATION_DELETE = 1;
public static final byte OPERATION_UPDATE = 2;
private static final int DEF_START_SIZE = 262144;
private static final int OFFSET_TX_ID = 2;
private static final int CLUSTER_OFFSET_SIZE = OClusterPositionFactory.INSTANCE.getSerializedSize();
private static final int OFFSET_RECORD_SIZE = 13 + CLUSTER_OFFSET_SIZE
+ OVersionFactory.instance().getVersionSize();
private static final int OFFSET_RECORD_CONTENT = 17 + CLUSTER_OFFSET_SIZE
+ OVersionFactory.instance().getVersionSize();
private final boolean synchEnabled;
private OSharedResourceAdaptiveExternal lock = new OSharedResourceAdaptiveExternal(
OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean(),
0, true);
public OTxSegment(final OStorageLocal iStorage, final OStorageTxConfiguration iConfig) throws IOException {
super(iStorage, iConfig, OGlobalConfiguration.TX_LOG_TYPE.getValueAsString());
synchEnabled = OGlobalConfiguration.TX_LOG_SYNCH.getValueAsBoolean();
}
/**
* Opens the file segment and recovers pending transactions if any
*/
@Override
public boolean open() throws IOException {
lock.acquireExclusiveLock();
try {
// IGNORE IF IT'S SOFTLY CLOSED
super.open();
// CHECK FOR PENDING TRANSACTION ENTRIES TO RECOVER
recoverTransactions();
return true;
} finally {
lock.releaseExclusiveLock();
}
}
@Override
public void create(final int iStartSize) throws IOException {
lock.acquireExclusiveLock();
try {
super.create(iStartSize > -1 ? iStartSize : DEF_START_SIZE);
} finally {
lock.releaseExclusiveLock();
}
}
/**
* Appends a log entry
*/
public void addLog(final byte iOperation, final int iTxId, final int iClusterId, final OClusterPosition iClusterOffset,
final byte iRecordType, final ORecordVersion iRecordVersion, final byte[] iRecordContent, int dataSegmentId)
throws IOException {
final int contentSize = iRecordContent != null ? iRecordContent.length : 0;
final int size = OFFSET_RECORD_CONTENT + contentSize;
lock.acquireExclusiveLock();
try {
int offset = file.allocateSpace(size);
file.writeByte(offset, STATUS_COMMITTING);
offset += OBinaryProtocol.SIZE_BYTE;
file.writeByte(offset, iOperation);
offset += OBinaryProtocol.SIZE_BYTE;
file.writeInt(offset, iTxId);
offset += OBinaryProtocol.SIZE_INT;
file.writeShort(offset, (short) iClusterId);
offset += OBinaryProtocol.SIZE_SHORT;
final byte[] clusterContent = iClusterOffset.toStream();
file.write(offset, clusterContent);
offset += CLUSTER_OFFSET_SIZE;
file.writeByte(offset, iRecordType);
offset += OBinaryProtocol.SIZE_BYTE;
offset += iRecordVersion.getSerializer().writeTo(file, offset, iRecordVersion);
file.writeInt(offset, dataSegmentId);
offset += OBinaryProtocol.SIZE_INT;
file.writeInt(offset, contentSize);
offset += OBinaryProtocol.SIZE_INT;
file.write(offset, iRecordContent);
offset += contentSize;
if (synchEnabled)
file.synch();
} finally {
lock.releaseExclusiveLock();
}
}
/**
* Clears the entire file.
*
* @param iTxId
* The id of transaction
*
* @throws IOException
*/
public void clearLogEntries(final int iTxId) throws IOException {
lock.acquireExclusiveLock();
try {
truncate();
} finally {
lock.releaseExclusiveLock();
}
}
public void rollback(final OTransaction iTx) throws IOException {
lock.acquireExclusiveLock();
try {
recoverTransaction(iTx.getId());
} finally {
lock.releaseExclusiveLock();
}
}
private void recoverTransactions() throws IOException {
if (file.getFilledUpTo() == 0)
return;
OLogManager.instance().debug(this, "Started the recovering of pending transactions after a hard shutdown. Scanning...");
int recoveredTxs = 0;
int recoveredRecords = 0;
int recs;
final Set<Integer> txToRecover = scanForTransactionsToRecover();
for (Integer txId : txToRecover) {
recs = recoverTransaction(txId);
if (recs > 0) {
recoveredTxs++;
recoveredRecords += recs;
}
}
// EMPTY THE FILE
file.shrink(0);
if (recoveredRecords > 0) {
OLogManager.instance().warn(this, "Recovering successfully completed:");
OLogManager.instance().warn(this, "- Recovered Tx.....: " + recoveredTxs);
OLogManager.instance().warn(this, "- Recovered Records: " + recoveredRecords);
} else
OLogManager.instance().debug(this, "Recovering successfully completed: no pending tx records found.");
}
/**
* Scans the segment and returns the set of transactions ids to recover.
*/
private Set<Integer> scanForTransactionsToRecover() throws IOException {
// SCAN ALL THE FILE SEARCHING FOR THE TRANSACTIONS TO RECOVER
final Set<Integer> txToRecover = new HashSet<Integer>();
final Set<Integer> txToNotRecover = new HashSet<Integer>();
// BROWSE ALL THE ENTRIES
for (long offset = 0; eof(offset); offset = nextEntry(offset)) {
// READ STATUS
final byte status = file.readByte(offset);
// READ TX-ID
final int txId = file.readInt(offset + OFFSET_TX_ID);
switch (status) {
case STATUS_FREE:
// NOT RECOVER IT SINCE IF FIND AT LEAST ONE "FREE" STATUS MEANS THAT ALL THE LOGS WAS COMMITTED BUT THE USER DIDN'T
// RECEIVED THE ACK
txToNotRecover.add(txId);
break;
case STATUS_COMMITTING:
// TO RECOVER UNLESS THE REQ/TX IS IN THE MAP txToNotRecover
txToRecover.add(txId);
break;
}
}
if (txToNotRecover.size() > 0)
// FILTER THE TX MAP TO RECOVER BY REMOVING THE TX WITH AT LEAST ONE "FREE" STATUS
txToRecover.removeAll(txToNotRecover);
return txToRecover;
}
/**
* Recover a transaction.
*
* @param iTxId
* @return Number of records recovered
*
* @throws IOException
*/
private int recoverTransaction(final int iTxId) throws IOException {
int recordsRecovered = 0;
final ORecordId rid = new ORecordId();
final List<Long> txRecordPositions = new ArrayList<Long>();
// BROWSE ALL THE ENTRIES
for (long beginEntry = 0; eof(beginEntry); beginEntry = nextEntry(beginEntry)) {
long offset = beginEntry;
final byte status = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
if (status != STATUS_FREE) {
// DIRTY TX LOG ENTRY
offset += OBinaryProtocol.SIZE_BYTE;
final int txId = file.readInt(offset);
if (txId == iTxId) {
txRecordPositions.add(beginEntry);
}
}
}
for (int i = txRecordPositions.size() - 1; i >= 0; i--) {
final long beginEntry = txRecordPositions.get(i);
long offset = beginEntry;
final byte status = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
// DIRTY TX LOG ENTRY
final byte operation = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
// TX ID FOUND
final int txId = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
rid.clusterId = file.readShort(offset);
offset += OBinaryProtocol.SIZE_SHORT;
final byte[] content = new byte[OClusterPositionFactory.INSTANCE.getSerializedSize()];
file.read(offset, content, content.length);
rid.clusterPosition = OClusterPositionFactory.INSTANCE.fromStream(content);
offset += CLUSTER_OFFSET_SIZE;
final byte recordType = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
final ORecordVersion recordVersion = OVersionFactory.instance().createVersion();
offset += recordVersion.getSerializer().readFrom(file, offset, recordVersion);
final int dataSegmentId = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
final int recordSize = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
final byte[] buffer;
if (recordSize > 0) {
buffer = new byte[recordSize];
file.read(offset, buffer, recordSize);
offset += recordSize;
} else
buffer = null;
recoverTransactionEntry(status, operation, txId, rid, recordType, recordVersion, buffer, dataSegmentId);
recordsRecovered++;
// CLEAR THE ENTRY BY WRITING '0'
file.writeByte(beginEntry, STATUS_FREE);
}
return recordsRecovered;
}
private void recoverTransactionEntry(final byte iStatus, final byte iOperation, final int iTxId, final ORecordId iRid,
final byte iRecordType, final ORecordVersion iRecordVersion, final byte[] iRecordContent, int dataSegmentId)
throws IOException {
final OCluster cluster = storage.getClusterById(iRid.clusterId);
if (!(cluster instanceof OClusterLocal || cluster instanceof OClusterLocalLHPEPS))
return;
OLogManager.instance().debug(this, "Recovering tx <%d>. Operation <%d> was in status <%d> on record %s size=%d...", iTxId,
iOperation, iStatus, iRid, iRecordContent != null ? iRecordContent.length : 0);
switch (iOperation) {
case OPERATION_CREATE:
// JUST DELETE THE RECORD
storage.deleteRecord(iRid, OVersionFactory.instance().createUntrackedVersion(), 0, null);
break;
case OPERATION_UPDATE:
// REPLACE WITH THE OLD ONE
iRecordVersion.setRollbackMode();
storage.updateRecord(cluster, iRid, iRecordContent, iRecordVersion, iRecordType);
break;
case OPERATION_DELETE:
final ODataLocal dataSegment = storage.getDataSegmentById(dataSegmentId);
storage.createRecord(dataSegment, cluster, iRecordContent, iRecordType, iRid, iRecordVersion);
break;
}
}
private boolean eof(final long iOffset) {
return iOffset + OFFSET_RECORD_CONTENT < file.getFilledUpTo();
}
private long nextEntry(final long iOffset) throws IOException {
final int recordSize = file.readInt(iOffset + OFFSET_RECORD_SIZE);
return iOffset + OFFSET_RECORD_CONTENT + recordSize;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.common.concur.resource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.orientechnologies.common.concur.OTimeoutException;
/**
* Shared resource. Sub classes can acquire and release shared and exclusive locks.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*
*/
public abstract class OSharedResourceTimeout {
protected final ReadWriteLock lock = new ReentrantReadWriteLock();
protected int timeout;
public OSharedResourceTimeout(final int timeout) {
this.timeout = timeout;
}
protected void acquireSharedLock() throws OTimeoutException {
try {
if (timeout == 0) {
lock.readLock().lock();
return;
} else if (lock.readLock().tryLock(timeout, TimeUnit.MILLISECONDS))
// OK
return;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
throw new OTimeoutException("Timeout on acquiring shared lock against resource: " + this);
}
protected void releaseSharedLock() {
lock.readLock().unlock();
}
protected void acquireExclusiveLock() throws OTimeoutException {
try {
if (timeout == 0) {
lock.writeLock().lock();
return;
} else if (lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS))
// OK
return;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
throw new OTimeoutException("Timeout on acquiring exclusive lock against resource: " + this);
}
protected void releaseExclusiveLock() {
lock.writeLock().unlock();
}
}
<file_sep>/*
* Copyright 1999-2005 <NAME> (l.garulli--at-orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.profiler;
import java.io.File;
import com.orientechnologies.common.profiler.OProfiler;
import com.orientechnologies.orient.core.memory.OMemoryWatchDog;
/**
* Profiling utility class. Handles chronos (times), statistics and counters. By default it's used as Singleton but you can create
* any instances you want for separate profiling contexts.
*
* To start the recording use call startRecording(). By default record is turned off to avoid a run-time execution cost.
*
* @author <NAME>
* @copyrights Orient Technologies.com
*/
public class OJVMProfiler extends OProfiler implements OMemoryWatchDog.Listener {
private final int metricProcessors = Runtime.getRuntime().availableProcessors();
public OJVMProfiler() {
registerHookValue(getSystemMetric("config.cpus"), "Number of CPUs", METRIC_TYPE.SIZE, new OProfilerHookValue() {
@Override
public Object getValue() {
return metricProcessors;
}
});
registerHookValue(getSystemMetric("config.os.name"), "Operative System name", METRIC_TYPE.TEXT, new OProfilerHookValue() {
@Override
public Object getValue() {
return System.getProperty("os.name");
}
});
registerHookValue(getSystemMetric("config.os.version"), "Operative System version", METRIC_TYPE.TEXT, new OProfilerHookValue() {
@Override
public Object getValue() {
return System.getProperty("os.version");
}
});
registerHookValue(getSystemMetric("config.os.arch"), "Operative System architecture", METRIC_TYPE.TEXT,
new OProfilerHookValue() {
@Override
public Object getValue() {
return System.getProperty("os.arch");
}
});
registerHookValue(getSystemMetric("config.java.vendor"), "Java vendor", METRIC_TYPE.TEXT, new OProfilerHookValue() {
@Override
public Object getValue() {
return System.getProperty("java.vendor");
}
});
registerHookValue(getSystemMetric("config.java.version"), "Java version", METRIC_TYPE.TEXT, new OProfilerHookValue() {
@Override
public Object getValue() {
return System.getProperty("java.version");
}
});
registerHookValue(getProcessMetric("runtime.availableMemory"), "Available memory for the process", METRIC_TYPE.SIZE,
new OProfilerHookValue() {
@Override
public Object getValue() {
return Runtime.getRuntime().freeMemory();
}
});
registerHookValue(getProcessMetric("runtime.maxMemory"), "Maximum memory usable for the process", METRIC_TYPE.SIZE,
new OProfilerHookValue() {
@Override
public Object getValue() {
return Runtime.getRuntime().maxMemory();
}
});
registerHookValue(getProcessMetric("runtime.totalMemory"), "Total memory used by the process", METRIC_TYPE.SIZE,
new OProfilerHookValue() {
@Override
public Object getValue() {
return Runtime.getRuntime().totalMemory();
}
});
final File[] roots = File.listRoots();
for (final File root : roots) {
String volumeName = root.getAbsolutePath();
int pos = volumeName.indexOf(":\\");
if (pos > -1)
volumeName = volumeName.substring(0, pos);
final String metricPrefix = "system.disk." + volumeName;
registerHookValue(metricPrefix + ".totalSpace", "Total used disk space", METRIC_TYPE.SIZE, new OProfilerHookValue() {
@Override
public Object getValue() {
return root.getTotalSpace();
}
});
registerHookValue(metricPrefix + ".freeSpace", "Total free disk space", METRIC_TYPE.SIZE, new OProfilerHookValue() {
@Override
public Object getValue() {
return root.getFreeSpace();
}
});
registerHookValue(metricPrefix + ".usableSpace", "Total usable disk space", METRIC_TYPE.SIZE, new OProfilerHookValue() {
@Override
public Object getValue() {
return root.getUsableSpace();
}
});
}
}
public String getSystemMetric(final String iMetricName) {
final StringBuilder buffer = new StringBuilder();
buffer.append("system.");
buffer.append(iMetricName);
return buffer.toString();
}
public String getProcessMetric(final String iMetricName) {
final StringBuilder buffer = new StringBuilder();
buffer.append("process.");
buffer.append(iMetricName);
return buffer.toString();
}
public String getDatabaseMetric(final String iDatabaseName, final String iMetricName) {
final StringBuilder buffer = new StringBuilder();
buffer.append("db.");
buffer.append(iDatabaseName);
buffer.append('.');
buffer.append(iMetricName);
return buffer.toString();
}
/**
* Frees the memory removing profiling information
*/
public void memoryUsageLow(final long iFreeMemory, final long iFreeMemoryPercentage) {
synchronized (snapshots) {
snapshots.clear();
}
synchronized (summaries) {
summaries.clear();
}
}
}
<file_sep>/*
* Copyright 1999-2005 <NAME> (l.garulli--at-orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.common.profiler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.WeakHashMap;
import com.orientechnologies.common.log.OLogManager;
/**
* Profiling utility class. Handles chronos (times), statistics and counters. By default it's used as Singleton but you can create
* any instances you want for separate profiling contexts.
*
* To start the recording use call startRecording(). By default record is turned off to avoid a run-time execution cost.
*
* @author <NAME>
* @copyrights Orient Technologies.com
*/
public class OProfilerData {
private long recordingFrom = 0;
private long recordingTo = Long.MAX_VALUE;
private Map<String, Long> counters;
private Map<String, OProfilerEntry> chronos;
private Map<String, OProfilerEntry> stats;
private Map<String, Object> hooks;
public class OProfilerEntry {
public String name = null;
public long entries = 0;
public long last = 0;
public long min = 999999999;
public long max = 0;
public long average = 0;
public long total = 0;
public String payLoad;
public String description;
public void toJSON(final StringBuilder buffer) {
buffer.append(String.format("\"%s\":{", name));
buffer.append(String.format("\"%s\":%d,", "entries", entries));
buffer.append(String.format("\"%s\":%d,", "last", last));
buffer.append(String.format("\"%s\":%d,", "min", min));
buffer.append(String.format("\"%s\":%d,", "max", max));
buffer.append(String.format("\"%s\":%d,", "average", average));
buffer.append(String.format("\"%s\":%d", "total", total));
if (payLoad != null)
buffer.append(String.format("\"%s\":%d", "payload", payLoad));
buffer.append("}");
}
@Override
public String toString() {
return String.format("Profiler entry [%s]: total=%d, average=%d, items=%d, last=%d, max=%d, min=%d", total, name, average,
entries, last, max, min);
}
}
public OProfilerData() {
counters = new HashMap<String, Long>();
chronos = new HashMap<String, OProfilerEntry>();
stats = new HashMap<String, OProfilerEntry>();
hooks = new WeakHashMap<String, Object>();
recordingFrom = System.currentTimeMillis();
}
public void clear() {
counters.clear();
chronos.clear();
stats.clear();
hooks.clear();
}
public long endRecording() {
recordingTo = System.currentTimeMillis();
return recordingTo;
}
public void mergeWith(final OProfilerData iToMerge) {
if (iToMerge.recordingFrom < recordingFrom)
recordingFrom = iToMerge.recordingFrom;
if (iToMerge.recordingTo > recordingTo)
recordingTo = iToMerge.recordingTo;
// COUNTERS
for (Entry<String, Long> entry : iToMerge.counters.entrySet()) {
Long currentValue = counters.get(entry.getKey());
if (currentValue == null)
currentValue = 0l;
counters.put(entry.getKey(), currentValue + entry.getValue());
}
// HOOKS
for (Entry<String, Object> entry : iToMerge.hooks.entrySet()) {
Object currentValue = hooks.get(entry.getKey());
if (currentValue == null)
currentValue = entry.getValue();
else {
// MERGE IT
final Object otherValue = entry.getValue();
if (currentValue instanceof Long)
currentValue = ((Long) currentValue).longValue() + ((Long) otherValue).longValue();
else if (currentValue instanceof Integer)
currentValue = ((Integer) currentValue).intValue() + ((Integer) otherValue).intValue();
else if (currentValue instanceof Short)
currentValue = ((Short) currentValue).shortValue() + ((Short) otherValue).shortValue();
else if (currentValue instanceof Float)
currentValue = ((Float) currentValue).floatValue() + ((Float) otherValue).floatValue();
else if (currentValue instanceof Double)
currentValue = ((Double) currentValue).doubleValue() + ((Double) otherValue).doubleValue();
else if (currentValue instanceof Boolean)
currentValue = otherValue;
else if (currentValue instanceof String)
currentValue = otherValue;
else
OLogManager.instance().warn(this, "Type of value '%s' not support on profiler hook '%s' to merge with value: %s",
currentValue, entry.getKey(), entry.getValue());
}
hooks.put(entry.getKey(), currentValue);
}
// CHRONOS
mergeEntries(chronos, iToMerge.chronos);
// STATS
mergeEntries(stats, iToMerge.stats);
}
public void toJSON(final StringBuilder buffer, final String iFilter) {
buffer.append("{");
buffer.append(String.format("\"from\": %d,", recordingFrom));
buffer.append(String.format("\"to\": %d,", recordingTo));
// HOOKS
buffer.append("\"hookValues\":{ ");
List<String> names = new ArrayList<String>(hooks.keySet());
Collections.sort(names);
boolean firstItem = true;
for (String k : names) {
if (iFilter != null && !k.startsWith(iFilter))
// APPLIED FILTER: DOESN'T MATCH
continue;
final Object value = hooks.get(k);
if (firstItem)
firstItem = false;
else
buffer.append(',');
if (value == null)
buffer.append(String.format("\"%s\":null", k));
else if (value instanceof Number)
buffer.append(String.format("\"%s\":%d", k, value));
else if (value instanceof Boolean)
buffer.append(String.format("\"%s\":%s", k, value));
else
buffer.append(String.format("\"%s\":\"%s\"", k, value.toString()));
}
buffer.append("}");
// CHRONOS
buffer.append(",\"chronos\":{");
names = new ArrayList<String>(chronos.keySet());
Collections.sort(names);
firstItem = true;
for (String k : names) {
if (iFilter != null && !k.startsWith(iFilter))
// APPLIED FILTER: DOESN'T MATCH
continue;
if (firstItem)
firstItem = false;
else
buffer.append(',');
chronos.get(k).toJSON(buffer);
}
buffer.append("}");
// STATISTICS
buffer.append(",\"statistics\":{");
names = new ArrayList<String>(stats.keySet());
Collections.sort(names);
firstItem = true;
for (String k : names) {
if (iFilter != null && !k.startsWith(iFilter))
// APPLIED FILTER: DOESN'T MATCH
continue;
if (firstItem)
firstItem = false;
else
buffer.append(',');
stats.get(k).toJSON(buffer);
}
buffer.append("}");
// COUNTERS
buffer.append(",\"counters\":{");
names = new ArrayList<String>(counters.keySet());
Collections.sort(names);
firstItem = true;
for (String k : names) {
if (iFilter != null && !k.startsWith(iFilter))
// APPLIED FILTER: DOESN'T MATCH
continue;
if (firstItem)
firstItem = false;
else
buffer.append(',');
buffer.append(String.format("\"%s\":%d", k, counters.get(k)));
}
buffer.append("}");
buffer.append("}");
}
public String dump() {
final StringBuilder buffer = new StringBuilder();
buffer.append("Dump of profiler data from " + new Date(recordingFrom) + " to " + new Date(recordingFrom) + "\n");
buffer.append(dumpHookValues());
buffer.append("\n");
buffer.append(dumpCounters());
buffer.append("\n\n");
buffer.append(dumpStats());
buffer.append("\n\n");
buffer.append(dumpChronos());
return buffer.toString();
}
public void updateCounter(final String iStatName, final long iPlus) {
if (iStatName == null)
return;
synchronized (counters) {
final Long stat = counters.get(iStatName);
final long oldValue = stat == null ? 0 : stat.longValue();
counters.put(iStatName, new Long(oldValue + iPlus));
}
}
public long getCounter(final String iStatName) {
if (iStatName == null)
return -1;
synchronized (counters) {
final Long stat = counters.get(iStatName);
if (stat == null)
return -1;
return stat.longValue();
}
}
public String dumpCounters() {
synchronized (counters) {
final StringBuilder buffer = new StringBuilder();
buffer.append("Dumping COUNTERS:");
buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
buffer.append(String.format("\n%50s | Value |", "Name"));
buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
final List<String> keys = new ArrayList<String>(counters.keySet());
Collections.sort(keys);
for (String k : keys) {
final Long stat = counters.get(k);
buffer.append(String.format("\n%-50s | %-65d |", k, stat));
}
buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
return buffer.toString();
}
}
public long stopChrono(final String iName, final long iStartTime, final String iPayload) {
return updateEntry(chronos, iName, System.currentTimeMillis() - iStartTime, iPayload);
}
public String dumpChronos() {
return dumpEntries(chronos, new StringBuilder("Dumping CHRONOS. Times in ms:"));
}
public long updateStat(final String iName, final long iValue) {
return updateEntry(stats, iName, iValue, null);
}
public String dumpStats() {
return dumpEntries(stats, new StringBuilder("Dumping STATISTICS. Times in ms:"));
}
public String dumpHookValues() {
final StringBuilder buffer = new StringBuilder();
synchronized (hooks) {
if (hooks.size() == 0)
return "";
buffer.append("Dumping HOOK VALUES:");
buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
buffer.append(String.format("\n%50s | Value |", "Name"));
buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
final List<String> names = new ArrayList<String>(hooks.keySet());
Collections.sort(names);
for (String k : names) {
final Object hookValue = hooks.get(k);
buffer.append(String.format("\n%-50s | %-65s |", k, hookValue != null ? hookValue.toString() : "null"));
}
}
buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
return buffer.toString();
}
public Object getHookValue(final String iName) {
if (iName == null)
return null;
synchronized (hooks) {
return hooks.get(iName);
}
}
public void setHookValues(final Map<String, Object> iHooks) {
synchronized (hooks) {
hooks.clear();
if (iHooks != null)
hooks.putAll(iHooks);
}
}
public String[] getCountersAsString() {
synchronized (counters) {
final String[] output = new String[counters.size()];
int i = 0;
for (Entry<String, Long> entry : counters.entrySet()) {
output[i++] = entry.getKey() + ": " + entry.getValue().toString();
}
return output;
}
}
public String[] getChronosAsString() {
synchronized (chronos) {
final String[] output = new String[chronos.size()];
int i = 0;
for (Entry<String, OProfilerEntry> entry : chronos.entrySet()) {
output[i++] = entry.getKey() + ": " + entry.getValue().toString();
}
return output;
}
}
public String[] getStatsAsString() {
synchronized (stats) {
final String[] output = new String[stats.size()];
int i = 0;
for (Entry<String, OProfilerEntry> entry : stats.entrySet()) {
output[i++] = entry.getKey() + ": " + entry.getValue().toString();
}
return output;
}
}
public List<String> getCounters() {
synchronized (counters) {
final List<String> list = new ArrayList<String>(counters.keySet());
Collections.sort(list);
return list;
}
}
public List<String> getHooks() {
synchronized (hooks) {
final List<String> list = new ArrayList<String>(hooks.keySet());
Collections.sort(list);
return list;
}
}
public List<String> getChronos() {
synchronized (chronos) {
final List<String> list = new ArrayList<String>(chronos.keySet());
Collections.sort(list);
return list;
}
}
public List<String> getStats() {
synchronized (stats) {
final List<String> list = new ArrayList<String>(stats.keySet());
Collections.sort(list);
return list;
}
}
public OProfilerEntry getStat(final String iStatName) {
if (iStatName == null)
return null;
synchronized (stats) {
return stats.get(iStatName);
}
}
public OProfilerEntry getChrono(final String iChronoName) {
if (iChronoName == null)
return null;
synchronized (chronos) {
return chronos.get(iChronoName);
}
}
protected synchronized long updateEntry(final Map<String, OProfilerEntry> iValues, final String iName, final long iValue,
final String iPayload) {
synchronized (iValues) {
OProfilerEntry c = iValues.get(iName);
if (c == null) {
// CREATE NEW CHRONO
c = new OProfilerEntry();
iValues.put(iName, c);
}
c.name = iName;
c.payLoad = iPayload;
c.entries++;
c.last = iValue;
c.total += c.last;
c.average = c.total / c.entries;
if (c.last < c.min)
c.min = c.last;
if (c.last > c.max)
c.max = c.last;
return c.last;
}
}
protected synchronized String dumpEntries(final Map<String, OProfilerEntry> iValues, final StringBuilder iBuffer) {
// CHECK IF CHRONOS ARE ACTIVED
synchronized (iValues) {
if (iValues.size() == 0)
return "";
OProfilerEntry c;
iBuffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
iBuffer.append(String.format("\n%50s | %10s %10s %10s %10s %10s %10s |", "Name", "last", "total", "min", "max", "average",
"items"));
iBuffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
final List<String> keys = new ArrayList<String>(iValues.keySet());
Collections.sort(keys);
for (String k : keys) {
c = iValues.get(k);
iBuffer.append(String.format("\n%-50s | %10d %10d %10d %10d %10d %10d |", k, c.last, c.total, c.min, c.max, c.average,
c.entries));
}
iBuffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
return iBuffer.toString();
}
}
protected void mergeEntries(final Map<String, OProfilerEntry> iMyEntries, final Map<String, OProfilerEntry> iOthersEntries) {
for (Entry<String, OProfilerEntry> entry : iOthersEntries.entrySet()) {
OProfilerEntry currentValue = iMyEntries.get(entry.getKey());
if (currentValue == null) {
currentValue = entry.getValue();
iMyEntries.put(entry.getKey(), currentValue);
} else {
// MERGE IT
currentValue.entries += entry.getValue().entries;
currentValue.last = entry.getValue().last;
currentValue.min = Math.min(currentValue.min, entry.getValue().min);
currentValue.max = Math.max(currentValue.max, entry.getValue().max);
currentValue.average = (currentValue.total + entry.getValue().total) / currentValue.entries;
currentValue.total += entry.getValue().total;
}
}
}
public boolean isInRange(final long from, final long to) {
return recordingFrom >= from && recordingTo <= to;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.task;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.Callable;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.server.OServerMain;
import com.orientechnologies.orient.server.config.OServerUserConfiguration;
import com.orientechnologies.orient.server.distributed.ODistributedAbstractPlugin;
import com.orientechnologies.orient.server.distributed.ODistributedServerManager;
import com.orientechnologies.orient.server.distributed.ODistributedServerManager.EXECUTION_MODE;
import com.orientechnologies.orient.server.distributed.OStorageSynchronizer;
/**
* Distributed task base abstract class used for distributed actions and events.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*
*/
public abstract class OAbstractDistributedTask<T> implements Callable<T>, Externalizable {
private static final long serialVersionUID = 1L;
public enum STATUS {
DISTRIBUTE, REMOTE_EXEC, ALIGN, LOCAL_EXEC
}
protected String nodeSource;
protected String databaseName;
protected long runId;
protected long operationSerial;
protected EXECUTION_MODE mode;
protected STATUS status;
protected boolean inheritedDatabase;
protected static OServerUserConfiguration replicatorUser;
static {
replicatorUser = OServerMain.server().getUser(ODistributedAbstractPlugin.REPLICATOR_USER);
}
/**
* Constructor used from unmarshalling.
*/
public OAbstractDistributedTask() {
status = STATUS.REMOTE_EXEC;
}
/**
* Constructor used on creation from log.
*
* @param iRunId
* @param iOperationId
*/
public OAbstractDistributedTask(final long iRunId, final long iOperationId) {
this.runId = iRunId;
this.operationSerial = iOperationId;
this.status = STATUS.ALIGN;
}
public OAbstractDistributedTask(final String nodeSource, final String databaseName, final EXECUTION_MODE iMode) {
this.nodeSource = nodeSource;
this.databaseName = databaseName;
this.mode = iMode;
this.status = STATUS.DISTRIBUTE;
this.runId = getDistributedServerManager().getRunId();
this.operationSerial = getDistributedServerManager().incrementDistributedSerial(databaseName);
}
/**
* Handles conflict between local and remote execution results.
*
* @param localResult
* The result on local node
* @param remoteResult
* the result on remote node
* @param remoteResult2
*/
public void handleConflict(final String iRemoteNode, Object localResult, Object remoteResult) {
}
public abstract String getName();
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
out.writeUTF(nodeSource);
out.writeUTF(databaseName);
out.writeLong(runId);
out.writeLong(operationSerial);
out.writeByte(mode.ordinal());
out.writeByte(status.ordinal());
}
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
nodeSource = in.readUTF();
databaseName = in.readUTF();
runId = in.readLong();
operationSerial = in.readLong();
mode = EXECUTION_MODE.values()[in.readByte()];
status = STATUS.values()[in.readByte()];
}
public String getNodeSource() {
return nodeSource;
}
public String getDatabaseName() {
return databaseName;
}
public long getOperationSerial() {
return operationSerial;
}
public long getRunId() {
return runId;
}
public EXECUTION_MODE getMode() {
return mode;
}
public void setMode(final EXECUTION_MODE iMode) {
mode = iMode;
}
public STATUS getStatus() {
return status;
}
public OAbstractDistributedTask<T> setStatus(final STATUS status) {
this.status = status;
return this;
}
public void setNodeSource(String nodeSource) {
this.nodeSource = nodeSource;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
@Override
public String toString() {
return getName();
}
protected OStorageSynchronizer getDatabaseSynchronizer() {
return getDistributedServerManager().getDatabaseSynchronizer(databaseName);
}
protected ODistributedServerManager getDistributedServerManager() {
return (ODistributedServerManager) OServerMain.server().getVariable("ODistributedAbstractPlugin");
}
protected void setAsCompleted(final OStorageSynchronizer dbSynchronizer, long operationLogOffset) throws IOException {
dbSynchronizer.getLog().changeOperationStatus(operationLogOffset, null);
}
protected ODatabaseDocumentTx openDatabase() {
inheritedDatabase = true;
final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
if (db != null && db.getName().equals(databaseName) && !db.isClosed()) {
if (db instanceof ODatabaseDocumentTx)
return (ODatabaseDocumentTx) db;
else if (db.getDatabaseOwner() instanceof ODatabaseDocumentTx)
return (ODatabaseDocumentTx) db.getDatabaseOwner();
}
inheritedDatabase = false;
return (ODatabaseDocumentTx) OServerMain.server().openDatabase("document", databaseName, replicatorUser.name,
replicatorUser.password);
}
protected void closeDatabase(final ODatabaseDocumentTx iDatabase) {
if (!inheritedDatabase)
iDatabase.close();
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.type.tree.provider;
import java.io.IOException;
import java.util.Arrays;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.serialization.OBinaryProtocol;
import com.orientechnologies.orient.core.serialization.OMemoryStream;
import com.orientechnologies.orient.core.serialization.OSerializableStream;
/**
* Handles a set of references optimizing the memory space used. This is used by LINKSET type and as SET of links of Not Unique
* indexes. The binary chunk is allocated the first time and never changes. This takes more memory but assure zero fragmentation at
* the storage level. Tree size field is used only in the root node to avoid to store the parent document.<br>
* Structure of binary chunk:<br>
* <code>
* +-----------+-----------+--------+------------+----------+-----------+---------------------+<br>
* | TREE SIZE | NODE SIZE | COLOR .| PARENT RID | LEFT RID | RIGHT RID | RID LIST .......... |<br>
* +-----------+-----------+--------+------------+----------+-----------+---------------------+<br>
* | 4 bytes . | 4 bytes . | 1 byte | 10 bytes ..| 10 bytes | 10 bytes .| 10 * MAX_SIZE bytes |<br>
* +-----------+-----------+--------+------------+----------+-----------+---------------------+<br>
* = 39 bytes + 10 * PAGE-SIZE bytes<br/>
* Where:
* <ul>
* <li><b>TREE SIZE</b> as signed integer (4 bytes) containing the size of the tree. Only the root node has this value updated, so to know the size of the collection you need to load the root node and get this field. other nodes can contain not updated values because upon rotation of pieces of the tree (made during tree rebalancing) the root can change and the old root will have the "old" size as dirty.</li>
* <li><b>NODE SIZE</b> as signed integer (4 bytes) containing number of entries in this node. It's always <= to the page-size defined at the tree level and equals for all the nodes. By default page-size is 16 items</li>
* <li><b>COLOR</b> as 1 byte containing 1=Black, 0=Red. To know more about the meaning of this look at [http://en.wikipedia.org/wiki/Red%E2%80%93black_tree Red-Black Trees]</li>
* <li><b>PARENT RID</b> as [Concepts#RecordID RID] (10 bytes) of the parent node record</li>
* <li><b>LEFT RID</b> as [Concepts#RecordID RID] (10 bytes) of the left node record</li>
* <li><b>RIGHT RID</b> as [Concepts#RecordID RID] (10 bytes) of the right node record</li>
* <li><b>RID LIST</b> as the list of [Concepts#RecordID RIDs] containing the references to the records. This is pre-allocated to the configured page-size. Since each [Concepts#RecordID RID] takes 10 bytes, a page-size of 16 means 16 x 10bytes = 160bytes</li>
* </ul>
* The size of the tree-node on disk (and memory) is fixed to avoid fragmentation. To compute it: 39 bytes + 10 * PAGE-SIZE bytes. For a page-size = 16 you'll have 39 + 160 = 199 bytes.
* </code>
*
* @author <NAME> (l.garulli--at--orientechnologies.com) *
*
*/
public class OMVRBTreeRIDEntryProvider extends OMVRBTreeEntryDataProviderAbstract<OIdentifiable, OIdentifiable> {
private static final long serialVersionUID = 1L;
protected final static int OFFSET_TREESIZE = 0;
protected final static int OFFSET_NODESIZE = OFFSET_TREESIZE + OBinaryProtocol.SIZE_INT;
protected final static int OFFSET_COLOR = OFFSET_NODESIZE + OBinaryProtocol.SIZE_INT;
protected final static int OFFSET_PARENT = OFFSET_COLOR + OBinaryProtocol.SIZE_BYTE;
protected final static int OFFSET_LEFT = OFFSET_PARENT + ORecordId.PERSISTENT_SIZE;
protected final static int OFFSET_RIGHT = OFFSET_LEFT + ORecordId.PERSISTENT_SIZE;
protected final static int OFFSET_RIDLIST = OFFSET_RIGHT + ORecordId.PERSISTENT_SIZE;
private int treeSize;
private final OIdentifiable[] rids;
public OMVRBTreeRIDEntryProvider(final OMVRBTreeRIDProvider iTreeDataProvider) {
super(iTreeDataProvider, OFFSET_RIDLIST + (iTreeDataProvider.getDefaultPageSize() * ORecordId.PERSISTENT_SIZE));
rids = OGlobalConfiguration.MVRBTREE_RID_NODE_SAVE_MEMORY.getValueAsBoolean() ? null : new OIdentifiable[pageSize];
}
public OMVRBTreeRIDEntryProvider(final OMVRBTreeRIDProvider iTreeDataProvider, final ORID iRID) {
super(iTreeDataProvider, iRID);
pageSize = treeDataProvider.getDefaultPageSize();
rids = OGlobalConfiguration.MVRBTREE_RID_NODE_SAVE_MEMORY.getValueAsBoolean() ? null : new OIdentifiable[pageSize];
}
/**
* Lazy unmarshall the RID if not in memory.
*/
public OIdentifiable getKeyAt(final int iIndex) {
if (rids != null && rids[iIndex] != null)
return rids[iIndex];
final ORecordId rid = itemFromStream(iIndex);
if (rids != null)
rids[iIndex] = rid;
return rid;
}
/**
* Returns the key
*/
public OIdentifiable getValueAt(final int iIndex) {
return getKeyAt(iIndex);
}
public boolean setValueAt(int iIndex, final OIdentifiable iValue) {
if (iValue == null)
return false;
try {
itemToStream(iValue, iIndex);
} catch (IOException e) {
throw new OSerializationException("Cannot serialize entryRID object: " + this, e);
}
if (rids != null)
rids[iIndex] = iValue;
return setDirty();
}
public boolean insertAt(final int iIndex, final OIdentifiable iKey, final OIdentifiable iValue) {
if (iIndex < size) {
// MOVE RIGHT TO MAKE ROOM FOR THE ITEM
stream.move(getKeyPositionInStream(iIndex), ORecordId.PERSISTENT_SIZE);
if (rids != null)
System.arraycopy(rids, iIndex, rids, iIndex + 1, size - iIndex - 1);
}
try {
itemToStream(iKey, iIndex);
} catch (IOException e) {
throw new OSerializationException("Cannot serialize entryRID object: " + this, e);
}
if (rids != null)
rids[iIndex] = iKey;
size++;
return setDirty();
}
public boolean removeAt(final int iIndex) {
if (iIndex > -1 && iIndex < size - 1) {
// SHIFT LEFT THE VALUES
stream.move(getKeyPositionInStream(iIndex + 1), ORecordId.PERSISTENT_SIZE * -1);
if (rids != null)
System.arraycopy(rids, iIndex + 1, rids, iIndex, size - iIndex - 1);
}
size--;
// FREE RESOURCES
if (rids != null)
rids[size] = null;
return setDirty();
}
public boolean copyDataFrom(final OMVRBTreeEntryDataProvider<OIdentifiable, OIdentifiable> iFrom, final int iStartPosition) {
size = iFrom.getSize() - iStartPosition;
final OMVRBTreeRIDEntryProvider from = (OMVRBTreeRIDEntryProvider) iFrom;
moveToIndex(0).copyFrom(from.moveToIndex(iStartPosition), size * ORecordId.PERSISTENT_SIZE);
if (rids != null)
System.arraycopy(from.rids, iStartPosition, rids, 0, size);
return setDirty();
}
public boolean truncate(final int iNewSize) {
moveToIndex(iNewSize).fill((size - iNewSize) * ORecordId.PERSISTENT_SIZE, (byte) 0);
if (rids != null)
Arrays.fill(rids, iNewSize, size, null);
size = iNewSize;
return setDirty();
}
public boolean copyFrom(final OMVRBTreeEntryDataProvider<OIdentifiable, OIdentifiable> iSource) {
final OMVRBTreeRIDEntryProvider source = (OMVRBTreeRIDEntryProvider) iSource;
stream = source.stream;
size = source.size;
return setDirty();
}
public OSerializableStream fromStream(final byte[] iStream) throws OSerializationException {
if (stream == null)
stream = new OMemoryStream(iStream);
else
stream.setSource(iStream);
treeSize = stream.jump(OFFSET_TREESIZE).getAsInteger();
size = stream.jump(OFFSET_NODESIZE).getAsInteger();
color = stream.jump(OFFSET_COLOR).getAsBoolean();
parentRid.fromStream(stream.jump(OFFSET_PARENT));
leftRid.fromStream(stream.jump(OFFSET_LEFT));
rightRid.fromStream(stream.jump(OFFSET_RIGHT));
if (rids != null)
// CREATE IN MEMORY RIDS FROM STREAM
Arrays.fill(rids, null);
return this;
}
public byte[] toStream() throws OSerializationException {
if (stream == null)
stream = new OMemoryStream();
try {
stream.jump(OFFSET_TREESIZE).set(treeSize);
stream.jump(OFFSET_NODESIZE).set(size);
stream.jump(OFFSET_COLOR).set(color);
parentRid.toStream(stream.jump(OFFSET_PARENT));
leftRid.toStream(stream.jump(OFFSET_LEFT));
rightRid.toStream(stream.jump(OFFSET_RIGHT));
if (rids != null)
// STREAM RIDS
for (int i = 0; i < size; ++i)
if (rids[i] != null)
itemToStream(rids[i], i);
} catch (IOException e) {
throw new OSerializationException("Cannot serialize tree entry RID node: " + this, e);
}
// RETURN DIRECTLY THE UNDERLYING BUFFER SINCE IT'S FIXED
final byte[] buffer = stream.getInternalBuffer();
record.fromStream(buffer);
return buffer;
}
protected OMemoryStream moveToIndex(final int iIndex) {
return stream.jump(getKeyPositionInStream(iIndex));
}
protected int getKeyPositionInStream(final int iIndex) {
return OFFSET_RIDLIST + (iIndex * ORecordId.PERSISTENT_SIZE);
}
public int getTreeSize() {
return treeSize;
}
public boolean setTreeSize(final int treeSize) {
if (this.treeSize != treeSize) {
this.treeSize = treeSize;
setDirty();
return true;
}
return false;
}
protected ORecordId itemFromStream(final int iIndex) {
return new ORecordId().fromStream(moveToIndex(iIndex));
}
protected int itemToStream(final OIdentifiable iKey, final int iIndex) throws IOException {
return iKey.getIdentity().toStream(moveToIndex(iIndex));
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.distributed.conflict;
import java.util.List;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.command.OCommandRequest;
import com.orientechnologies.orient.core.db.ODatabaseComplex;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordOperation;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OClass.INDEX_TYPE;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.core.version.ORecordVersion;
import com.orientechnologies.orient.server.OServerMain;
import com.orientechnologies.orient.server.config.OServerUserConfiguration;
import com.orientechnologies.orient.server.distributed.ODistributedAbstractPlugin;
import com.orientechnologies.orient.server.distributed.ODistributedServerManager;
/**
* Default conflict resolver.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*/
public class ODefaultReplicationConflictResolver implements OReplicationConflictResolver {
private static final String DISTRIBUTED_CONFLICT_CLASS = "ODistributedConflict";
private static final String FIELD_RECORD = "record";
private static final String FIELD_NODE = "node";
private static final String FIELD_DATE = "date";
private static final String FIELD_OPERATION = "operation";
private static final String FIELD_OTHER_RID = "otherRID";
private static final String FIELD_CURRENT_VERSION = "currentVersion";
private static final String FIELD_OTHER_VERSION = "otherVersion";
private boolean ignoreIfSameContent;
private boolean ignoreIfMergeOk;
private boolean latestAlwaysWin;
private ODatabaseComplex<?> database;
private OIndex<?> index = null;
public ODefaultReplicationConflictResolver() {
}
public void startup(final ODistributedServerManager iDManager, final String iDatabaseName) {
synchronized (this) {
if (index != null)
return;
final OServerUserConfiguration replicatorUser = OServerMain.server().getUser(ODistributedAbstractPlugin.REPLICATOR_USER);
database = OServerMain.server().openDatabase("document", iDatabaseName, replicatorUser.name, replicatorUser.password);
OClass cls = database.getMetadata().getSchema().getClass(DISTRIBUTED_CONFLICT_CLASS);
final OProperty p;
if (cls == null) {
cls = database.getMetadata().getSchema().createClass(DISTRIBUTED_CONFLICT_CLASS);
index = cls.createProperty(FIELD_RECORD, OType.LINK).createIndex(INDEX_TYPE.UNIQUE);
} else {
p = cls.getProperty(FIELD_RECORD);
if (p == null)
index = cls.createProperty(FIELD_RECORD, OType.LINK).createIndex(INDEX_TYPE.UNIQUE);
else {
index = p.getIndex();
}
}
}
}
public void shutdown() {
if (database != null)
database.close();
if (index != null)
index = null;
}
@Override
public void handleCreateConflict(final String iRemoteNode, final ORecordId iCurrentRID, final ORecordId iOtherRID) {
OLogManager.instance().warn(this, "CONFLICT against node %s CREATE record %s (other RID=%s)...", iRemoteNode, iCurrentRID,
iOtherRID);
if (!existConflictsForRecord(iCurrentRID)) {
// WRITE THE CONFLICT AS RECORD
final ODocument doc = createConflictDocument(ORecordOperation.CREATED, iCurrentRID, iRemoteNode);
doc.field(FIELD_OTHER_RID, iOtherRID);
doc.save();
}
}
@Override
public void handleUpdateConflict(final String iRemoteNode, final ORecordId iCurrentRID, final ORecordVersion iCurrentVersion,
final int iOtherVersion) {
OLogManager.instance().warn(this, "CONFLICT against node %s UDPATE record %s (current=v%d, other=v%d)...", iRemoteNode,
iCurrentRID, iCurrentVersion, iOtherVersion);
if (!existConflictsForRecord(iCurrentRID)) {
// WRITE THE CONFLICT AS RECORD
final ODocument doc = createConflictDocument(ORecordOperation.UPDATED, iCurrentRID, iRemoteNode);
doc.field(FIELD_CURRENT_VERSION, iCurrentVersion);
doc.field(FIELD_OTHER_VERSION, iOtherVersion);
doc.save();
}
}
@Override
public void handleDeleteConflict(final String iRemoteNode, final ORecordId iCurrentRID) {
OLogManager.instance().warn(this, "CONFLICT against node %s DELETE record %s (cannot be deleted on other node)", iRemoteNode,
iCurrentRID);
if (!existConflictsForRecord(iCurrentRID)) {
// WRITE THE CONFLICT AS RECORD
final ODocument doc = createConflictDocument(ORecordOperation.DELETED, iCurrentRID, iRemoteNode);
doc.save();
}
}
@Override
public void handleCommandConflict(final String iRemoteNode, OCommandRequest iCommand, Object iLocalResult, Object iRemoteResult) {
OLogManager.instance().warn(this, "CONFLICT against node %s COMMAND execution %s result local=%s, remote=%s", iRemoteNode,
iCommand, iLocalResult, iRemoteResult);
}
@Override
public ODocument getAllConflicts() {
ODatabaseRecordThreadLocal.INSTANCE.set((ODatabaseRecord) database);
final List<OIdentifiable> entries = database.query(new OSQLSynchQuery<OIdentifiable>("select from "
+ DISTRIBUTED_CONFLICT_CLASS));
// EARLY LOAD CONTENT
final ODocument result = new ODocument().field("entries", entries);
for (int i = 0; i < entries.size(); ++i) {
final ODocument record = entries.get(i).getRecord();
record.setClassName(null);
record.addOwner(result);
record.getIdentity().reset();
entries.set(i, record);
}
return result;
}
/**
* Searches for a conflict by RID.
*
* @param iRID
* RID to search
*/
public boolean existConflictsForRecord(final ORecordId iRID) {
ODatabaseRecordThreadLocal.INSTANCE.set((ODatabaseRecord) database);
if (index.contains(iRID)) {
OLogManager.instance().warn(this, "Conflict already present for record %s, skip it", iRID);
return true;
}
return false;
}
protected ODocument createConflictDocument(final byte iOperation, final ORecordId iRid, final String iServerNode) {
ODatabaseRecordThreadLocal.INSTANCE.set((ODatabaseRecord) database);
final ODocument doc = new ODocument(DISTRIBUTED_CONFLICT_CLASS);
doc.field(FIELD_OPERATION, iOperation);
doc.field(FIELD_DATE, System.currentTimeMillis());
doc.field(FIELD_RECORD, iRid);
doc.field(FIELD_NODE, iServerNode);
return doc;
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.plugin.mail;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.script.Bindings;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.script.OScriptInjection;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.config.OServerParameterConfiguration;
import com.orientechnologies.orient.server.handler.OServerHandlerAbstract;
public class OMailPlugin extends OServerHandlerAbstract implements OScriptInjection {
private static final String CONFIG_PROFILE_PREFIX = "profile.";
private static final String CONFIG_MAIL_PREFIX = "mail.";
private Map<String, OMailProfile> profiles = new HashMap<String, OMailProfile>();
public OMailPlugin() {
Orient.instance().getScriptManager().registerInjection(this);
}
@Override
public void config(final OServer oServer, final OServerParameterConfiguration[] iParams) {
for (OServerParameterConfiguration param : iParams) {
if (param.name.equalsIgnoreCase("enabled")) {
if (!Boolean.parseBoolean(param.value))
// DISABLE IT
return;
} else if (param.name.startsWith(CONFIG_PROFILE_PREFIX)) {
final String parts = param.name.substring(CONFIG_PROFILE_PREFIX.length());
int pos = parts.indexOf('.');
if (pos == -1)
continue;
final String profileName = parts.substring(0, pos);
final String profileParam = parts.substring(pos + 1);
OMailProfile profile = profiles.get(profileName);
if (profile == null) {
profile = new OMailProfile();
profiles.put(profileName, profile);
}
if (profileParam.startsWith(CONFIG_MAIL_PREFIX)) {
profile.properties.setProperty("mail." + profileParam.substring(CONFIG_MAIL_PREFIX.length()), param.value);
}
}
}
OLogManager.instance().info(this, "Mail plugin installed and active. Loaded %d profile(s): %s", profiles.size(),
profiles.keySet());
}
/**
* Sends an email. Supports the following configuration: subject, message, to, cc, bcc, date, attachments
*
* @param iMessage
* Configuration as Map<String,Object>
* @throws AddressException
* @throws MessagingException
* @throws ParseException
*/
public void send(final Map<String, Object> iMessage) throws AddressException, MessagingException, ParseException {
final String profileName = (String) iMessage.get("profile");
OMailProfile profile = profiles.get(profileName);
if (profile == null)
throw new IllegalArgumentException("Mail profile '" + profileName + "' is not configured on server");
final Properties prop = profile.properties;
// creates a new session with an authenticator
Authenticator auth = new OSMTPAuthenticator((String) prop.get("mail.smtp.user"), (String) prop.get("mail.smtp.password"));
Session session = Session.getInstance(prop, auth);
// creates a new e-mail message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress((String) prop.get("mail.smtp.user")));
InternetAddress[] toAddresses = { new InternetAddress((String) iMessage.get("to")) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
InternetAddress[] ccAddresses = { new InternetAddress((String) iMessage.get("cc")) };
msg.setRecipients(Message.RecipientType.CC, ccAddresses);
InternetAddress[] bccAddresses = { new InternetAddress((String) iMessage.get("bcc")) };
msg.setRecipients(Message.RecipientType.BCC, bccAddresses);
msg.setSubject((String) iMessage.get("subject"));
// DATE
Object date = iMessage.get("date");
final Date sendDate;
if (date == null)
// NOT SPECIFIED = NOW
sendDate = new Date();
else if (date instanceof Date)
// PASSED
sendDate = (Date) date;
else {
// FORMAT IT
String dateFormat = (String) prop.get("mail.date.format");
if (dateFormat == null)
dateFormat = "yyyy-MM-dd HH:mm:ss";
sendDate = new SimpleDateFormat(dateFormat).parse(date.toString());
}
msg.setSentDate(sendDate);
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(iMessage.get("message"), "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
final String[] attachments = (String[]) iMessage.get("attachments");
// adds attachments
if (attachments != null && attachments.length > 0) {
for (String filePath : attachments) {
addAttachment(multipart, filePath);
}
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
/**
* Adds a file as an attachment to the email's content
*
* @param multipart
* @param filePath
* @throws MessagingException
*/
private void addAttachment(final Multipart multipart, final String filePath) throws MessagingException {
MimeBodyPart attachPart = new MimeBodyPart();
DataSource source = new FileDataSource(filePath);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(new File(filePath).getName());
multipart.addBodyPart(attachPart);
}
@Override
public void bind(Bindings binding) {
binding.put("mail", this);
}
@Override
public void unbind(Bindings binding) {
binding.remove("mail");
}
@Override
public String getName() {
return "mail";
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.util;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* Contains information about current host.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class OHostInfo {
/**
* Gets mac address of current host.
*
* @return mac address
*/
public static byte[] getMac() {
try {
final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
final byte[] mac = networkInterface.getHardwareAddress();
if (mac != null && mac.length == 6)
return mac;
}
} catch (SocketException e) {
throw new IllegalStateException("Error during MAC address retrieval.", e);
}
throw new IllegalStateException("Node id is possible to generate only on machine which have at least"
+ " one network interface with mac address.");
}
}
<file_sep>package com.orientechnologies.orient.core.processor;
import com.orientechnologies.common.exception.OException;
public class OProcessException extends OException {
private static final long serialVersionUID = 1L;
public OProcessException() {
}
public OProcessException(String arg0) {
super(arg0);
}
public OProcessException(Throwable arg0) {
super(arg0);
}
public OProcessException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.index;
import com.orientechnologies.common.concur.resource.OCloseable;
import com.orientechnologies.common.util.OMultiKey;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.dictionary.ODictionary;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.OMetadata;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.type.ODocumentWrapper;
import com.orientechnologies.orient.core.type.ODocumentWrapperNoClass;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Abstract class to manage indexes.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*/
@SuppressWarnings("unchecked")
public abstract class OIndexManagerAbstract extends ODocumentWrapperNoClass implements OIndexManager, OCloseable {
public static final String CONFIG_INDEXES = "indexes";
public static final String DICTIONARY_NAME = "dictionary";
protected Map<String, OIndexInternal<?>> indexes = new ConcurrentHashMap<String, OIndexInternal<?>>();
protected final Map<String, Map<OMultiKey, Set<OIndex<?>>>> classPropertyIndex = new HashMap<String, Map<OMultiKey, Set<OIndex<?>>>>();
protected String defaultClusterName = OMetadata.CLUSTER_INDEX_NAME;
protected String manualClusterName = OMetadata.CLUSTER_MANUAL_INDEX_NAME;
protected ReadWriteLock lock = new ReentrantReadWriteLock();
public OIndexManagerAbstract(final ODatabaseRecord iDatabase) {
super(new ODocument());
}
protected abstract OIndex<?> getIndexInstance(final OIndex<?> iIndex);
protected void acquireSharedLock() {
lock.readLock().lock();
}
protected void releaseSharedLock() {
lock.readLock().unlock();
}
protected void acquireExclusiveLock() {
lock.writeLock().lock();
}
protected void releaseExclusiveLock() {
lock.writeLock().unlock();
}
@Override
public OIndexManagerAbstract load() {
acquireExclusiveLock();
try {
if (getDatabase().getStorage().getConfiguration().indexMgrRecordId == null)
// @COMPATIBILITY: CREATE THE INDEX MGR
create();
// CLEAR PREVIOUS STUFF
indexes.clear();
classPropertyIndex.clear();
// RELOAD IT
((ORecordId) document.getIdentity()).fromString(getDatabase().getStorage().getConfiguration().indexMgrRecordId);
super.reload("*:-1 index:0");
return this;
} finally {
releaseExclusiveLock();
}
}
@Override
public <RET extends ODocumentWrapper> RET reload() {
acquireExclusiveLock();
try {
return (RET) super.reload();
} finally {
releaseExclusiveLock();
}
}
@Override
public <RET extends ODocumentWrapper> RET save() {
acquireExclusiveLock();
try {
return (RET) super.save();
} finally {
releaseExclusiveLock();
}
}
public void create() {
acquireExclusiveLock();
try {
save(OMetadata.CLUSTER_INTERNAL_NAME);
getDatabase().getStorage().getConfiguration().indexMgrRecordId = document.getIdentity().toString();
getDatabase().getStorage().getConfiguration().update();
createIndex(DICTIONARY_NAME, OClass.INDEX_TYPE.DICTIONARY.toString(), new OSimpleKeyIndexDefinition(OType.STRING), null, null);
} finally {
releaseExclusiveLock();
}
}
public void flush() {
for (final OIndexInternal<?> idx : indexes.values())
idx.flush();
}
public Collection<? extends OIndex<?>> getIndexes() {
final Collection<OIndexInternal<?>> rawResult = indexes.values();
final List<OIndex<?>> result = new ArrayList<OIndex<?>>(rawResult.size());
for (final OIndexInternal<?> index : rawResult)
result.add(preProcessBeforeReturn(index));
return result;
}
public OIndex<?> getIndex(final String iName) {
final OIndexInternal<?> index = indexes.get(iName.toLowerCase());
if (index == null)
return null;
return preProcessBeforeReturn(index);
}
public boolean existsIndex(final String iName) {
return indexes.containsKey(iName.toLowerCase());
}
public String getDefaultClusterName() {
acquireSharedLock();
try {
return defaultClusterName;
} finally {
releaseSharedLock();
}
}
public void setDefaultClusterName(final String defaultClusterName) {
acquireExclusiveLock();
try {
this.defaultClusterName = defaultClusterName;
} finally {
releaseExclusiveLock();
}
}
public ODictionary<ORecordInternal<?>> getDictionary() {
acquireExclusiveLock();
OIndex<?> idx;
try {
idx = getIndex(DICTIONARY_NAME);
if (idx == null)
idx = createIndex(DICTIONARY_NAME, OClass.INDEX_TYPE.DICTIONARY.toString(), new OSimpleKeyIndexDefinition(OType.STRING),
null, null);
} finally {
releaseExclusiveLock();
}
return new ODictionary<ORecordInternal<?>>((OIndex<OIdentifiable>) idx);
}
public ODocument getConfiguration() {
acquireSharedLock();
try {
return getDocument();
} finally {
releaseSharedLock();
}
}
protected ODatabaseRecord getDatabase() {
return ODatabaseRecordThreadLocal.INSTANCE.get();
}
public void close() {
acquireExclusiveLock();
try {
flush();
indexes.clear();
classPropertyIndex.clear();
} finally {
releaseExclusiveLock();
}
}
public OIndexManager setDirty() {
acquireExclusiveLock();
try {
document.setDirty();
return this;
} finally {
releaseExclusiveLock();
}
}
public OIndex<?> getIndex(final ORID iRID) {
for (final OIndex<?> idx : indexes.values()) {
if (idx.getIdentity().equals(iRID)) {
return getIndexInstance(idx);
}
}
return null;
}
protected void addIndexInternal(final OIndexInternal<?> index) {
acquireExclusiveLock();
try {
indexes.put(index.getName().toLowerCase(), index);
final OIndexDefinition indexDefinition = index.getDefinition();
if (indexDefinition == null || indexDefinition.getClassName() == null)
return;
Map<OMultiKey, Set<OIndex<?>>> propertyIndex = classPropertyIndex.get(indexDefinition.getClassName().toLowerCase());
if (propertyIndex == null) {
propertyIndex = new HashMap<OMultiKey, Set<OIndex<?>>>();
classPropertyIndex.put(indexDefinition.getClassName().toLowerCase(), propertyIndex);
}
final int paramCount = indexDefinition.getParamCount();
for (int i = 1; i <= paramCount; i++) {
final List<String> fields = indexDefinition.getFields().subList(0, i);
final OMultiKey multiKey = new OMultiKey(normalizeFieldNames(fields));
Set<OIndex<?>> indexSet = propertyIndex.get(multiKey);
if (indexSet == null)
indexSet = new HashSet<OIndex<?>>();
indexSet.add(index);
propertyIndex.put(multiKey, indexSet);
}
} finally {
releaseExclusiveLock();
}
}
public Set<OIndex<?>> getClassInvolvedIndexes(final String className, Collection<String> fields) {
acquireSharedLock();
try {
fields = normalizeFieldNames(fields);
final OMultiKey multiKey = new OMultiKey(fields);
final Map<OMultiKey, Set<OIndex<?>>> propertyIndex = classPropertyIndex.get(className.toLowerCase());
if (propertyIndex == null || !propertyIndex.containsKey(multiKey))
return Collections.emptySet();
final Set<OIndex<?>> rawResult = propertyIndex.get(multiKey);
final Set<OIndex<?>> transactionalResult = new HashSet<OIndex<?>>(rawResult.size());
for (final OIndex<?> index : rawResult) {
transactionalResult.add(preProcessBeforeReturn((OIndexInternal<?>) index));
}
return transactionalResult;
} finally {
releaseSharedLock();
}
}
public Set<OIndex<?>> getClassInvolvedIndexes(final String className, final String... fields) {
return getClassInvolvedIndexes(className, Arrays.asList(fields));
}
public boolean areIndexed(final String className, Collection<String> fields) {
acquireSharedLock();
try {
fields = normalizeFieldNames(fields);
final OMultiKey multiKey = new OMultiKey(fields);
final Map<OMultiKey, Set<OIndex<?>>> propertyIndex = classPropertyIndex.get(className.toLowerCase());
if (propertyIndex == null)
return false;
return propertyIndex.containsKey(multiKey) && !propertyIndex.get(multiKey).isEmpty();
} finally {
releaseSharedLock();
}
}
public boolean areIndexed(final String className, final String... fields) {
return areIndexed(className, Arrays.asList(fields));
}
public Set<OIndex<?>> getClassIndexes(final String className) {
acquireSharedLock();
try {
final Set<OIndex<?>> result = new HashSet<OIndex<?>>();
final Map<OMultiKey, Set<OIndex<?>>> propertyIndex = classPropertyIndex.get(className.toLowerCase());
if (propertyIndex == null)
return Collections.emptySet();
for (final Set<OIndex<?>> propertyIndexes : propertyIndex.values())
for (final OIndex<?> index : propertyIndexes)
result.add(preProcessBeforeReturn((OIndexInternal<?>) index));
return result;
} finally {
releaseSharedLock();
}
}
public OIndex<?> getClassIndex(String className, String indexName) {
className = className.toLowerCase();
indexName = indexName.toLowerCase();
final OIndexInternal<?> index = indexes.get(indexName);
if (index != null && index.getDefinition() != null && index.getDefinition().getClassName() != null
&& className.equals(index.getDefinition().getClassName().toLowerCase()))
return preProcessBeforeReturn(index);
return null;
}
protected List<String> normalizeFieldNames(final Collection<String> fieldNames) {
final ArrayList<String> result = new ArrayList<String>(fieldNames.size());
for (final String fieldName : fieldNames)
result.add(fieldName.toLowerCase());
return result;
}
protected OIndex<?> preProcessBeforeReturn(final OIndexInternal<?> index) {
getDatabase().registerListener(index);
if (index instanceof OIndexMultiValues)
return new OIndexTxAwareMultiValue(getDatabase(), (OIndex<Collection<OIdentifiable>>) getIndexInstance(index));
else if (index instanceof OIndexDictionary)
return new OIndexTxAwareDictionary(getDatabase(), (OIndex<OIdentifiable>) getIndexInstance(index));
else if (index instanceof OIndexOneValue)
return new OIndexTxAwareOneValue(getDatabase(), (OIndex<OIdentifiable>) getIndexInstance(index));
return index;
}
}
<file_sep>package com.orientechnologies.orient.core.storage.impl.local;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
import com.orientechnologies.orient.core.storage.OStorage;
/**
* @author <NAME>
*/
public class ClusterLocalLHPEPSTest {
private static final String PATH_TO_FILE = "target/databases/123";
private static final String FILE_NAME = "name";
private static final int KEYS_COUNT = 100000;
private OCluster getCluster() throws IOException {
OStorage storage = new OStorageLocal(FILE_NAME + System.currentTimeMillis(), PATH_TO_FILE + System.currentTimeMillis(), "rw");
storage.create(null);
Collection<? extends OCluster> clusterInstances = storage.getClusterInstances();
OCluster cluster = null;
for (OCluster clusterInstance : clusterInstances) {
System.out.println(clusterInstance.getClass().getCanonicalName() + " : " + clusterInstance.getName());
Assert.assertTrue(clusterInstance instanceof OClusterLocalLHPEPS);
if ("default".equals(clusterInstance.getName()))
cluster = clusterInstance;
}
Assert.assertNotNull(cluster);
return cluster;
}
@BeforeClass
public void setUp() {
OGlobalConfiguration.USE_LHPEPS_CLUSTER.setValue(true);
}
@AfterClass
public void tearDown() {
OGlobalConfiguration.USE_LHPEPS_CLUSTER.setValue(false);
}
@Test(enabled = false)
public void testKeyPut() throws IOException {
OCluster localCluster = getCluster();
for (int i = 0; i < KEYS_COUNT; i++) {
localCluster.addPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(i)));
Assert.assertNotNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(i))));
}
for (int i = 0; i < KEYS_COUNT; i++) {
Assert.assertNotNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(i))), i
+ " key is absent");
}
for (int i = KEYS_COUNT; i < 2 * KEYS_COUNT; i++) {
Assert.assertNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(i))));
}
}
@Test(enabled = false)
public void testKeyPutRandom() throws IOException {
OCluster localCluster = getCluster();
List<Long> keys = new ArrayList<Long>();
Random random = new Random();
while (keys.size() < KEYS_COUNT) {
long key = random.nextLong();
if (key < 0)
key = -key;
if (localCluster.addPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(key)))) {
keys.add(key);
Assert
.assertNotNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(key))));
}
}
for (long key : keys)
Assert.assertNotNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(key))));
}
@Test(enabled = false)
public void testKeyDelete() throws IOException {
OCluster localCluster = getCluster();
for (int i = 0; i < KEYS_COUNT; i++)
localCluster.addPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(i)));
for (int i = 0; i < KEYS_COUNT; i++) {
if (i % 3 == 0)
localCluster.removePhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(i));
// Assert.assertNull(localCluster.getPhysicalPosition(new OPhysicalPosition(i)));
}
for (int i = 0; i < KEYS_COUNT; i++) {
if (i % 3 == 0)
Assert.assertNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(i))));
else
Assert.assertNotNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(i))));
}
}
@Test(enabled = false)
public void testKeyDeleteRandom() throws IOException {
OCluster localCluster = getCluster();
Set<Long> longs = new HashSet<Long>();
final Random random = new Random();
for (int i = 0; i < KEYS_COUNT; i++) {
long key = random.nextLong();
if (key < 0)
key = -key;
localCluster.addPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(key)));
longs.add(key);
}
for (long key : longs) {
if (key % 3 == 0) {
localCluster.removePhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(key));
}
}
for (long key : longs) {
if (key % 3 == 0)
Assert.assertNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(key))));
else
Assert
.assertNotNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(key))));
}
}
@Test(enabled = false)
public void testKeyAddDelete() throws IOException {
OCluster localCluster = getCluster();
for (int i = 0; i < KEYS_COUNT; i++)
Assert.assertNotNull(localCluster.addPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(i))));
for (int i = 0; i < KEYS_COUNT; i++) {
if (i % 3 == 0)
localCluster.removePhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(i));
if (i % 2 == 0)
Assert.assertNotNull(localCluster.addPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE
.valueOf(KEYS_COUNT + i))));
}
for (int i = 0; i < KEYS_COUNT; i++) {
if (i % 3 == 0)
Assert.assertNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(i))));
else
Assert.assertNotNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(i))));
if (i % 2 == 0)
Assert.assertNotNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE
.valueOf(KEYS_COUNT + i))));
}
}
@Test(enabled = false)
public void testKeyAddDeleteRandom() throws IOException {
OCluster localCluster = getCluster();
List<Long> longs = getUniqueRandomValuesArray(2 * KEYS_COUNT);
// add
for (int i = 0; i < KEYS_COUNT; i++) {
localCluster.addPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(longs.get(i))));
}
// remove+add
for (int i = 0; i < KEYS_COUNT; i++) {
if (i % 3 == 0) {
localCluster.removePhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(longs.get(i)));
}
if (i % 2 == 0) {
localCluster
.addPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(longs.get(i + KEYS_COUNT))));
}
}
// check removed ok
for (int i = 0; i < KEYS_COUNT; i++) {
if (i % 3 == 0)
Assert.assertNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(longs
.get(i)))));
else
Assert.assertNotNull(localCluster.addPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(longs
.get(i)))));
if (i % 2 == 0)
Assert.assertNotNull(localCluster.getPhysicalPosition(new OPhysicalPosition(OClusterPositionFactory.INSTANCE.valueOf(longs
.get(KEYS_COUNT + i)))));
}
}
private List<Long> getUniqueRandomValuesArray(int size) {
Random random = new Random();
long data[] = new long[size];
for (int i = 0, dataLength = data.length; i < dataLength; i++) {
data[i] = i * 5 + random.nextInt(5);
}
int max = data.length - 1;
List<Long> list = new ArrayList<Long>(size);
while (max > 0) {
swap(data, max, Math.abs(random.nextInt(max)));
list.add(data[max--]);
}
return list;
}
private void swap(long[] data, int firstIndex, int secondIndex) {
long tmp = data[firstIndex];
data[firstIndex] = data[secondIndex];
data[secondIndex] = tmp;
}
}
<file_sep>package com.orientechnologies.orient.core.config;
/**
* @author <NAME>
* @since 03.08.12
*/
public class OStoragePhysicalClusterLHPEPSConfiguration extends OStorageSegmentConfiguration implements
OStoragePhysicalClusterConfiguration {
private static final String START_SIZE = "7Mb";
private int dataSegmentId;
private OStorageSegmentConfiguration overflowFile;
private OStorageFileConfiguration overflowStatisticsFile;
public OStoragePhysicalClusterLHPEPSConfiguration(OStorageConfiguration iRoot, int iId, int dataSegmentId) {
super(iRoot, null, iId);
this.dataSegmentId = dataSegmentId;
fileStartSize = START_SIZE;
}
public OStoragePhysicalClusterLHPEPSConfiguration(final OStorageConfiguration iStorageConfiguration, final int iId,
final int iDataSegmentId, final String iSegmentName) {
super(iStorageConfiguration, iSegmentName, iId);
this.dataSegmentId = iDataSegmentId;
fileStartSize = START_SIZE;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getDataSegmentId() {
return dataSegmentId;
}
public OStorageFileConfiguration[] getInfoFiles() {
return infoFiles;
}
public String getMaxSize() {
return maxSize;
}
public void setDataSegmentId(int dataSegmentId) {
this.dataSegmentId = dataSegmentId;
}
public OStorageSegmentConfiguration getOverflowSegment() {
return overflowFile;
}
public void setOverflowFile(OStorageSegmentConfiguration overflowFile) {
this.overflowFile = overflowFile;
}
public OStorageFileConfiguration getOverflowStatisticsFile() {
return overflowStatisticsFile;
}
public void setOverflowStatisticsFile(OStorageFileConfiguration overflowStatisticsFile) {
this.overflowStatisticsFile = overflowStatisticsFile;
}
@Override
public void setRoot(final OStorageConfiguration root) {
super.setRoot(root);
overflowFile.root = root;
overflowStatisticsFile.parent = this;
}
}
<file_sep>package com.orientechnologies.common.collection;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test
public class OMVRBTreeNonCompositeTest {
protected OMVRBTree<Double, Double> tree;
@BeforeMethod
public void beforeMethod() throws Exception {
tree = new OMVRBTreeMemory<Double, Double>(4, 0.5f);
for (double i = 1; i < 10; i++) {
tree.put(i, i);
}
}
@Test
public void testGetEntry() {
assertEquals(tree.get(1.0), 1.0);
assertEquals(tree.get(3.0), 3.0);
assertEquals(tree.get(7.0), 7.0);
assertEquals(tree.get(9.0), 9.0);
assertNull(tree.get(10.0));
}
@Test
public void testSubMapInclusive() {
final ONavigableMap<Double, Double> navigableMap = tree.subMap(2.0, true, 7.0, true);
assertEquals(navigableMap.size(), 6);
for (double i = 2; i <= 7; i++) {
assertTrue(navigableMap.containsKey(i));
}
}
@Test
public void testSubMapFromInclusive() {
final ONavigableMap<Double, Double> navigableMap = tree.subMap(2.0, true, 7.0, false);
assertEquals(navigableMap.size(), 5);
for (double i = 2; i < 7; i++) {
assertTrue(navigableMap.containsKey(i));
}
}
@Test
public void testSubMapToInclusive() {
final ONavigableMap<Double, Double> navigableMap = tree.subMap(2.0, false, 7.0, true);
assertEquals(navigableMap.size(), 5);
for (double i = 3; i <= 7; i++) {
assertTrue(navigableMap.containsKey(i));
}
}
@Test
public void testSubMapNonInclusive() {
final ONavigableMap<Double, Double> navigableMap = tree.subMap(2.0, false, 7.0, false);
assertEquals(navigableMap.size(), 4);
for (double i = 3; i < 7; i++) {
assertTrue(navigableMap.containsKey(i));
}
}
@Test
public void testTailMapInclusive() {
final ONavigableMap<Double, Double> navigableMap = tree.tailMap(2.0, true);
assertEquals(navigableMap.size(), 8);
for (double i = 2; i <= 9; i++) {
assertTrue(navigableMap.containsKey(i));
}
}
@Test
public void testTailMapNonInclusive() {
final ONavigableMap<Double, Double> navigableMap = tree.tailMap(2.0, false);
assertEquals(navigableMap.size(), 7);
for (double i = 3; i <= 9; i++) {
assertTrue(navigableMap.containsKey(i));
}
}
@Test
public void testHeadMapInclusive() {
final ONavigableMap<Double, Double> navigableMap = tree.headMap(7.0, true);
assertEquals(navigableMap.size(), 7);
for (double i = 1; i <= 7; i++) {
assertTrue(navigableMap.containsKey(i));
}
}
@Test
public void testHeadMapNonInclusive() {
final ONavigableMap<Double, Double> navigableMap = tree.headMap(7.0, false);
assertEquals(navigableMap.size(), 6);
for (double i = 1; i < 7; i++) {
assertTrue(navigableMap.containsKey(i));
}
}
@Test
public void testGetCeilingEntryKeyExist() {
OMVRBTreeEntry<Double, Double> entry = tree.getCeilingEntry(4.0, OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey(), 4.0);
entry = tree.getCeilingEntry(4.0, OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), 4.0);
entry = tree.getCeilingEntry(4.0, OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), 4.0);
}
@Test
public void testGetCeilingEntryKeyNotExist() {
OMVRBTreeEntry<Double, Double> entry = tree.getCeilingEntry(4.3, OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey(), 5.0);
entry = tree.getCeilingEntry(4.3, OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), 5.0);
entry = tree.getCeilingEntry(4.3, OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), 5.0);
entry = tree.getCeilingEntry(20.0, OMVRBTree.PartialSearchMode.NONE);
assertNull(entry);
entry = tree.getCeilingEntry(-1.0, OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey(), 1.0);
}
@Test
public void testGetFloorEntryKeyExist() {
OMVRBTreeEntry<Double, Double> entry = tree.getFloorEntry(4.0, OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey(), 4.0);
entry = tree.getFloorEntry(4.0, OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), 4.0);
}
@Test
public void testGetFloorEntryKeyNotExist() {
OMVRBTreeEntry<Double, Double> entry = tree.getFloorEntry(4.3, OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey(), 4.0);
entry = tree.getFloorEntry(4.3, OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), 4.0);
entry = tree.getFloorEntry(4.3, OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), 4.0);
entry = tree.getFloorEntry(20.0, OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey(), 9.0);
entry = tree.getFloorEntry(-1.0, OMVRBTree.PartialSearchMode.NONE);
assertNull(entry);
}
@Test
public void testHigherEntryKeyExist() {
OMVRBTreeEntry<Double, Double> entry = tree.getHigherEntry(4.0);
assertEquals(entry.getKey(), 5.0);
}
@Test
public void testHigherEntryKeyNotExist() {
OMVRBTreeEntry<Double, Double> entry = tree.getHigherEntry(4.5);
assertEquals(entry.getKey(), 5.0);
}
@Test
public void testHigherEntryNullResult() {
OMVRBTreeEntry<Double, Double> entry = tree.getHigherEntry(12.0);
assertNull(entry);
}
@Test
public void testLowerEntryNullResult() {
OMVRBTreeEntry<Double, Double> entry = tree.getLowerEntry(0.0);
assertNull(entry);
}
@Test
public void testLowerEntryKeyExist() {
OMVRBTreeEntry<Double, Double> entry = tree.getLowerEntry(4.0);
assertEquals(entry.getKey(), 3.0);
}
@Test
public void testLowerEntryKeyNotExist() {
OMVRBTreeEntry<Double, Double> entry = tree.getLowerEntry(4.5);
assertEquals(entry.getKey(), 4.0);
}
}
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.common.directmemory;
import com.orientechnologies.common.serialization.types.OBinarySerializer;
/**
* Abstraction of different kind of implementations of non-GC memory, memory that managed not by GC but directly by application.
* Access to such memory is slower than to "native" Java memory but we get performance gain eliminating GC overhead. The main
* application of such memory different types of caches.
*
* @author <NAME>, <NAME>
*/
public interface ODirectMemory {
/**
* Presentation of null pointer in given memory model.
*/
public int NULL_POINTER = -1;
/**
* Allocates amount of memory that is needed to write passed in byte array and writes it.
*
* @param bytes
* Data that is needed to be written.
* @return Pointer to the allocated piece of memory.
*/
int allocate(byte[] bytes);
/**
* Allocates given amount of memory (in bytes) from pool and returns pointer on allocated memory or {@link #NULL_POINTER} if there
* is no enough memory in pool.
*
* @param size
* Size that is needed to be allocated.
* @return Pointer to the allocated memory.
*/
int allocate(int size);
/**
* Returns allocated memory back to the pool.
*
* @param pointer
* Pointer to the allocated piece of memory.
*/
void free(int pointer);
/**
* Calculates actual size that has been allocated for this entry.
*
* @param pointer
* to allocated entry
* @return actual size of this entry in memory
*/
int getActualSpace(int pointer);
/**
* Reads raw data from given piece of memory.
*
* @param pointer
* Memory pointer, returned by {@link #allocate(int)} method.
* @param offset
* Memory offset.
* @param length
* Size of data which should be returned.
* @return Raw data from given piece of memory.
*/
byte[] get(int pointer, int offset, int length);
/**
* Writes data to the given piece of memory.
*
* @param pointer
* Memory pointer, returned by {@link #allocate(int)} method.
* @param offset
* Memory offset.
* @param length
* Size of data which should be written.
* @param content
* Raw data is going to be written.
*/
void set(int pointer, int offset, int length, byte[] content);
/**
* Returns converted data from given piece of memory. This operation is much faster than {@link #get(int, int, int)}.
*
* @param pointer
* Memory pointer, returned by {@link #allocate(int)} method.
* @param offset
* Memory offset.
* @param serializer
* Serializer which will be used to convert data from byte array.
* @param <T>
* Data type.
* @return Data instance.
*/
<T> T get(int pointer, int offset, OBinarySerializer<T> serializer);
/**
* Write data to given piece of memory. This operation is much faster than {@link #set(int, int, int, byte[])}.
*
* @param pointer
* Memory pointer, returned by {@link #allocate(int)} method.
* @param offset
* Memory offset.
* @param serializer
* Serializer which will be used to convert data to byte array.
* @param <T>
* Data type.
*/
<T> void set(int pointer, int offset, T data, OBinarySerializer<T> serializer);
/**
* Return <code>int</code> value from given piece of memory.
*
* @param pointer
* Memory pointer, returned by {@link #allocate(int)} method.
* @param offset
* Memory offset.
* @return Int value.
*/
int getInt(int pointer, int offset);
/**
* Write <code>int</code> value to given piece of memory.
*
* @param pointer
* Memory pointer, returned by {@link #allocate(int)} method.
* @param offset
* Memory offset.
*/
void setInt(int pointer, int offset, int value);
/**
* Return <code>long</code> value from given piece of memory.
*
* @param pointer
* Memory pointer, returned by {@link #allocate(int)} method.
* @param offset
* Memory offset.
* @return long value.
*/
long getLong(int pointer, int offset);
/**
* Write <code>long</code> value to given piece of memory.
*
* @param pointer
* Memory pointer, returned by {@link #allocate(int)} method.
* @param offset
* Memory offset.
*/
void setLong(int pointer, int offset, long value);
/**
* Return <code>byte</code> value from given piece of memory.
*
* @param pointer
* Memory pointer, returned by {@link #allocate(int)} method.
* @param offset
* Memory offset.
* @return byte value.
*/
byte getByte(int pointer, int offset);
/**
* Write <code>byte</code> value to given piece of memory.
*
* @param pointer
* Memory pointer, returned by {@link #allocate(int)} method.
* @param offset
* Memory offset.
*/
void setByte(int pointer, int offset, byte value);
/**
* The amount whole direct memory (free and used). This method does not take into account amount of memory that will be needed to
* perform system operations.
*
* @return The amount whole direct memory (free and used).
*/
int capacity();
/**
* The amount available direct memory, that is, how much memory can be potentially used by users. This method does not take into
* account amount of memory that will be needed to perform system operations and can be used only for rough estimation of
* available memory.
*
* @return The amount available direct memory.
*/
int freeSpace();
/**
* Removes all data from the memory.
*/
void clear();
/**
* Performs copying of raw data in memory from one offset to another.
*
* @param srcPointer
* Memory pointer, returned by {@link #allocate(int)} method, from which data will be copied.
* @param fromOffset
* Offset in memory from which data will be copied.
* @param destPointer
* Memory pointer to which data will be copied.
* @param toOffset
* Offset in memory to which data will be copied.
* @param len
* Data length.
*/
void copyData(int srcPointer, int fromOffset, int destPointer, int toOffset, int len);
}
<file_sep>package com.orientechnologies.orient.graph.gremlin;
import java.io.IOException;
import java.util.List;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.graph.OGraphDatabase;
import com.orientechnologies.orient.core.db.graph.OGraphDatabasePool;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
public class LocalGraphDbTest {
private static String DB_URL = "local:target/databases/tinkerpop";
public static void main(String[] args) throws IOException {
new LocalGraphDbTest().multipleDatabasesSameThread();
}
public LocalGraphDbTest() {
OGremlinHelper.global().create();
}
@BeforeClass
public void before() {
OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(false);
}
@AfterClass
public void after() {
OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(true);
}
@Test
public void multipleDatabasesSameThread() throws IOException {
OGraphDatabase db1 = OGraphDatabasePool.global().acquire(DB_URL, "admin", "admin");
ODocument doc1 = db1.createVertex();
doc1.field("key", "value");
doc1.save();
db1.close();
OGraphDatabase db2 = OGraphDatabasePool.global().acquire(DB_URL, "admin", "admin");
ODocument doc2 = db2.createVertex();
doc2.field("key", "value");
doc2.save();
db2.close();
db1 = OGraphDatabasePool.global().acquire(DB_URL, "admin", "admin");
final List<?> result = db1.query(new OSQLSynchQuery<ODocument>("select out[weight=3].size() from V where out.size() > 0"));
doc1 = db1.createVertex();
doc1.field("newkey", "newvalue");
doc1.save();
db1.close();
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.enterprise.channel.binary;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import com.orientechnologies.common.concur.OTimeoutException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OContextConfiguration;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
/**
* Implementation that supports multiple client requests.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*
*/
public class OChannelBinaryAsynch extends OChannelBinary {
private final ReentrantLock lockRead = new ReentrantLock(true);
private final Condition readCondition = lockRead.newCondition();
private final ReentrantLock lockWrite = new ReentrantLock();
private boolean channelRead = false;
private byte currentStatus;
private int currentSessionId;
private final int maxUnreadResponses;
public OChannelBinaryAsynch(final Socket iSocket, final OContextConfiguration iConfig) throws IOException {
super(iSocket, iConfig);
maxUnreadResponses = OGlobalConfiguration.NETWORK_BINARY_READ_RESPONSE_MAX_TIMES.getValueAsInteger();
}
public void beginRequest() {
lockWrite.lock();
}
public void endRequest() throws IOException {
flush();
lockWrite.unlock();
}
public void beginResponse(final int iRequesterId) throws IOException {
beginResponse(iRequesterId, timeout);
}
public void beginResponse(final int iRequesterId, final long iTimeout) throws IOException {
try {
int unreadResponse = 0;
final long startClock = iTimeout > 0 ? System.currentTimeMillis() : 0;
// WAIT FOR THE RESPONSE
do {
if (iTimeout <= 0)
lockRead.lock();
else if (!lockRead.tryLock(iTimeout, TimeUnit.MILLISECONDS))
throw new OTimeoutException("Cannot acquire read lock against channel: " + this);
if (!channelRead) {
channelRead = true;
try {
currentStatus = readByte();
currentSessionId = readInt();
if (debug)
OLogManager.instance().debug(this, "%s - Read response: %d-%d", socket.getLocalAddress(), (int) currentStatus,
currentSessionId);
} catch (IOException e) {
// UNLOCK THE RESOURCE AND PROPAGATES THE EXCEPTION
readCondition.signalAll();
lockRead.unlock();
channelRead = false;
throw e;
}
}
if (currentSessionId == iRequesterId)
// IT'S FOR ME
break;
try {
if (debug)
OLogManager.instance().debug(this, "%s - Session %d skip response, it is for %d", socket.getLocalAddress(),
iRequesterId, currentSessionId);
if (iTimeout > 0 && (System.currentTimeMillis() - startClock) > iTimeout)
throw new OTimeoutException("Timeout on reading response from the server for the request " + iRequesterId);
if (unreadResponse > maxUnreadResponses) {
if (debug)
OLogManager.instance().info(this, "Unread responses %d > %d, consider the buffer as dirty: clean it", unreadResponse,
maxUnreadResponses);
close();
throw new IOException("Timeout on reading response");
}
// WAIT 1 SECOND AND RETRY
readCondition.signalAll();
if (debug)
OLogManager.instance().debug(this, "Session %d is going to sleep...", iRequesterId);
final long start = System.currentTimeMillis();
readCondition.await(1, TimeUnit.SECONDS);
final long now = System.currentTimeMillis();
if (debug)
OLogManager.instance().debug(this, "Waked up: slept %dms, checking again from %s for session %d", (now - start),
socket.getLocalAddress(), iRequesterId);
if (now - start >= 1000)
unreadResponse++;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lockRead.unlock();
}
} while (true);
if (debug)
OLogManager.instance().debug(this, "%s - Session %d handle response", socket.getLocalAddress(), iRequesterId);
handleStatus(currentStatus, currentSessionId);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// NEVER HAPPENS?
e.printStackTrace();
}
}
public void endResponse() {
channelRead = false;
// WAKE UP ALL THE WAITING THREADS
try {
readCondition.signalAll();
lockRead.unlock();
} catch (IllegalMonitorStateException e) {
// IGNORE IT
}
}
public ReentrantLock getLockRead() {
return lockRead;
}
public ReentrantLock getLockWrite() {
return lockWrite;
}
@Override
public void close() {
if (lockRead.tryLock())
try {
readCondition.signalAll();
} finally {
lockRead.unlock();
}
super.close();
}
@Override
public void clearInput() throws IOException {
lockRead.lock();
try {
super.clearInput();
} finally {
lockRead.unlock();
}
}
}
<file_sep>package com.orientechnologies.orient.core.storage.impl.memory.lh;
import com.orientechnologies.common.util.MersenneTwisterFast;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.id.OClusterPosition;
/**
* @author <NAME> (<EMAIL>)
*/
abstract class OLinearHashingHashCalculatorFactory {
public static final OLinearHashingHashCalculatorFactory INSTANCE;
private static final ThreadLocal<MersenneTwisterFast> threadLocalRandom = new ThreadLocal();
static {
if (OGlobalConfiguration.USE_NODE_ID_CLUSTER_POSITION.getValueAsBoolean())
INSTANCE = new OLinearHashingHashCalculatorNodeId();
else
INSTANCE = new OLinearHashingHashCalculatorLong();
}
public int calculateNaturalOrderedHash(OClusterPosition key, int level) {
return (int) Math.floor(Math.pow(2, level) * calculateHashIn01Range(key, level));
}
public int calculateBucketNumber(int hash, int level) {
final int result;
if (level == 0 && hash == 0)
return 0;
if ((hash % 2 == 0) && (level > 0))
return calculateBucketNumber(hash / 2, level - 1);
else
result = (hash - 1) / 2 + (int) Math.pow(2, level - 1);
assert result >= 0;
return result;
}
public double calculateHashIn01Range(OClusterPosition key, int level) {
assert key != null;
double result = ((key.doubleValue() + (getNegativeElementCount())) / getElementCount());
// TODO remove this hack and use same valid workaround
if (result >= 1) {
result = 0.999999999999999;
}
assert result >= 0;
assert result < 1;
return result;
}
protected abstract double getElementCount();
protected abstract double getNegativeElementCount();
public byte calculateSignature(OClusterPosition key) {
if(threadLocalRandom.get() == null){
threadLocalRandom.set(new MersenneTwisterFast());
}
MersenneTwisterFast random = threadLocalRandom.get();
random.setSeed(key.longValue());
return (byte) (random.nextInt() & 0xFF);
}
private static final class OLinearHashingHashCalculatorLong extends OLinearHashingHashCalculatorFactory {
private static final double ELEMENTS_COUNT = Math.pow(2, 64);
@Override
protected double getElementCount() {
return ELEMENTS_COUNT;
}
@Override
protected double getNegativeElementCount() {
return -(double) Long.MIN_VALUE;
}
}
private static final class OLinearHashingHashCalculatorNodeId extends OLinearHashingHashCalculatorFactory {
private static final double ELEMENTS_COUNT = Math.pow(2, 192);
private static final double HALF_OF_ELEMENTS_COUNT = ELEMENTS_COUNT / 2;
@Override
protected double getElementCount() {
return ELEMENTS_COUNT;
}
@Override
protected double getNegativeElementCount() {
return HALF_OF_ELEMENTS_COUNT;
}
}
}
<file_sep>package com.orientechnologies.orient.test.database.auto;
import com.orientechnologies.common.listener.OProgressListener;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.index.*;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.schema.OType;
import org.testng.annotations.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import static org.testng.Assert.*;
@Test
public class IndexManagerTest {
private static final String CLASS_NAME = "classForIndexManagerTest";
private ODatabaseDocument databaseDocument;
private String url;
@Parameters(value = "url")
public IndexManagerTest(String iURL) {
url = iURL;
}
@BeforeClass
public void beforeClass() {
databaseDocument = new ODatabaseDocumentTx(url);
databaseDocument.open("admin", "admin");
final OSchema schema = databaseDocument.getMetadata().getSchema();
final OClass oClass = schema.createClass(CLASS_NAME);
oClass.createProperty("fOne", OType.INTEGER);
oClass.createProperty("fTwo", OType.STRING);
oClass.createProperty("fThree", OType.BOOLEAN);
oClass.createProperty("fFour", OType.INTEGER);
oClass.createProperty("fSix", OType.STRING);
oClass.createProperty("fSeven", OType.STRING);
schema.save();
databaseDocument.close();
}
@BeforeMethod
public void beforeMethod() {
databaseDocument.open("admin", "admin");
}
@AfterMethod
public void afterMethod() {
databaseDocument.close();
}
@AfterClass
public void afterClass() {
databaseDocument.open("admin", "admin");
databaseDocument.getMetadata().getSchema().dropClass(CLASS_NAME);
databaseDocument.getMetadata().getSchema().dropClass("indexManagerTestClassTwo");
databaseDocument.close();
}
@Test
public void testCreateSimpleKeyInvalidNameIndex() {
final OIndexManagerProxy indexManager = databaseDocument.getMetadata().getIndexManager();
try {
indexManager.createIndex("simple:key", OClass.INDEX_TYPE.UNIQUE.toString(),
new OSimpleKeyIndexDefinition(OType.INTEGER),
null, null);
fail();
} catch (Exception e) {
if(e.getCause() != null)
e = (Exception)e.getCause();
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testCreateSimpleKeyIndexTest() {
final OIndexManagerProxy indexManager = databaseDocument.getMetadata().getIndexManager();
final OIndex result = indexManager.createIndex("simplekey", OClass.INDEX_TYPE.UNIQUE.toString(),
new OSimpleKeyIndexDefinition(OType.INTEGER),
null, null);
assertEquals(result.getName(), "simplekey");
indexManager.reload();
assertNull(databaseDocument.getMetadata().getIndexManager().getClassIndex(CLASS_NAME, "simplekey"));
assertEquals(databaseDocument.getMetadata().getIndexManager().getIndex("simplekey").getName(), result.getName());
}
@Test
public void testCreateNullKeyDefinitionIndexTest() {
final OIndexManagerProxy indexManager = databaseDocument.getMetadata().getIndexManager();
final OIndex result = indexManager.createIndex("nullkey", OClass.INDEX_TYPE.UNIQUE.toString(),
null, null, null);
assertEquals(result.getName(), "nullkey");
indexManager.reload();
assertNull(databaseDocument.getMetadata().getIndexManager().getClassIndex(CLASS_NAME, "nullkey"));
assertEquals(databaseDocument.getMetadata().getIndexManager().getIndex("nullkey").getName(), result.getName());
}
@Test
public void testCreateOnePropertyIndexTest() {
final OIndexManagerProxy indexManager = databaseDocument.getMetadata().getIndexManager();
final OIndex result = indexManager.createIndex("propertyone", OClass.INDEX_TYPE.UNIQUE.toString(),
new OPropertyIndexDefinition(CLASS_NAME, "fOne", OType.INTEGER),
new int[]{databaseDocument.getClusterIdByName(CLASS_NAME)}, null);
assertEquals(result.getName(), "propertyone");
indexManager.reload();
assertEquals(databaseDocument.getMetadata().getIndexManager().getClassIndex(CLASS_NAME, "propertyone").getName(),
result.getName());
}
@Test
public void createCompositeIndexTestWithoutListener() {
final OIndexManagerProxy indexManager = databaseDocument.getMetadata().getIndexManager();
final OIndex result = indexManager.createIndex("compositeone", OClass.INDEX_TYPE.NOTUNIQUE.toString(),
new OCompositeIndexDefinition(CLASS_NAME, Arrays.asList(
new OPropertyIndexDefinition(CLASS_NAME, "fOne", OType.INTEGER),
new OPropertyIndexDefinition(CLASS_NAME, "fTwo", OType.STRING)
)), new int[]{databaseDocument.getClusterIdByName(CLASS_NAME)}, null);
assertEquals(result.getName(), "compositeone");
indexManager.reload();
assertEquals(databaseDocument.getMetadata().getIndexManager().getClassIndex(CLASS_NAME, "compositeone").getName(),
result.getName());
}
@Test
public void createCompositeIndexTestWithListener() {
final AtomicInteger atomicInteger = new AtomicInteger(0);
final OProgressListener progressListener = new OProgressListener() {
public void onBegin(final Object iTask, final long iTotal) {
atomicInteger.incrementAndGet();
}
public boolean onProgress(final Object iTask, final long iCounter, final float iPercent) {
return true;
}
public void onCompletition(final Object iTask, final boolean iSucceed) {
atomicInteger.incrementAndGet();
}
};
final OIndexManagerProxy indexManager = databaseDocument.getMetadata().getIndexManager();
final OIndex result = indexManager.createIndex("compositetwo", OClass.INDEX_TYPE.NOTUNIQUE.toString(),
new OCompositeIndexDefinition(CLASS_NAME, Arrays.asList(
new OPropertyIndexDefinition(CLASS_NAME, "fOne", OType.INTEGER),
new OPropertyIndexDefinition(CLASS_NAME, "fTwo", OType.STRING),
new OPropertyIndexDefinition(CLASS_NAME, "fThree", OType.BOOLEAN)
)), new int[]{databaseDocument.getClusterIdByName(CLASS_NAME)}, progressListener);
assertEquals(result.getName(), "compositetwo");
assertEquals(atomicInteger.get(), 2);
indexManager.reload();
assertEquals(databaseDocument.getMetadata().getIndexManager().getClassIndex(CLASS_NAME, "compositetwo").getName(),
result.getName());
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedOneProperty() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, Arrays.asList("fOne"));
assertTrue(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedDoesNotContainProperty() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, Arrays.asList("fSix"));
assertFalse(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedTwoProperties() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, Arrays.asList("fTwo", "fOne"));
assertTrue(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedThreeProperties() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, Arrays.asList("fTwo", "fOne", "fThree"));
assertTrue(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedThreePropertiesBrokenFiledNameCase() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, Arrays.asList("ftwO", "Fone", "fThrEE"));
assertTrue(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedThreePropertiesBrokenClassNameCase() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed("ClaSSForIndeXManagerTeST", Arrays.asList("fTwo", "fOne", "fThree"));
assertTrue(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedPropertiesNotFirst() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, Arrays.asList("fTwo", "fTree"));
assertFalse(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedPropertiesMoreThanNeeded() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, Arrays.asList("fTwo", "fOne", "fThee", "fFour"));
assertFalse(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedOnePropertyArrayParams() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, "fOne");
assertTrue(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedDoesNotContainPropertyArrayParams() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, "fSix");
assertFalse(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedTwoPropertiesArrayParams() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, "fTwo", "fOne");
assertTrue(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedThreePropertiesArrayParams() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, "fTwo", "fOne", "fThree");
assertTrue(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedPropertiesNotFirstArrayParams() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, "fTwo", "fTree");
assertFalse(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testAreIndexedPropertiesMoreThanNeededArrayParams() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final boolean result = indexManager.areIndexed(CLASS_NAME, "fTwo", "fOne", "fThee", "fFour");
assertFalse(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesOnePropertyArrayParams() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes(CLASS_NAME, "fOne");
assertEquals(result.size(), 3);
assertTrue(containsIndex(result, "propertyone"));
assertTrue(containsIndex(result, "compositeone"));
assertTrue(containsIndex(result, "compositetwo"));
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesTwoPropertiesArrayParams() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes(CLASS_NAME, "fTwo", "fOne");
assertEquals(result.size(), 2);
assertTrue(containsIndex(result, "compositeone"));
assertTrue(containsIndex(result, "compositetwo"));
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesThreePropertiesArrayParams() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes(CLASS_NAME, "fTwo", "fOne", "fThree");
assertEquals(result.size(), 1);
assertEquals(result.iterator().next().getName(), "compositetwo");
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesNotInvolvedPropertiesArrayParams() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes(CLASS_NAME, "fTwo", "fFour");
assertEquals(result.size(), 0);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesPropertiesMorThanNeededArrayParams() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes(CLASS_NAME, "fTwo", "fOne", "fThee", "fFour");
assertEquals(result.size(), 0);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetInvolvedIndexesPropertiesMorThanNeeded() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes(CLASS_NAME,
Arrays.asList("fTwo", "fOne", "fThee", "fFour"));
assertEquals(result.size(), 0);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesNotExistingClass() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes("testlass", Arrays.asList("fOne"));
assertTrue(result.isEmpty());
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesOneProperty() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes(CLASS_NAME, Arrays.asList("fOne"));
assertEquals(result.size(), 3);
assertTrue(containsIndex(result, "propertyone"));
assertTrue(containsIndex(result, "compositeone"));
assertTrue(containsIndex(result, "compositetwo"));
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesOnePropertyBrokenClassNameCase() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes("ClaSSforindeXmanagerTEST", Arrays.asList("fOne"));
assertEquals(result.size(), 3);
assertTrue(containsIndex(result, "propertyone"));
assertTrue(containsIndex(result, "compositeone"));
assertTrue(containsIndex(result, "compositetwo"));
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesTwoProperties() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes(CLASS_NAME, Arrays.asList("fTwo", "fOne"));
assertEquals(result.size(), 2);
assertTrue(containsIndex(result, "compositeone"));
assertTrue(containsIndex(result, "compositetwo"));
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesThreeProperties() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes(CLASS_NAME,
Arrays.asList("fTwo", "fOne", "fThree"));
assertEquals(result.size(), 1);
assertEquals(result.iterator().next().getName(), "compositetwo");
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesThreePropertiesBrokenFiledNameTest() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes(CLASS_NAME,
Arrays.asList("ftwO", "foNe", "fThrEE"));
assertEquals(result.size(), 1);
assertEquals(result.iterator().next().getName(), "compositetwo");
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesNotInvolvedProperties() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes(CLASS_NAME, Arrays.asList("fTwo", "fFour"));
assertEquals(result.size(), 0);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassInvolvedIndexesPropertiesMorThanNeeded() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> result = indexManager.getClassInvolvedIndexes(CLASS_NAME,
Arrays.asList("fTwo", "fOne", "fThee", "fFour"));
assertEquals(result.size(), 0);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassIndexes() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> indexes = indexManager.getClassIndexes(CLASS_NAME);
final Set<OIndexDefinition> expectedIndexDefinitions = new HashSet<OIndexDefinition>();
final OCompositeIndexDefinition compositeIndexOne = new OCompositeIndexDefinition(CLASS_NAME);
compositeIndexOne.addIndex(new OPropertyIndexDefinition(CLASS_NAME, "fOne", OType.INTEGER));
compositeIndexOne.addIndex(new OPropertyIndexDefinition(CLASS_NAME, "fTwo", OType.STRING));
expectedIndexDefinitions.add(compositeIndexOne);
final OCompositeIndexDefinition compositeIndexTwo = new OCompositeIndexDefinition(CLASS_NAME);
compositeIndexTwo.addIndex(new OPropertyIndexDefinition(CLASS_NAME, "fOne", OType.INTEGER));
compositeIndexTwo.addIndex(new OPropertyIndexDefinition(CLASS_NAME, "fTwo", OType.STRING));
compositeIndexTwo.addIndex(new OPropertyIndexDefinition(CLASS_NAME, "fThree", OType.BOOLEAN));
expectedIndexDefinitions.add(compositeIndexTwo);
final OPropertyIndexDefinition propertyIndex = new OPropertyIndexDefinition(CLASS_NAME, "fOne", OType.INTEGER);
expectedIndexDefinitions.add(propertyIndex);
assertEquals(indexes.size(), 3);
for (final OIndex index : indexes) {
assertTrue(expectedIndexDefinitions.contains(index.getDefinition()));
}
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassIndexesBrokenClassNameCase() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final Set<OIndex<?>> indexes = indexManager.getClassIndexes("ClassforindeXMaNAgerTeST");
final Set<OIndexDefinition> expectedIndexDefinitions = new HashSet<OIndexDefinition>();
final OCompositeIndexDefinition compositeIndexOne = new OCompositeIndexDefinition(CLASS_NAME);
compositeIndexOne.addIndex(new OPropertyIndexDefinition(CLASS_NAME, "fOne", OType.INTEGER));
compositeIndexOne.addIndex(new OPropertyIndexDefinition(CLASS_NAME, "fTwo", OType.STRING));
expectedIndexDefinitions.add(compositeIndexOne);
final OCompositeIndexDefinition compositeIndexTwo = new OCompositeIndexDefinition(CLASS_NAME);
compositeIndexTwo.addIndex(new OPropertyIndexDefinition(CLASS_NAME, "fOne", OType.INTEGER));
compositeIndexTwo.addIndex(new OPropertyIndexDefinition(CLASS_NAME, "fTwo", OType.STRING));
compositeIndexTwo.addIndex(new OPropertyIndexDefinition(CLASS_NAME, "fThree", OType.BOOLEAN));
expectedIndexDefinitions.add(compositeIndexTwo);
final OPropertyIndexDefinition propertyIndex = new OPropertyIndexDefinition(CLASS_NAME, "fOne", OType.INTEGER);
expectedIndexDefinitions.add(propertyIndex);
assertEquals(indexes.size(), 3);
for (final OIndex index : indexes) {
assertTrue(expectedIndexDefinitions.contains(index.getDefinition()));
}
}
@Test
public void testDropIndex() throws Exception {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
indexManager.createIndex("anotherproperty", OClass.INDEX_TYPE.UNIQUE.toString(),
new OPropertyIndexDefinition(CLASS_NAME, "fOne", OType.INTEGER),
new int[]{databaseDocument.getClusterIdByName(CLASS_NAME)}, null);
assertNotNull(indexManager.getIndex("anotherproperty"));
assertNotNull(indexManager.getClassIndex(CLASS_NAME, "anotherproperty"));
indexManager.dropIndex("anotherproperty");
assertNull(indexManager.getIndex("anotherproperty"));
assertNull(indexManager.getClassIndex(CLASS_NAME, "anotherproperty"));
}
@Test
public void testDropSimpleKey() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
indexManager.createIndex("simplekeytwo", OClass.INDEX_TYPE.UNIQUE.toString(),
new OSimpleKeyIndexDefinition(OType.INTEGER),
null, null);
assertNotNull(indexManager.getIndex("simplekeytwo"));
indexManager.dropIndex("simplekeytwo");
assertNull(indexManager.getIndex("simplekeytwo"));
}
@Test
public void testDropNullKeyDefinition() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
indexManager.createIndex("nullkeytwo", OClass.INDEX_TYPE.UNIQUE.toString(),
null, null, null);
assertNotNull(indexManager.getIndex("nullkeytwo"));
indexManager.dropIndex("nullkeytwo");
assertNull(indexManager.getIndex("nullkeytwo"));
}
@Test
public void testDropAllClassIndexes() {
final OClass oClass = databaseDocument.getMetadata().getSchema().createClass("indexManagerTestClassTwo");
oClass.createProperty("fOne", OType.INTEGER);
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
indexManager.createIndex("twoclassproperty", OClass.INDEX_TYPE.UNIQUE.toString(),
new OPropertyIndexDefinition("indexManagerTestClassTwo", "fOne", OType.INTEGER),
new int[]{databaseDocument.getClusterIdByName("indexManagerTestClassTwo")}, null);
assertFalse(indexManager.getClassIndexes("indexManagerTestClassTwo").isEmpty());
indexManager.dropIndex("twoclassproperty");
assertTrue(indexManager.getClassIndexes("indexManagerTestClassTwo").isEmpty());
}
@Test(dependsOnMethods = "testDropAllClassIndexes")
public void testDropNonExistingClassIndex() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
indexManager.dropIndex("twoclassproperty");
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassIndex() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final OIndex<?> result = indexManager.getClassIndex(CLASS_NAME, "propertyone");
assertNotNull(result);
assertEquals(result.getName(), "propertyone");
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassIndexBrokenClassNameCase() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final OIndex<?> result = indexManager.getClassIndex("ClaSSforindeXManagerTeST", "propertyone");
assertNotNull(result);
assertEquals(result.getName(), "propertyone");
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassIndexWrongIndexName() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final OIndex<?> result = indexManager.getClassIndex(CLASS_NAME, "propertyonetwo");
assertNull(result);
}
@Test(dependsOnMethods = {"createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
"testCreateOnePropertyIndexTest"})
public void testGetClassIndexWrongClassName() {
final OIndexManager indexManager = databaseDocument.getMetadata().getIndexManager();
final OIndex<?> result = indexManager.getClassIndex("testClassTT", "propertyone");
assertNull(result);
}
private boolean containsIndex(final Collection<? extends OIndex> classIndexes, final String indexName) {
for (final OIndex index : classIndexes) {
if (index.getName().equals(indexName))
return true;
}
return false;
}
}
<file_sep>package com.orientechnologies.common.comparator;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author <NAME>
* @since 11.07.12
*/
@Test(enabled = false)
public class UnsafeComparatorTest {
public void testOneByteArray() {
final byte[] keyOne = new byte[] { 1 };
final byte[] keyTwo = new byte[] { 2 };
Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyOne, keyTwo) < 0);
Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyTwo, keyOne) > 0);
Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyTwo, keyTwo) == 0);
}
public void testOneLongArray() {
final byte[] keyOne = new byte[] { 0, 1, 0, 0, 0, 0, 0, 0 };
final byte[] keyTwo = new byte[] { 1, 0, 0, 0, 0, 0, 0, 0 };
Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyOne, keyTwo) < 0);
Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyTwo, keyOne) > 0);
Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyTwo, keyTwo) == 0);
}
public void testOneLongArrayAndByte() {
final byte[] keyOne = new byte[] { 1, 1, 0, 0, 0, 0, 0, 0, 0 };
final byte[] keyTwo = new byte[] { 1, 1, 0, 0, 0, 0, 0, 0, 1 };
Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyOne, keyTwo) < 0);
Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyTwo, keyOne) > 0);
Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyTwo, keyTwo) == 0);
}
}
<file_sep>/*
* Copyright 2010-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.server.distributed.conflict;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.server.distributed.ODistributedException;
/**
* Exception thrown when the two servers are not aligned.
*
* @author <NAME> (l.garulli--at--orientechnologies.com)
*
*/
public class OReplicationConflictException extends ODistributedException {
private static final String MESSAGE_REMOTE_VERSION = "remote=v";
private static final String MESSAGE_LOCAL_VERSION = "local=v";
private static final long serialVersionUID = 1L;
private final ORID localRID;
private final int localVersion;
private final ORID remoteRID;
private final int remoteVersion;
/**
* Rebuilds the original exception from the message.
*/
public OReplicationConflictException(final String message) {
super(message);
int beginPos = message.indexOf(ORID.PREFIX);
int endPos = message.indexOf(' ', beginPos);
localRID = new ORecordId(message.substring(beginPos, endPos));
beginPos = message.indexOf(MESSAGE_LOCAL_VERSION, endPos) + MESSAGE_LOCAL_VERSION.length();
endPos = message.indexOf(' ', beginPos);
localVersion = Integer.parseInt(message.substring(beginPos, endPos));
beginPos = message.indexOf(MESSAGE_REMOTE_VERSION, endPos) + MESSAGE_REMOTE_VERSION.length();
endPos = message.indexOf(')', beginPos);
remoteVersion = Integer.parseInt(message.substring(beginPos, endPos));
remoteRID = null;
}
public OReplicationConflictException(final String message, final ORID iRID, final int iDatabaseVersion, final int iRecordVersion) {
super(message);
localRID = iRID;
remoteRID = null;
localVersion = iDatabaseVersion;
remoteVersion = iRecordVersion;
}
public OReplicationConflictException(final String message, final ORID iOriginalRID, final ORID iRemoteRID) {
super(message);
localRID = iOriginalRID;
remoteRID = iRemoteRID;
localVersion = remoteVersion = 0;
}
@Override
public String getMessage() {
final StringBuilder buffer = new StringBuilder(super.getMessage());
if (remoteRID != null) {
// RID CONFLICT
buffer.append("local RID=");
buffer.append(localRID);
buffer.append(" remote RID=");
buffer.append(remoteRID);
} else {
// VERSION CONFLICT
buffer.append("local=v");
buffer.append(localVersion);
buffer.append(" remote=v");
buffer.append(remoteVersion);
}
return buffer.toString();
}
@Override
public String toString() {
return getMessage();
}
public int getLocalVersion() {
return localVersion;
}
public int getRemoteVersion() {
return remoteVersion;
}
public ORID getLocalRID() {
return localRID;
}
public ORID getRemoteRID() {
return remoteRID;
}
}
<file_sep>/*
* Copyright 1999-2012 <NAME> (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.id;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Arrays;
import com.orientechnologies.common.serialization.types.OIntegerSerializer;
import com.orientechnologies.common.serialization.types.OLongSerializer;
import com.orientechnologies.common.util.MersenneTwister;
/**
* Id of the server node in autoshareded storage. It is presented as 192 bit number with values from -2<sup>192</sup>+1 till
* 2<sup>192</sup>-1.
*
* Internally it presents as unsigned 192 bit number with signature flag.
*
* @author <NAME>
* @since 12.11.12
*/
public class ONodeId extends Number implements Comparable<ONodeId> {
private static final int CHUNKS_SIZE = 6;
public static final int NODE_SIZE_BYTES = CHUNKS_SIZE * OIntegerSerializer.INT_SIZE;
public static final int NODE_SIZE_BITS = NODE_SIZE_BYTES * 8;
public static final int SERIALIZED_SIZE = NODE_SIZE_BYTES + 1;
private static final long LONG_INT_MASK = 0xFFFFFFFFL;
private static final int UNSIGNED_INT_MAX_VALUE = 0xFFFFFFFF;
public static final ONodeId MAX_VALUE = new ONodeId(new int[] { UNSIGNED_INT_MAX_VALUE,
UNSIGNED_INT_MAX_VALUE, UNSIGNED_INT_MAX_VALUE, UNSIGNED_INT_MAX_VALUE, UNSIGNED_INT_MAX_VALUE, UNSIGNED_INT_MAX_VALUE }, 1);
public static final ONodeId MIN_VALUE = new ONodeId(new int[] { UNSIGNED_INT_MAX_VALUE,
UNSIGNED_INT_MAX_VALUE, UNSIGNED_INT_MAX_VALUE, UNSIGNED_INT_MAX_VALUE, UNSIGNED_INT_MAX_VALUE, UNSIGNED_INT_MAX_VALUE }, -1);
public static final ONodeId ZERO = new ONodeId(new int[CHUNKS_SIZE], 0);
public static final ONodeId ONE = new ONodeId(new int[] { 0, 0, 0, 0, 0, 1 }, 1);
public static final ONodeId TWO = new ONodeId(new int[] { 0, 0, 0, 0, 0, 2 }, 1);
private static final MersenneTwister random = new MersenneTwister();
private static final SecureRandom secureRandom = new SecureRandom();
static {
random.setSeed(OLongSerializer.INSTANCE.deserialize(secureRandom.generateSeed(OLongSerializer.LONG_SIZE), 0));
}
private final int[] chunks;
private final int signum;
private ONodeId(int[] chunks, int signum) {
this.chunks = chunks;
this.signum = signum;
}
@Override
public int compareTo(ONodeId o) {
if (signum > o.signum)
return 1;
else if (signum < o.signum)
return -1;
if (signum == 0 && o.signum == 0)
return 0;
final int result = compareChunks(chunks, o.chunks);
if (signum < 0)
return -result;
return result;
}
public ONodeId add(final ONodeId idToAdd) {
if (idToAdd.signum == 0)
return new ONodeId(chunks, signum);
if (signum == 0)
return new ONodeId(idToAdd.chunks, idToAdd.signum);
final int[] result;
if (signum == idToAdd.signum) {
result = addArrays(chunks, idToAdd.chunks);
if (Arrays.equals(ZERO.chunks, result))
return ZERO;
return new ONodeId(result, signum);
}
final int cmp = compareChunks(chunks, idToAdd.chunks);
if (cmp == 0)
return ZERO;
if (cmp > 0)
result = substructArrays(chunks, idToAdd.chunks);
else
result = substructArrays(idToAdd.chunks, chunks);
return new ONodeId(result, cmp == signum ? 1 : -1);
}
public ONodeId subtract(final ONodeId idToSubtract) {
if (idToSubtract.signum == 0)
return this;
if (signum == 0)
return new ONodeId(idToSubtract.chunks, -idToSubtract.signum);
final int[] result;
if (signum != idToSubtract.signum) {
result = addArrays(chunks, idToSubtract.chunks);
if (Arrays.equals(ZERO.chunks, result))
return ZERO;
return new ONodeId(result, signum);
}
int cmp = compareChunks(chunks, idToSubtract.chunks);
if (cmp == 0)
return ZERO;
if (cmp > 0)
result = substructArrays(chunks, idToSubtract.chunks);
else
result = substructArrays(idToSubtract.chunks, chunks);
return new ONodeId(result, cmp == signum ? 1 : -1);
}
public ONodeId multiply(final int value) {
if (value == 0)
return ZERO;
final int[] result = new int[CHUNKS_SIZE];
long carry = 0;
for (int j = CHUNKS_SIZE - 1; j >= 0; j--) {
final long product = (chunks[j] & LONG_INT_MASK) * (value & LONG_INT_MASK) + carry;
result[j] = (int) product;
carry = product >>> 32;
}
return new ONodeId(result, signum);
}
public ONodeId shiftLeft(final int shift) {
int nInts = shift >>> 5;
if (nInts == CHUNKS_SIZE)
return ZERO;
final int nBits = shift & 0x1f;
final int result[] = new int[CHUNKS_SIZE];
if (nBits != 0) {
int nBits2 = 32 - nBits;
int i = nInts;
int j = 0;
while (i < CHUNKS_SIZE - 1)
result[j++] = chunks[i++] << nBits | chunks[i] >>> nBits2;
result[j] = chunks[i] << nBits;
} else
System.arraycopy(chunks, nInts, result, 0, CHUNKS_SIZE - nInts);
if (Arrays.equals(ZERO.chunks, result))
return ZERO;
return new ONodeId(result, signum);
}
public ONodeId shiftRight(final int shift) {
int nInts = shift >>> 5;
if (nInts == CHUNKS_SIZE)
return ZERO;
int nBits = shift & 0x1f;
final int result[] = new int[CHUNKS_SIZE];
if (nBits != 0) {
int nBits2 = 32 - nBits;
int i = 0;
int j = nInts;
result[j++] = chunks[i] >>> nBits;
while (j < CHUNKS_SIZE)
result[j++] = chunks[i++] << nBits2 | chunks[i] >>> nBits;
} else
System.arraycopy(chunks, 0, result, nInts, CHUNKS_SIZE - nInts);
if (Arrays.equals(ZERO.chunks, result))
return ZERO;
return new ONodeId(result, signum);
}
public static ONodeId generateUniqueId() {
final long clusterPosition = random.nextLong(Long.MAX_VALUE);
final int[] chunks = new int[CHUNKS_SIZE];
final byte[] uuid = new byte[16];
secureRandom.nextBytes(uuid);
chunks[0] = (int) (clusterPosition >>> 32);
chunks[1] = (int) clusterPosition;
chunks[2] = OIntegerSerializer.INSTANCE.deserialize(uuid, 0);
chunks[3] = OIntegerSerializer.INSTANCE.deserialize(uuid, 4);
chunks[4] = OIntegerSerializer.INSTANCE.deserialize(uuid, 8);
chunks[5] = OIntegerSerializer.INSTANCE.deserialize(uuid, 12);
return new ONodeId(chunks, 1);
}
private static int[] addArrays(int[] chunksToAddOne, int[] chunksToAddTwo) {
int[] result = new int[CHUNKS_SIZE];
int index = CHUNKS_SIZE;
long sum = 0;
while (index > 0) {
index--;
sum = (chunksToAddTwo[index] & LONG_INT_MASK) + (chunksToAddOne[index] & LONG_INT_MASK) + (sum >>> 32);
result[index] = (int) sum;
}
return result;
}
private static int compareChunks(int[] chunksOne, int[] chunksTwo) {
for (int i = 0; i < CHUNKS_SIZE; i++) {
final long chunk = chunksOne[i] & LONG_INT_MASK;
final long otherChunk = chunksTwo[i] & LONG_INT_MASK;
if (chunk == otherChunk)
continue;
if (chunk > otherChunk)
return 1;
return -1;
}
return 0;
}
private static int[] substructArrays(int[] chunksOne, int[] chunksTwo) {
int[] result = new int[CHUNKS_SIZE];
int index = CHUNKS_SIZE;
long difference = 0;
while (index > 0) {
index--;
difference = (chunksOne[index] & LONG_INT_MASK) - (chunksTwo[index] & LONG_INT_MASK) + (difference >> 32);
result[index] = (int) difference;
}
return result;
}
private static void multiplyAndAdd(int[] chunks, int multiplier, int summand) {
long carry = 0;
for (int j = CHUNKS_SIZE - 1; j >= 0; j--) {
final long product = (chunks[j] & LONG_INT_MASK) * (multiplier & LONG_INT_MASK) + carry;
chunks[j] = (int) product;
carry = product >>> 32;
}
if (summand == 0)
return;
long sum = (chunks[CHUNKS_SIZE - 1] & LONG_INT_MASK) + (summand & LONG_INT_MASK);
chunks[CHUNKS_SIZE - 1] = (int) sum;
int j = CHUNKS_SIZE - 2;
while (j >= 0 && sum > 0) {
sum = (chunks[j] & LONG_INT_MASK) + (sum >>> 32);
chunks[j] = (int) sum;
j--;
}
}
public int intValue() {
final int reslut = chunks[CHUNKS_SIZE - 1];
if(signum < 0)
return -reslut;
return reslut;
}
@Override
public long longValue() {
final long reslut = (((chunks[CHUNKS_SIZE - 2] & LONG_INT_MASK) << 32) + (chunks[CHUNKS_SIZE - 1] & LONG_INT_MASK))
& Long.MAX_VALUE;
if (signum < 0)
return -reslut;
return reslut;
}
@Override
public float floatValue() {
return Float.parseFloat(toString());
}
@Override
public double doubleValue() {
return Double.parseDouble(toString());
}
public byte[] toStream() {
final byte[] bytes = new byte[SERIALIZED_SIZE];
int pos = 0;
for (int i = 0; i < CHUNKS_SIZE; i++) {
OIntegerSerializer.INSTANCE.serialize(chunks[i], bytes, pos);
pos += OIntegerSerializer.INT_SIZE;
}
bytes[pos] = (byte) signum;
return bytes;
}
public byte[] chunksToByteArray() {
final byte[] bytes = new byte[NODE_SIZE_BYTES];
int pos = 0;
for (int i = 0; i < CHUNKS_SIZE; i++) {
OIntegerSerializer.INSTANCE.serialize(chunks[i], bytes, pos);
pos += OIntegerSerializer.INT_SIZE;
}
return bytes;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ONodeId oNodeId = (ONodeId) o;
if (signum != oNodeId.signum)
return false;
return Arrays.equals(chunks, oNodeId.chunks);
}
@Override
public int hashCode() {
int result = Arrays.hashCode(chunks);
result = 31 * result + signum;
return result;
}
public String toString() {
return new BigInteger(signum, chunksToByteArray()).toString();
}
public static ONodeId valueOf(long value) {
final ONodeId constant = findInConstantPool(value);
if (constant != null)
return constant;
final int signum;
if (value > 0)
signum = 1;
else {
signum = -1;
value = -value;
}
final int[] chunks = new int[CHUNKS_SIZE];
chunks[5] = (int) (value & LONG_INT_MASK);
chunks[4] = (int) (value >>> 32);
return new ONodeId(chunks, signum);
}
public static ONodeId parseString(String value) {
final int intChunkLength = 9;
final int longChunkLength = 18;
int signum;
int pos;
if (value.charAt(0) == '-') {
pos = 1;
signum = -1;
} else {
pos = 0;
signum = 1;
}
while (pos < value.length() && Character.digit(value.charAt(pos), 10) == 0)
pos++;
if (pos == value.length())
return ZERO;
int chunkToRead = Math.min(pos + longChunkLength, value.length());
long initialValue = Long.parseLong(value.substring(pos, chunkToRead));
pos = chunkToRead;
int[] result = new int[CHUNKS_SIZE];
result[CHUNKS_SIZE - 1] = (int) initialValue;
result[CHUNKS_SIZE - 2] = (int) (initialValue >>> 32);
while (pos < value.length()) {
chunkToRead = Math.min(pos + intChunkLength, value.length());
int parsedValue = Integer.parseInt(value.substring(pos, chunkToRead));
final int multiplier = (chunkToRead == intChunkLength) ? 1000000000 : (int) Math.pow(10, chunkToRead - pos);
multiplyAndAdd(result, multiplier, parsedValue);
pos = chunkToRead;
}
return new ONodeId(result, signum);
}
public static ONodeId fromStream(byte[] content, int start) {
final int[] chunks = new int[CHUNKS_SIZE];
int pos = start;
for (int i = 0; i < CHUNKS_SIZE; i++) {
chunks[i] = OIntegerSerializer.INSTANCE.deserialize(content, pos);
pos += OIntegerSerializer.INT_SIZE;
}
final int signum = content[pos];
return new ONodeId(chunks, signum);
}
public static ONodeId parseHexSting(String value) {
int pos;
int signum;
if (value.charAt(0) == '-') {
pos = 1;
signum = -1;
} else {
pos = 0;
signum = 1;
}
final int[] chunks = new int[6];
for (int i = 0; i < CHUNKS_SIZE; i++) {
final String chunk = value.substring(pos, pos + OIntegerSerializer.INT_SIZE * 2);
chunks[i] = (int) Long.parseLong(chunk, 16);
pos += OIntegerSerializer.INT_SIZE * 2;
}
if (Arrays.equals(ZERO.chunks, chunks))
return ZERO;
return new ONodeId(chunks, signum);
}
public String toHexString() {
final StringBuilder builder = new StringBuilder();
if (signum < 0)
builder.append("-");
for (int chunk : chunks)
builder.append(String.format("%1$08x", chunk));
return builder.toString();
}
private static ONodeId findInConstantPool(long value) {
if (value == 0)
return ZERO;
if (value == 1)
return ONE;
if (value == 2)
return TWO;
return null;
}
}
|
d4d84e61a42147ce59eed18ab72aba636d598bbb
|
[
"Java",
"Maven POM",
"INI"
] | 102 |
Java
|
nengxu/OrientDB
|
60eb4bf2a645142fb4a0905db9d466609bd379d0
|
0bc39c04b957b103658ab61c8d18938e936f4a13
|
refs/heads/master
|
<repo_name>davekooi/Multipeer-test<file_sep>/Multipeer test/ViewController.swift
//
// ViewController.swift
// Multipeer test
//
// Created by <NAME> on 1/7/18.
// Copyright © 2018 David. All rights reserved.
//
import UIKit
import MultipeerConnectivity
extension UIView {
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
}
class ViewController: UIViewController, MCSessionDelegate, MCBrowserViewControllerDelegate {
@IBOutlet weak var messageDisplayLabel: UITextView!
@IBOutlet weak var messageInput: UITextField!
var peerID:MCPeerID!
var mcSession:MCSession!
var mcAdvertiserAssistant:MCAdvertiserAssistant!
override func viewDidLoad() {
super.viewDidLoad()
setupConnectivity()
// Do any additional setup after loading the view, typically from a nib.
}
func setupConnectivity() {
peerID = MCPeerID(displayName: UIDevice.current.name)
mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required)
mcSession.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func clearChat(_ sender: Any) {
self.messageDisplayLabel.text = "Chat:"
}
@IBAction func sendMessage(_ sender: Any) {
requestSendMessage(messageInput.text!)
messageInput.text = ""
}
func requestSendMessage(_ message:String) {
if mcSession.connectedPeers.count > 0 {
if let myData = message.data(using: .utf8) {
do {
try mcSession.send(myData, toPeers: mcSession.connectedPeers, with: .reliable)
} catch {
fatalError("Could not send message")
}
messageDisplayLabel.text = messageDisplayLabel.text + "\n" + message
}
} else {
print("Not connected to other devices")
}
}
@IBAction func showConnectivityAction(_ sender: Any) {
let actionSheet = UIAlertController(title: "Connect devices", message: "Do you want to host or join session?", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Host Session", style: .default, handler: { (action:UIAlertAction) in
self.mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "Dave-type", discoveryInfo: nil, session: self.mcSession)
self.mcAdvertiserAssistant.start()
}))
actionSheet.addAction(UIAlertAction(title: "Join Session", style: .default, handler: { (action:UIAlertAction) in
let mcBrowser = MCBrowserViewController(serviceType: "Dave-type", session: self.mcSession)
mcBrowser.delegate = self
self.present(mcBrowser, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
// MARK: - MC Delegate Functions
func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
switch state {
case MCSessionState.connected:
print("Connected: \(peerID.displayName)")
case MCSessionState.connecting:
print("Connecting: \(peerID.displayName)")
case MCSessionState.notConnected:
print("Not Connected: \(peerID.displayName)")
}
}
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
print(data.base64EncodedString())
DispatchQueue.main.async {
self.messageDisplayLabel.text = self.messageDisplayLabel.text + "\n" + String(data: data, encoding: String.Encoding.utf8)! as String!
}
}
func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
}
func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
}
func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {
}
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
dismiss(animated: true, completion: nil)
}
func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
dismiss(animated: true, completion: nil)
}
}
|
1a153df6de8742cdd970641a017522828559a6a2
|
[
"Swift"
] | 1 |
Swift
|
davekooi/Multipeer-test
|
46ca388573c92efb878daf6ea0771405d1abb90e
|
1059000d262a868eb7ef00777c211499ceb61383
|
refs/heads/master
|
<repo_name>gwappa/python-stappy<file_sep>/setup.py
import setuptools
from stappy import VERSION_STR
setuptools.setup(
name='stappy',
version=VERSION_STR,
description='a storage-access protocol for python',
url='https://github.com/gwappa/python-stappy',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
install_requires=[
'numpy>=1.0',
],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
],
packages=['stappy',],
entry_points={
# nothing for the time being
}
)
<file_sep>/stappy/__init__.py
# MIT License
#
# Copyright (c) 2019 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys as _sys
import pathlib as _pathlib
import json as _json
import zlib as _zlib
from collections import OrderedDict as _OrderedDict
from functools import wraps
import numpy as _np
"""
stappy -- a storage-access protocol in python.
currently byte-order (i.e. endian-ness) support is write-only.
`stappy` does not support reading dataset that differ from native byte order.
TODO:
BIDS may need to be supported.
it may have been a bad idea to prepare "get/put/delete_xxx" for all types of data.
should work like e.g.:
```
base.create["path/to/entry"]
base["path/to/entry"].dataset["name"] = data
# or: base.dataset["path/to/entry/name"] = data
base["path/to/entry"].table["name"] = table
base["path/to/entry"].keyvalue["name"] = mapped
base["path/to/entry"].namedtuple["name"] = value
```
Ideally, these virtual attributes could be used ad hoc e.g. by calling:
```
class SubInterface(AbstractInterface):
def __getdata__(self, name, type):
...
def __setdata__(self, name, type, value):
...
def __deldata__(self, name, type):
...
```
"""
VERSION_STR = "0.5"
DEBUG = False
SEP = '/'
INFO_TYPES = (int, float, str)
def debug(msg):
if DEBUG == True:
print(f"[DEBUG] {msg}")
def abstractmethod(meth):
@wraps(meth)
def __invalid_call__(self, *args, **kwargs):
raise NotImplementedError(meth.__name__)
return __invalid_call__
def is_namedtuple_struct(obj):
if isinstance(obj, tuple):
if hasattr(obj, '_fields'):
if all(isinstance(getattr(obj, fld), INFO_TYPES + (_np.ndarray,)) for fld in obj._fields):
return True
return False
def is_mapping(obj):
for attr in ('keys', 'values', 'items', '__getitem__'):
if not hasattr(obj, attr) or not callable(getattr(obj, attr)):
return False
return True
class AttributeManager:
"""interface for editing entry attributes."""
def __init__(self, interface):
self._interface = interface
self._updating = False
self._dirtyflag = False
def lock(self):
if self._updating == True:
return False
self._updating = True
return True
def flag(self):
if self._updating == True:
self._dirtyflag = True
else:
self._interface._store_info()
def commit(self):
self._updating = False
if self._dirtyflag == True:
self._interface._store_info()
self._dirtyflag = False
def rollback(self):
self._updating = False
if self._dirtyflag == True:
self._interface._load_info()
self._dirtyflag = False
def keys(self):
return self._interface._info.keys()
def values(self):
return self._interface._info.values()
def items(self):
return self._interface._info.items()
def __getitem__(self, keypath):
entry, key = self.__resolve_keypath(keypath, create=False)
return entry[key]
def __setitem__(self, keypath, value):
entry, key = self.__resolve_keypath(keypath, create=True)
entry[key] = value
debug(f"AttributeManager: {repr(keypath)} <- {repr(value)}")
self.flag()
def __delitem__(self, keypath):
entry, key = self.__resolve_keypath(keypath, create=False)
del entry[key]
debug(f"AttributeManager: `rm` {repr(keypath)}")
self.flag()
def __resolve_keypath(self, keypath, create=True):
entry = self._interface._info
keypath = keypath.split(SEP)
# traverse to the deepest entry
for key in keypath[:-1]:
if key not in entry.keys():
if create == True:
entry[key] = _OrderedDict()
else:
raise KeyError(key)
entry = entry[key]
return entry, keypath[-1]
class EntryCreation:
"""utility interface for creating entries. called as AbstractInterface.create[<keypath>]."""
def __init__(self, interface):
self._interface = interface
def __getitem__(self, keypath):
entry, key = self._interface.resolve_path(keypath, create=True)
if key in entry.dataset_names():
return entry.get_dataset(key)
else:
return entry.get_entry(key, create=True)
def __setitem__(self, keypath, value):
raise NotImplementedError("use AbstractInterface[<keypath>] to modify entries/datasets")
class EntryRetrieval:
"""utility interface for retrieving entries. called as AbstractInterface.get[<keypath>]."""
def __init__(self, interface):
self._interface = interface
def __getitem__(self, keypath):
entry, key = self._interface.resolve_path(keypath, create=False)
if key in entry.dataset_names():
return entry.get_dataset(key)
elif key in entry.child_names():
return entry.get_entry(key, create=False)
else:
raise KeyError(key)
def __setitem__(self, keypath, value):
raise NotImplementedError("use AbstractInterface[<keypath>] to modify entries/datasets")
class AbstractInterface:
"""base class that provides common functionality.
The default implementation is:
- it uses the JSON-format file for storing dataset information.
- it uses the directory structure to organize entry hierarchy.
Subclasses must implement (at minimum):
- `_data_suffix`: to distinguish dataset file from the other child entries.
- `_load_child_dataset`: to deserialize datasets into numpy.ndarrays.
- `_store_child_dataset`: to serialize numpy.ndarrays.
- `_delete_child_dataset`: to remove datasets from the storage.
If the subclasses intend to use the structure other than the file system,
they must implement the other methods:
- `_open_root_repr`
- `_free_root_repr`
- `_get_volatile_repr`
- `_list_contents`
- `_load_info`
- `_store_info`
- `_delete_info`
- `_store_child_entry`:
- `_delete_child_entry`:
"""
_info_suffix = ".json"
_data_suffix = None
_byteorders = {
'<': 'little',
'>': 'big',
'=': _sys.byteorder,
'|': 'NA'
}
@classmethod
def _open_root_repr(cls, rootpath):
"""initializes the physical representation of the root at `rootpath`.
returns (new, obj) tuple, where `new` indicates whether the root `obj`
is newly created."""
raise NotImplementedError("_root_repr")
@classmethod
def _free_root_repr(cls, rootrepr):
raise NotImplementedError("_free_root_repr")
@abstractmethod
def _get_volatile_repr(self, parent, name):
"""creates `self`'s physical representation based on
`parent` and `name` information.
note that `parent` may not have a justified type.
if `parent` is None, it implies that this is the root entry."""
pass
@abstractmethod
def _load_info(self):
"""reads info from the existing physical representation,
and stores it in the instance's `info` attribute."""
pass
@abstractmethod
def _store_info(self):
"""writes the current `info` attribute to its physical
representation."""
pass
@abstractmethod
def _delete_info(self):
"""deletes the information for the entry.
this is only supposed to occur during the deletion of the entry itself."""
pass
@abstractmethod
def _list_contents(self, children=True, datasets=True):
"""returns the contents of the entry as a sequence."""
pass
@abstractmethod
def _get_child_entry(self, name):
"""tries to get the specified child entry in this entry.
it returns the corresponding AbstractInterface object."""
pass
@abstractmethod
def _delete_child_entry(self, name, child):
"""remove the child entry `child` that has `name`."""
pass
@abstractmethod
def _load_child_dataset(self, name):
"""tries to get the specified child dataset in this entry.
it must return the corresponding numpy.ndarray object."""
pass
@abstractmethod
def _store_child_dataset(self, name, value):
"""store `value` with the specified `name`."""
pass
@abstractmethod
def _delete_child_dataset(self, name):
"""remove the dataset that has `name`."""
pass
@abstractmethod
def _load_child_dict(self, name):
pass
@abstractmethod
def _store_child_dict(self, name):
pass
@abstractmethod
def _delete_child_dict(self, name):
pass
@classmethod
def open(cls, rootpath, **kwargs):
"""returns the 'root' entry (that has different terminology)."""
root = cls("", parent=None)
created, root._repr = cls._open_root_repr(rootpath)
root._root = root._repr
root._path = ''
if not created:
root._load_info()
def _update(src):
return root.__class__._copy_from_another_root(src=src, dest=root)
def _close():
return root.__class__.close(root)
root.update = _update
root.close = _close
if len(kwargs) > 0:
for key, value in kwargs:
setattr(root, key, value)
return root
@classmethod
def close(cls, rootobj=None):
"""free the physical representation of this root object."""
if not rootobj.is_root():
raise ValueError("close() not applied to the root object")
else:
cls._free_root_repr(rootobj._repr)
rootobj.invalidate()
@classmethod
def _copy_from_another_root(cls, src=None, dest=None):
if (not src.is_root()) or (not dest.is_root()):
raise ValueError("invalid call to copy()")
for name, value in src.items():
dest[name] = value
def __init__(self, name, parent=None):
"""creates (ensures) the directory with the matched name.
`parent` must be either None (root) or the instance of the same classs.
`info` will be only used when """
if (len(name.strip()) == 0) and (parent is not None):
raise ValueError("entry name cannot be empty")
if SEP in name:
if parent is None:
raise ValueError("use of path is not allowed for the root name")
else:
comps = name.split(SEP)
parent = self.__class__(SEP.join(comps[:-1]), parent=parent)
name = comps[-1]
self._name = name
self._info = _OrderedDict()
self._parent= parent
if parent is not None:
self._root = parent._root
self._repr = self._get_volatile_repr(parent, name)
self._path = f"{parent._path}{SEP}{name}"
self._load_info()
self.attrs = AttributeManager(self)
self._valid = True
def __repr__(self):
if self._valid == True:
return f"{self.__class__.__name__}({repr(str(self._root))})[{repr(str(self._path))}]"
else:
return f"{self.__class__.__name__}(#invalid)"
def __getattr__(self, name):
if name == 'create':
return EntryCreation(self)
elif name == 'get':
return EntryRetrieval(self)
else:
return super().__getattr__(name)
def __getitem__(self, keypath):
entry, key = self.resolve_path(keypath, create=False)
if key in entry.child_names():
return entry.get_entry(key, create=False)
elif key in entry.dataset_names():
return entry.get_dataset(key)
else:
raise KeyError(key)
def __setitem__(self, keypath, value):
if (not isinstance(value, (AbstractInterface, _np.ndarray))) \
and (not is_namedtuple_struct(value)) and (not is_mapping(value)):
raise ValueError(f"stappy only accepts entry-types, numpy arrays, array-based named tuples, or mappings, but got {value.__class__}")
entry, key = self.resolve_path(keypath, create=True)
if isinstance(value, AbstractInterface):
entry.put_entry(key, value)
elif isinstance(value, _np.ndarray):
entry.put_dataset(key, value)
elif is_namedtuple_struct(value):
entry.put_namedtuple_struct(key, value)
elif is_mapping(value):
entry.put_dict(key, value)
else:
raise RuntimeError("fatal error: class assertion failed")
def __delitem__(self, keypath):
entry, key = self.resolve_path(keypath, create=False)
if key in entry.child_names():
# entry
entry.delete_entry(key)
elif key in entry.dataset_names():
# dataset
entry.delete_dataset(key)
else:
raise KeyError(key)
def __contains__(self, keypath):
try:
entry, key = self.resolve_path(keypath, create=False)
except KeyError:
return False
try:
entry = entry.get_entry(key, create=False)
return True
except NameError:
return False
def resolve_path(self, keypath, create=True):
"""returns (dparent, key), where `dparent` indicates the
direct parent of the value specified by `keypath`."""
keys = keypath.split(SEP)
entry = self
for key in keys[:-1]:
entry = entry.get_entry(key, create=create)
return entry, keys[-1]
def invalidate(self):
"""makes this object invalid as a reference."""
self._name = None
self._root = None
self._parent = None
self._info = None
self._repr = None
self._valid = False
def is_root(self):
return (self._parent is None)
def keys(self):
"""returns a sequence of names of children (child entries and datasets irrelevant)."""
return self._list_contents(children=True, datasets=True)
def child_names(self):
"""returns a sequence of its child entries."""
return self._list_contents(children=True, datasets=False)
def dataset_names(self):
"""returns a sequence of datasets that this entry contains."""
return self._list_contents(children=False, datasets=True)
def values(self):
"""returns a generator of children (entries and datasets)."""
for name in self.keys():
yield self.__getitem__(name)
def children(self):
for name in self.child_names():
yield self.get_entry(name, create=False)
def datasets(self):
for name in self.dataset_names():
yield self.get_dataset(name)
def items(self):
for name in self.keys():
yield name, self.__getitem__(name)
def get_entry(self, name, create=True):
"""returns the specified child entry.
if `create` is True and the entry does not exist,
the entry is newly generated before being returned."""
if name in self.child_names():
entry = self._get_child_entry(name)
else:
if create == False:
raise NameError(f"name not found: {name}")
entry = self.__class__(name, parent=self)
return entry
def put_entry(self, name, entry, overwrite=True, deletesource=False):
"""puts `entry` to this entry with `name`."""
if name in self.child_names():
if overwrite == False:
raise NameError(f"entry '{name}' already exists")
else:
self.delete_entry(name)
# copy recursively
child = self.get_entry(name, create=True)
child._info.update(entry._info)
for dataname in entry.dataset_names():
child.put_dataset(dataname, entry.get_dataset(dataname))
for grandchild in entry.child_names():
child.put_entry(grandchild, entry.get_entry(grandchild))
child._store_info()
if deletesource == True:
if entry._parent is None:
# TODO: remove the root file
pass
else:
entry._parent.delete_entry(entry.name)
def delete_entry(self, name):
"""deletes a child entry with 'name' from this entry."""
if name not in self.child_names():
raise NameError(f"entry '{name}' does not exist")
child = self.get_entry(name, create=False)
# deletes grandchildren recursively
for dataname in child.dataset_names():
child.delete_dataset(dataname)
for grandchild in child.child_names():
child.delete_entry(grandchild)
child._delete_info()
self._delete_child_entry(name, child)
child.invalidate()
def get_dataset(self, name):
"""returns the dataset with the specified name."""
if name not in self.dataset_names():
raise NameError(f"dataset not found: {name}")
data = self._load_child_dataset(name)
locked = self.attrs.lock()
self.attrs[f"{name}/dtype"] = str(data.dtype)
self.attrs[f"{name}/shape"] = data.shape
self.attrs[f"{name}/byteorder"] = self._byteorders[data.dtype.byteorder]
if locked == True:
self.attrs.commit()
return data
def put_dataset(self, name, value, overwrite=True):
"""puts `value` to this entry with `name`."""
if name in self.dataset_names():
if overwrite == False:
raise NameError(f"the dataset '{name}' already exists")
else:
self.delete_dataset(name)
self._store_child_dataset(name, value)
locked = self.attrs.lock()
self.attrs[f"{name}/dtype"] = str(value.dtype)
self.attrs[f"{name}/shape"] = value.shape
self.attrs[f"{name}/byteorder"] = self._byteorders[value.dtype.byteorder]
if locked == True:
self.attrs.commit()
def put_namedtuple_struct(self, name, value, overwrite=True):
if not is_namedtuple_struct(value):
raise ValueError(f"not conforming to the 'named-tuple structure': {value.__class__}")
if name in self.child_names():
if overwrite == False:
raise NameError(f"the entry '{name}' already exists")
else:
self.delete_entry(name)
entry = self.get_entry(name, create=True)
locked = entry.attrs.lock()
entry.attrs["type"] = value.__class__.__name__
for field in value._fields:
item = getattr(value, field)
if isinstance(item, INFO_TYPES):
entry.attrs[field] = item
else:
# must be np.ndarray b/c of is_namedtuple_struct() impl
entry.put_dataset(field, item, overwrite=True)
if locked == True:
entry.attrs.commit()
def delete_dataset(self, name):
"""deletes a child dataset with 'name' from this entry."""
self._delete_child_dataset(name)
locked = self.attrs.lock()
del self.attrs[f"{name}/dtype"]
del self.attrs[f"{name}/shape"]
del self.attrs[f"{name}/byteorder"]
if locked == True:
self.attrs.commit()
def get_dict(self, name):
return self._load_child_dict(name)
def put_dict(self, name, value):
if not isinstance(value, (dict, _OrderedDict)): # FIXME: how to check if it is mapping type?
raise ValueError(f"expected dict, got '{value.__class__}'")
self._store_child_dict(name, value)
def delete_dict(self, name):
self._delete_child_dict(name)
class FileSystemInterface(AbstractInterface):
"""base class that provides a file system-based data access.
it proides implementations for some abstract functions in AbstractInterface:
- `open`
- `_get_volatile_repr`
- `_list_contents`
- `_load_info`
- `_store_info`
- `_delete_info`
- `_store_child_entry`
- `_delete_child_entry`
- `_delete_child_dataset`
subclasses still needs to implement the following methods:
- `_data_suffix`: to distinguish dataset file from the other child entries.
- `_load_child_dataset`: to deserialize datasets into numpy.ndarrays.
- `_store_child_dataset`: to serialize numpy.ndarrays.
"""
_meta_base = "entry_metadata"
_info_suffix = ".json"
_data_suffix = None
def _datafile(self, name):
return self._repr / f"{name}{self._data_suffix}"
def _get_volatile_repr(self, parent, name):
if parent is None:
# root; necessary paths must have been already initialized
return
else:
file = _pathlib.Path(parent._repr) / name
if file.is_file():
raise FileExistsError("cannot create another entry (file in place of directory)")
if not file.exists():
file.mkdir()
debug(f"FileSystemInterface._get_volatile_repr: created '{name}' under '{str(parent)}'")
return file
def _load_child_dict(self, name):
dictfile = self._repr / f"{name}.json"
if not dictfile.exists():
raise FileNotFoundError(str(dictfile))
else:
with open(dictfile, 'r') as src:
return _json.load(src, object_hook=_OrderedDict)
def _store_child_dict(self, name, value):
dictfile = self._repr / f"{name}.json"
with open(dictfile, 'w') as out:
_json.dump(value, out, indent=4)
def _delete_child_dict(self, name):
dictfile = self._repr / f"{name}.json"
if dictfile.exists():
dictfile.unlink()
def _load_info(self):
infofile = self._repr / f"{self._meta_base}{self._info_suffix}"
if not infofile.exists():
debug(f"FileSystemInterface._load_info: {repr(str(infofile))} was not found; leave the info empty.")
self._info = _OrderedDict()
else:
with open(infofile, 'r') as info:
self._info = _json.load(info, object_hook=_OrderedDict)
debug(f"FileSystemInterface._load_info: loaded from '{self._name}': '{self._info}'")
def _store_info(self):
if len(self._info) > 0:
with open(self._repr / f"{self._meta_base}{self._info_suffix}", 'w') as out:
_json.dump(self._info, out, indent=4)
debug(f"FileSystemInterface._store_info: stored into '{self._name}': '{self._info}'")
def _delete_info(self):
infofile = self._repr / f"{self._meta_base}{self._info_suffix}"
if not infofile.exists():
return
else:
infofile.unlink()
def _list_contents(self, children=True, datasets=True):
_listed = []
for path in self._repr.iterdir():
if path.name.startswith('.'):
# hidden
pass
elif path.suffix == self._info_suffix:
# info
pass
elif path.suffix == self._data_suffix:
# data
if datasets == True:
_listed.append(path.stem)
else:
# child
if children == True:
_listed.append(path.name)
return tuple(_listed)
def _get_child_entry(self, name):
return self.__class__(name, parent=self)
def _delete_child_entry(self, name, child):
child._repr.rmdir()
@abstractmethod
def _load_child_dataset(self, name):
"""tries to get the specified child dataset in this entry.
it must return the corresponding numpy.ndarray object."""
pass
@abstractmethod
def _store_child_dataset(self, name, value):
"""stores `value` with the specified `name` (with appropriate
suffix, if you use the `_data_suffix` functionality)."""
pass
def _delete_child_dataset(self, name):
"""removes the dataset that has `name` (with appropriate suffix,
if you use the `_data_suffix` functionality)."""
self._datafile(name).unlink()
@classmethod
def _open_root_repr(cls, rootpath):
rootrepr = _pathlib.Path(rootpath)
if not rootrepr.exists():
created = True
rootrepr.mkdir(parents=True)
else:
created = False
return created, rootrepr
@classmethod
def _free_root_repr(cls, rootrepr):
pass
class NPYInterface(FileSystemInterface):
_data_suffix = '.npy'
def __init__(self, name, parent=None):
super().__init__(name, parent=parent)
def _load_child_dataset(self, name):
data = _np.load(str(self._datafile(name)))
return data
def _store_child_dataset(self, name, value):
_np.save(str(self._datafile(name)), value)
class BareZInterface(FileSystemInterface):
_data_suffix = ".zarr"
_default_compression_level = 6
compression_level = None
def __init__(self, name, parent=None):
super().__init__(name, parent=parent)
if parent is not None:
if hasattr(parent, 'compression_level'):
self.compression_level = parent.compression_level
if self.compression_level is None:
self.compression_level = self._default_compression_level
def _load_child_dataset(self, name):
dtype = _np.dtype(self.attrs[f"{name}/dtype"])
shape = self.attrs[f"{name}/shape"]
file = str(self._datafile(name))
with open(file, 'rb') as src:
binary = _zlib.decompress(src.read())
return _np.frombuffer(binary, dtype=dtype).reshape(shape, order='C')
def _store_child_dataset(self, name, value):
self.attrs[f"{name}/compression"] = 'zlib'
with open(self._datafile(name), 'wb') as dst:
dst.write(_zlib.compress(value.tobytes(order='C'), level=self.compression_level))
<file_sep>/README.md
# stappy
the name `stappy` comes from "**ST**orage-**A**ccess **P**rotocol for **PY**thon".
It intends to unify the protocol to access datasets that are organized in a hierarchy.
For the time being, the following format is supported (and should be expanding):
- NPY-based file-system interface
|
e4151ba4106fa1e3b54d99edd1773b97572afe51
|
[
"Markdown",
"Python"
] | 3 |
Python
|
gwappa/python-stappy
|
c70c862ff8c1d356fba73f145329a17a2430e227
|
974c5f28d6162aa852c0d23fd053024da6190ff1
|
refs/heads/master
|
<file_sep>-- MySQL dump 10.13 Distrib 5.7.23, for Linux (x86_64)
--
-- Host: localhost Database: olericulture
-- ------------------------------------------------------
-- Server version 5.7.23-0ubuntu0.16.04.1
/*!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 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `orders`
--
DROP TABLE IF EXISTS `orders`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orders` (
`order_id` int(11) NOT NULL AUTO_INCREMENT,
`purchase_id` int(11) DEFAULT NULL,
`customer_id` int(11) DEFAULT NULL,
`cus_name` varchar(255) DEFAULT NULL,
`total_amount` int(11) DEFAULT NULL,
PRIMARY KEY (`order_id`),
KEY `customer_id` (`customer_id`),
CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `user` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `orders`
--
LOCK TABLES `orders` WRITE;
/*!40000 ALTER TABLE `orders` DISABLE KEYS */;
INSERT INTO `orders` VALUES (4,150,3,'testuser',1200);
/*!40000 ALTER TABLE `orders` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `product`
--
DROP TABLE IF EXISTS `product`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `product` (
`product_no` int(11) NOT NULL AUTO_INCREMENT,
`product_type` varchar(20) DEFAULT NULL,
`product_name` varchar(20) DEFAULT NULL,
`amount` int(11) DEFAULT NULL,
`quantity` int(11) DEFAULT NULL,
PRIMARY KEY (`product_no`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `product`
--
LOCK TABLES `product` WRITE;
/*!40000 ALTER TABLE `product` DISABLE KEYS */;
INSERT INTO `product` VALUES (6,'Root Crops','Potatoes',40,10),(7,'Root Crops','Ginger',50,10),(8,'Root Crops','Clery',75,10),(9,'Bulb Crops','Oninon',50,10),(10,'Bulb Crops','Garlic',70,10),(11,'Legumes','Alfalfa',20,10),(12,'Legumes','Clover',45,10),(13,'Legumes','Peas',55,10),(14,'Cucurbits','Pumpkin',150,10),(15,'Cucurbits','Squash',160,10);
/*!40000 ALTER TABLE `product` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `purchase`
--
DROP TABLE IF EXISTS `purchase`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `purchase` (
`purchase_id` int(11) DEFAULT NULL,
`product_id` int(11) DEFAULT NULL,
`customer_id` int(11) DEFAULT NULL,
`amount` int(11) DEFAULT NULL,
`product_name` varchar(20) DEFAULT NULL,
KEY `product_id` (`product_id`),
KEY `customer_id` (`customer_id`),
CONSTRAINT `purchase_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `product` (`product_no`) ON DELETE CASCADE,
CONSTRAINT `purchase_ibfk_2` FOREIGN KEY (`customer_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `purchase`
--
LOCK TABLES `purchase` WRITE;
/*!40000 ALTER TABLE `purchase` DISABLE KEYS */;
INSERT INTO `purchase` VALUES (150,7,3,500,'Ginger'),(150,10,3,700,'Garlic');
/*!40000 ALTER TABLE `purchase` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `seller`
--
DROP TABLE IF EXISTS `seller`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `seller` (
`seller_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL,
`email` varchar(30) DEFAULT NULL,
`phone` int(11) DEFAULT NULL,
PRIMARY KEY (`seller_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `seller`
--
LOCK TABLES `seller` WRITE;
/*!40000 ALTER TABLE `seller` DISABLE KEYS */;
INSERT INTO `seller` VALUES (1,'testadmin','testadmin','<EMAIL>',789456123);
/*!40000 ALTER TABLE `seller` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `user`
--
DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`email` varchar(20) DEFAULT NULL,
`phone` decimal(10,0) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `user`
--
LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (3,'testuser','testuser','<EMAIL>',789456);
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!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 */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2018-12-01 8:52:53
<file_sep>
import java.awt.Color;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import java.util.Random;
/*
* 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.
*/
/**
*
* @author whitehat
*/
public class Products extends javax.swing.JFrame {
public int index,pro_id,amount,cost,user_id,purchase_id,totalcost;
public String product_name,product_type,username;
/**
* Creates new form Products
*/
public Products(String username,int user_id) {
initComponents();
getContentPane().setBackground(Color.WHITE);
this.username=username;
this.user_id=user_id;
//create_list();
Random rand = new Random();
int n= rand.nextInt(500);
purchase_id = user_id+n;
}
public void update(){
product_name =jList1.getSelectedValue();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/olericulture","root", "root123");
String sql="select * from product where product_type='"+product_type+"' and product_name='"+product_name+"'";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultListModel d=new DefaultListModel();
if(rs.next()){
cost=rs.getInt(4);
jLabel8.setText(Integer.toString(cost));
// d.addElement(""+name);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
public void updatelist(){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/olericulture","root", "root123");
String sql="select * from product where product_type='"+product_type+"'";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultListModel d=new DefaultListModel();
while(rs.next()){
String name=rs.getString(3);
d.addElement(""+name);
}
jList1.setModel(d);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
public void updatelabel(){
jLabel6.setText(jList1.getSelectedValue().toString());
update();
}
public void cost(int amount){
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
jRadioButton4 = new javax.swing.JRadioButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList<>();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel11 = new javax.swing.JLabel();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Abyssinica SIL", 0, 18)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Products Avialabe");
jLabel2.setFont(new java.awt.Font("Noto Sans", 1, 12)); // NOI18N
jLabel2.setText("Types ");
buttonGroup1.add(jRadioButton1);
jRadioButton1.setFont(new java.awt.Font("Abyssinica SIL", 0, 14)); // NOI18N
jRadioButton1.setText("Root Crops");
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton2);
jRadioButton2.setFont(new java.awt.Font("Abyssinica SIL", 0, 14)); // NOI18N
jRadioButton2.setText("Bulb Crops");
jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton2ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton3);
jRadioButton3.setFont(new java.awt.Font("Abyssinica SIL", 0, 14)); // NOI18N
jRadioButton3.setText("Legumes");
jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton3ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton4);
jRadioButton4.setFont(new java.awt.Font("Abyssinica SIL", 0, 14)); // NOI18N
jRadioButton4.setText("Cucurbits");
jRadioButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton4ActionPerformed(evt);
}
});
jList1.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "Select The Type", "To View", "The List" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jList1.addAncestorListener(new javax.swing.event.AncestorListener() {
public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
}
public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
}
public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
jList1AncestorRemoved(evt);
}
});
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jList1);
jLabel3.setFont(new java.awt.Font("Abyssinica SIL", 0, 14)); // NOI18N
jLabel3.setText("Select From List Of Items");
jLabel4.setFont(new java.awt.Font("Abyssinica SIL", 0, 14)); // NOI18N
jLabel4.setText("Product : ");
jLabel5.setFont(new java.awt.Font("Abyssinica SIL", 0, 14)); // NOI18N
jLabel5.setText("Enter The Weight");
jButton1.setText("Check Cost");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel6.setText("..........");
jLabel7.setFont(new java.awt.Font("Abyssinica SIL", 0, 14)); // NOI18N
jLabel7.setText("Cost : ");
jLabel8.setText("..........");
jLabel9.setFont(new java.awt.Font("Abyssinica SIL", 0, 14)); // NOI18N
jLabel9.setText("Total Cost :");
jLabel10.setText("............");
jButton2.setText("Add");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Check Out");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/images.png"))); // NOI18N
jLabel11.setText("jLabel11");
jButton4.setText("Check My Pervious Orders");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 770, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jRadioButton1)
.addComponent(jRadioButton2)
.addComponent(jRadioButton3)
.addComponent(jRadioButton4))
.addGap(124, 124, 124)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9)
.addGap(12, 12, 12)
.addComponent(jLabel10))
.addGroup(layout.createSequentialGroup()
.addGap(74, 74, 74)
.addComponent(jButton2)
.addGap(12, 12, 12)
.addComponent(jButton3))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(12, 12, 12)
.addComponent(jLabel6))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(30, 30, 30)
.addComponent(jLabel8)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(29, 29, 29)
.addComponent(jRadioButton1)
.addGap(28, 28, 28)
.addComponent(jRadioButton2)
.addGap(29, 29, 29)
.addComponent(jRadioButton3)
.addGap(28, 28, 28)
.addComponent(jRadioButton4))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(127, 127, 127)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel6))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(jLabel8))
.addGap(8, 8, 8))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(jLabel5))
.addComponent(jButton1)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(23, 23, 23))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(jLabel10))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addComponent(jButton3)))))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
// TODO add your handling code here:
product_type = "Root Crops";
updatelist();
}//GEN-LAST:event_jRadioButton1ActionPerformed
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
// TODO add your handling code here:
index = jList1.getSelectedIndex();
product_name=jList1.getSelectedValue().toString();
jLabel6.setText(jList1.getSelectedValue().toString());
updatelabel();
}//GEN-LAST:event_jList1MouseClicked
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/olericulture","root", "root123");
String sql="select * from product where product_type='"+product_type+"'and product_name='"+product_name+"'";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
if(rs.next()){
pro_id=rs.getInt(1);
amount=rs.getInt("amount");
}
int weight=(new Integer(jTextField1.getText()));
totalcost = amount*weight;
jLabel10.setText(Integer.toString(totalcost));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
//call procedure
}//GEN-LAST:event_jButton1ActionPerformed
private void jList1AncestorRemoved(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_jList1AncestorRemoved
// TODO add your handling code here:
}//GEN-LAST:event_jList1AncestorRemoved
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/olericulture","root", "root123");
String sql = "insert into purchase values(?,?,?,?,?)";
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setInt(1,purchase_id);
pstmt.setInt(2,pro_id);
pstmt.setInt(3,user_id);
pstmt.setInt(4,totalcost);
pstmt.setString(5,product_name);
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null,"Added");
conn.close();
//new Welcome().setVisible(true);
//dispose();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
new Purchase(username,user_id,purchase_id).setVisible(true);
dispose();
}//GEN-LAST:event_jButton3ActionPerformed
private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
// TODO add your handling code here:
product_type = "Bulb Crops";
updatelist();
}//GEN-LAST:event_jRadioButton2ActionPerformed
private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton3ActionPerformed
// TODO add your handling code here:
product_type = "Legumes";
updatelist();
}//GEN-LAST:event_jRadioButton3ActionPerformed
private void jRadioButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton4ActionPerformed
// TODO add your handling code here:
product_type = "Cucurbits";
updatelist();
}//GEN-LAST:event_jRadioButton4ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
new customerorders(user_id).setVisible(true);
}//GEN-LAST:event_jButton4ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Products.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Products.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Products.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Products.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// new Products().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JList<String> jList1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JRadioButton jRadioButton4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
|
d3f6cc395abbb45074953eae8bfa05d8df2bdd9f
|
[
"Java",
"SQL"
] | 2 |
SQL
|
Vishnutejk98/DBMS-Project-2
|
c7890689701c8b79a9b42c9b2f310fb90330ac0c
|
0843dc12bce2c03561c4d3bbef1e9bd3ed683e2b
|
refs/heads/master
|
<file_sep>module.exports = class captchatestservice
{
constructor(config,dist)
{
this.statics=config.statics
this.context=config.context
}
async test(msg,func,self)
{
var a = await global.captcha.validate(msg.data.id)
console.log(a)
if(a)
{
return func(null,{m:"accepted"})
}
return func(null,{m:"not accepted"})
}
}
<file_sep>module.exports = [
{
'id': 'cba7b9d6-6182-499d-bbcd-3fcc83522de1',
'name': 'module',
'type': 'endpoint',
'isNpm': true,
'config': {
'connections': [{
'name': 'PublicSite',
'type': 'express',
'sessionManager': 'sessionRedis',
'protocol': {
'type': 'http',
'port': 9101
},
'public': ['./public']
}]
}
},
{
'id': '21f91c9b-f279-4e03-a929-bfadf610030e',
'name': 'module',
'type': 'database',
'isNpm': true,
'config': {
'connection': [{
'name': 'default',
'type': 'mongodb',
'host': 'localhost',
'database': 'testdb'
}]
}
},
{
'id': '4198847e-25f7-466b-905d-9495eb4ca9c4',
'name': 'module',
'type': 'wallet',
'isNpm': true,
'config': {
'context': 'default',
'attach': {}
}
},
{
'id': 'ef473098-8d69-40d0-986a-3fa1b34fa267',
'name': 'service',
'context': '{databse connection name }',
'domain': 'test',
'driver': global.path + '/services/test/index.js',
'structure': global.path + '/services/test/struct.js',
'funcs': [{
'name': 'test',
'title': 'test'
}],
'auth': ['test']
}
];<file_sep>module.exports = class testservice
{
constructor(config,dist)
{
this.statics=config.statics
this.context=config.context
}
async test(msg,func,self)
{
var logs=[]
try{
logs.push(await global.wallet.request('test1','rial',1200,"1234"))
logs.push(await global.wallet.request('test2','rial',-200,"1234"))
logs.push(await global.wallet.request('test3','rial',-1200,"1234"))
}catch(exp){
console.log('--->',exp)
}
return func(null,logs)
}
}
<file_sep>module.exports = [
{
'id': 'cba7b9d6-6182-499d-bbcd-3fcc83522de1',
'name': 'module',
'type': 'endpoint',
'isNpm': true,
'config': {
'connections': [{
'name': 'PublicSite',
'type': 'express',
'sessionManager': 'sessionRedis',
'protocol': {
'type': 'http',
'port': 9101
},
'public': ['./public']
}]
}
},
{
'id': '30e0b115-c15a-4f8a-9404-212af9c1ff31',
'name': 'module',
'type': 'notification',
'isNpm': true,
'config': {
drivers: [{
type: 'webService',
name: 'publicsms',
protocol: 'http',
context: 'default',
protocolType: 'get',
toField: 'destination',
textField: 'message',
sendUrl: 'http://panel.asanak.ir/webservice/v1rest/sendsms',
option: {
username: '',
password: '',
source: ''
}
}]
}
},
{
'id': '21f91c9b-f279-4e03-a929-bfadf610030e',
'name': 'module',
'type': 'database',
'isNpm': true,
'config': {
'connection': [{
'name': 'default',
'type': 'mongodb',
'host': 'localhost',
'database': 'testdb'
}]
}
},
{
'id': 'e68234be-9180-4463-acd2-c5ea5cf30b87',
'name': 'module',
'type': 'base',
'isNpm': true,
'config': {
drivers: [
{ name: 'web' },
{ name: 'global' }
]
}
},
{
'id': '82bb9d4b-4999-4d3d-b256-b7ba939064c6',
'name': 'service',
'context': '{databse connection name }',
'domain': 'test',
'driver': global.path + '/services/test/index.js',
'structure': global.path + '/services/test/struct.js',
'funcs': [{
'name': 'test',
'title': 'test'
}],
'auth': ['test']
},
{
'id': '36c4e157-7076-4427-a87d-be8d2de2e2b0',
'name': 'module',
'type': 'smsauth',
'isNpm': true,
'config': {
'context': 'default',
'attach': {}
}
},
{
'id': '5d05da9f-1ced-4440-8d97-6cd90befcfed',
'name': 'module',
'type': 'account',
'isNpm': true,
'config': {
'context': 'default',
}
}
];<file_sep>module.exports = class testservice
{
constructor(config,dist)
{
this.statics=config.statics
this.context=config.context
}
async test(msg,func,self)
{
try{
//var x = await global.notification.send('publicsms','loginsms',{code:'1234',to:"09378092520"});
console.log('----->',global.ori.RandomInt())
}catch(exp){
console.log('----->',exp)
}
return func(null,{m:"hello."})
}
}
<file_sep>module.exports = {
sampleInterface:{
struct:{
test1:{type:"number"},
test2:{type:"string"},
test1:{type:"boolean",nullable:true},
}
}
}
|
98a0ad4e53f5c385b43345229d3148e45af8d5fb
|
[
"JavaScript"
] | 6 |
JavaScript
|
vahidHossaini/origami-test
|
4f713ed6492790c4a527167aaff43f920bb85a7e
|
fd7c9470c0cf11c4e464483f5c078af1b5c2c9d3
|
refs/heads/master
|
<file_sep>
# 📕 Test-Driven Development : By Example
- 켄트 백 지음
<div align="center">
<img src='https://i.imgur.com/GubRzQw.png' />
</div>
# 🗣 About TDD
- **테스트 주도 개발에서의 규칙 두 가지**
- 오직 자동화된 테스트가 실패할 경우에만 새로운 코드를 작성한다.
- 중복을 제거한다.
- **프로그래밍 순서**
- 빨강 : 실패하는 작은 테스트 작성한다. 컴파일조차 되지 않을 수 있다.
- 초록 : 빨리 테스트가 통과하게끔 한다.
- 리팩토링 : 모든 중복을 제거한다.
# 1️⃣ Chapter 1 - 화폐 예제
- **TDD의 리듬**
- 빠르게 **테스트 추가한다.**
- 모든 테스트를 실행하고, 새로 추가한 것이 실패하는지 확인한다.
- **코드를 조금 바꾼다.**.
- 모든 테스트를 실행하고 **전부 성공하는지 확인한다.**
- 리팩토링을 통한 **중복을 제거한다.**
## ⚡️ 1장 - 다중 통화를 지원하는 Money 객체
#### 1. 테스트부터 작성하기
- 테스트를 작성할 때는 오퍼레이션의 완벽한 인터페이스에 대해 상상해보는 것이 좋다.
- 가능한 최선의 API에서 시작해서 거꾸로 작업한다.
#### 2. 1장에서 실행한 TDD의 순서
- 작업해야 할 테스트 목록 만든다.
- 오퍼레이션이 외부에서 어떻게 보이길 원하는지를 코드로 표현한다.
- 스텁 구현을 통해 테스트를 컴파일한다.
- 스텁 : 메서드를 호출하는 코드가 컴파일 될 수 있도록 껍데기만 만드는 것.
- 무조건 테스트에 통과시키도록 한다.
- 상수를 변수로 변경하여, 점진적으로 일반화한다.
- 새로운 할 일을 한 번에 처리하는 대신, 할 일 목록에 추가하고 넘어간다.
#### 3. 작은 단계를 밟을 능력을 갖추는 것의 중요성
- 작은 단계를 연습하면서, 나에게 작은 단계를 밟을 능력이 있다는 것을 느낄 수 있다.
- 작은 단계로 작업하는 방법을 배우면, 저절로 적절한 크기의 단계로 작업할 수 있게 된다.
## ⚡️ 2장 - 타락한 객체
#### 1. 나누어서 정복하기
목표는 **작동하는 깔끔한 코드를 얻는 것**이다. 이 목표는 도달하기 어려우므로, 일단 Divide and Conquer를 해보자.
- 우선, **작동하는 코드**를 먼저 정복하고, **깔끔한 코드**로 만드는 것이다.
#### 2. 인터페이스와 테스트의 수정
새로운 테스트를 하려고 했을 때, 기존의 인터페이스와 테스트를 수정해야할 수 있다.
<u>문제될 것은 없다!</u>
- 어떤 구현이 올바른가에 대한 추측이 완벽하지 못한 것과 마찬가지로, 올바른 인터페이스에 대한 추측 역시 완벽하지 못하다. => 그러므로, 수정을 거듭할 수 있다.
#### 3. 느낌을 테스트로 변환하기
- 부작용에 대한 느낌을 테스트로 변환하는 것은 TDD의 일반적인 주제이다.
- 일단 올바른 행위에 대한 결정을 내린 후에, 그 행위를 얻어낼 수 있는 최상의 방법에 대해 이야기할 수 있다.
#### 4. 2장에서 실행한 TDD
- **설계상의 결함을 그 결함으로 인해 실패하는 테스트로 변환**했다.
- 스텁 구현으로 컴파일이 될 수 있도록 한다.
- 올바르다고 생각하는 코드를 작성하여 테스트를 통과한다.
#### 느낀점
- 우선 작동하게 만들기
그동안 나는 깔끔한 코드를 먼저 작성하기 위해 고군분투한 것 같다.
처음부터 깔끔하기란 너무 어려운 것이었다.
우선 작동하는 코드를 먼저 만들고 난 후에, 깔끔한 코드로 만드는 것이 방법이라는 것을 알게되었다.
- 목표를 설정하기
테스트 코드를 먼저 작성하는 이유가, "올바른 행위"와, "원하는 인터페이스"를 먼저 정의해야, 그 방법에 대해 생각해볼 수 있다는 것을 알게 되었다.
원하는 바를 명확하게 설정하고, 그것을 얻어내기 위핸 길을 찾아내야 하는 것 같다.
- 수정하는 것에 대한 두려움 없애기
처음부터 완벽한 구현을 하는 것은 없는 것 같다. 구현을 하는 시기에는 좋은 설계를 위한 고민을 해야 한다. 하지만, 변화를 주어야 할 때는 이전의 구현에서의 잘못을 인정하고 수정할 수 있어야 하는 것 같다. 테스트와 인터페이스를 수정하는 것은 이상한 일이 아니었다.
<file_sep>import fetch from "../async";
test("reject test", async () => {
try {
await fetch();
} catch (e) {
expect(e.message).toMatch("err in fetch");
}
});
test("reject test", () => {
return expect(fetch()).rejects.toEqual(new Error("err in fetch"));
});
|
2873255c6bd8162a9cd0c05e9d82c88db51c1621
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
yejineee/TDD
|
2f1229625f687dc4e05566998d3a903217dcf332
|
592777ef66519456d94b1eba7fcf7208e8660e60
|
refs/heads/master
|
<repo_name>tkxiong/pynqz2_dpu140<file_sep>/zynq7020_dnndk_v3.0/pkgs/driver/dpucore.c
/*
* Copyright (C) 2019 Xilinx, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
*/
#include "dpucore.h"
#include "dpuext.h"
#define DEVICE_NAME "dpu"
#define PROCFNAME "dpu_info"
//DPU signature base address
unsigned long signature_addr = SIG_BASE;
module_param(signature_addr, ulong, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
//control which extension is enabled(corresponding bit set to 1)
unsigned long extension = -1; // whether use cache; 0:no, 1:yes
module_param(extension, ulong, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#if defined(CACHE_OFF)
int cache = 0; // whether use cache; 0:no, 1:yes
#else
int cache = 1; // whether use cache; 0:no, 1:yes
#endif
module_param(cache, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
int timeout = 5; // (s)
module_param(timeout, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
char *mode = "normal";
module_param(mode, charp, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
int profiler = 0;
module_param(profiler, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
int debuglevel = PLEVEL_ERR; // debug level
module_param(debuglevel, uint, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
char *version = "DPU Driver version " DPU_DRIVER_VERSION "\nBuild Label: " __DATE__ " " __TIME__;
module_param(version, charp, S_IRUSR | S_IRGRP | S_IROTH);
uint coremask = 0xff;
module_param(coremask, uint, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
uint accipmask = 0x0;
module_param(accipmask, uint, S_IRUSR | S_IRGRP | S_IROTH);
// the following parameters read from device tree
static int DPU_CORE_NUM;
//static uint32_t DPU_BASE;
void *RAM_BASEADDR_VIRT;
dma_addr_t RAM_BASEADDR;
static uint32_t RAM_SIZE;
static uint32_t PROF_RAM_SIZE = 0x100000;
// debug proc file infomation
struct proc_dir_entry *proc_file;
static struct device *dev_handler;
static struct dpu_dev dpudev;
dpu_caps_t dpu_caps;
// debug vars
int _run_counter[MAX_CORE_NUM] = { 0 }, _int_counter[MAX_CORE_NUM] = { 0 };
/*dpu registers*/
DPUReg *pdpureg;
#ifdef PORT_COUNTER
spinlock_t portlock;
u32 *port_counter;
#endif
struct list_head head_alloc; /*head of alloced memory block*/
struct semaphore memblk_lock;
spinlock_t tasklstlock;
spinlock_t idlock, corelock, taskidlock;
spinlock_t reglock;
/**
* dpu_alloc_mem - alloc a memory block from the available memory list.
* @memsize : size of memory
*
* RETURN: address of alloced memory; NULL returned if no enough space exists
*/
unsigned long dpu_alloc_mem(uint32_t memsize)
{
void *virtaddr;
dma_addr_t phy_addr;
struct memblk_node *pnewnode;
memsize = (memsize + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1); //at least one page frame
virtaddr = dma_alloc_coherent(dev_handler, memsize, &phy_addr, GFP_KERNEL);
if (NULL != virtaddr) {
pnewnode = kmalloc(sizeof(struct memblk_node), GFP_KERNEL);
dprint(PLEVEL_DBG, "Alloc Mem:0x%lx size=0x%x\n", (unsigned long)phy_addr, memsize);
if (pnewnode) {
pnewnode->virt_addr = (unsigned long)virtaddr;
pnewnode->size = memsize;
pnewnode->phy_addr = phy_addr;
pnewnode->pid = current->pid;
down(&memblk_lock);
list_add(&pnewnode->list, &head_alloc);
up(&memblk_lock);
} else {
dma_free_coherent(dev_handler, memsize, virtaddr, phy_addr);
phy_addr = 0;
dprint(PLEVEL_ERR, "kmalloc fail when adding memory node\n");
}
return phy_addr;
} else {
return 0;
}
}
/**
* dpu_free_mem - remove the memory block frome alloc list to the available
* memory list and merge with the neighbor node if necessary
* @paddr : address of memory block to be free
*/
int dpu_free_mem(void *paddr)
{
struct list_head *plist;
struct memblk_node *p;
down(&memblk_lock);
list_for_each (plist, &head_alloc) {
p = list_entry(plist, struct memblk_node, list);
if (p->phy_addr == (dma_addr_t)paddr) {
dma_free_coherent(dev_handler, p->size, (void *)p->virt_addr, p->phy_addr);
list_del(&p->list);
kfree(p);
up(&memblk_lock);
return 0;
}
}
up(&memblk_lock);
dprint(PLEVEL_ERR, "free memory failed,address=0x%p\n", paddr);
return -ENXIO;
}
/**
* dpu_create_kernel - create a kernel ID
* the generated ID increased by one on each call
* @pkernel : kernel structure
*/
static void dpu_create_kernel(struct ioc_kernel_manu_t *pkernel)
{
static unsigned long dpu_kernel_id = 1;
spin_lock(&idlock);
pkernel->kernel_id = dpu_kernel_id++;
spin_unlock(&idlock);
}
/**
* dpu_create_task - create a task ID
* the generated ID increased by one on each call
* @pkernel : kernel structure
*/
static void dpu_create_task(struct ioc_task_manu_t *pkernel)
{
static unsigned long dpu_task_id = 1;
spin_lock(&taskidlock);
pkernel->task_id = dpu_task_id++;
spin_unlock(&taskidlock);
}
/**
* _dpu_regs_init - dpu registers initialize
* @channel: the dpu channel [0,DPU_CORE_NUM) need to be initialize,
* set all channel if the para is DPU_CORE_NUM
*/
static void _dpu_regs_init(int channel)
{
uint32_t tmp;
// reset specific channel : only one dpu now,set the reset reg bit0
int i = 0;
int j;
if ((channel >= 0) && (channel < DPU_CORE_NUM)) {
tmp = ioread32(&pdpureg->pmu.reset);
iowrite32(tmp & ~(1 << channel), &pdpureg->pmu.reset);
udelay(1); // wait 1us
iowrite32(tmp | (1 << channel), &pdpureg->pmu.reset);
iowrite32(0x07070f0f, &pdpureg->ctlreg[channel].hp_ctrl);
iowrite32(0, &pdpureg->ctlreg[channel].prof_en);
iowrite32(0, &pdpureg->ctlreg[channel].start);
iowrite32((1 << channel), &pdpureg->intreg.icr);
udelay(1); // wait 1us
iowrite32(0, &pdpureg->intreg.icr);
} else if (channel == DPU_CORE_NUM) {
iowrite32(0, &pdpureg->pmu.reset);
udelay(1); // wait 1us
iowrite32(0xFFFFFFFF, &pdpureg->pmu.reset);
for (i = 0; i < DPU_CORE_NUM; i++) {
iowrite32(0x07070f0f, &pdpureg->ctlreg[i].hp_ctrl);
iowrite32(0, &pdpureg->ctlreg[i].prof_en);
iowrite32(0, &pdpureg->ctlreg[i].start);
iowrite32(0, &(pdpureg->ctlreg[i].addr_code));
iowrite32(0, &(pdpureg->ctlreg[i].addr_prof));
iowrite32(0, &(pdpureg->ctlreg[i].addr_io));
iowrite32(0, &(pdpureg->ctlreg[i].addr_weight));
for (j = 0; j < 16; j++)
iowrite32(0, &(pdpureg->ctlreg[i].com_addr[j]));
}
iowrite32(0xFF, &pdpureg->intreg.icr);
udelay(1); // wait 1us
iowrite32(0, &pdpureg->intreg.icr);
}
}
/**
* _show_debug_info - print information for debug
*
*/
inline void _show_debug_info(void)
{
int i;
dprint(PLEVEL_ERR, "[DPU debug info]\nlevel = %d\n", debuglevel);
for (i = 0; i < DPU_CORE_NUM; i++) {
dprint(PLEVEL_ERR, "Core %d schedule counter: %d\n", i, _run_counter[i]);
dprint(PLEVEL_ERR, "Core %d interrupt counter: %d\n", i, _int_counter[i]);
}
}
/**
* _show_dpu_regs - print dpu registers' value
*
*/
inline void _show_dpu_regs(void)
{
int i = 0, j = 0;
unsigned long flags;
spin_lock_irqsave(®lock, flags);
dprint(PLEVEL_ERR, "[DPU Registers]\n");
dprint(PLEVEL_ERR, "%-10s\t: 0x%.8x\n", "VER", pdpureg->pmu.version);
dprint(PLEVEL_ERR, "%-10s\t: 0x%.8x\n", "RST", pdpureg->pmu.reset);
dprint(PLEVEL_ERR, "%-10s\t: 0x%.8x\n", "ISR", pdpureg->intreg.isr);
dprint(PLEVEL_ERR, "%-10s\t: 0x%.8x\n", "IMR", pdpureg->intreg.imr);
dprint(PLEVEL_ERR, "%-10s\t: 0x%.8x\n", "IRSR", pdpureg->intreg.irsr);
dprint(PLEVEL_ERR, "%-10s\t: 0x%.8x\n", "ICR", pdpureg->intreg.icr);
dprint(PLEVEL_ERR, "\n");
for (i = 0; i < DPU_CORE_NUM; i++) {
dprint(PLEVEL_ERR, "%-8s\t: %d\n", "DPU Core", i);
dprint(PLEVEL_ERR, "%-8s\t: 0x%.8x\n", "HP_CTL", pdpureg->ctlreg[i].hp_ctrl);
dprint(PLEVEL_ERR, "%-8s\t: 0x%.8x\n", "ADDR_IO", pdpureg->ctlreg[i].addr_io);
dprint(PLEVEL_ERR, "%-8s\t: 0x%.8x\n", "ADDR_WEIGHT",
pdpureg->ctlreg[i].addr_weight);
dprint(PLEVEL_ERR, "%-8s\t: 0x%.8x\n", "ADDR_CODE", pdpureg->ctlreg[i].addr_code);
dprint(PLEVEL_ERR, "%-8s\t: 0x%.8x\n", "ADDR_PROF", pdpureg->ctlreg[i].addr_prof);
dprint(PLEVEL_ERR, "%-8s\t: 0x%.8x\n", "PROF_VALUE", pdpureg->ctlreg[i].prof_value);
dprint(PLEVEL_ERR, "%-8s\t: 0x%.8x\n", "PROF_NUM", pdpureg->ctlreg[i].prof_num);
dprint(PLEVEL_ERR, "%-8s\t: 0x%.8x\n", "PROF_EN", pdpureg->ctlreg[i].prof_en);
dprint(PLEVEL_ERR, "%-8s\t: 0x%.8x\n", "START", pdpureg->ctlreg[i].start);
#if defined(CONFIG_DPU_v1_3_0)
for (j = 0; j < 8; j++) {
dprint(PLEVEL_ERR, "%-8s%d\t: 0x%.8x\n", "COM_ADDR_L", j,
pdpureg->ctlreg[i].com_addr[j * 2]);
dprint(PLEVEL_ERR, "%-8s%d\t: 0x%.8x\n", "COM_ADDR_H", j,
pdpureg->ctlreg[i].com_addr[j * 2 + 1]);
}
#endif
dprint(PLEVEL_ERR, "\n");
}
spin_unlock_irqrestore(®lock, flags);
}
/**
* _get_state_str - get dpu state description string
*/
inline char *_get_state_str(int core)
{
int state = dpudev.state[core];
if (!(coremask & (1 << core)))
return "Disable";
switch (state) {
case DPU_IDLE:
return "Idle";
case DPU_RUNNING:
return "Running";
case DPU_DISABLE:
return "Disable";
default:
return "UNDEF";
}
}
/**
* _get_available_core - get an available dpu core
* @ret : return the dpu core number
* @note: the valid dpu core number range: [0,DPU_CORE_NUM) ;
* invalid if return DPU_CORE_NUM
*/
inline int _get_available_core(void)
{
int ret, i, dpu_core = DPU_CORE_NUM;
unsigned long flags;
do {
ret = down_interruptible(&dpudev.sem);
} while (ret < 0);
spin_lock_irqsave(&corelock, flags);
for (i = 0; i < DPU_CORE_NUM; i++) {
if (dpudev.state[i] == DPU_IDLE) {
dpudev.state[i] = DPU_RUNNING;
dpudev.intflg[i] = FALSE;
dpu_core = i;
break;
}
}
spin_unlock_irqrestore(&corelock, flags);
return dpu_core;
}
/**
* dpu_run -run dpu function
* @prun : dpu run struct, contains the necessary address info
*
*/
int dpu_run(struct ioc_kernel_run2_t *prun)
{
int i, ret = 0;
unsigned long flags;
int dpu_core = DPU_CORE_NUM;
dpu_core = _get_available_core();
if (dpu_core == DPU_CORE_NUM) {
// should never get here
dprint(PLEVEL_ERR, "ERR_CORE_NUMBER!\n");
spin_lock_irqsave(&corelock, flags);
for (i = 0; i < DPU_CORE_NUM; i++) {
dprint(PLEVEL_ERR, "Core%d state:%d,task_id:%ld\n", i, dpudev.state[i],
dpudev.task_id[i]);
}
spin_unlock_irqrestore(&corelock, flags);
return -EINTR;
}
dpudev.task_id[dpu_core] = prun->handle_id;
dpudev.pid[dpu_core] = current->pid;
_run_counter[dpu_core]++;
spin_lock_irqsave(®lock, flags);
// extract the address info
#ifdef CONFIG_DPU_v1_1_X
iowrite32(prun->addr_code >> 12, &(pdpureg->ctlreg[dpu_core].addr_code));
iowrite32(prun->addr_io >> 12, &(pdpureg->ctlreg[dpu_core].addr_io));
iowrite32(prun->addr_weight >> 12, &(pdpureg->ctlreg[dpu_core].addr_weight));
if (profiler) {
iowrite32((RAM_BASEADDR + PROF_RAM_SIZE * (dpu_core)) >> 12,
&(pdpureg->ctlreg[dpu_core].addr_prof));
iowrite32(0x1, &(pdpureg->ctlreg[dpu_core].prof_en));
}
iowrite32(0x1, &(pdpureg->ctlreg[dpu_core].start));
#elif defined CONFIG_DPU_v1_3_0
iowrite32(prun->addr_code >> 12, &(pdpureg->ctlreg[dpu_core].addr_code));
iowrite32(prun->addr0, &pdpureg->ctlreg[dpu_core].com_addr[0]);
iowrite32(prun->addr1, &pdpureg->ctlreg[dpu_core].com_addr[2]);
iowrite32(prun->addr2, &pdpureg->ctlreg[dpu_core].com_addr[4]);
iowrite32(prun->addr3, &pdpureg->ctlreg[dpu_core].com_addr[6]);
iowrite32(prun->addr4, &pdpureg->ctlreg[dpu_core].com_addr[8]);
iowrite32(prun->addr5, &pdpureg->ctlreg[dpu_core].com_addr[10]);
iowrite32(prun->addr6, &pdpureg->ctlreg[dpu_core].com_addr[12]);
iowrite32(prun->addr7, &pdpureg->ctlreg[dpu_core].com_addr[14]);
for (i = 0; i < 8; i++) // ADDR_H not support now, just write 0
iowrite32(0, &pdpureg->ctlreg[dpu_core].com_addr[i * 2 + 1]);
if (profiler) {
iowrite32((RAM_BASEADDR + PROF_RAM_SIZE * (dpu_core)) >> 12,
&(pdpureg->ctlreg[dpu_core].addr_prof));
iowrite32(0x1, &(pdpureg->ctlreg[dpu_core].prof_en));
}
iowrite32(0x1, &(pdpureg->ctlreg[dpu_core].start));
#endif
// record the start time
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)
prun->time_start = ktime_get();
#else
prun->time_start = ktime_get().tv64;
#endif
prun->core_id = dpu_core;
dpudev.time_start[dpu_core] = prun->time_start;
spin_unlock_irqrestore(®lock, flags);
#ifndef CONFIG_DPU_COMPATIBLE_V1_07
// wait for the dpu task to be finished
ret = wait_event_interruptible_timeout(dpudev.waitqueue[dpu_core],
dpudev.intflg[dpu_core] == TRUE, timeout * USER_HZ);
dpudev.intflg[dpu_core] = FALSE;
if (ret == 0) {
dprint(PLEVEL_ERR,
"[PID %d][taskID %ld]Core %d Run timeout,failed to get finish interrupt!\n",
current->pid, prun->handle_id, dpu_core);
_show_debug_info();
_show_dpu_regs();
_dpu_regs_init(dpu_core);
} else if (ret < 0) {
dprint(PLEVEL_INFO, "program interrupted by user!\n");
dprint(PLEVEL_INFO, "[ret=%d][core=%d,status=%d]\n", ret, dpu_core,
dpudev.state[dpu_core]);
_dpu_regs_init(dpu_core);
} else {
dprint(PLEVEL_DBG, "[core %i]Task takes: %lld ns\n", dpu_core,
dpudev.time_end[dpu_core] - dpudev.time_start[dpu_core]);
prun->time_end = dpudev.time_end[dpu_core];
}
spin_lock_irqsave(&corelock, flags);
dpudev.state[dpu_core] = DPU_IDLE;
spin_unlock_irqrestore(&corelock, flags);
up(&dpudev.sem);
#endif
return ret > 0 ? 0 : (ret == 0 ? -ETIMEDOUT : ret);
}
#ifdef CONFIG_DPU_COMPATIBLE_V1_07
/**
* dpu_wait_task_finish - check if dpu finished its job
* @pkernel : contains task_id info
* */
int dpu_wait_task_finish(struct ioc_kernel_done_t *pkernel)
{
int ret, i;
unsigned long flags;
int dpu_core = DPU_CORE_NUM;
spin_lock_irqsave(&corelock, flags);
for (i = 0; i < DPU_CORE_NUM; i++) {
if (dpudev.task_id[i] == pkernel->handle_id) {
dpu_core = i;
break;
}
}
spin_unlock_irqrestore(&corelock, flags);
if (dpu_core == DPU_CORE_NUM) {
_show_debug_info();
return -EINVAL;
}
// wait for the dpu task to be finished
ret = wait_event_interruptible_timeout(dpudev.waitqueue[dpu_core],
dpudev.intflg[dpu_core] == TRUE, timeout * USER_HZ);
dpudev.intflg[dpu_core] = FALSE;
if (ret == 0) {
dprint(PLEVEL_ERR,
"[PID %d][taskID %ld]Core %d Run timeout,failed to get finish interrupt!\n",
current->pid, pkernel->handle_id, dpu_core);
_show_debug_info();
_show_dpu_regs();
_dpu_regs_init(dpu_core);
} else if (ret < 0) {
dprint(PLEVEL_INFO, "program interrupted by user!\n");
dprint(PLEVEL_INFO, "[ret=%d][core=%d,status=%d]\n", ret, dpu_core,
dpudev.state[dpu_core]);
_dpu_regs_init(dpu_core);
} else {
dprint(PLEVEL_DBG, "[core %i]finish time: %lld\n", dpu_core,
dpudev.time_end[dpu_core]);
pkernel->time_end = dpudev.time_end[dpu_core];
}
spin_lock_irqsave(&corelock, flags);
dpudev.state[dpu_core] = DPU_IDLE;
up(&dpudev.sem);
spin_unlock_irqrestore(&corelock, flags);
return 0;
}
#endif
static void get_port_counter(struct port_profile_t *counter)
{
#ifdef PORT_COUNTER
spin_lock(&portlock);
// ugly code for a special hardware.
counter->hp0_read_cnt = ioread32(port_counter + 0);
counter->hp0_write_cnt = ioread32(port_counter + 1);
counter->hp1_read_cnt = ioread32(port_counter + 2);
counter->hp1_write_cnt = ioread32(port_counter + 3);
counter->hp2_read_cnt = ioread32(port_counter + 4);
counter->hp2_write_cnt = ioread32(port_counter + 5);
counter->hp3_read_cnt = ioread32(port_counter + 6);
counter->hp3_write_cnt = ioread32(port_counter + 7);
counter->gp_read_cnt = ioread32(port_counter + 8);
counter->gp_write_cnt = ioread32(port_counter + 9);
counter->clock_cnt = ioread32(port_counter + 10) + ioread32(port_counter + 11) << 32;
spin_unlock(&portlock);
#endif
}
/**
* _flush_cache_range - flush memory range to ensure content is flushed to RAM
* @pmem: memory fresh structure contains start virtual address and size
*/
void _flush_cache_range(struct ioc_mem_fresh_t *pmem)
{
dma_sync_single_for_device(dev_handler, pmem->paddr, pmem->size, DMA_BIDIRECTIONAL);
}
/**
* _invalid_cache_range - invalid memory range to ensure following reading comes from RAM
* @pmem: memory fresh structure contains start virtual address and size
*/
void _invalid_cache_range(struct ioc_mem_fresh_t *pmem)
{
dma_sync_single_for_cpu(dev_handler, pmem->paddr, pmem->size, DMA_BIDIRECTIONAL);
}
/**
* dpu ioctl function
*/
static long dpu_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
int ret = 0;
dprint(PLEVEL_DBG, "[PID %i]name:%s,func:%s\n", current->pid, current->comm, __func__);
dprint(PLEVEL_INFO, "IOCTL CMD = 0x%x (1:Create;2:Alloc;3:Free;4:Run;6:Done)\n", cmd);
switch (cmd) {
case DPU_IOCTL_CREATE_KERNEL: { // create a kernel
struct ioc_kernel_manu_t t;
dpu_create_kernel(&t);
if (copy_to_user((void *)arg, &t, sizeof(struct ioc_kernel_manu_t)))
return -EINVAL;
break;
}
case DPU_IOCTL_MEM_ALLOC: { // memory alloc
struct ioc_mem_alloc_t t;
if (copy_from_user(&t, (void *)arg, sizeof(struct ioc_mem_alloc_t))) {
return -EINVAL;
}
if (t.size == 0)
return -EINVAL;
t.addr_phy = dpu_alloc_mem(t.size);
if (t.addr_phy == 0)
return -ENOMEM;
if (copy_to_user((void *)arg, &t, sizeof(struct ioc_mem_alloc_t)))
return -EINVAL;
break;
}
case DPU_IOCTL_MEM_FREE: { // memory free
struct ioc_mem_free_t t;
if (copy_from_user(&t, (void *)arg, sizeof(struct ioc_mem_free_t))) {
return -EINVAL;
}
ret = dpu_free_mem((void *)t.addr_phy);
break;
}
case DPU_IOCTL_RUN: { // run dpu
struct ioc_kernel_run_t t;
struct ioc_kernel_run2_t t2;
if (copy_from_user(&t, (void *)arg, sizeof(struct ioc_kernel_run_t))) {
return -EINVAL;
}
#ifdef CONFIG_DPU_v1_1_X
t2.handle_id = t.handle_id;
t2.addr_code = t.addr_code;
t2.addr0 = t.addr_io;
t2.addr1 = t.addr_weight;
#elif defined(CONFIG_DPU_v1_3_0)
t2.handle_id = t.handle_id;
t2.addr_code = t.addr_code;
t2.addr0 = t.addr0;
t2.addr1 = t.addr1;
t2.addr2 = t.addr2;
t2.addr3 = t.addr3;
t2.addr4 = t.addr4;
t2.addr5 = t.addr5;
t2.addr6 = t.addr6;
t2.addr7 = t.addr7;
#endif
ret = dpu_run(&t2);
t.time_start = t2.time_start;
t.time_end = t2.time_end;
t.core_id = t2.core_id;
if (copy_to_user((void *)arg, &t, sizeof(struct ioc_kernel_run_t)))
return -EINVAL;
break;
}
case DPU_IOCTL_RUN2: { // run dpu
struct ioc_kernel_run2_t t;
if (copy_from_user(&t, (void *)arg, sizeof(struct ioc_kernel_run2_t))) {
return -EINVAL;
}
ret = dpu_run(&t);
if (copy_to_user((void *)arg, &t, sizeof(struct ioc_kernel_run2_t)))
return -EINVAL;
break;
}
case DPU_IOCTL_RESET: { // reset dpu
_dpu_regs_init(DPU_CORE_NUM);
break;
}
#ifdef CONFIG_DPU_COMPATIBLE_V1_07
case DPU_IOCTL_DONE: { // wait for the dpu task done
struct ioc_kernel_done_t t;
if (copy_from_user(&t, (void *)arg, sizeof(struct ioc_kernel_done_t))) {
return -EINVAL;
}
ret = dpu_wait_task_finish(&t);
if ((ret != 0)
return ret;
if (copy_to_user((void *)arg, &t, sizeof(struct ioc_kernel_done_t)))
return -EINVAL;
break;
}
#endif
case DPU_IOCTL_DUMP_STATUS: {
return -EINVAL;
break;
}
case DPU_IOCTL_CREATE_TASK: { // create taskid
struct ioc_task_manu_t t;
dpu_create_task(&t);
if (copy_to_user((void *)arg, &t, sizeof(struct ioc_task_manu_t)))
return -EINVAL;
break;
}
case DPU_IOCTL_PORT_PROFILE: { // create taskid
struct port_profile_t t;
get_port_counter(&t);
if (copy_to_user((void *)arg, &t, sizeof(struct port_profile_t)))
return -EINVAL;
break;
}
case DPU_IOCTL_RUN_SOFTMAX: { // run softmax
{ // softmax calculation using SMFC
struct ioc_softmax_t t;
if (copy_from_user(&t, (void *)arg, sizeof(struct ioc_softmax_t))) {
return -EINVAL;
}
ret = dpu_softmax(&t);
}
break;
}
case DPU_IOCTL_CACHE_FLUSH: { // flush cache range by physical address
struct ioc_mem_fresh_t t;
if (copy_from_user(&t, (void *)arg, sizeof(struct ioc_mem_fresh_t)))
return -EINVAL;
_flush_cache_range(&t);
break;
}
case DPU_IOCTL_CACHE_INVALID: { // invalidate cache range by physical address
struct ioc_mem_fresh_t t;
if (copy_from_user(&t, (void *)arg, sizeof(struct ioc_mem_fresh_t)))
return -EINVAL;
_invalid_cache_range(&t);
break;
}
case DPU_IOCTL_SET_CACHEFLG: { // set cache flag
if (arg == 0 || arg == 1) {
cache = arg;
} else {
return -EINVAL;
}
break;
}
case DPU_IOCTL_RUN_FC: {
struct ioc_fc_t t;
if (copy_from_user(&t, (void *)arg, sizeof(struct ioc_fc_t))) {
return -EINVAL;
}
ret = dpu_fullconnect(&t);
break;
}
case DPU_IOCTL_RUN_RESIZE: {
run_resize_t t;
if (copy_from_user(&t, (void *)arg, sizeof(run_resize_t))) {
return -EINVAL;
}
//ret = dpu_resize(&t);
break;
}
case DPU_IOCTL_CAPS: { // dpu capabilities
if (copy_to_user((void *)arg, &dpu_caps, sizeof(dpu_caps_t))) {
return -EINVAL;
}
break;
}
case DPU_IOCTL_CAPS_CORE: { // dpu capabilities
if (copy_to_user((void *)arg, dpu_caps.p_dpu_info,
sizeof(dpu_info_t) * dpu_caps.dpu_cnt)) {
return -EINVAL;
}
break;
}
default: {
dprint(PLEVEL_INFO, "IOCTL CMD NOT SUPPORT!\n");
ret = -EPERM;
break;
}
}
return ret;
}
/**
* dpu interrupt service routine
* when a task finished, dpu will generate a interrupt,
* we can look up the IRQ No. to determine the channel
*/
irqreturn_t dpu_isr(int irq, void *data)
{
int i = 0;
unsigned long flags;
spin_lock_irqsave(®lock, flags);
// Determine which channel generated the interrupt
for (i = 0; i < DPU_CORE_NUM; i++) {
if (irq == dpudev.irq_no[i]) {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)
dpudev.time_end[i] = ktime_get(); // ioread32(&pdpureg[i]->prof_tstamp); //
#else
dpudev.time_end[i] = ktime_get().tv64;
#endif
// clear the interrupt
iowrite32(0, &pdpureg->ctlreg[i].prof_en);
iowrite32(0, &pdpureg->ctlreg[i].start);
iowrite32((1 << i), &pdpureg->intreg.icr);
udelay(1);
iowrite32(0, &pdpureg->intreg.icr);
_int_counter[i]++;
// set the finish flag,record the time,and notify the waiting queue
dpudev.intflg[i] = TRUE;
wake_up_interruptible(&dpudev.waitqueue[i]);
}
}
spin_unlock_irqrestore(®lock, flags);
return IRQ_HANDLED;
}
/**
* dpu_open - some initialization
*/
int dpu_open(struct inode *inode, struct file *filp)
{
dprint(PLEVEL_INFO, "[PID %i]name:%s,func:%s\n", current->pid, current->comm, __func__);
if (atomic_read(&dpudev.ref_count) == 0) {
int i;
int available_core = DPU_CORE_NUM;
for (i = 0; i < DPU_CORE_NUM; i++) {
if (coremask & (1 << i)) {
_dpu_regs_init(i);
dpudev.state[i] = DPU_IDLE;
} else {
dpudev.state[i] = DPU_DISABLE;
available_core--;
}
}
sema_init(&dpudev.sem, available_core);
}
atomic_inc(&dpudev.ref_count);
return 0;
}
/**
* dpu_release - dpu close function
* */
int dpu_release(struct inode *inode, struct file *filp)
{
struct list_head *plist, *nlist;
struct memblk_node *p;
dprint(PLEVEL_INFO, "[PID %i]name:%s,func:%s\n", current->pid, current->comm, __func__);
if (atomic_dec_and_test(&dpudev.ref_count)) {
down(&memblk_lock);
list_for_each_safe (plist, nlist, &head_alloc) {
p = list_entry(plist, struct memblk_node, list);
dma_free_coherent(dev_handler, p->size, (void *)p->virt_addr, p->phy_addr);
list_del(&p->list);
kfree(p);
}
INIT_LIST_HEAD(&head_alloc);
up(&memblk_lock);
INIT_LIST_HEAD(&dpudev.tasklist);
}
return 0;
}
/**
* dpu_read - not SUPPORT now
*/
static ssize_t dpu_read(struct file *filp, char __user *buf, size_t count, loff_t *ppos)
{
dprint(PLEVEL_INFO, "[PID %i]name:%s,func:%s\n", current->pid, current->comm, __func__);
return 0;
}
/**
* dpu_write - not SUPPORT now
*/
ssize_t dpu_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos)
{
dprint(PLEVEL_INFO, "[PID %i]name:%s,func:%s\n", current->pid, current->comm, __func__);
return 0;
}
/**
* dpu mmap function
*/
static int dpu_mmap(struct file *file, struct vm_area_struct *vma)
{
size_t size = vma->vm_end - vma->vm_start;
if (!cache)
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, size, vma->vm_page_prot)) {
return -EAGAIN;
}
return 0;
}
/*dpu file operation define */
static struct file_operations dev_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = dpu_ioctl,
.open = dpu_open,
.release = dpu_release,
.read = dpu_read,
.write = dpu_write,
.mmap = dpu_mmap,
};
/**
* _dpu_devstate_init - dpu device state initialize
* @channel: the dpu channel [0,DPU_CORE_NUM) need to be initialize,
* set all channel if the para is DPU_CORE_NUM
*/
static inline void _dpu_devstate_init(int channel)
{
int i;
if (channel == DPU_CORE_NUM) {
dpudev.dev.name = DEVICE_NAME;
dpudev.dev.minor = MISC_DYNAMIC_MINOR;
dpudev.dev.fops = &dev_fops;
dpudev.dev.mode = S_IWUGO | S_IRUGO;
atomic_set(&dpudev.core, DPU_CORE_NUM);
sema_init(&dpudev.sem, DPU_CORE_NUM);
INIT_LIST_HEAD(&dpudev.tasklist);
for (i = 0; i < DPU_CORE_NUM; i++) {
init_waitqueue_head(&dpudev.waitqueue[i]);
dpudev.state[i] = DPU_IDLE;
dpudev.pid[i] = 0;
dpudev.task_id[i] = 0;
dpudev.time_start[i] = 0;
dpudev.time_end[i] = 0;
}
} else if ((channel >= 0) && (channel < DPU_CORE_NUM)) {
init_waitqueue_head(&dpudev.waitqueue[channel]);
dpudev.state[channel] = DPU_IDLE;
dpudev.pid[channel] = 0;
dpudev.task_id[channel] = 0;
dpudev.time_start[channel] = 0;
dpudev.time_end[channel] = 0;
}
}
//////////////////////////////////////////////////////////
/**
* proc_write - dpu proc file write function
* you can set debug level by "echo levelnum > /proc/dpu_info"
*/
static ssize_t proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *f_pos)
{
int flg_memblk_reset = 0;
char *kbuf = kzalloc((count + 1), GFP_KERNEL);
if (!kbuf)
return -ENOMEM;
if (copy_from_user(kbuf, buffer, count)) {
kfree(kbuf);
return -EFAULT;
}
sscanf(kbuf, "%d%d", &debuglevel, &flg_memblk_reset);
dprint(PLEVEL_DBG, "debug lever set to %d", debuglevel);
if (flg_memblk_reset) {
INIT_LIST_HEAD(&head_alloc);
}
return count;
}
/**
* proc_show_dpuinfo - dpu proc file show infomation function:
* type "cat /proc/dpu_info " to get dpu driver
*information
*/
static int proc_show_dpuinfo(struct seq_file *file, void *v)
{
int i = 0, j = 0;
uint32_t MemInUse = 0;
unsigned long flags;
struct list_head *plist;
struct memblk_node *p;
seq_printf(file, "[DPU Debug Info]\n");
seq_printf(file, "%-10s\t: %d\n", "Debug level", debuglevel);
for (i = 0; i < DPU_CORE_NUM; i++) {
seq_printf(file, "Core %d schedule : %d\n", i, _run_counter[i]);
seq_printf(file, "Core %d interrupt: %d\n", i, _int_counter[i]);
}
seq_printf(file, "\n");
seq_printf(file, "[DPU Resource]\n");
spin_lock_irqsave(&corelock, flags);
for (i = 0; i < DPU_CORE_NUM; i++) {
seq_printf(file, "%-10s\t: %d\n", "DPU Core", i);
seq_printf(file, "%-10s\t: %s\n", "State", _get_state_str(i));
seq_printf(file, "%-10s\t: %d\n", "PID", (dpudev.pid[i]));
seq_printf(file, "%-10s\t: %ld\n", "TaskID", (dpudev.task_id[i]));
seq_printf(file, "%-10s\t: %lld\n", "Start", dpudev.time_start[i]);
seq_printf(file, "%-10s\t: %lld\n", "End", dpudev.time_end[i]);
seq_printf(file, "\n");
}
spin_unlock_irqrestore(&corelock, flags);
spin_lock_irqsave(®lock, flags);
seq_printf(file, "[DPU Registers]\n");
seq_printf(file, "%-10s\t: 0x%.8x\n", "VER", pdpureg->pmu.version);
seq_printf(file, "%-10s\t: 0x%.8x\n", "RST", pdpureg->pmu.reset);
seq_printf(file, "%-10s\t: 0x%.8x\n", "ISR", pdpureg->intreg.isr);
seq_printf(file, "%-10s\t: 0x%.8x\n", "IMR", pdpureg->intreg.imr);
seq_printf(file, "%-10s\t: 0x%.8x\n", "IRSR", pdpureg->intreg.irsr);
seq_printf(file, "%-10s\t: 0x%.8x\n", "ICR", pdpureg->intreg.icr);
seq_printf(file, "\n");
for (i = 0; i < DPU_CORE_NUM; i++) {
seq_printf(file, "%-8s\t: %d\n", "DPU Core", i);
seq_printf(file, "%-8s\t: 0x%.8x\n", "HP_CTL", pdpureg->ctlreg[i].hp_ctrl);
seq_printf(file, "%-8s\t: 0x%.8x\n", "ADDR_IO", pdpureg->ctlreg[i].addr_io);
seq_printf(file, "%-8s\t: 0x%.8x\n", "ADDR_WEIGHT", pdpureg->ctlreg[i].addr_weight);
seq_printf(file, "%-8s\t: 0x%.8x\n", "ADDR_CODE", pdpureg->ctlreg[i].addr_code);
seq_printf(file, "%-8s\t: 0x%.8x\n", "ADDR_PROF", pdpureg->ctlreg[i].addr_prof);
seq_printf(file, "%-8s\t: 0x%.8x\n", "PROF_VALUE", pdpureg->ctlreg[i].prof_value);
seq_printf(file, "%-8s\t: 0x%.8x\n", "PROF_NUM", pdpureg->ctlreg[i].prof_num);
seq_printf(file, "%-8s\t: 0x%.8x\n", "PROF_EN", pdpureg->ctlreg[i].prof_en);
seq_printf(file, "%-8s\t: 0x%.8x\n", "START", pdpureg->ctlreg[i].start);
#if defined(CONFIG_DPU_v1_3_0)
for (j = 0; j < 8; j++) {
seq_printf(file, "%-8s%d\t: 0x%.8x\n", "COM_ADDR_L", j,
pdpureg->ctlreg[i].com_addr[j * 2]);
seq_printf(file, "%-8s%d\t: 0x%.8x\n", "COM_ADDR_H", j,
pdpureg->ctlreg[i].com_addr[j * 2 + 1]);
}
#endif
seq_printf(file, "\n");
}
spin_unlock_irqrestore(®lock, flags);
seq_printf(file, "[Memory Resource]\n");
down(&memblk_lock);
list_for_each(plist, &head_alloc) {
p = list_entry(plist, struct memblk_node, list);
MemInUse += p->size;
}
MemInUse /= 1024 * 1024;
seq_printf(file, "%-8s\t: %8d MB\n", "MemInUse", MemInUse);
if (PLEVEL_DBG >= debuglevel) {
seq_printf(file, "************** memory in use **************\n");
list_for_each(plist, &head_alloc) {
p = list_entry(plist, struct memblk_node, list);
seq_printf(file, "addr:0x%.8lx,size:0x%.8lx,pid:%8d\n", p->virt_addr,
p->size, p->pid);
}
}
up(&memblk_lock);
_show_ext_regs(file, accipmask);
return 0;
}
static int proc_key_open(struct inode *inode, struct file *file)
{
single_open(file, proc_show_dpuinfo, NULL);
return 0;
}
// dpu proc debug file structure
static struct file_operations proc_file_ops = {
.owner = THIS_MODULE,
.open = proc_key_open,
.write = proc_write,
.read = seq_read,
.release = single_release,
};
uint32_t field_mask_value(uint32_t val, uint32_t mask)
{
int i;
int max_bit = sizeof(uint32_t) * 8;
int lowest_set_bit = max_bit - 1;
/* Iterate through each bit of mask */
for (i = 0; i < max_bit; i++) {
/* If current bit is set */
if ((mask >> i) & 1) {
lowest_set_bit = i;
break;
}
}
return (val & mask) >> lowest_set_bit;
};
static const char *dts_node_prefix[] = {
"xilinx,",
"xilinx, ",
"Xilinx,",
"Xilinx, ",
"deephi,",
"deephi, ",
"Deephi,",
"Deephi, ",
};
struct device_node *dpu_compatible_node(const char *compat)
{
int idx=0, max=0;
char dst_node[255];
struct device_node *pdpu_node = NULL;
if (strlen(compat)>128) {
return NULL;
}
max = sizeof(dts_node_prefix)/sizeof(char *);
for (idx=0; idx<max; idx++) {
memset(dst_node, 0x0, sizeof(dst_node));
sprintf(dst_node, "%s%s", dts_node_prefix[idx], compat);
pdpu_node = of_find_compatible_node(NULL, NULL, dst_node);
if (pdpu_node)
break;
}
return pdpu_node;
};
/**
* dpu_probe - platform probe method for the dpu driver
* @pdev: Pointer to the platform_device structure
*
* This function initializes the driver data structures and the hardware.
*
* @return: 0 on success and error value on failure
*/
static int dpu_probe(struct platform_device *pdev)
{
int ret, i;
void *prop;
struct device_node *pdpu_node, *dpucore_node;
struct resource *res;
unsigned long base_addr_dtsi = 0 ;
uint32_t signature_length = 0;
uint32_t signature_field = 0;
uint32_t signature_temp;
uint32_t *signature_va;
uint32_t irqs[DPU_CORE_MAX];
dpu_info_t dpu_info;
dprint(PLEVEL_INFO, "[PID %i]name:%s,func:%s\n", current->pid, current->comm, __func__);
dev_handler = &(pdev->dev);
dpucore_node = dpu_compatible_node("dpucore");
pdpu_node = dpu_compatible_node("dpu");
if (!pdpu_node) {
dpr_init("Not found DPU device node!\n");
return -ENXIO;
} else {
prop = of_get_property(pdpu_node, "base-addr", NULL);
if (prop) {
base_addr_dtsi = of_read_ulong(prop, 1);
}
if (base_addr_dtsi) {
dpr_init("Found DPU signature addr = 0x%lx in device-tree\n", base_addr_dtsi);
signature_addr = base_addr_dtsi + 0x00F00000;
}
if (signature_addr != SIG_BASE_NULL) {
dpr_init("Checking DPU signature at addr = 0x%lx, \n", signature_addr);
signature_va =
ioremap((phys_addr_t)signature_addr, 1 * sizeof(signature_field));
signature_field = ioread32(signature_va);
}
if ((signature_field & SIG_MAGIC_MASK) == SIG_MAGIC) {
dpu_caps.signature_valid = 1;
signature_length = field_mask_value(signature_field, SIG_SIZE_MASK);
iounmap(signature_va);
signature_va = ioremap((phys_addr_t)signature_addr,
signature_length * sizeof(signature_field));
//reserved field checking.
signature_temp = 0;
for (i = 0; i < VER_MAX_ENTRY; i++) {
signature_field = ioread32(signature_va + i);
signature_temp =
field_mask_value(signature_field, VER_RESERVERD[i]);
if (signature_temp != 0) {
dpr_init(
"Unknown reserved field found in DPU signature at offset: %#X.\n",
i * 4);
dpr_init(
"Try to update DPU driver to the latest version to resolve this issue.\n");
return -ENXIO;
}
}
// offset 1
signature_field = ioread32(signature_va + 1);
sprintf(dpu_caps.hw_timestamp, "20%02d-%02d-%02d %02d:%02d:00",
field_mask_value(signature_field, YEAR_MASK),
field_mask_value(signature_field, MONTH_MASK),
field_mask_value(signature_field, DATE_MASK),
field_mask_value(signature_field, HOUR_MASK),
field_mask_value(signature_field, BIT_VER_MASK) * 15);
dpu_info.dpu_freq = field_mask_value(signature_field, FREQ_MASK);
// offset 2
signature_field = ioread32(signature_va + 2);
dpu_caps.irq_base0 = field_mask_value(signature_field, PS_INTBASE0_MASK);
dpu_caps.irq_base1 = field_mask_value(signature_field, PS_INTBASE1_MASK);
// offset 3
signature_field = ioread32(signature_va + 3);
dpu_caps.hp_width = field_mask_value(signature_field, HP_WIDTH_MASK);
dpu_caps.data_width = field_mask_value(signature_field, DATA_WIDTH_MASK);
dpu_caps.bank_group = field_mask_value(signature_field, BANK_GROUP_MASK);
dpu_info.dpu_arch = field_mask_value(signature_field, DPU_ARCH_MASK);
dpu_info.dpu_target = field_mask_value(signature_field, DPU_TARGET_MASK);
dpu_caps.dpu_cnt = field_mask_value(signature_field, DPU_CORENUM_MASK);
if (dpu_caps.hp_width >= DPU_HP_WIDTH_RESERVE) {
dpr_init("Invalid hp width '%d' found in DPU signature.\n",
dpu_caps.hp_width);
return -ENXIO;
}
if (dpu_caps.data_width >= DPU_DATA_WIDTH_RESERVE) {
dpr_init("Invalid data width '%d' found in DPU signature.\n",
dpu_caps.data_width);
return -ENXIO;
}
if (dpu_caps.bank_group >= DPU_BANK_GROUP_RESERVE ||
DPU_BANK_GROUP_1 == dpu_caps.bank_group) {
dpr_init("Invalid bank group '%d' found in DPU signature.\n",
dpu_caps.bank_group);
return -ENXIO;
}
// offset 4
signature_field = ioread32(signature_va + 4);
for (i = 0; i < 8; i++) {
signature_temp = field_mask_value(signature_field, 0xF << (4 * i));
irqs[i] = signature_temp & 0x8 ?
(signature_temp & 0x7) + dpu_caps.irq_base1 :
(signature_temp & 0x7) + dpu_caps.irq_base0;
}
// offset 5
signature_field = ioread32(signature_va + 5);
for (i = 0; i < 8; i++) {
signature_temp = field_mask_value(signature_field, 0xF << (4 * i));
irqs[8 + i] = signature_temp & 0x8 ?
(signature_temp & 0x7) + dpu_caps.irq_base1 :
(signature_temp & 0x7) + dpu_caps.irq_base0;
}
if (dpu_caps.dpu_cnt > 0) {
dpu_caps.p_dpu_info =
kzalloc(sizeof(dpu_info_t) * dpu_caps.dpu_cnt, GFP_ATOMIC);
if (!dpu_caps.p_dpu_info) {
dpr_init("kzalloc fail!\n");
return -ENXIO;
} else {
int idx;
for (idx = 0; idx < dpu_caps.dpu_cnt; idx++) {
(*(dpu_caps.p_dpu_info + idx)).dpu_arch =
dpu_info.dpu_arch;
(*(dpu_caps.p_dpu_info + idx)).dpu_target =
dpu_info.dpu_target;
(*(dpu_caps.p_dpu_info + idx)).dpu_freq =
dpu_info.dpu_freq;
(*(dpu_caps.p_dpu_info + idx)).irq = irqs[idx];
if ((*(dpu_caps.p_dpu_info + idx)).dpu_arch >
DPU_ARCH_RESERVE) {
dpr_init(
"Unknown DPU arch type '%d' found in DPU signature.\n",
(*(dpu_caps.p_dpu_info + idx))
.dpu_arch);
dpr_init(
"Try to update DPU driver to the latest version to resolve this issue.\n");
return -ENXIO;
}
if ((*(dpu_caps.p_dpu_info + idx)).dpu_target >
DPU_TARGET_RESERVE) {
dpr_init(
"Unknown DPU target type '%d' found in DPU signature.\n",
(*(dpu_caps.p_dpu_info + idx))
.dpu_target);
dpr_init(
"Try to update DPU driver to the latest version to resolve this issue.\n");
return -ENXIO;
}
}
}
} else {
dpr_init(
"Error of no DPU core found in current configuration of DPU IP!\n");
return -ENXIO;
}
// offset 6
signature_field = ioread32(signature_va + 6);
dpu_caps.avgpool.version = field_mask_value(signature_field, AVGPOOL_MASK);
dpu_caps.conv_depthwise.version =
field_mask_value(signature_field, CONV_DEPTHWISE_MASK);
dpu_caps.relu_leaky.version =
field_mask_value(signature_field, RELU_LEAKY_MASK);
dpu_caps.relu_p.version = field_mask_value(signature_field, RELU_P_MASK);
// offset 7
signature_field = ioread32(signature_va + 7);
dpu_caps.serdes_nonlinear.version =
field_mask_value(signature_field, SERDES_NONLINEAR_MASK);
// offset 9
signature_field = ioread32(signature_va + 9);
dpu_caps.hdmi.enable = field_mask_value(extension, DPU_EXT_HDMI);
dpu_caps.hdmi.version = field_mask_value(signature_field, HDMI_VER_MASK);
dpu_caps.hdmi.valid = field_mask_value(signature_field, HDMI_VLD_MASK);
dpu_caps.hdmi.enable &= dpu_caps.hdmi.valid;
signature_temp = field_mask_value(signature_field, HDMI_IRQ_MASK);
dpu_caps.hdmi.irq = signature_temp & 0x8 ?
(signature_temp & 0x7) + dpu_caps.irq_base1 :
(signature_temp & 0x7) + dpu_caps.irq_base0;
dpu_caps.bt1120.enable = field_mask_value(extension, DPU_EXT_BT1120);
dpu_caps.bt1120.version =
field_mask_value(signature_field, BT1120_VER_MASK);
dpu_caps.bt1120.valid = field_mask_value(signature_field, BT1120_VLD_MASK);
dpu_caps.bt1120.enable &= dpu_caps.bt1120.valid;
signature_temp = field_mask_value(signature_field, BT1120_IRQ_MASK);
dpu_caps.bt1120.irq = signature_temp & 0x8 ?
(signature_temp & 0x7) + dpu_caps.irq_base1 :
(signature_temp & 0x7) + dpu_caps.irq_base0;
dpu_caps.fullconnect.enable =
field_mask_value(extension, DPU_EXT_FULLCONNECT);
dpu_caps.fullconnect.version =
field_mask_value(signature_field, FC_VER_MASK);
dpu_caps.fullconnect.valid = field_mask_value(signature_field, FC_VLD_MASK);
dpu_caps.fullconnect.enable &= dpu_caps.fullconnect.valid;
signature_temp = field_mask_value(signature_field, FC_IRQ_MASK);
dpu_caps.fullconnect.irq =
signature_temp & 0x8 ? (signature_temp & 0x7) + dpu_caps.irq_base1 :
(signature_temp & 0x7) + dpu_caps.irq_base0;
dpu_caps.softmax.enable = field_mask_value(extension, DPU_EXT_SOFTMAX);
dpu_caps.softmax.version =
field_mask_value(signature_field, SOFTMAX_VER_MASK);
dpu_caps.softmax.valid =
field_mask_value(signature_field, SOFTMAX_VLD_MASK);
dpu_caps.softmax.enable &= dpu_caps.softmax.valid;
signature_temp = field_mask_value(signature_field, SOFTMAX_IRQ_MASK);
dpu_caps.softmax.irq = signature_temp & 0x8 ?
(signature_temp & 0x7) + dpu_caps.irq_base1 :
(signature_temp & 0x7) + dpu_caps.irq_base0;
// offset 10
signature_field = ioread32(signature_va + 10);
dpu_caps.resize.enable = field_mask_value(extension, DPU_EXT_RESIZE);
dpu_caps.resize.version =
field_mask_value(signature_field, RESIZE_VER_MASK);
dpu_caps.resize.valid = field_mask_value(signature_field, RESIZE_VLD_MASK);
dpu_caps.resize.enable &= dpu_caps.resize.valid;
signature_temp = field_mask_value(signature_field, RESIZE_IRQ_MASK);
dpu_caps.resize.irq = signature_temp & 0x8 ?
(signature_temp & 0x7) + dpu_caps.irq_base1 :
(signature_temp & 0x7) + dpu_caps.irq_base0;
dpr_init("DPU signature checking done!\n");
dpu_caps.reg_base = DPU_BASE;
dpu_caps.reg_size = DPU_SIZE;
DPU_CORE_NUM = dpu_caps.dpu_cnt;
} else if (base_addr_dtsi == signature_addr) {
dpr_init("Invalid 'signature-addr' value specified in DPU device tree, please check.\n");
return -ENXIO;
} else {
dpr_init("DPU signature NOT found, fallback to device-tree.\n");
of_property_read_u32(pdpu_node, "core-num", &DPU_CORE_NUM);
dpu_caps.dpu_cnt = DPU_CORE_NUM;
if (dpu_caps.dpu_cnt > 0) {
dpu_caps.p_dpu_info =
kzalloc(sizeof(dpu_info_t) * dpu_caps.dpu_cnt, GFP_ATOMIC);
if (!dpu_caps.p_dpu_info) {
dpr_init("kzalloc fail!\n");
return -ENXIO;
} else {
int idx;
for (idx = 0; idx < dpu_caps.dpu_cnt; idx++) {
(*(dpu_caps.p_dpu_info + idx)).dpu_target =
DPU_TARGET_V1_1_3; //default to target:1.1.3 due to massively deployed
}
}
} else {
dpr_init(
"Error of no DPU core found in current configuration of DPU IP!\n");
return -ENXIO;
}
}
}
if ((DPU_CORE_NUM == 0) || (DPU_CORE_NUM > MAX_CORE_NUM)) {
dpr_init("Core number %d invalid!\n", DPU_CORE_NUM);
return -EINVAL;
}
RAM_SIZE = PROF_RAM_SIZE * DPU_CORE_NUM;
RAM_BASEADDR_VIRT = dma_alloc_coherent(dev_handler, RAM_SIZE, &RAM_BASEADDR, GFP_KERNEL);
// map the dpu Register
if (dpu_caps.signature_valid) {
res = kzalloc(sizeof(struct resource), GFP_ATOMIC);
res->start = dpu_caps.reg_base;
res->end = dpu_caps.reg_base + dpu_caps.reg_size - 1;
} else {
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
}
if (res) {
pdpureg = (DPUReg *)ioremap(res->start, res->end - res->start + 1);
if (!pdpureg) {
dpr_init("Map DPU registers error!\n");
return -ENXIO;
}
if (dpu_caps.signature_valid) {
kfree(res);
}
} else {
dpr_init("Not found DPU reg resources!\n");
}
_dpu_regs_init(DPU_CORE_NUM);
_dpu_devstate_init(DPU_CORE_NUM);
// memory structure init
sema_init(&memblk_lock, 1);
INIT_LIST_HEAD(&head_alloc);
spin_lock_init(&tasklstlock);
spin_lock_init(&idlock);
spin_lock_init(&taskidlock);
spin_lock_init(&corelock);
spin_lock_init(®lock);
// register interrupt service routine for DPU
for (i = 0; i < DPU_CORE_NUM; i++) {
dpudev.irq_no[i] = dpucore_node? irq_of_parse_and_map(dpucore_node, i): platform_get_irq(pdev, i);
if (dpudev.irq_no[i] < 0) {
dprint(PLEVEL_ERR, "IRQ resource not found for DPU core %d\n", i);
return dpudev.irq_no[i];
}
ret = request_irq(dpudev.irq_no[i], (irq_handler_t)dpu_isr, 0, "dpu_isr", NULL);
if (ret != 0) {
dpr_init("Request IRQ %d failed!\n", dpudev.irq_no[i]);
return ret;
} else {
}
}
init_ext(pdpu_node); // initialize extent modules
// create the proc file entry
proc_file = proc_create(PROCFNAME, 0644, NULL, &proc_file_ops);
// Register the dpu device
return misc_register(&dpudev.dev);
}
/**
* dpu_remove - platform remove method for the dpu driver
* @pdev: Pointer to the platform_device structure
*
* This function is called if a device is physically removed from the system or
* if the driver module is being unloaded. It frees all resources allocated to
* the device.
*
* @return: 0 on success and error value on failure
*/
static int dpu_remove(struct platform_device *pdev)
{
int i;
dprint(PLEVEL_INFO, "[PID %i]name:%s,func:%s\n", current->pid, current->comm, __func__);
if (dpu_caps.p_dpu_info) {
kfree(dpu_caps.p_dpu_info);
}
if (RAM_BASEADDR_VIRT) {
dma_free_coherent(dev_handler, RAM_SIZE, (void *)RAM_BASEADDR_VIRT, RAM_BASEADDR);
}
misc_deregister(&dpudev.dev);
remove_proc_entry(PROCFNAME, NULL);
exit_ext(); // clear extend mdoules
for (i = 0; i < DPU_CORE_NUM; i++)
free_irq(dpudev.irq_no[i], NULL);
iounmap(pdpureg);
return 0;
}
static const struct of_device_id dpu_dt_ids[] = { { .compatible = "deephi, dpu" },
{ .compatible = "deephi,dpu" },
{ .compatible = "xilinx, dpu" },
{ .compatible = "xilinx,dpu" },
{ /* end of table */ } };
static struct platform_driver dpu_drv = {
.driver = {
.name = "dpu",
.of_match_table = dpu_dt_ids,
},
.probe = dpu_probe,
.remove = dpu_remove,
};
/*==========================================================*/
/**
* dpu initialize function
*/
static int __init dpu_init(void)
{
dprint(PLEVEL_INFO, "[PID %i]name:%s,func:%s\n", current->pid, current->comm, __func__);
return platform_driver_register(&dpu_drv);
}
/**
* dpu uninstall function
*/
static void __exit dpu_exit(void)
{
dprint(PLEVEL_INFO, "[PID %i]name:%s,func:%s\n", current->pid, current->comm, __func__);
platform_driver_unregister(&dpu_drv);
}
/*==========================================================*/
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Xilinx");
module_init(dpu_init);
module_exit(dpu_exit);
<file_sep>/README.md
# PYNQ-Z2_DPU_TRD
Reference: https://github.com/alexhegit/zc702_dpu140_trd
# Running Yolo on PYNQ-Z2 ( DPU v1.4)


# Quick Start
## Prerequisites
- Xilinx Vivado v2018.3
- Xilinx Petalinux v2018.3
- Xilinx DNNDK v3.0
- Xilinx DPU IP v1.4.0
# File tree in this git project

## Vivado Design Suite
1. Create a new project for the PYNQ-Z2.
2. Add the DPU IP to the project.
3. Use a .tcl script to hook up the block design in the Vivado IP integrator.
4. Examine the DPU configuration and connections.
5. Generate the bitstream
6. Export the .hdf file.
## PetaLinux
1. Create a new PetaLinux project with the "Template Flow."
2. Import the .hdf file from the Vivado Design Suite.
3. Add some necessary packages to the root filesystem.
4. Update the device-tree to add the DPU.
5. Build the project.
6. Create a boot image.
## Application
1. Install DNNDK v3.0
2. Run the yolov3 application
# Building the Hardware Platform in the Vivado Design Suite
## Step 1: Create a project in the Vivado Design Suite
1. Create a new project based on the PYNQ-Z2 boards files
- Project Name: **pynq_dpu**
- Project Location: `<PROJ ROOT>/vivado`

- Do not specify sources
- Select **PYNQ-Z2 Evaluation Platform**

2. Click **Finish**.
## Step 2: Add the DPU IP repository to the IP catalog
1. Click **Setting** in the Project Manager.
2. Click **IP Repository** in the Project Settings.
3. Select **Add IP Repository** into DPU IP directory. ( `<PROJ ROOT>/vivado/dpu_ip_v140` )
4. Click **OK**.

## Step 3: Create the Block Design
1. Open the TCL Console tab, `cd` to the `<PROJ ROOT>/vivado` directory, and source the `.tcl` script :
```
source design_1.tcl
```

2. Click **Regenerate Layout** in the Block Design

## Step 4: Examine the DPU configuration and connections
The details in step by step can refer to PG338 and here just some highlight attentions.
- S_AXI Clock @ 100MHz
- M_AXI Clock @ 150MHz for DPU and Clock @ 300MHz for DPU DSP
- DPU IRQ connect to IRQ_F2P[0]

- DPU S_AXI address set 0x4F000000 - 0x4FFFFFFF(16M)

When the block design is complete, right-click on the **design_1** in the Sources tab and select **Create HDL Wrapper**.

## Step 5: Generate the bitstream
1. Click **Generate Bitstream**.
The FPGA resource for DPU 1152 on PYNQ-Z2

## Step 6: Export the .hdf file.
1. Click **File** > **Export** > **Export Hardware**.
2. Make sure to include the bitstream.
3. Click **OK**.

You can find the HDF from the path `<PROJ ROOT>/pynq_dpu/vivado/pynq_dpu/project_1.sdk`
# Generating the Linux Platform in PetaLinux
You may export the HDF(*.hdf) from Vivado projcet to Petalinux project here
## Step 1: Create a PetaLinux project
```
source /opt/pkg/petalinux/2018.3/settings.sh
cd <PROJ ROOT>
petalinux-create -t project -n pynq_dpu --template zynq
```
## Step 2: Import the .hdf file
```
$cd pynq_dpu
$petalinux-config --get-hw-description=[PATH to vivado HDF file]
```
Set SD rootfs mode Petalinux-config Menu run auto after imported HDF.
Please set SD rootfs by :
**Image Packaging Configuration** --> **Root filesystem type (SD card)** --> **SD card**

## Step 3: Copy recipes to the PetaLinux project
1. Add a recipe to add the DPU utilities, libraries, and header files into the root file system.
```
$cp -rp <PROJ ROOT>/petalinux/meta-user/recipes-apps/dnndk/ project-spec/meta-user/recipes-apps/
```
2. Add a recipe to build the DPU driver kernel module.
```
$cp -rp <PROJ ROOT>/petalinux/meta-user/recipes-modules project-spec/meta-user
```
3. Add a recipe to create hooks for adding an “austostart” script to run automatically during Linux init.
```
$cp -rp <PROJ ROOT>/petalinux/meta-user/recipes-apps/autostart project-spec/meta-user/recipes-apps/
```
4. Add a `bbappend` for the base-files recipe to do various things like auto insert the DPU driver, auto mount the SD card, modify the PATH, etc.
```
$cp -rp <PROJ ROOT>/petalinux/meta-user/recipes-core/base-files/ project-spec/meta-user/recipes-core/
```
5. Add DPU to the device tree
At the bottom of `project-spec/meta-user/recipes-bsp/device-tree/files/system-user.dtsi`, add the following text:
```
/include/ "system-conf.dtsi"
/ {
amba_pl: amba_pl {
#address-cells = <1>;
#size-cells = <1>;
compatible = "simple-bus";
ranges ;
dpu_eu_0: dpu_eu@4f000000 {
clock-names = "s_axi_aclk", "dpu_2x_clk", "m_axi_dpu_aclk";
clocks = <&misc_clk_0>, <&misc_clk_1>, <&misc_clk_2>;
compatible = "xlnx,dpu-eu-2.0";
interrupt-names = "dpu_interrupt";
interrupt-parent = <&intc>;
interrupts = <0 29 4>;
reg = <0x4f000000 0x1000000>;
};
misc_clk_0: misc_clk_0 {
#clock-cells = <0>;
clock-frequency = <100000000>;
compatible = "fixed-clock";
};
misc_clk_1: misc_clk_1 {
#clock-cells = <0>;
clock-frequency = <300000000>;
compatible = "fixed-clock";
};
misc_clk_2: misc_clk_2 {
#clock-cells = <0>;
clock-frequency = <150000000>;
compatible = "fixed-clock";
};
};
};
&dpu_eu_0{
compatible = "xilinx,dpu";
};
```
Note: the **reg = <0x4f000000 0x1000000>** should be match with the DPU S_AXI address set **0x4F000000 ** ( Vivado : Step 4)
## Step 4: Configure PetaLinux to install the `dnndk` files
```
$vi project-spec/meta-user/recipes-core/images/petalinux-image.bbappend
```
Add the following lines:
```
IMAGE_INSTALL_append = " dnndk"
IMAGE_INSTALL_append = " autostart"
IMAGE_INSTALL_append = " dpu"
```
## Step 5: Configure the rootfs
Use the following to open the top-level PetaLinux project configuration GUI.
```
$petalinux-config -c rootfs
```
1. Enable each item listed below:
**Filesystem Packages ->**
- console -> utils -> pkgconfig -> pkgconfig
**Petalinux Package Groups ->**
- opencv
- opencv-dev
- v4lutils
- v4lutils-dev
- self-hosted
- self-hosted-dev
- x11
**Apps ->**
- autostart
**Modules ->**
- dpu
2. **Exit** and **save** the changes.
## Step 6: Build the kernel and root file system
```
$petalinux-build
```
## Step 7: Create the boot image
```
$cd images/linux
petalinux-package --boot --fsbl --u-boot --fpga
```
## Step 8: Boot the linux image
1. Prepare SD card and partion it by `gparted `.
```
$sudo gparted
```
If `gparted` is not installed, enter
```
$sudo apt-get install gparted
```
Select SD card in `gparted `

Umount the SD card and delete the existing partitions on the SD card


Unallocated in Gparted

Right click on the allocated space and create a new partition according to the settings below

The first is BOOT partioin in FAT32
Free Space Proceeding (MiB): 4, New Size (MiB) : 1024, File System : FAT32, Label : BOOT

The second is ROOTFS partion in ext4
Free Space Proceeding (MiB): 0, Free Space Following(MiB): 0, File System : ext4, Label :ROOTFS

Turn off `gparted ` and mount the two partitions you just formatted.
Copy images files to SD card(BOOT.bin and image.ub to BOOT partion and extract rootfs.tar.bz2 into ROOTFS partion.)
```
$sudo tar xzf rootfs.tar.gz -C /media/{user}/ROOTFS/
$sync
$cp BOOT.bin image.ub /media/{user}/BOOT
```
2. Boot the PYNQ-Z2 with this image

PYNQ-Z2 Board Setup
1. Set the **Boot** jumper to the SD position. (This sets the board to boot from the Micro-SD card)
2. To power the board from the micro USB cable, set the Power jumper to the USB position
3. Insert the Micro SD card loaded with the image into the Micro SD
4. Connect the **USB cable** to your PC/Laptop, and to the PROG - UART MicroUSB port on the board
5. Connect the **Ethernet cable** to your PC/Laptop, and to the RJ45 port on the board
6. Turn on the PYNQ-Z2 board

Opening a USB Serial Terminal
Installed **Tera Term**(or **Putty**) on your computer.
To open a terminal, you will need to know the **COM port** for the board.

**Setup** -> **Serial Port**

Full terminal Settings:
• baud rate: 115200 bps
• data bit: 8
• no parity
• stop bit: 1

Login by enter **root**
Password : **<PASSWORD>**

# Application #
Before Running the application , you should copy DNNDK Tools and Application to the Evaluation Board
The steps below illustrate how to setup DNNDK running environment for DNNDK package is stored on a Windows system.
Download and install **MobaXterm** on Windows system. MobaXterm is a terminal for Windows, and is available online at https://mobaxterm.mobatek.net/.
Setup the address IP on the Board in the **tera term**, enter below
```
$ifconfig eth0 192.168.0.10
```

Assign your laptop/PC a static IP address
- Double click on the network interface to open it, and click on Properties
- Select Internet Protocol Version 4 (TCP/IPv4) and click Properties
- Set the Ip address to **192.168.0.1** (or any other address in the same range as the board)
- Set the subnet mask to 255.255.255.0 and click OK

Launch MobaXterm and click Start local terminal
- Click **New Session**

- Enter **192.168.0.10** in the Remote Host
- Make sure X11-Forwarding is Checked

- Copying DNNDK Tools and Application to the PYNQ-Z2 Board

1. Install DNNDK into PYNQ-Z2 board
- Execute the sudo ./install.sh command under the zynq7020_dnndk_v3.0 folder
```
$./zynq7020_dnndk_v3.0/install.sh
```
- Check the DPU of the board.
```
$dexplorer -w
```
- Check the version information of DNNDK
```
$dexplorer -v
```
2. Run the yolov3 applications
- Change to the directory into `apps folder` and run make
```
$cd <PROJ ROOT>/apps
$make
```
- After running make,generate the complier file under the foloder

Launch it with the command
```
./yolo ./image i
```

<file_sep>/zynq7020_dnndk_v3.0/pkgs/driver/dpucore.h
/*
* Copyright (C) 2019 Xilinx, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
*/
#ifndef _DPUCORE_H_
#define _DPUCORE_H_
#include <asm/cacheflush.h>
#include <asm/delay.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/thread_info.h>
#include <asm/uaccess.h>
#include <linux/debugfs.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/dma-direction.h>
#include <linux/export.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/mempolicy.h>
#include <linux/miscdevice.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/proc_fs.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/stat.h>
#include <linux/version.h>
#include <linux/wait.h>
#include "dpudef.h"
#define DPU_DRIVER_VERSION "2.2.0"
#define DPU_IDLE 0
#define DPU_RUNNING 1
#define DPU_DISABLE 2
#define FALSE 0
#define TRUE 1
#define MAX_CORE_NUM 4
#define PLEVEL_ERR 9
#define PLEVEL_INFO 5
#define PLEVEL_DBG 1
#define MAX_REG_NUM 32
#define dprint(level, fmt, args...) \
do { \
if ((level) >= debuglevel) \
printk(KERN_ERR "[DPU][%d]" fmt, current->pid, \
##args); \
} while (0)
#define dpr_init(fmt, args...) pr_alert("[DPU][%d]" fmt, current->pid, ##args);
/*dpu registers*/
typedef struct __DPUReg {
/*dpu pmu registers*/
struct __regs_dpu_pmu {
volatile uint32_t version;
volatile uint32_t reset;
volatile uint32_t _rsv[62];
} pmu;
/*dpu rgbout registers*/
struct __regs_dpu_rgbout {
volatile uint32_t display;
volatile uint32_t _rsv[63];
} rgbout;
/*dpu control registers struct*/
struct __regs_dpu_ctrl {
volatile uint32_t hp_ctrl;
volatile uint32_t addr_io;
volatile uint32_t addr_weight;
volatile uint32_t addr_code;
volatile uint32_t addr_prof;
volatile uint32_t prof_value;
volatile uint32_t prof_num;
volatile uint32_t prof_en;
volatile uint32_t start;
volatile uint32_t com_addr[16]; //< extension for DPUv1.3.0
volatile uint32_t _rsv[39];
} ctlreg[MAX_CORE_NUM];
/*dpu interrupt registers struct*/
struct __regs_dpu_intr {
volatile uint32_t isr;
volatile uint32_t imr;
volatile uint32_t irsr;
volatile uint32_t icr;
volatile uint32_t _rsv[60];
} intreg;
} DPUReg;
/*dpu device struct*/
struct dpu_dev {
struct miscdevice dev; //< dpu device
atomic_t core; //< dpu core number available
atomic_t ref_count; //< dpu device open count
struct semaphore sem; //< task semaphore, in simple schedule strategy
struct list_head tasklist; //< task list waiting
wait_queue_head_t waitqueue[MAX_CORE_NUM]; //< waitqueue of each DPU
int irq_no[MAX_CORE_NUM]; //< interrupt NO. of DPU
pid_t pid[MAX_CORE_NUM]; //< pid of current task
int state[MAX_CORE_NUM]; //< state of DPU (IDEL/RUNNING)
unsigned long task_id[MAX_CORE_NUM]; //< task id of current task
u64 time_start[MAX_CORE_NUM]; //< start time of current task
u64 time_end[MAX_CORE_NUM]; //< finish time of current task
int intflg[MAX_CORE_NUM];
};
/*task node struct*/
struct task_node {
unsigned long task_id;
unsigned long pid;
unsigned long priority;
wait_queue_head_t runwait;
struct semaphore runsem;
struct list_head list;
};
/*memory block node struct*/
struct memblk_node {
unsigned long size;
unsigned long virt_addr;
dma_addr_t phy_addr;
pid_t pid;
struct list_head list;
};
//////////////////////////////////////////////////
// helper functions declare
struct device_node *dpu_compatible_node(const char *compat);
//////////////////////////////////////////////////
#endif /*_DPU_H_*/
|
fc6ed22d0bb4831479279c5c6813c68bf12c737c
|
[
"Markdown",
"C"
] | 3 |
C
|
tkxiong/pynqz2_dpu140
|
62467b33f00159cfe320427a7cb0e96a707ecd8d
|
da2c6ba1d46ce45b3c2db66c4f47c1917c34c5b0
|
refs/heads/master
|
<repo_name>azureskydiver/LMProjects<file_sep>/Stats.cs
using System;
namespace Lobstermania
{
public class Stats
{
// CUMULATIVE SESSION COUNTERS
public long numJackpots = 0L;
public long hitCount = 0L; // Count of winning spins
public long spins = 0L;
double hitFreq = 0.0; // line hit frequency. (1.00 = 100%)
double jackpotFreq = 0.0; // Number of jackpots / (number of spins * activeLines)
public long paybackCredits = 0L; // Line + Scatter winnings in credits (Line wins includes bonus wins)
double paybackPercentage = 0.0; // Payback %, (1.00 = 100%)
public long scatterWinCount = 0L;
public long scatterWinCredits = 0L;
public long bonusWinCount = 0L;
public long bonusWinCredits = 0L;
// INDIVIDUAL GAME COUNTERS
public int igWin = 0; // ig = individual game, win (all paylines)
public int igScatterWin = 0;
public int igBonusWin = 0;
public void ResetGameStats()
{
igWin = 0;
igScatterWin = 0;
igBonusWin = 0;
} // End method ResetGameStats
public void ResetSessionStats()
{
numJackpots = 0L;
hitCount = 0L; // Count of winning spins
spins = 0L;
hitFreq = 0.0; // line hit frequency. (1.00 = 100%)
jackpotFreq = 0.0;
paybackCredits = 0L; // Line + Scatter winnings in credits (Line wins includes bonus wins)
paybackPercentage = 0.0; // Payback %, (1.00 = 100%)
scatterWinCount = 0L;
scatterWinCredits = 0L;
bonusWinCount = 0L;
bonusWinCredits = 0L;
} // End method ResetSessionStats
public void DisplaySessionStats(int activePaylines)
{
hitFreq = (double)hitCount / ((double)spins * (double)activePaylines);
paybackPercentage = (double)paybackCredits / ((double)spins * (double)activePaylines);
jackpotFreq = (double)numJackpots / ((double)spins * (double)activePaylines);
Console.WriteLine("\nPlaying {0} active paylines.", activePaylines);
Console.WriteLine("\nMEASURED SESSION STATISTICS:");
Console.WriteLine("----------------------------");
Console.WriteLine("\nThere are {0:N0} winning line combinations out of {1:N0} spins ({2:P1} hit frequency).",
hitCount, spins, hitFreq);
Console.WriteLine("\n{0:N0} credits spent, {1:N0} credits won, {2:P1} payback percentage.",
spins * activePaylines, paybackCredits, paybackPercentage);
Console.WriteLine("\nThere were {0:N0} bonus wins out of {1:N0} spins. (Average win was {2:N0} credits per bonus.)",
bonusWinCount, spins, (double)bonusWinCredits / (double)bonusWinCount);
Console.WriteLine("\nThere were {0:N0} scatter wins out of {1:N0} spins. (Average win was {2:N0} credits per scatter.)",
scatterWinCount, spins, (double)scatterWinCredits / (double)scatterWinCount);
Console.WriteLine("\nThere were {0:N0} JACKPOT wins out of {1:N0} spins (Jackpot Hit Freq of {2:P6}).\n",
numJackpots, spins, jackpotFreq);
Console.WriteLine("Average number of spins to JACKPOT: {0:N0}", (double)spins / (double)numJackpots);
Console.WriteLine("Average number of spins to Bonus : {0:N0}", (double)spins / (double)bonusWinCount);
Console.WriteLine("Average number of spins to Scatter: {0:N0}\n", (double)spins / (double)scatterWinCount);
} // End method DisplaySessionStats
public void DisplayGameStats()
{
Console.WriteLine("\nTOTAL CREDITS WON: {0:N0} SCATTER WIN: {1:N0} BONUS WIN: {2:N0}\n",
igWin, igScatterWin, igBonusWin);
} // End method DisplayGameStats
} // end class Stats
} // end namespace
<file_sep>/LM962.cs
using System;
namespace Lobstermania
{
class LM962
{
const int NUM_REELS = 5;
const int GAMEBOARD_ROWS = 3;
const int MAX_PAYLINES = 15;
readonly string[] SYMBOLS123 = { "WS", "LM", "BU", "BO", "LH", "TU", "CL", "SG", "SF", "LO", "LT" }; // All 11 game symbols
readonly string[] SYMBOLS45 = { "WS", "LM", "BU", "BO", "LH", "TU", "CL", "SG", "SF", "LT" }; // Reels 4 and 5 -- missing LO (bonus) symbol
readonly int[][] SYMBOL_COUNTS = new int[][]
{
new int[] { 2, 4, 4, 6, 5, 6, 6, 5, 5, 2, 2 },
new int[] { 2, 4, 4, 4, 4, 4, 6, 6, 5, 5, 2 },
new int[] { 1, 3, 5, 4, 6, 5, 5, 5, 6, 6, 2 },
new int[] { 4, 4, 4, 4, 6, 6, 6, 6, 8, 2 },
new int[] { 2, 4, 5, 4, 7, 7, 6, 6, 7, 2 }
};
readonly int[,] PAYOUTS =
{
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 100, 40, 25, 25, 10, 10, 5, 5, 5, 331, 5 },
{ 500, 200, 100, 100, 50, 50, 30, 30, 30, 0,25 },
{ 10000, 1000, 500, 500, 500, 250, 200, 200, 150, 0, 200 }
};
public static readonly Random rand = new Random(); // Random Number Generator (RNG) object
readonly string[][] reels = new string[][] // 5 reels in this game
{
new string[47], // 47 slots in this reel
new string[46],
new string[48],
new string[50],
new string[50]
};
readonly string[,] gameBoard = new string[GAMEBOARD_ROWS, NUM_REELS];
readonly string[][] payLines = new string[MAX_PAYLINES][];
public int activePaylines = MAX_PAYLINES; //number of active paylines, default of 15
// Print flags
public bool printReels = false;
public bool printGameboard = false;
public bool printPaylines = false;
public Stats stats = new Stats(); // Game statistics object
public LM962()
{
// Build the reels
BuildReels();
// Randomize the reels
for(int i=0;i<NUM_REELS;i++) // randomize each of the 5 reels
ArrayShuffle.Shuffle(reels[i]);
} // End constructor
private void BuildReels()
{
for (int i = 0; i < 3; i++) // 1st 3 reels
{
int idx = 0; // reel slot index
for (int j = 0; j < SYMBOLS123.Length; j++)
for (int k = 0; k < SYMBOL_COUNTS[i][j]; k++) // number of times to repeat each symbol
reels[i][idx++] = SYMBOLS123[j]; // assign symbol to slot
}
for (int i = 3; i < 5; i++) // last 2 reels (they don't have the LO (bonus) symbol)
{
int idx = 0; // reel slot index
for (int j = 0; j < SYMBOLS45.Length; j++)
for (int k = 0; k < SYMBOL_COUNTS[i][j]; k++) // number of times to repeat each symbol
reels[i][idx++] = SYMBOLS45[j]; // assign symbol to slot
}
} // End method BuildReels
private void PrintReels()
{
for(int num=0; num<NUM_REELS; num++) // all 5 reels
{
Console.Write("\nReel[{0}]: [ ", num);
for (int s = 0; s < reels[num].Length - 1; s++)
Console.Write("{0}, ", reels[num][s]);
Console.WriteLine("{0} ]", reels[num][reels[num].Length-2]);
}
} // End method PrintReels
public void Spin()
{
stats.spins++;
if (printReels)
PrintReels();
UpdateGameboard();
if (printGameboard)
PrintGameboard();
UpdatePaylines();
if (printPaylines)
{
Console.WriteLine("WINNING PAY LINES");
Console.WriteLine("-----------------");
}
for (int i = 0; i < activePaylines; i++) // for each payline
{
int linePayout = GetLinePayout(payLines[i]); // will include any bonus win
if(linePayout > 0)
{
stats.igWin += linePayout;
stats.hitCount++;
stats.paybackCredits += linePayout;
if (printPaylines)
PrintPayline(i+1, payLines[i], linePayout);
}
} // end for (each payLine)
int scatterWin = GetScatterWin();
if (scatterWin > 0)
{
// stats.paybackCredits are updated in GetScatterWin()
stats.hitCount++;
stats.igScatterWin = scatterWin; // only 1 scatter win allowed per game
stats.igWin += scatterWin; // add to total game win
}
} // End method Spin
private int GetLinePayout(string[] line)
{
int count = 1; // count of consecutive matching symbols, left to right
string sym = line[0];
int bonusWin = 0;
switch (sym)
{
case "LO": // Bonus
for (int i = 1; i < 3; i++)
{
if (line[i] == "LO")
count++;
else
break;
}
if (count == 3)
{
bonusWin = Bonus.GetPrizes();
stats.bonusWinCount++;
stats.bonusWinCredits += bonusWin;
stats.igBonusWin += bonusWin;
}
else
bonusWin = 0;
break; // case "LO"
case "LT": // Scatter
count = 1; // Scatter handled at gameboard level
break; // case "LT"
case "WS": // Wild
string altSym = "WS";
for (int i = 1; i < NUM_REELS; i++)
if ((line[i] == sym) || (line[i] == altSym))
count++;
else
{
if (line[i] != "LO" && line[i] != "LT" && altSym == "WS")
{
altSym = line[i];
count++;
}
else
{
break;
}
}
sym = altSym; // count and sym are now set correctly
// ANOMOLY FIX
// 3 wilds pay more than 4 of anything but lobstermania
// 4 wilds pay more than 5 of anything but lobstermania
// Take greatest win possible
// Leading 4 wilds
if ((line[1] == "WS") && (line[2] == "WS") && (line[3] == "WS"))
{
if (line[4] == "LM")
{
sym = "LM";
count = 5;
}
else
if (line[4] != "WS")
{
sym = "WS";
count = 4;
}
}
// Leading 3 wilds
if ((line[1] == "WS") && (line[2] == "WS") && (line[3] == "LM") && (line[4] == "WS") && (line[4] != "LM"))
{
sym = "LM";
count = 4;
goto Done;
}
if ((line[1] == "WS") && (line[2] == "WS") && (line[3] != "LM") && (line[3] != "WS") && (line[4] != line[3]))
{
sym = "WS";
count = 3;
}
Done:
break; // case "WS"
default: // Handle all other 1st symbols not handled in cases above
sym = line[0];
for (int i = 1; i < NUM_REELS; i++)
if ((line[i] == sym) || (line[i] == "WS"))
count++;
else
break;
break; // case default
} // end switch
if ((sym == "WS") && (count == 5))
stats.numJackpots++;
// count variable now set for number of consecutive line[0] symbols (1 based)
count--; // adjust for zero based indexing
if (bonusWin > 0) return bonusWin;
int lineWin = PAYOUTS[count, GetSymIndex(sym)];
return lineWin;
} // End method GetLinePayout
private int GetSymIndex(string sym)
{
int symidx = 0;
switch (sym)
{
case "WS":
symidx = 0;
break;
case "LM":
symidx = 1;
break;
case "BU":
symidx = 2;
break;
case "BO":
symidx = 3;
break;
case "LH":
symidx = 4;
break;
case "TU":
symidx = 5;
break;
case "CL":
symidx = 6;
break;
case "SG":
symidx = 7;
break;
case "SF":
symidx = 8;
break;
case "LO":
symidx = 9;
break;
case "LT":
symidx = 10;
break;
} // end switch
return symidx;
} // End method GetSymIndex
private void UpdateGameboard()
{
int[] lineIdxs = new int[5]; // Random starting slots for each reel
for (int i = 0; i < NUM_REELS; i++)
lineIdxs[i] = rand.Next(reels[i].Length);
int i1, i2, i3;
int r = 0; // reel number 1-5 zero adjusted
foreach (int reelIdx in lineIdxs)
{
// set i1,i2, i3 to consecutive slot numbers on this reel, wrap if needed
i1 = reelIdx;
// set i2, correct if past last slot in reel
if ((i1 + 1) == reels[r].Length)
i2 = 0;
else
i2 = i1 + 1;
// set i3, correct if past last slot in reel
if ((i2 + 1) == reels[r].Length)
i3 = 0;
else
i3 = i2 + 1;
// i1, i2, i3 are now set to consecutive slot indexes on this reel (r)
// Populate Random Gameboard
gameBoard[0, r] = reels[r][i1];
gameBoard[1, r] = reels[r][i2];
gameBoard[2, r] = reels[r][i3];
r++; // increment to next reel
} // end foreach
} // End method UpdateGameboard
private void PrintGameboard()
{
Console.WriteLine("GAMEBOARD:");
Console.WriteLine("------------------");
for (int r = 0; r < GAMEBOARD_ROWS; r++)
{
for (int c = 0; c < NUM_REELS; c++)
Console.Write("{0} ", gameBoard[r, c]);
Console.WriteLine();
}
Console.WriteLine();
} // End method PrintGameboard
private void UpdatePaylines()
{
payLines[0] = new string[] { gameBoard[1, 0], gameBoard[1, 1], gameBoard[1, 2], gameBoard[1, 3], gameBoard[1, 4] };
payLines[1] = new string[] { gameBoard[0, 0], gameBoard[0, 1], gameBoard[0, 2], gameBoard[0, 3], gameBoard[0, 4] };
payLines[2] = new string[] { gameBoard[2, 0], gameBoard[2, 1], gameBoard[2, 2], gameBoard[2, 3], gameBoard[2, 4] };
payLines[3] = new string[] { gameBoard[0, 0], gameBoard[1, 1], gameBoard[2, 2], gameBoard[1, 3], gameBoard[0, 4] };
payLines[4] = new string[] { gameBoard[2, 0], gameBoard[1, 1], gameBoard[0, 2], gameBoard[1, 3], gameBoard[2, 4] };
payLines[5] = new string[] { gameBoard[2, 0], gameBoard[2, 1], gameBoard[1, 2], gameBoard[0, 3], gameBoard[0, 4] };
payLines[6] = new string[] { gameBoard[0, 0], gameBoard[0, 1], gameBoard[1, 2], gameBoard[2, 3], gameBoard[2, 4] };
payLines[7] = new string[] { gameBoard[1, 0], gameBoard[2, 1], gameBoard[1, 2], gameBoard[0, 3], gameBoard[1, 4] };
payLines[8] = new string[] { gameBoard[1, 0], gameBoard[0, 1], gameBoard[1, 2], gameBoard[2, 3], gameBoard[1, 4] };
payLines[9] = new string[] { gameBoard[2, 0], gameBoard[1, 1], gameBoard[1, 2], gameBoard[1, 3], gameBoard[0, 4] };
payLines[10] = new string[] { gameBoard[0, 0], gameBoard[1, 1], gameBoard[1, 2], gameBoard[1, 3], gameBoard[2, 4] };
payLines[11] = new string[] { gameBoard[1, 0], gameBoard[2, 1], gameBoard[2, 2], gameBoard[1, 3], gameBoard[0, 4] };
payLines[12] = new string[] { gameBoard[1, 0], gameBoard[0, 1], gameBoard[0, 2], gameBoard[1, 3], gameBoard[2, 4] };
payLines[13] = new string[] { gameBoard[1, 0], gameBoard[1, 1], gameBoard[2, 2], gameBoard[1, 3], gameBoard[0, 4] };
payLines[14] = new string[] { gameBoard[1, 0], gameBoard[1, 1], gameBoard[0, 2], gameBoard[1, 3], gameBoard[2, 4] };
} // End method UpdatePaylines
private void PrintPayline(int payLineNum, string[] line, int payout)
{
if (payLineNum > 9) // for formatting purposes
Console.Write("Payline[{0}]: [ ", payLineNum);
else
Console.Write("Payline[{0}]: [ ", payLineNum);
foreach (string sym in line)
Console.Write("{0} ", sym);
Console.WriteLine("] PAYS {0} credits.", payout);
} // End method PrintPayline
// Only count 1 scatter per column
private int GetScatterWin() // in credits
{
int count = 0;
// Check each column (reel) in GameBoard for Scatters
// Scatter wins only count 1 scatter per column
for (int c = 0; c < NUM_REELS; c++)
{
for (int r = 0; r < GAMEBOARD_ROWS; r++)
{
if (gameBoard[r, c] == "LT")
{
count++;
break; // already 1 scatter in this column. Move on to next column
}
}
}
int win = 0;
switch (count)
{
case 1:
case 2:
win = 0;
stats.scatterWinCredits += 0;
stats.paybackCredits += 0;
break;
case 3:
win = 5;
stats.scatterWinCredits += 5;
stats.paybackCredits += 5;
break;
case 4:
win = 25;
stats.scatterWinCredits += 25;
stats.paybackCredits += 25;
break;
case 5:
win = 200;
stats.scatterWinCredits += 200;
stats.paybackCredits += 200;
break;
} // end switch (count)
if (count > 2)
stats.scatterWinCount++;
return win;
} // end GetScatterWin()
/*
public void PaybackPercentage()
{
byte[] lineIdxs = new byte[5];
hitCount = 0;
hitFreq = 0.0; // line hit frequency. 1.00 = 100%
// 259,440,000 combinations (47x46x48x50x50)
for (byte s1Idx = 0; s1Idx < reel1.Length; s1Idx++) // reel 1
for (byte s2Idx = 0; s2Idx < reel2.Length; s2Idx++) // reel 2
for (byte s3Idx = 0; s3Idx < reel3.Length; s3Idx++) // reel 3
for(byte s4Idx = 0; s4Idx < reel4.Length; s4Idx++) // reel 4
for(byte s5Idx = 0; s5Idx <reel5.Length; s5Idx++) // reel 5
{
paybackSpins++;
if ((paybackSpins % 25000000) == 0)
Console.WriteLine("-> {0:N0}", paybackSpins);
line[0] = reel1[s1Idx]; line[1] = reel2[s2Idx]; line[2] = reel3[s3Idx];
line[3] = reel4[s4Idx]; line[4] = reel5[s5Idx];
lineIdxs[0] = s1Idx;
lineIdxs[1] = s2Idx;
lineIdxs[2] = s3Idx;
lineIdxs[3] = s4Idx;
lineIdxs[4] = s5Idx;
int lineWin = GetLinePayout(line);
paybackCredits += lineWin;
// Scatter win check MUST appear after line win check.
// Line check win is set to 0 for all scatters in GetLinePayout()
// Scatter wins are a board level win, and the gameboard will change with each new line
// in this test.
int scatterCount = 0;
byte i1, i2, i3;
byte r = 0; // reel number 1-5 zero adjusted
foreach (byte reelIdx in lineIdxs)
{
// set i1,i2, i3 to consecutive slot numbers on this reel, wrap if needed
i1 = reelIdx;
// set i2, correct if past last slot in reel
if ((byte)(i1 + 1) == SYMBOLS_PER_REEL[r])
i2 = 0;
else
i2 = (byte)(i1 + 1);
// set i3, correct if past last slot in reel
if ((byte)(i2 + 1) == SYMBOLS_PER_REEL[r])
i3 = 0;
else
i3 = (byte)(i2 + 1);
// i1, i2, i3 are now set to consecutive slots on this reel (r)
// Count 1 scatter symbol per reel
switch (r)
{
case 0:
if (reel1[i1] == 'K' || reel1[i2] == 'K' || reel1[i3] == 'K') scatterCount++;
break;
case 1:
if (reel2[i1] == 'K' || reel2[i2] == 'K' || reel2[i3] == 'K') scatterCount++;
break;
case 2:
if (reel3[i1] == 'K' || reel3[i2] == 'K' || reel3[i3] == 'K') scatterCount++;
break;
case 3:
if (reel4[i1] == 'K' || reel4[i2] == 'K' || reel4[i3] == 'K') scatterCount++;
break;
case 4:
if (reel5[i1] == 'K' || reel5[i2] == 'K' || reel5[i3] == 'K') scatterCount++;
break;
} // end switch (r)
r++; // next reel
} // end foreach (byte reelIdx in lineIdxs)
// scatter now contains count of scatters on gameboard
switch (scatterCount)
{
case 3:
scatterWinCount++;
scatterWinCredits += 5;
paybackCredits += 5;
break;
case 4:
scatterWinCount++;
scatterWinCredits += 25;
paybackCredits += 25;
break;
case 5:
scatterWinCount++;
scatterWinCredits += 200;
paybackCredits += 200;
break;
} // end switch
if (lineWin > 0) hitCount++;
if (scatterCount > 2) hitCount++;
} // End for s5Idx
paybackPercentage = (double)paybackCredits / (double)paybackSpins; // total wins divided by credits spent (1 credit per line bet)
hitFreq = (double)hitCount / (double)paybackSpins;
} // End method PaybackPercentage
public int GetLinePayout(char[] line)
{
byte count = 1; // count of consecutive matching symbols, left to right
char sym = line[0];
int bonusWin = 0;
switch (sym)
{
case 'J': // Bonus
for (byte i = 1; i < 3; i++)
{
if (line[i].Equals('J'))
count++;
else
break;
}
if (count == 3)
{
bonusWin = Bonus.GetPrizes();
bonusWinCount++;
bonusWinSum += bonusWin;
}
else
bonusWin = 0;
break; // case 'J'
case 'K': // Scatter
count = 1; // Scatter handled at gameboard level
break; // case 'K'
case 'A': // Wild
char altSym = 'A';
for (byte i = 1; i < 5; i++)
if (line[i].Equals(sym) || line[i].Equals(altSym))
count++;
else
{
if (!line[i].Equals('J') && !line[i].Equals('K') && altSym.Equals('A'))
{
altSym = line[i];
count++;
}
else
{
break;
}
}
sym = altSym;
// 3 wilds pay more than 4 of anything but lobstermania
// 4 wilds pay more than 5 of anything but bobstermania
// Take greatest win possible
// Leading 4 wilds
if (line[1].Equals('A') && line[2].Equals('A') && line[3].Equals('A') )
{
if (line[4].Equals('B'))
{
sym = 'B';
count = 5;
}
else
if (!line[4].Equals('A'))
{
sym = 'A';
count = 4;
}
}
// Leading 3 wilds
if (line[1].Equals('A') && line[2].Equals('A') && line[3].Equals('B') && !line[4].Equals('A') && !line[4].Equals('B'))
{
sym = 'B';
count = 4;
goto Done;
}
if (line[1].Equals('A') && line[2].Equals('A') && !line[3].Equals('B') && !line[3].Equals('A') && !line[4].Equals(line[3]))
{
sym = 'A';
count = 3;
}
Done:
break; // case 'A'
default:
sym = line[0];
for (byte i = 1; i < 5; i++)
if (line[i].Equals(sym) || line[i].Equals('A'))
count++;
else
break;
break; // case default
} // end switch
// count variable now set for number of consecutive line[0] symbols (1 based)
count--; // adjust for zero based indexing
if (bonusWin > 0) return bonusWin;
int lineWin = PAYOUTS[count, GetSymIndex(sym)];
if(DEBUG_LINE_LEVEL)
#pragma warning disable CS0162 // Unreachable code detected
PrintLine(line, sym, count, lineWin);
#pragma warning restore CS0162 // Unreachable code detected
return lineWin;
} // End method GetLinePayout
private byte GetSymIndex(char sym)
{
byte symidx = 0;
switch (sym)
{
case 'A':
symidx = 0;
break;
case 'B':
symidx = 1;
break;
case 'C':
symidx = 2;
break;
case 'D':
symidx = 3;
break;
case 'E':
symidx = 4;
break;
case 'F':
symidx = 5;
break;
case 'G':
symidx = 6;
break;
case 'H':
symidx = 7;
break;
case 'I':
symidx = 8;
break;
case 'J':
symidx = 9;
break;
case 'K':
symidx = 10;
break;
} // end switch
return symidx;
} // End method GetSymIndex
private void PrintLine(char[] line, char sym, byte count, int lineWin)
{
Console.Write("Line {0}: [ ", ++lineNum);
for (int i = 0; i < 5; i++)
Console.Write("{0}", line[i]);
Console.WriteLine(" ] Symbol = {0}, count = {1}, Payout = {2}\n", sym, count + 1, lineWin);
} // End method PrintLine
*/
} // End class LM962
}
<file_sep>/Program.cs
using System;
using System.Threading;
namespace Lobstermania
{
public static class Program
{
// IMPORTANT NUMBERS
// -----------------
// Theoretical spins per JACKPOT 8,107,500
// Number of all slot combinations (47x46x48x50x50 -- 1 slot per reel) = 259,440,000
// Number of all possible symbol combinations on a line (11x11x11x10x10) = 133,100
public static void Main()
{
mainMenu:
Console.Clear();
Console.WriteLine("PRESS:\n");
Console.WriteLine("\t1 for Bulk Game Spins\n\t2 for Individual Games\n\t3 to quit\n");
Console.Write("Your choice: ");
string res = Console.ReadLine();
int num;
try
{
num = Convert.ToInt32(res);
}
catch (Exception)
{
Console.WriteLine("\n***ERROR: Please enter number 1, 2, or 3 !!!");
Thread.Sleep(2000); // sleep for 2 seconds
goto mainMenu;
}
switch(num)
{
case 1:
long numSpins;
int paylines; // number of paylines to play
labelNumSpins:
Console.Write("\nEnter the number of spins: ");
try
{
numSpins = Convert.ToInt64(Console.ReadLine()); // convert to a long
if (numSpins <= 0)
throw new ArgumentOutOfRangeException();
}
catch (Exception)
{
Console.WriteLine("\n***ERROR: Please enter a positive number greater than 0 !!!");
goto labelNumSpins;
}
labelActivePaylines:
Console.Write("Enter the number of active paylines (1 through 15): ");
try
{
paylines = Convert.ToInt32(Console.ReadLine()); // convert to an int
if (paylines < 1 || paylines > 15)
throw new ArgumentOutOfRangeException();
}
catch (Exception)
{
Console.WriteLine("\n***ERROR: Please enter a positive number between 1 and 15 !!!");
goto labelActivePaylines;
}
Console.Clear();
BulkGameSpins(numSpins,paylines);
Console.WriteLine("Press any key to continue to Main Menu ...");
Console.ReadKey();
goto mainMenu;
case 2:
Console.Clear();
IndividualGames();
goto mainMenu;
case 3:
Environment.Exit(0); // planned exit
break;
default:
goto mainMenu;
}
} // End method Main
private static void BulkGameSpins(long numSpins, int numPayLines)
{
LM962 game = new LM962()
{
activePaylines = numPayLines
};
DateTime start_t = DateTime.Now;
Console.WriteLine("Progress Bar ({0:N0} spins)\n",numSpins);
Console.WriteLine("0% 100%");
Console.WriteLine("|--------|");
if (numSpins <= 10)
{
Console.WriteLine("**********"); // 10 markers
for (long i = 1; i <= numSpins; i++)
game.Spin();
}
else
{
int marks = 1; // Number of printed marks
long markerEvery = (long)Math.Ceiling((double)numSpins / (double)10); // print progression marker at every 1/10th of total spins.
for (long i = 1; i <= numSpins; i++)
{
game.Spin();
if ((i % markerEvery == 0))
{
Console.Write("*");
marks++;
}
}
for (int i = marks; i <= 10; i++)
Console.Write("*");
}
Console.WriteLine();
game.stats.DisplaySessionStats(numPayLines);
DateTime end_t = DateTime.Now;
TimeSpan runtime = end_t - start_t;
Console.WriteLine("\nRun completed in {0:t}\n", runtime);
} // End method BulkGameSpins
private static void IndividualGames()
{
LM962 game = new LM962
{
printGameboard = true,
printPaylines = true
};
for (; ;) // ever
{
Console.Clear(); // clear the console screen
Console.WriteLine("\nPlaying {0} active paylines.\n", game.activePaylines);
game.Spin();
game.stats.DisplayGameStats ();
game.stats.ResetGameStats();
Console.WriteLine("Press the P key to change the number of pay lines");
Console.WriteLine("Press the Escape key to return to the Main Menu");
Console.WriteLine("\nPress any other key to continue playing.");
ConsoleKeyInfo cki = Console.ReadKey(true);
if (cki.KeyChar == 'p')
{
getPayLines:
Console.Write("\nEnter the new number of active paylines (1 through 15): ");
int paylines;
try
{
paylines = Convert.ToInt32(Console.ReadLine()); // convert to an int
if (paylines < 1 || paylines > 15)
throw new ArgumentOutOfRangeException();
}
catch (Exception)
{
Console.WriteLine("\n***ERROR: Please enter a positive number between 1 and 15 !!!");
goto getPayLines;
}
game.activePaylines = paylines;
} // end if cki.KeyChar == 'p'
if (cki.Key == ConsoleKey.Escape) // quit when you hit the escape key
break;
} // end for ever
} // End method IndividualGames
} // End class Program
} // end namespace
<file_sep>/Bonus.cs
using System;
namespace Lobstermania
{
static class Bonus
{
// Constants
private const int NUM_PRIZE_SLOTS = 322;
private const int MAX_PRIZES = 12; // 4 buoys picked x 3 prizes per buoy
// Fields
private readonly static int[] PrizeLookupTable = new int[NUM_PRIZE_SLOTS];
private static int BouysPicked = 0; // will be either 2, 3, or 4
private static int PrizesPerBuoy = 0; // will be either 2 or 3
private readonly static int[] Prizes = new int[MAX_PRIZES]; // each individual prize amount, array will be right sized
private static int BonusWin = 0;
private static bool IsInitialized = false;
// Properties
// Methods
private static void Initialize()
{
// Set each PrizeLookupTable element to prize value in credits
for (int i = 0; i <= 9; i++) PrizeLookupTable[i] = 10;
for (int i = 10; i <= 14; i++) PrizeLookupTable[i] = 5;
for (int i = 15; i <= 19; i++) PrizeLookupTable[i] = 6;
for (int i = 20; i <= 24; i++) PrizeLookupTable[i] = 7;
for (int i = 25; i <= 29; i++) PrizeLookupTable[i] = 8;
for (int i = 30; i <= 39; i++) PrizeLookupTable[i] = 10;
for (int i = 40; i <= 49; i++) PrizeLookupTable[i] = 12;
for (int i = 50; i <= 59; i++) PrizeLookupTable[i] = 15;
for (int i = 60; i <= 79; i++) PrizeLookupTable[i] = 20;
for (int i = 80; i <= 99; i++) PrizeLookupTable[i] = 22;
for (int i = 100; i <= 119; i++) PrizeLookupTable[i] = 25;
for (int i = 120; i <= 139; i++) PrizeLookupTable[i] = 27;
for (int i = 140; i <= 158; i++) PrizeLookupTable[i] = 30;
for (int i = 159; i <= 180; i++) PrizeLookupTable[i] = 35;
for (int i = 181; i <= 204; i++) PrizeLookupTable[i] = 45;
for (int i = 205; i <= 223; i++) PrizeLookupTable[i] = 50;
for (int i = 224; i <= 238; i++) PrizeLookupTable[i] = 55;
for (int i = 239; i <= 253; i++) PrizeLookupTable[i] = 60;
for (int i = 254; i <= 268; i++) PrizeLookupTable[i] = 65;
for (int i = 269; i <= 283; i++) PrizeLookupTable[i] = 70;
for (int i = 284; i <= 298; i++) PrizeLookupTable[i] = 75;
for (int i = 299; i <= 308; i++) PrizeLookupTable[i] = 100;
for (int i = 309; i <= 316; i++) PrizeLookupTable[i] = 150;
for (int i = 317; i <= 321; i++) PrizeLookupTable[i] = 250;
IsInitialized = true;
}
public static int GetPrizes()
{
if (!IsInitialized)
Initialize(); // Build the PrizeLookupTable
BouysPicked = LM962.rand.Next(2, 5); // 2, 3, or 4
PrizesPerBuoy = LM962.rand.Next(2, 4); // 2 or 3
int numPrizes = BouysPicked * PrizesPerBuoy;
// Set all elements of the Prizes array to 0
Array.Clear(Prizes, 0, MAX_PRIZES);
// Get each prize and save it to the Prizes array, add each prize to BonusWin
BonusWin = 0;
for(int i=0; i<numPrizes; i++)
{
int idx = LM962.rand.Next(322); // indexes between 0 and 321 inclusive
Prizes[i] = PrizeLookupTable[idx];
BonusWin += Prizes[i];
}
return BonusWin;
} // End method GetPrizes
} // End class Bonus
} // End namespace Lobstermania
|
0b5859841d193058a80d304cddda34e32fab73e4
|
[
"C#"
] | 4 |
C#
|
azureskydiver/LMProjects
|
dbd191c582b7a1951aa3a321683248d993af142d
|
e89c8a2561ef0bf850f904af28b530827b33547e
|
refs/heads/master
|
<repo_name>tarun-ssharma/mini-ecommerce-app<file_sep>/README.md
# miniEcommerceApp
This is a mini e-commerce web application developed using Flask web framework and SQLAlchemy ORM framework with sqlite database in python programming language.
To run the web app:
1. Install requirements mentioned in requirements.txt: pip install -r requirements.txt
2. Run the application: python run.py
3. Access the admin user at: http://127.0.0.1:5000/admin (Use 'admin' as username and 'admin' as password) : Create agent and customers
4. Access the agent user at: http://127.0.0.1:5000/agent (Login using added agents in step3)
5. Access the customer user at: http://127.0.0.1:5000/customer (Login using added customers in step3)
In the existing db, I have created a few orders, a product with two skus and:
1. Agent with username = 'agent', password='<PASSWORD>'
2. Customer with phone = 7665424890 , OTP = 1234
To run the application with a fresh db: disable comment [#db.drop_all()] in ecomm/__init__.py
<file_sep>/ecomm/admin/views.py
from ecomm.admin import User, Admin, Role, RoleValues
from ecomm.agent import Agent
from ecomm.customer import Customer
from ecomm.products.models import Product
from ecomm.products.views import get_all_products
from flask import Blueprint, request, render_template, session, redirect, url_for, flash
from ecomm import db
#Initialize the blueprint
admin_bp = Blueprint('admin',__name__)
def is_logged_in():
return 'username' in session
def is_admin():
return ('role' in session) and (session['role'] == 'ADMIN')
def get_all_agents():
'''
Get a List of all agents.
'''
agents = {}
for agent in Agent.query.all():
agents[agent.id] = agent
return agents
def get_all_customers():
'''
Get a List of all customers.
'''
customers = {}
for customer in Customer.query.all():
customers[customer.id] = customer
return customers
@admin_bp.route('/login',methods=['GET','POST'])
def login():
'''
Handles login for admin user.
'''
if request.method == 'POST':
if(request.form['pwd'] != '<PASSWORD>'):
#TODO: query db
flash('Incorrect credentials. Please try to login again.')
return render_template('admin_login.html', url= url_for('admin.login'))
else:
session['username'] = request.form['user']
session['role'] = 'ADMIN'
flash('Logged in successfully!')
return redirect(url_for('admin.home'))
else:
return render_template('admin_login.html', url= url_for('admin.login'))
@admin_bp.route('/')
@admin_bp.route('/home')
def home():
'''
Renders home page of the admin user.
'''
if (not is_logged_in()) or (not is_admin()):
return redirect(url_for('admin.login'))
else:
#Logged in admin
return render_template('admin_home.html',products=get_all_products(),agents=get_all_agents(),customers=get_all_customers())
@admin_bp.route('/logout')
def logout():
'''
Handles logout for admin user.
'''
session.pop('username', None)
session.pop('role', None)
flash('Logged out successfully!')
return redirect(url_for('admin.login'))
@admin_bp.route('/addAgent',methods=['GET','POST'])
def add_agent():
'''
Add a new user in agent role.
'''
if (not is_logged_in()) or (not is_admin()):
return redirect(url_for('admin.login'))
else:
if request.method == 'POST':
password = request.form['pwd']
username = request.form['user']
email = request.form['email']
first_name = request.form['firstName']
last_name = request.form['lastName']
#First, validate the field values
if(not username or not password):
#basic empty field validation
flash('Incomplete credentials. Please try again.')
#use AJAX
render_template('admin_add_customer.html')
else:
agent = Agent.query.filter_by(username=username).first()
if agent is None:
try:
agent = Agent(username, password, first_name, last_name,email)
role = Role(RoleValues.AGENT)
agent.roles.append(role)
db.session.add(agent)
db.session.commit()
flash('Agent created successfully!')
except Exception as e:
flash(str(e))
db.session.rollback()
return redirect(url_for('admin.home'))
else:
flash('An agent with the same username already exists.')
render_template('admin_add_customer.html')
else:
return render_template('admin_add_agent.html')
@admin_bp.route('/addCustomer',methods=['GET','POST'])
def add_customer():
'''
Add a new user in customer role.
'''
if (not is_logged_in()) or (not is_admin()):
return redirect(url_for('admin.login'))
else:
if request.method == 'POST':
#If id exists, flash(already exists)
password = request.form['pwd']
username = request.form['user']
#make sure this is None when no field sent
email = request.form['email']
first_name = request.form['firstName']
last_name = request.form['lastName']
phone = request.form['phone']
#First, validate the field values
if(not username or not password or not phone):
#basic empty field validation
flash('Incomplete credentials. Please try again.')
return render_template('admin_add_customer.html')
else:
customer = Customer.query.filter_by(username=username).first()
if customer is None:
try:
customer = Customer(username, password, first_name, last_name, phone, email)
role = Role(RoleValues.CUSTOMER)
customer.roles.append(role)
db.session.add(customer)
db.session.commit()
flash('Customer created successfully!')
except Exception as e:
flash(str(e))
db.session.rollback()
return redirect(url_for('admin.home'))
else:
flash('A customer with the same username/phone already exists.')
#use AJAX
return render_template('admin_add_customer.html')
else:
return render_template('admin_add_customer.html')<file_sep>/ecomm/admin/__init__.py
from ecomm.admin.models import User, Admin, Role, RoleValues<file_sep>/ecomm/customer/views.py
from flask import Blueprint, request, render_template, session, redirect, url_for, flash
from ecomm.invoice import Invoice, CartSkus, OrderSkus
from datetime import datetime
from ecomm.customer.models import Customer
from ecomm.products.views import get_all_products
from ecomm.products import SKU
from ecomm import db
from multiprocessing import Process
import time
customer_bp = Blueprint('customer',__name__)
def send_sms(phone, message):
'''
Logic to send a given message SMS to a phone number.
'''
time.sleep(2000)
return True
def generate_otp():
'''
Mocking the OTP generation process
'''
return 1234
def is_logged_in():
'''
Utility method to ascertain if the user is logged in.
'''
return 'user_id' in session
def is_customer():
'''
Utility method to ascertain if the user is logged in as a customer.
'''
return ('role' in session) and (session['role'] == 'CUSTOMER')
@customer_bp.route('/login',methods=['GET','POST'])
def login():
'''
Handles the login functionality for customers.
'''
if request.method == 'POST':
#Validations for login page
if(('login_username' in request.form and request.form['pwd'] != '<PASSWORD>') or('login_phone' in request.form and not request.form['phone'].isdigit())):
flash('Incorrect credentials. Please try to login again.')
return render_template('customer_login.html', url= url_for('customer.login'))
#Validations for OTP page
elif('login_otp' in request.form and int(request.form['otp']) != session['generated_otp']):
flash('Incorrect OTP. Retry.')
return render_template('enter_otp.html')
else:
if('login_phone' in request.form):
session['phone'] = request.form['phone']
customer = Customer.query.filter_by(phone=session['phone']).first()
if customer is None:
flash('Incorrect credentials. Please try to login again.')
return render_template('customer_login.html', url= url_for('customer.login'))
#Mock the OTP generation process
session['generated_otp'] = generate_otp()
#Spawn a new process which will take care of sending the OTP to the customer.
process_send_otp = Process(
target=send_sms,
args=(session['phone'],'Your OTP for loggin in is'+str(session['generated_otp'])),
daemon=True
)
process_send_otp.start()
return render_template('enter_otp.html',url= url_for('customer.login'))
elif('login_otp' in request.form):
customer = Customer.query.filter_by(phone=session['phone']).first()
session['user_id'] = customer.id
session.pop('generated_otp',None)
session.pop('phone',None)
elif('login_username' in request.form):
customer = Customer.query.filter_by(username=request.form['user']).first()
session['user_id'] = customer.id
session['role'] = 'CUSTOMER'
flash('Logged in successfully!')
return redirect(url_for('customer.home'))
else:
return render_template('customer_login.html', url= url_for('customer.login'))
@customer_bp.route('/')
@customer_bp.route('/home')
def home():
'''
Handles login functionality for customers.
'''
if(not is_logged_in() or not is_customer()):
return redirect(url_for('customer.login'))
else:
return render_template('customer_home.html',products=get_all_products())
@customer_bp.route('/logout')
def logout():
'''
Handles logout functionality for customers.
'''
session.pop('user_id', None)
session.pop('role',None)
flash('Logged out successfully!')
return redirect(url_for('customer.login'))
@customer_bp.route('/viewCart')
def show_cart():
'''
Renders the incomplete cart for customers. There can only be one per customer.
'''
if(not is_logged_in() or not is_customer()):
return redirect(url_for('customer.login'))
else:
cart_skus = CartSkus.query.filter_by(customer_id=session['user_id']).all()
last_prices = {}
stock_qtys = {}
prices = {}
properties = {}
for cart_sku in cart_skus:
sku = SKU.query.get_or_404(cart_sku.sku_id)
properties[sku.id] = sku.properties
prices[sku.id] = sku.price
stock_qtys[cart_sku.sku_id] = sku.stock_qty
#Query to obtain the last ordered prices of current cart items.
last_invoice = Invoice.query.filter_by(customer_id=session['user_id']).filter(Invoice.order_skus.any(sku_id=cart_sku.sku_id)).order_by(Invoice.time.desc()).first()
if last_invoice is None:
last_prices[cart_sku.sku_id] = -1
else:
last_prices[cart_sku.sku_id] = OrderSkus.query.filter_by(order_id=last_invoice.id).first().price
return render_template('show_cart.html',cart_skus=cart_skus,last_prices=last_prices,stock_qtys=stock_qtys,prices=prices,properties=properties)
@customer_bp.route('/orderHistory')
def show_order_history():
'''
Display brief information about previous orders placed by a customer.
'''
if(not is_logged_in() or not is_customer()):
return redirect(url_for('customer.login'))
else:
invoices = Invoice.query.filter_by(customer_id=session['user_id']).all()
return render_template('order_history.html',invoices=invoices)
@customer_bp.route('/placeOrder',methods=['POST'])
def place_order():
'''
Handle operations involved during placing an order, involving:
1. Ascertain sufficient stocks
2. Move cart skus to order skus, remove cart skus, reduce stock levels to account for ordered products.
3. Create a new Invoice with state='ACCEPTED'
4. Send 'Order Placed' notification to customer.
NOTE/ASSUMPTION: Ledger is updated not now, but only once payment is recieved by an agent.
'''
if(not is_logged_in() or not is_customer()):
return redirect(url_for('customer.login'))
else:
with db.session.no_autoflush:
try:
customer_id = session['user_id']
cart_skus = CartSkus.query.filter_by(customer_id=customer_id).all()
customer = Customer.query.get_or_404(customer_id)
#Empty cart scenario
if cart_skus is None:
abort(404, description="Cart has no items!")
total = 0
order_skus = []
for cart_sku in cart_skus:
sku = SKU.query.get_or_404(cart_sku.sku_id)
sku_stock_qty = sku.stock_qty
#Abort the place order process if any of the cart items is not in sufficient stock.
if(cart_sku.quantity > sku_stock_qty):
raise Exception('Sku'+cart_sku.sku_id+' has insufficient stock')
subtotal = cart_sku.quantity*(sku.price)
order_sku = OrderSkus(cart_sku.quantity,sku.price,subtotal)
if(cart_sku.quantity == sku_stock_qty):
sku.in_stock = False
#Reduce stock levels
sku.stock_qty -= cart_sku.quantity
sku.order_skus.append(order_sku)
order_skus.append(order_sku)
#Calculate order total
total += subtotal
db.session.delete(cart_sku)
invoice = Invoice("ACCEPTED", False, datetime.now(), total)
invoice.order_skus.extend(order_skus)
customer.orders.append(invoice)
db.session.add(invoice)
for order_sku in order_skus:
db.session.add(order_sku)
db.session.commit()
flash('Order Placed!')
#Mock the Confirmation Messsage sending process
process_send_sms = Process(
target=send_sms,
args=(customer.phone,'Order '+str(invoice.id)+' has been accepted and will be prepared for departure.'),
daemon=True
)
#Once this process has started, the application will proceed while this process continues separately
# to try to send confirmation message.
process_send_sms.start()
return redirect(url_for('customer.show_order_history'))
except Exception as e:
db.session.rollback()
flash('Could not place the order.' + str(e))
return redirect(url_for('customer.show_cart'))<file_sep>/ecomm/customer/__init__.py
from ecomm.customer.models import Customer,FinancialLedgerEntry<file_sep>/ecomm/customer/models.py
from ecomm import db
from ecomm.admin import User
from ecomm.invoice import Invoice,CartSkus
class Customer(User):
id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
ledgerEntries = db.relationship('FinancialLedgerEntry', backref= db.backref('customer'),lazy='dynamic')
orders = db.relationship('Invoice', backref= db.backref('customer'))
cart_skus = db.relationship('CartSkus',backref=db.backref('customer'))
phone = db.Column(db.Integer)
def __init__(self, username, password, first_name, last_name, phone=None, email=None):
super().__init__(username, password, first_name, last_name,email)
self.phone = -1 if phone is None else phone
__mapper_args__ = {
'polymorphic_identity':'customer'
}
'''
Class to serve as a record tracker for all the transactions involving customers.
'''
class FinancialLedgerEntry(db.Model):
id = db.Column(db.Integer, primary_key=True)
customer_id = db.Column(db.Integer,db.ForeignKey('customer.id'))
transaction_date = db.Column(db.DateTime)
amount = db.Column(db.Float)
balance = db.Column(db.Float)
def __init__(self,transaction_date,amount,balance):
self.transaction_date = transaction_date
self.amount = amount
self.balance = balance
<file_sep>/ecomm/products/views.py
from ecomm.products.models import Product, SKU
from flask import Blueprint, render_template, request,abort,session, flash, redirect, url_for
from ecomm import db
from ecomm.invoice import CartSkus
from ecomm.customer import Customer
#Initialize the products blueprint.
products_bp = Blueprint('product',__name__)
def is_logged_in():
return 'username' in session
def is_customer_logged_in():
return 'user_id' in session
def is_admin():
return ('role' in session) and (session['role'] == 'ADMIN')
def is_customer():
return ('role' in session) and (session['role'] == 'CUSTOMER')
def get_all_products():
'''
Get all the products and associated skus.
'''
products = {}
for product in Product.query.all():
#Is python pass by object
product.get_key_values(products)
return products
@products_bp.route('/')
@products_bp.route('/home')
def show_all():
return render_template('show_all.html',products=get_all_products())
@products_bp.route('/detail/<prod_key>')
@products_bp.route('/detail')
def show_product_detail(prod_key=None):
'''
Show details about a product and its related skus.
'''
if(prod_key is None):
prod_key = request.args.get('prod_key')
product = Product.query.get_or_404(int(prod_key))
return render_template('show_product_details.html',products=product.get_key_values())
@products_bp.route('/addProduct',methods=['GET','POST'])
def add_product():
'''
Add a new product to the catalog.
'''
if (not is_logged_in()) or (not is_admin()):
return redirect(url_for('admin.login'))
else:
if request.method == 'POST':
#If id exists, flash(already exists)
name = request.form['name']
description = request.form['description']
if(not name):
flash('Incomplete info. Please try again.')
return render_template('admin_add_product.html')
else:
product = Product.query.filter_by(name=name).first()
if product is None:
try:
product = Product(name,description)
db.session.add(product)
db.session.commit()
flash('Product added successfully!')
return redirect(url_for('product.show_product_detail',prod_key=product.id))
except Exception as e:
flash(str(e))
db.session.rollback()
return redirect(url_for('product.add_product'),code=307)
else:
flash('Product already exists!')
return redirect(url_for('product.add_product'),code=307)
else:
return render_template('admin_add_product.html')
@products_bp.route('/<prod_key>/addSKU',methods=['GET','POST'])
def add_sku(prod_key):
'''
Add a new sku to an existing product.
'''
if (not is_logged_in()) or (not is_admin()):
return redirect(url_for('admin.login'))
else:
if request.method == 'POST':
if(not request.form['properties'] or not request.form['price'] or not request.form['stock_qty']):
#empty fields validation
flash('Invalid details. Please try again.')
return render_template('admin_add_sku.html')
else:
properties = request.form['properties']
price = request.form['price']
stock_qty = request.form['stock_qty']
product = Product.query.get_or_404(int(prod_key))
sku = SKU(properties,stock_qty,price)
product.skus.append(sku)
db.session.add(sku)
db.session.commit()
flash('SKU added successfully!')
return redirect(url_for('product.show_product_detail',prod_key=prod_key))
else:
product = Product.query.get_or_404(int(prod_key), description="Product does not exist!")
return render_template('admin_add_sku.html',prod_key=prod_key)
@products_bp.route('/<sku_id>/updateSKU/',methods=['GET','POST'])
def update_sku(sku_id):
'''
Update a sku with fields like price, stock level etc.
'''
if (not is_logged_in()) or (not is_admin()):
return redirect(url_for('admin.login'))
else:
if request.method == 'POST':
#If id exists, flash(already exists)
properties = request.form['properties']
price = request.form['price']
stock_qty = request.form['stock_qty']
if(not properties or not price or not stock_qty or (int(stock_qty) < 0)):
flash('Incomplete info. Please try again.')
return render_template('admin_update_sku.html')
else:
sku = SKU.query.get_or_404(int(sku_id), description="SKU does not exist!")
try:
#Update sku
sku.properties = properties
sku.price = float(price)
sku.stock_qty = int(stock_qty)
if(sku.stock_qty>0):
sku.in_stock = True
else:
sku.in_stock = False
db.session.commit()
flash('Sku updated successfully!')
except Exception as e:
flash(str(e))
db.session.rollback()
return redirect(url_for('product.show_product_detail',prod_key=sku.product_id))
else:
sku = SKU.query.get_or_404(int(sku_id))
return render_template('admin_update_sku.html',sku=sku)
@products_bp.route('/<sku_id>/addSkuToCart',methods=['POST'])
def add_to_cart(sku_id):
'''
Add a sku to cart. A product with no skus can't be added to cart.
'''
if (not is_customer_logged_in()) or (not is_customer()):
return redirect(url_for('customer.login'))
else:
quantity = int(request.form['quantity'])
customer_id = session['user_id']
sku = SKU.query.get_or_404(int(sku_id))
customer = Customer.query.get_or_404(customer_id)
cart_entry = CartSkus.query.filter_by(sku_id=int(sku_id)).filter_by(customer_id=int(customer_id)).first()
#Check if we have sufficient stocks for the selected SKUs.
if quantity > sku.stock_qty:
flash('Insufficient stock!')
return redirect(url_for('product.show_product_detail',prod_key=sku.product_id))
if cart_entry is None:
with db.session.no_autoflush:
#Case 1: This sku is being added for first time to cart.
try:
cart_entry = CartSkus(quantity)
cart_entry.id = 1234
sku.carts.append(cart_entry)
customer.cart_skus.append(cart_entry)
db.session.add(cart_entry)
db.session.commit()
flash('Sku added successfully to cart!')
except Exception as e:
db.session.rollback()
flash(str(e))
else:
#Case 2: This sku is already present in the cart.
try:
cart_entry.quantity += quantity
db.session.commit()
flash('Sku added successfully to cart!')
except Exception as e:
db.session.rollback()
flash(str(e))
return redirect(url_for('customer.show_cart'))<file_sep>/ecomm/products/models.py
from ecomm import db
from ecomm import app
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255),nullable=False)
description = db.Column(db.String(255), default="")
skus = db.relationship('SKU',backref='product',lazy='dynamic')
def __init__(self, name, description=None):
self.name = str(name)
if(description is not None):
self.description = description
def get_key_values(self,products=None):
if products is None:
products = {}
products[self.id] = {
'name': self.name,
'description': self.description,
}
skus = {}
for sku in self.skus.all():
sku.get_key_values(skus)
products[self.id]['skus'] = skus
return products
class SKU(db.Model):
__tablename__ = 'sku'
id = db.Column(db.Integer, primary_key=True)
properties = db.Column(db.String(255))
product_id = db.Column(db.Integer, db.ForeignKey('product.id'),nullable=False)
in_stock = db.Column(db.Boolean,default=False)
stock_qty = db.Column(db.Integer,nullable=False)
price = db.Column(db.Float,nullable=False)
carts = db.relationship('CartSkus',backref=db.backref('sku'))
order_skus = db.relationship('OrderSkus', backref=db.backref('sku',lazy=True))
def __init__(self,properties,stock_qty,price):
self.properties = properties
self.price = float(price)
self.stock_qty = int(stock_qty)
if(self.stock_qty > 0):
self.in_stock = True
def get_key_values(self,skus=None):
if skus is None:
skus = {}
sku = {}
sku['price'] = self.price
sku['stock quantity'] = self.stock_qty
sku['In stock'] = self.in_stock
sku['Properties'] = self.properties
skus[self.id] = sku
return skus<file_sep>/run.py
from ecomm import app
app.config['SESSION_TYPE'] = 'memcached'
app.secret_key = "random_string"
'''
Initialization of the main application.
'''
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/ecomm/agent/views.py
from flask import Blueprint, request, render_template, session, redirect, url_for, flash
from ecomm.agent import Agent
from ecomm import db
from ecomm.customer import Customer,FinancialLedgerEntry
from ecomm.invoice import Invoice
from datetime import datetime
#Initialize the agent blueprint.
agent_bp = Blueprint('agent',__name__)
def is_logged_in():
return 'user_id' in session
def is_agent():
return ('role' in session) and (session['role'] == 'AGENT')
@agent_bp.route('/login',methods=['GET','POST'])
def login():
'''
Handles the agent login functionality.
'''
if request.method == 'POST':
if(not request.form['pwd'] or not request.form['user'] or \
(Agent.query.filter_by(username=request.form['user']).first() is None) or \
request.form['pwd'] != Agent.query.filter_by(username=request.form['user']).first().password):
flash('Incorrect credentials. Please try to login again.')
return render_template('admin_login.html', url= url_for('agent.login'))
else:
session['user_id'] = Agent.query.filter_by(username=request.form['user']).first().id
session['role'] = 'AGENT'
flash('Logged in successfully!')
return redirect(url_for('agent.home'))
else:
return render_template('admin_login.html', url= url_for('agent.login'))
@agent_bp.route('/')
@agent_bp.route('/home')
def home():
'''
Renders the agent home page.
'''
if (not is_logged_in()) or (not is_agent()):
return redirect(url_for('agent.login'))
else:
#Logged in agent
return render_template('agent_home.html')
@agent_bp.route('/logout')
def logout():
'''
Handles the agent logout functionality.
'''
session.pop('user_id', None)
session.pop('role', None)
flash('Logged out successfully!')
return redirect(url_for('agent.login'))
@agent_bp.route('/customerDetails',methods=['POST'])
def display_customer_details():
'''
Processes and displays orders and financial transactions related to a customer.
'''
if not(is_logged_in() and is_agent()):
flash('You have to log in as an agent to perform this function!')
return redirect(url_for('agent.login'))
else:
customer_id = request.form['customer_id']
#Need to convert the string time recieved from front-end to a datetime object
#So that we can compare with time columns
starting_date_time = datetime.strptime(request.form['starting_date'], "%Y-%m-%dT%H:%M")
ending_date_time = datetime.strptime(request.form['ending_date'], "%Y-%m-%dT%H:%M")
if(request.form['function'] == "Display Orders"):
#If 'Display Orders' functionality was invoked
orders = Invoice.query.filter_by(customer_id=customer_id).filter(Invoice.time >= starting_date_time).\
filter(Invoice.time <= ending_date_time).all()
return render_template('agent_display_orders.html',orders=orders)
elif(request.form['function'] == "Display financial transactions"):
#If 'Display financial transactions' functionality was invoked
customer = Customer.query.filter_by(id=customer_id).first_or_404(description='Customer does not exist!')
ledgerEntries = customer.ledgerEntries.filter(FinancialLedgerEntry.transaction_date >= starting_date_time).\
filter(FinancialLedgerEntry.transaction_date <= ending_date_time).all()
return render_template('agent_display_transactions.html',ledgerEntries=ledgerEntries)
@agent_bp.route('/updateOrder',methods=['POST'])
def update_order():
'''
Handles operations on orders like recording payment, marking an order delivered and cancelling an accepted order.
'''
if not(is_logged_in() and is_agent()):
flash('You have to log in as an agent to perform this function!')
return redirect(url_for('agent.login'))
else:
order_id = request.form['order_id']
order = Invoice.query.get_or_404(order_id, description='Order does not exist!')
if(request.form['function'] == "Record Payment"):
if(order.is_paid == True):
flash('Order is already paid for!')
return redirect(url_for('agent.home'))
customer = Customer.query.get_or_404(order.customer_id)
#Query the latest financial transaction to fetch the current balance.
latest_entry = customer.ledgerEntries.order_by(FinancialLedgerEntry.transaction_date.desc()).first()
#Assuming balance of the customer decreases after paying for the order.
if latest_entry is None:
balance = 0 - order.total
else:
balance = latest_entry.balance - order.total
try:
#Update order and ledger entry to reflect the payment.
order.is_paid = True
order.agent_id = session['user_id']
ledgerEntry = FinancialLedgerEntry(datetime.now(),-1*order.total,balance)
customer.ledgerEntries.append(ledgerEntry)
db.session.add(ledgerEntry)
db.session.commit()
flash('Successfully recorded payment!')
except Exception as e:
db.session.rollback()
flash(str(e))
return redirect(url_for('agent.home'))
elif(request.form['function'] == "Mark Delivered"):
try:
order.status = "DELIVERED"
order.agent_id = session['user_id']
db.session.commit()
flash('State successfully updated!')
except Exception as e:
flash(str(e))
db.session.rollback()
return redirect(url_for('agent.home'))
elif(request.form['function'] == "Cancel Order"):
if(order.status == "DELIVERED"):
flash('Order has been delivered and can\'t be cancelled now.')
return redirect(url_for('agent.home'))
elif(order.status == "CANCELLED"):
flash('Order has already been cancelled.')
return redirect(url_for('agent.home'))
elif(order.status == "ACCEPTED"):
customer = Customer.query.get_or_404(order.customer_id, description="Customer does not exist!")
#Query the latest financial transaction to fetch the current balance.
latest_entry = customer.ledgerEntries.order_by(FinancialLedgerEntry.transaction_date.desc()).first()
if latest_entry is None:
balance = 0 + order.total
else:
balance = latest_entry.balance + order.total
try:
#Update order and ledger entry to reflect order cancellation.
order.status = "CANCELLED"
order.agent_id = session['user_id']
ledgerEntry = FinancialLedgerEntry(datetime.now(), order.total, balance)
customer.ledgerEntries.append(ledgerEntry)
db.session.add(ledgerEntry)
db.session.commit()
flash('Order cancelled successfully!')
except Exception as e:
flash(str(e))
db.session.rollback()
return redirect(url_for('agent.home'))
<file_sep>/ecomm/agent/models.py
from ecomm import db
from ecomm.admin import User
from ecomm.invoice import Invoice
class Agent(User):
id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
orders = db.relationship('Invoice',backref=db.backref('agent'))
__mapper_args__ = {
'polymorphic_identity':'agent'
}
<file_sep>/ecomm/agent/__init__.py
from ecomm.agent.models import Agent<file_sep>/requirements.txt
####### pip install -r rqrmnts.txt #######
flask
flask-sqlalchemy<file_sep>/ecomm/invoice/__init__.py
from ecomm.invoice.models import Invoice, CartSkus, OrderSkus<file_sep>/ecomm/invoice/models.py
from ecomm import db
import enum
'''
ACCEPTED/CANCELLED/DELIVERED orders.
'''
class Invoice(db.Model):
__tablename__ = 'order'
id = db.Column(db.Integer,primary_key=True)
status = db.Column(db.String(50))
customer_id = db.Column(db.Integer,db.ForeignKey('customer.id'))
is_paid = db.Column(db.Boolean,default=False)
time = db.Column(db.DateTime)
order_skus = db.relationship('OrderSkus', backref=db.backref('invoice',lazy=True))
total = db.Column(db.Integer)
agent_id = db.Column(db.Integer,db.ForeignKey('agent.id'))
def __init__(self,status,is_paid,time, total):
self.status = status
self.is_paid = is_paid
self.time = time
self.total = total
'''
SKU Details of orders.
'''
class OrderSkus(db.Model):
__tablename__ = 'order_skus'
order_id = db.Column(db.Integer, db.ForeignKey('order.id'),primary_key=True)
sku_id = db.Column(db.Integer, db.ForeignKey('sku.id'),primary_key=True)
quantity = db.Column(db.Integer)
price = db.Column(db.Integer)
subtotal = db.Column(db.Integer)
def __init__(self,quantity,price, subtotal):
self.quantity= quantity
self.price = price
self.subtotal = subtotal
'''
SKU details of cart items.
'''
class CartSkus(db.Model):
id = db.Column(db.Integer,primary_key=True)
customer_id = db.Column(db.Integer,db.ForeignKey('customer.id'),primary_key=True)
sku_id = db.Column(db.Integer, db.ForeignKey('sku.id'),primary_key=True)
quantity = db.Column(db.Integer)
def __init__(self,quantity):
self.quantity= quantity
<file_sep>/ecomm/admin/models.py
from ecomm import db
import enum
user_roles = db.Table('user_roles',
db.Column('user_id',db.Integer, db.ForeignKey('user.id'),primary_key=True),
db.Column('role_id',db.Integer, db.ForeignKey('role.id'),primary_key=True)
)
'''
Parent class for Admin, Agent and Customer Users.
'''
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String)
password = db.Column(db.String)
email = db.Column(db.String)
first_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
last_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
roles = db.relationship('Role',secondary=user_roles, backref=db.backref('users',lazy='dynamic'))
type = db.Column(db.String(50))
__mapper_args__ = {
'polymorphic_identity':'user',
'polymorphic_on':'type'
}
def __init__(self, username, password, first_name, last_name,email=None):
self.username = username
self.password = <PASSWORD>
self.email = "" if email is None else email
self.first_name = first_name
self.last_name = last_name
def get_key_values(self,users=None):
if users is None:
users = {}
users[user.id] = {
'name': self.username,
'mail': self.email
}
return users
class Admin(User):
id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
__mapper_args__ = {
'polymorphic_identity':'admin'
}
class RoleValues(enum.Enum):
ADMIN = 'Admin'
AGENT = 'Agent'
CUSTOMER = 'Customer'
class Role(db.Model):
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.Enum(RoleValues))
def __init__(self, type):
self.type = type
<file_sep>/ecomm/products/__init__.py
from ecomm.products.models import Product,SKU<file_sep>/ecomm/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db/database.db'
db = SQLAlchemy(app)
from ecomm.admin.views import admin_bp
from ecomm.products.views import products_bp
from ecomm.agent.views import agent_bp
from ecomm.customer.views import customer_bp
app.register_blueprint(admin_bp, url_prefix='/admin')
app.register_blueprint(products_bp, url_prefix='/products')
app.register_blueprint(agent_bp, url_prefix='/agent')
app.register_blueprint(customer_bp, url_prefix='/customer')
#db.drop_all()
db.create_all()
|
19dc12e48a91e6c9e668c279d231fac042e38c20
|
[
"Markdown",
"Python",
"Text"
] | 18 |
Markdown
|
tarun-ssharma/mini-ecommerce-app
|
2cd737aa87feaff164abd6df4a0b230239cc4dc2
|
9bd9540340151b2982a329def973ee83d2b0f82a
|
refs/heads/master
|
<file_sep>package productsstore.demo.utils.validators;
import org.springframework.stereotype.Repository;
import productsstore.demo.entities.Product;
import productsstore.demo.utils.validators.base.Validator;
public class ProductValidator implements Validator<Product> {
private static final int MIN_NAME_LENGTH = 4;
private static final float MIN_PRICE = 0;
private static final int MIN_QUANTITY = 0;
private static final int MAX_NAME_LENGTH = 20;
@Override
public boolean isValid(Product product) {
return product != null &&
isNameValid(product.getName()) &&
isPriceValid(product.getPrice()) &&
isQuantityValid(product.getQuantity());
}
private boolean isQuantityValid(int quantity) {
return quantity > MIN_QUANTITY;
}
private boolean isPriceValid(float price) {
return price > MIN_PRICE;
}
private boolean isNameValid(String name) {
return name != null &&
name.length() >= MIN_NAME_LENGTH &&
name.length() <= MAX_NAME_LENGTH;
}
}
<file_sep>package productsstore.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProductsStoreApplication {
public static void main(String[] args) {
SpringApplication.run(ProductsStoreApplication.class, args);
}
}
<file_sep>package productsstore.demo.entities;
import productsstore.demo.entities.base.ModelEntity;
import javax.persistence.*;
import java.util.Set;
@Entity
@Table(name = "users")
public class User implements ModelEntity {
private int id;
private String username;
private String password;
private Set<Product> products;
@Column(name = "id")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Override
public int getId() {
return id;
}
@Override
public void setId(int id) {
this.id = id;
}
@Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
public Set<Product> getProducts() {
return products;
}
void setProducts(Set<Product> products) {
this.products = products;
}
}
<file_sep>package productsstore.demo.services.base;
import productsstore.demo.entities.Product;
import java.io.InvalidObjectException;
import java.util.List;
public interface ProductsService {
List<Product> getAllProducts();
List<Product> getProductsByCategory(String category);
Product getProductById(int id);
List<Product> getAllProductsByPage(int pageNumber);
List<Product> getProductsByCategoryAndPage(String category, int pageNumber);
void createProduct(Product product) throws InvalidObjectException;
}
<file_sep>package productsstore.demo.config;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import productsstore.demo.entities.Category;
import productsstore.demo.entities.Product;
import productsstore.demo.entities.User;
public class HibernateUtils {
static SessionFactory sessionFactory;
static {
org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration()
.configure();
configuration.addAnnotatedClass(Product.class);
configuration.addAnnotatedClass(Category.class);
configuration.addAnnotatedClass(User.class);
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(configuration.getProperties());
StandardServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
<file_sep>package productsstore.demo.repositories.base;
import productsstore.demo.entities.base.ModelEntity;
import java.util.List;
public interface GenericRepository<T extends ModelEntity> {
List<T> getAll();
T getById(int id);
T create(T entity);
}
<file_sep>package productsstore.demo.config;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import productsstore.demo.entities.Product;
import productsstore.demo.entities.User;
import productsstore.demo.repositories.HibernateRepository;
import productsstore.demo.repositories.base.GenericRepository;
import productsstore.demo.utils.validators.ProductValidator;
import productsstore.demo.utils.validators.base.Validator;
@Configuration
public class AppConfig {
@Bean
@Autowired
GenericRepository<Product> provideProductsGenericRepository(SessionFactory sessionFactory) {
HibernateRepository<Product> repo = new HibernateRepository<>(sessionFactory);
repo.setEntityClass(Product.class);
return repo;
}
@Bean
@Autowired
GenericRepository<User> provideUsersGenericRepository(SessionFactory sessionFactory) {
HibernateRepository<User> repo = new HibernateRepository<>(sessionFactory);
repo.setEntityClass(User.class);
return repo;
}
@Bean
SessionFactory provideSessionFactory() {
return HibernateUtils.getSessionFactory();
}
@Bean
Validator<Product> provideProductValidator() {
return new ProductValidator();
}
}
<file_sep>package productsstore.demo.services;
import org.springframework.stereotype.Service;
import productsstore.demo.entities.Product;
import productsstore.demo.repositories.base.GenericRepository;
import productsstore.demo.services.base.ProductsService;
import productsstore.demo.utils.validators.base.Validator;
import java.io.InvalidObjectException;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class ProductsServiceImpl implements ProductsService {
private static final int PAGE_SIZE = 10;
private static final int PRODUCT_NAME_MIN_LENGTH = 4;
private final GenericRepository<Product> productsRepository;
private final Validator<Product> productValidator;
public ProductsServiceImpl(GenericRepository<Product> productsRepository, Validator<Product> productValidator) {
this.productsRepository = productsRepository;
this.productValidator = productValidator;
}
@Override
public List<Product> getAllProducts() {
return productsRepository.getAll();
}
@Override
public List<Product> getProductsByCategory(String categoryName) {
List<Product> products = productsRepository.getAll();
return products.stream()
.filter(product -> product.getCategories()
.stream()
.anyMatch(category ->
category.getName().equals(categoryName))
)
.collect(Collectors.toList());
}
@Override
public Product getProductById(int id) {
return productsRepository.getById(id);
}
// page: 2, max: 2
// page: 2, max: 1
@Override
public List<Product> getAllProductsByPage(int pageNumber) {
int fromIndex = pageNumber * PAGE_SIZE;
int toIndex = (pageNumber + 1) * PAGE_SIZE;
return getAllProducts()
.subList(fromIndex, toIndex);
}
@Override
public List<Product> getProductsByCategoryAndPage(String category, int pageNumber) {
int fromIndex = pageNumber * PAGE_SIZE;
int toIndex = (pageNumber + 1) * PAGE_SIZE;
return getProductsByCategory(category)
.subList(fromIndex, toIndex);
}
@Override
public void createProduct(Product product) throws InvalidObjectException {
if (!productValidator.isValid(product)) {
throw new InvalidObjectException("Invalid product");
}
productsRepository.create(product);
}
}
|
4b805708fc03a413eacf71bb0965327384c07fb2
|
[
"Java"
] | 8 |
Java
|
Minkov/spring-demo
|
1bcfceb6c39adf6cde9f17b9859af31259c2b800
|
8f54598df1d0146845e935389c78974f1e16d54c
|
refs/heads/master
|
<repo_name>mrwm/williamchung.me<file_sep>/archive/archive/art175/art101/project3/proj3/sketch.js
function clog(x){
console.log(x);
}
var h, m, s; // Hour/minute/second
var colorH, colorM, colorS;
/////////////////////////////////////
// TIME EMULATION
/////////////////////////////////////
var sec = 0;
var mins = 0;
var hrs = 0;
function timeTrack(x){
if (sec >= 59){
sec = 0;
mins++;
}
if (mins >= 59){
mins = 0;
hrs++;
}
if (hrs >= 59){
hrs = 0;
}
if (frameCount % 60 == 0){
sec++;
//clog(hrs+":"+mins+":"+sec);
}
}
/////////////////////////////////////
function setup() {
colorMode(HSB);
createCanvas(windowWidth - (windowWidth/250), windowHeight - (windowHeight/250));
background(20);
//stroke(255);
noStroke();
angleMode(DEGREES);
}
function draw() {
//timeTrack();
background(0);
push();
let h = hour();
//let h = hrs;
let colorH = map(h,0,23,0,255);
fill(colorH, 100, 100);
//console.log(s);
if(h > 11){
translate(width/2, height);
rotate(180);
}
else{
translate(0, 0);
rotate(0);
}
var hMap = map(h,0,23,0,height); // this scales up the values of 0-60 to 0-height
//rotate(-90); // offset rotate
//rotate(hMap);
rect(0,0,width/2,hMap);
pop();
push();
let m = minute();
//let m = mins;
let colorM = map(m,0,60,0,255);
fill(colorM, 100, 100);
//console.log(colorM);
translate(width/2, 0);
var mMap = map(m,0,60,0,height); // this scales up the values of 0-60 to 0-width
//rotate(-90); // offset rotate
//rotate(mMap);
rect(0,0,width/2,mMap);
pop();
/*
push();
//let s = second();
let s = sec;
let colorS = map(s,0,60,0,255);
fill(colorS, 100, 100);
//console.log(s);
translate(width/2, height/2);
var sMap = map(s,0,60,0,360); // this scales up the values of 0-60 to 0-360
rotate(-90); // offset rotate
rotate(sMap);
line(0,0,100,0);
pop();
*/
push();
let s = second();
//s = sec;
colorS = map(s,0,60,0,255);
fill(colorS, 100, 100);
//console.log(s);
var sMapW = map(s,0,60,0,width); // this scales up the values of 0-60 to 0-width
var sMapH = map(s,0,60,0,height); // this scales up the values of 0-60 to 0-height
rect(0,0,sMapW,width/100);
rect(0,0,height/100,sMapH);
pop();
}
<file_sep>/archive/archive/GID56/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="shortcut icon" href="../img/favicon.ico" type="image/x-icon" />
<meta name="description" content="William's Web Portfolio" />
<meta name="keywords" content="portfolio, web, job" />
<meta name="author" content="<NAME>" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="./main.css" rel="stylesheet" type="text/css" media="screen">
<link href="../image.css" rel="stylesheet" type="text/css" media="screen">
<title>GID56 – Home</title>
<style>
picture .picture {
float:right;
width: auto;
margin-left: 12px;
margin: 0.5em;
}
picture:nth-of-type(even) .picture {
float:left;
width: auto;
margin-right: 12px;
}
</style>
</head>
<div class="taco">
<header>
<div class="sub-title">
<a href="index.html"><h1 id="myName"><NAME></h1></a>
<span>GID56 – Home</span>
</div>
</header>
<nav id="mainnav">
<a class="currentNav" href="./index.html">Home</a>
<a class="" href="./gridTheory.html" title="Alum Rock Park">Alum Rock</a>
<a class="" href="./images.html" title="Penitencia Creek Park">Penitencia</a>
<a class="" href="./gridTheoryExtra.html">Photography</a>
<div class="dropDown">
<button class="dropbtn" onclick="toggleMenu(this)">3D Printers</button>
<div class="dropContent">
<a class="" href="./colorTheory.html">Tronxy XY100</a>
<a class="" href="./colorPalette.html">Tronxy XY100 (recolored)</a>
<a class="" href="./linesShapesShadows.html">CR-10</a>
</div>
</div>
<a class="" href="./typography.html">Blocked_</a>
</nav>
<body>
<wrap>
<div class="sub-title">
<a href="#"><h1 class="section-title">About Me</h1></a>
<!--<span> </span>-->
</div>
<!-- Learning another way to implement images -->
<picture onclick="imageThisP(this)">
<source srcset="../img/webp/DSC09275.webp" type="image/webp">
<img class="picture" src="../img/jpg/DSC09275.jpg" alt="Picture of William" title="Picture of William" >
</picture>
<p>Hi, My name is William! I am currently a second year student studying Graphic Design at San Jose State University. From time to time, I like to work on small side projects. <a title="fishies.me" href="https://fishies.me" target="_blank" rel="noopener">Fishies.me</a>, <a title="Doggo Bar" href="https://chrome.google.com/webstore/detail/doggo-bar/jcpkamjdbelgcadjpljdljkelglhkbcg" target="_blank" rel="noopener">Doggo Bar</a>, <a title="Beluga on my Desk" href="https://youtu.be/-Q2aOfKdMvM" target="_blank" rel="noopener">Beluga on my Desk</a>, <a title="Woof" href="https://youtu.be/8K12atna3wc" target="_blank" rel="noopener">Woof</a> are among the many projects I have created! Besides side projects, I also like to go running and hiking while taking <a href="../photography0.html" target="_blank" rel="noopener">pictures</a>. What I like the most about hiking and running around is the part where I get to view the nature around me. On the other hand, I cannot stand running on treadmills. It is not the same as running outside.</p>
<picture onclick="imageThisP(this)">
<source srcset="images/Pikaboo.gif" type="image/gif">
<img class="picture" src="images/Pikaboo.gif" alt="Dog poking head out" title="Pikaboo" >
</picture>
<br>
<br>
<p>I am taking the GID 56 course to learn more about web design and the practices that go along with it. I learned a bit of HTML, CSS, and JS awhile back in a high school course, and I thought that the course did not teach me everything that I wanted to know. I also hope that this course will teach me more about what not to do along with some things that are recommended when designing websites as well. Another reason why I'm taking this course is because I felt that I still have more to learn that I could not learn by myself.</p>
<picture onclick="imageThisP(this)">
<source srcset="../img/webp/P_20170409_144117.webp" type="image/webp">
<img class="picture" src="../img/jpg/P_20170409_144117.jpg" alt="Flowery Tree" title="Flowery Tree" >
</picture>
<picture onclick="imageThisP(this)">
<source srcset="../img/webp/IMG_20160704_172417040_HDR.webp" type="image/webp">
<img class="picture" src="../img/jpg/IMG_20160704_172417040_HDR.jpg" alt="Alviso Park" title="Alviso Park" >
</picture>
<!-- Image Modal -->
<div id="imgModal" class="modal">
<span id="closeBtn">×</span>
<span id="closeScreen"> </span>
<img class="modal-content" id="imgMod">
<div id="caption"></div>
</div>
<footer>
</footer>
</wrap>
</body>
<!-- end taco -->
</div>
<script type="text/javascript" src="../siteFunctions.js"></script>
</html>
<file_sep>/archive/archive/art175/art101/project4/Ex6/sketch.js
var face0 = [
[4, 3, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 3],
[4, 3, 3, 4, 4, 4, 3, 1, 0, 1, 3, 4, 4, 4, 3, 2],
[4, 2, 1, 1, 2, 2, 3, 1, 0, 1, 3, 2, 2, 1, 1, 3],
[4, 3, 2, 4, 4, 4, 2, 1, 0, 1, 2, 4, 4, 2, 1, 3],
[4, 1, 3, 3, 2, 2, 1, 1, 0, 1, 1, 2, 2, 3, 1, 1],
[4, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1],
[3, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 2],
[3, 2, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2],
[3, 2, 2, 1, 2, 3, 4, 2, 2, 4, 3, 1, 1, 1, 1, 2],
[0, 3, 2, 1, 1, 2, 3, 3, 3, 3, 2, 1, 1, 1, 2, 3],
[0, 3, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3],
[0, 3, 2, 1, 3, 4, 0, 0, 0, 0, 0, 4, 0, 2, 3, 3],
[0, 0, 3, 1, 2, 3, 0, 0, 0, 0, 3, 2, 0, 2, 3, 0],
[0, 0, 3, 2, 0, 2, 3, 3, 3, 3, 2, 1, 2, 3, 0, 0],
[0, 0, 0, 3, 0, 1, 2, 2, 2, 2, 1, 1, 2, 3, 0, 0],
[0, 0, 0, 3, 2, 0, 1, 1, 1, 1, 1, 2, 3, 0, 0, 0],
];
var fingers0 = [
[4, 4, 0, 0, 0, 0, 0, 0, 1, 2, 4, 0, 0, 0, 0, 0],
[1, 2, 4, 0, 0, 0, 0, 0, 1, 2, 4, 0, 0, 0, 0, 0],
[1, 1, 2, 4, 0, 0, 0, 0, 1, 2, 4, 0, 0, 0, 0, 0],
[0, 1, 2, 4, 0, 0, 0, 0, 1, 2, 4, 0, 0, 0, 0, 0],
[0, 1, 1, 2, 4, 0, 0, 0, 1, 2, 4, 0, 0, 0, 0, 0],
[0, 0, 1, 2, 4, 0, 0, 0, 3, 3, 3, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 2, 4, 0, 3, 2, 2, 3, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 2, 3, 3, 2, 1, 4, 4, 4, 0, 0, 0, 0],
[0, 0, 0, 1, 2, 3, 2, 1, 3, 2, 3, 4, 0, 0, 0, 0],
[0, 0, 0, 1, 3, 2, 1, 3, 3, 3, 4, 3, 2, 3, 0, 0],
[0, 0, 0, 0, 3, 1, 0, 2, 3, 3, 2, 2, 2, 2, 3, 0],
[0, 0, 0, 0, 2, 0, 1, 2, 3, 2, 2, 2, 2, 1, 3, 0],
[0, 0, 0, 2, 2, 1, 0, 1, 1, 0, 0, 3, 3, 0, 1, 3],
[0, 0, 0, 2, 1, 0, 2, 3, 4, 4, 4, 4, 3, 1, 0, 3],
[0, 0, 0, 2, 1, 0, 1, 2, 3, 4, 4, 3, 3, 1, 0, 2],
[0, 0, 0, 2, 1, 0, 1, 2, 3, 4, 4, 3, 1, 0, 1, 2],
];
var face1 = [
[2, 2, 2, 2, 2, 2, 2],
[2, 0, 0, 0, 0, 0, 2],
[2, 0, 4, 0, 4, 0, 2],
[2, 0, 0, 0, 0, 0, 2],
[2, 4, 0, 0, 0, 4, 2],
[2, 4, 4, 4, 4, 4, 2],
[2, 2, 2, 2, 2, 2, 2]
];
var face2 = [
['w', 'w', 'w', 'w', 'w', 'w', 'w'],
['w', 'g', 'g', 'g', 'g', 'g', 'w'],
['w', 'g', 'b', 'g', 'b', 'g', 'w'],
['w', 'g', 'g', 'g', 'g', 'g', 'w'],
['w', 'b', 'b', 'b', 'b', 'b', 'w'],
['w', 'b', 'g', 'g', 'g', 'b', 'w'],
['w', 'w', 'w', 'w', 'w', 'w', 'w']
];
function setup() {
createCanvas(1000, 500);
colorMode(HSB); // I'd prefer CMYK
background(180,100,50);
noStroke();
//first part
drawarray(face0, "rect", 15, 15, 15);
drawarray(fingers0, "ellipse", 15, 285, 23);
//second part
drawarray(face1, "rect", 15, 540, 15);
drawarray(face2, "rect", 15, 540, 150);
//third part
push();
translate(20, 300);
drawarray(face1, "ellipse", 15, 0, 0);
pop();
push();
translate(150, 300);
rotate(radians(45));
drawarray(face2, "rect", 15, 50, -50);
pop();
push();
translate(600, 490);
rotate(radians(180));
scale(2);
drawarray(face1, "rect", 15, 0, 0);
pop();
}
function setGreyscale(c){
switch(c) {
case 0:
fill(0, 0, 100); //white
break;
case 1:
fill(0, 0, 75); //dark grey
break;
case 2:
fill(0, 0, 50); //grey
break;
case 3:
fill(0, 0, 25); //light grey
break;
case 'w':
fill(0, 0, 100); //white
break;
case 'dg':
fill(0, 0, 75); //dark grey
break;
case 'g':
fill(0, 0, 50); //grey
break;
case 'lg':
fill(0, 0, 25); //light grey
break;
default: // black (left out for 4)
fill(0, 0, 0);
break;
}
}
function drawarray(array, shape, boxSize, xOffset, yOffset) {
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[i].length; j++) {
setGreyscale(array[i][j]);
// typical way of mapping out a grid (counter * scale) + offset
// where counter is a var from the forloop
// scale is value that will term the size/position of each drawing
// offset is a relative movement to place
// the grid collection around on the canvas
//rect((j * 30) + 15, (i * 30) + 15, 20, 20);
if (shape == "rect"){
rect((j * boxSize) + xOffset, (i * boxSize) + yOffset, boxSize, boxSize);
}
else if (shape == "ellipse"){
ellipse((j * boxSize) + xOffset, (i * boxSize) + yOffset, boxSize, boxSize);
}
}
}
}
<file_sep>/archive/archive/art175/art101/project5/proj5/help.js
function setup(){
createCanvas(windowWidth, windowHeight);
background(255);
rect(0, (height/4)*1 + 5, width, -20);
rect(0, (height/4)*2 + 50, width, -70);
rect(0, (height/4)*3 + 50, width, -70);
textAlign(CENTER);
text("Cat is hungry. Guide cat around for cat to eat with the mouse cursor", width/2, (height/4)*1);
let a = createA('cat.html', 'Click here to start');
a.position(width/3, (height/4)*2);
let b = createA('index.html', 'Click here to go back');
b.position(width/3, (height/4)*3);
//text("click here for help", width/2, (height/4)*3);
}
// Resize the canvas when the browser window is changed
function windowResized(){
resizeCanvas(windowWidth, windowHeight);
}
<file_sep>/page.js
/*
Make sure that the text value here match the value inside the links.
To get the google doc link, go to File -> Publish to the web -> embed
and copy the iframe code.
Then take the iframe code and grab the link inside the src=... and paste it
to the number that corresponds to the dictionary.
*/
let pageDict = { // Compare the text within the anchor tags to link index's
"Portfolio": 0,
"Resume": 1,
};
let linkDict = { // then use the index to grab the iframe link
0: "https://docs.google.com/document/d/e/2<KEY>/pub?embedded=true",
1: "https://docs.google.com/document/d/e/2<KEY>Ox<KEY>/pub?embedded=true",
};
function page(x){
/*
This function show/hides the homepage text and frame according to
what is clicked. If a frame is shown, this function will change the
frame source according to what is selected.
eg: If page(1) is called, then the page 1 will be loaded.
*/
// Remove all currentNav classes from the page
let nav = document.getElementsByClassName("currentNav");
for (i=0; i < nav.length; i++){
nav[i].classList.remove("currentNav");
}
// Prepare to get content of 'x'
let inHTML = null;
let targetID = null;
if (x !== null && x.tagName !== undefined){
// Then add the currentNav to the item clicked
x.classList.add("currentNav");
// Grab the text inside the a tag, then set the link accordingly.
inHTML = x.innerHTML;
targetID = pageDict[inHTML];
}
else {
// Set targetID to whatever value x was passed
targetID = pageDict[decodeURI(x)]; //decodeURI() is used to change "%20" to spaces
document.getElementById(targetID).classList.add("currentNav");
}
// Grab the content and frame.
let init = document.getElementById("init");
let frame = document.getElementById("frame");
// Setup the frame text
frame.src = linkDict[targetID];
//// hide the homepage text and show frame if home page is not selected
//if (targetID != 0){
// init.classList.add("hidden");
frame.classList.remove("hidden");
//}
//// otherwise, hide the frame and show the home page
//else {
// frame.src = linkDict[targetID];
// frame.classList.add("hidden");
// init.classList.remove("hidden");
//}
// Enlargen the details tag after clicking the link
detailOpen(true);
// Close the details tag
document.getElementsByTagName("details")[0].removeAttribute("open");
// Force reload the page to clear cache... hope this works?
//location.reload(true);
}
function initialize(){
/*
This function is loaded whenever the page is loaded. This starts by
checking the URL for any hashes (#) and sets the page accordingly.
eg: If the page is loaded with #reading1 in the URL,
the page reading1 will be loaded
*/
// Look for any hashes in the URL
let pageHash = window.location.hash.substr(1);
// Set the value to null if there's no hash
if (pageHash.length == 0 || isNaN(pageDict[pageHash]))
pageHash = "Portfolio";
// Load the page selected in the hash
page(pageHash);
}
// Update the page when the hash changes
window.onhashchange = initialize;
function detailOpen(stat){
/*
This function counts the number of links and subtracts the combined
height of those links from the frame height to keep the iframe in view
*/
// Grab the iframe
let frame = document.getElementById("frame");
// Get the number of links available
let aCount = document.getElementsByTagName("a").length;
// Stat is only passed when passed from the header links,
// so only shorten the iframe when the details tag is open.
if (!document.getElementsByTagName("details")[0].hasAttribute("open") && stat == undefined){
frame.style.height = "calc(100vh - var(--font-size) * (2.6 * " + aCount + ")";
}
else {
//frame.style.height = "calc(100vh - " + fontSizeFloat + "em)";
frame.style.height = "calc(100vh - var(--font-size) * 2.5";
}
}
<file_sep>/archive/archive/art175/art101/project4/proj4/stravaToken.js
/*------------------------------------------------------------------------------
API examples
https://www.strava.com/api/v3/athletes/11865000/stats?access_token=66096461ead04dbc949d54c063e602b65ab70607
http://www.strava.com/oauth/authorize?client_id=40946&response_code=type&redirect_uri=http://localhost:8000/exchange_token&approval_prompt=force&scope=activity:read_all
http://www.strava.com/oauth/authorize?client_id=40946&response_type=code&redirect_uri=http://localhost:8000/index.html&exchange_token&approval_prompt=force&scope=activity:read_all
------------------------------------------------------------------------------*/
//https://stackoverflow.com/questions/5448545/how-to-retrieve-get-parameters-from-javascript/21210643#21210643
//save data into strava
let strava = {}
location.search.substr(1).split("&").forEach(function(item) {strava[item.split("=")[0]] = item.split("=")[1]})
/*
code: ??? <--That's what we want!!! (strava.code)
scope: read,activity:read_all
state: ""
*/
//Reference code for strava api example
//https://yizeng.me/2017/01/11/get-a-strava-api-access-token-with-write-permission/
//Reference code for using XMLHttpRequest()
//https://www.taniarascia.com/how-to-connect-to-an-api-with-javascript/
//Reference code to learn how to use XMLHttpRequest()
//https://stackoverflow.com/questions/49383982/how-to-convert-curl-to-javascript-post-request/49384293#49384293
//Reference code to convert code from api docs (curl -> js)
//https://stackoverflow.com/questions/44097797/how-to-convert-this-curl-command-to-xmlhttprequest-in-javascript/44098794#44098794
var accessToken; //we don't have the access_token yet
var athleteID; //we don't have the ID either
let request = new XMLHttpRequest() //open an ajax request
let baseURL = 'https://www.strava.com/oauth/token'; //URL to grab access_token
let beforeDate = 1546300800; //search for activities before Jan 1, 2019 (epoch)
//let access_token = '<KEY>';
let client_id = 40946; //taken from personal settings
//client_secret was supposed to be here, but removed in the git repo
let grant_type = 'grant_type=authorization_code';//has to be this no matter what
//create a form for grabbing the access key
let formData = new FormData();
//add all the data above into the form:
formData.append('client_id',client_id);
formData.append('client_secret',client_secret);
formData.append('code',strava.code);
formData.append('grant_type','authorization_code');
request.open('POST', baseURL , true);//open the link
request.onload = function() {
// Begin accessing JSON data here
let data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
// data.forEach(this => {
//console.log("this");
//console.log(this);
// })
// } else {
//console.log(data.access_token)
accessToken = data.access_token;
athleteID = data.athlete.id;
getData();
}
}
request.send(formData);
<file_sep>/archive/archive/art175/art101/project4/proj4/stravaData.js
/*------------------------------------------------------------------------------
API examples
https://www.strava.com/api/v3/athletes/11865000/stats?access_token=66096461ead04dbc949d54c063e602b65ab70607
http://www.strava.com/oauth/authorize?client_id=40946&response_code=type&redirect_uri=http://localhost:8000/exchange_token&approval_prompt=force&scope=activity:read_all
http://www.strava.com/oauth/authorize?client_id=40946&response_type=code&redirect_uri=http://localhost:8000/index.html&exchange_token&approval_prompt=force&scope=activity:read_all
------------------------------------------------------------------------------*/
var data;
function getData(){
//https://www.strava.com/api/v3/athletes/11865000/activities?before=1546300800&after=1514764800&per_page=100&access_token=<KEY>
let dataRequest = new XMLHttpRequest() //open an ajax request
let baseURL = "https://www.strava.com/api/v3/athletes/";
let beforeDate = 1546300800;//Jan1 2019
let afterDate = 1514764800;//Jan1 2018
let page = 1; //# of pages
let perPage = 100;//activities per page
let compiledURL = baseURL + athleteID + "/activities?before=" + beforeDate
+ "&after=" + afterDate + "&page=" + page + "&per_page=" + perPage
+ "&access_token=" + accessToken;
dataRequest.open('GET', compiledURL , true);
dataRequest.onload = function() {
//console.log(this);
//console.log(this.response);
// Begin accessing JSON data here
data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
// data.forEach(movie => {
// console.log(movie.title)
// })
// } else {
// console.log(data);
compileData();
}
}
dataRequest.send();
}
var maxDistArr = new Array();
var maxElevArr = new Array();
function compileData(){
let innerDistList = new Array();
let innerElevList = new Array();
let distance = 0;
let elevation = 0;
for(let i=0; i<data.length; i++){
distance += data[i].distance;//total distance
elevation += (data[i].elev_high - data[i].elev_low);//total elevation
let distIndex = parseInt(data[i].distance);
innerDistList[distIndex] = data[i].distance;//sort distance
let elevIndex = parseInt((data[i].elev_high - data[i].elev_low));
innerElevList[elevIndex] = (data[i].elev_high - data[i].elev_low);//sort elevation
}
maxDistArr = innerDistList.filter(function(e){return e});
maxElevArr = innerElevList.filter(function(e){return e});
// console.log(distance +":"+ elevation);
}
<file_sep>/archive/archive/art175/art101/project4/proj4/old/sketch.js
//https://api.census.gov/data/2018/pep/population?get=GEONAME,POP&for=state:*
//https://api.census.gov/data/2017/pep/population?get=GEONAME,POP&for=state:*
//https://api.census.gov/data/2016/pep/population?get=GEONAME,POP&for=state:*
//https://api.census.gov/data/2015/pep/population?get=GEONAME,POP&for=state:*
/*
YEAR | LEAST | MOST
2015 | 586107 | 39144818
2016 | 585501 | 39250017
2017 | 579315 | 39536653
2018 | *577737 | *39557045
* - extremeties
*/
//hold all population data from 2015 to 2018 in an array
var populationList = new Array();
var filteredPop = new Array(); //hold the sorted data
const By = Object.freeze({state:1, population:2, statenumber:3});
function preload() {
//get data from 2015 to 2018
for (let i=0; i<4; ++i){
populationList[i] = loadJSON("https://api.census.gov/data/201" +
(i+5) + //make the increments add to 5, 6, 7, 8
"/pep/population?get=GEONAME,POP&for=state:*");
}
}
function setup() {
colorMode(HSB);
createCanvas(1000, 1000);
background(0);
noStroke();
background(0);
sortPopulationData(By.population);
colorTheData(By.statenumber);
}
//function draw() {
//
//}
function colorTheData(sort){
//workaround for bad practice setting enum value to zero
let sortNum = sort -1;
for (let i=filteredPop.length-1; i>0; i--){ //reverse the draw order
let innerPopList = new Array(); //hold current data
let popIndex = filteredPop[i] //which object list to filter thru
let popSize = Object.keys(popIndex).length; //Can't length objects w/o keys
for (let j=0; j<popSize; j++){
let currentPop = parseInt(popIndex[j][sortNum]);
let popHeight = 0;
let jColorMap = 0;
let jAlphaMap = 0;
switch(sortNum){
case 2: //state numbers aren't consistent, so map to array index instead
popHeight = map(currentPop, 0, 72, 0, height);
jColorMap = (255/i)/i;//map(currentPop, 0, 72, 0, 255);
jAlphaMap = map(currentPop, 0, 72, 255, 0);
break;
default: //can't sort by state name, so only population or state number.
popHeight = map(currentPop, 0, 39557045, 0, height);
jColorMap = map(currentPop, 0, 39557045, 0, 255);
jAlphaMap = map(currentPop, 0, 39557045, 255, 0);
break;
}
//set the X position of each rectangle
let jXposMap = map(j, 0, popSize, 0, width);
fill(jColorMap, 100, 100, jAlphaMap);
var r = rect(jXposMap, 0, width/popSize, popHeight)
}
}
}
function sortPopulationData(sort){
//workaround for bad practice setting enum value to zero
let sortNum = sort -1;
for (let i=0; i<populationList.length; i++){
let innerPopList = new Array(); //used to hold data for sorting later
let popIndex = populationList[i] //which object list to filter thru
let popSize = Object.keys(popIndex).length; //Can't length objects w/o keys
for (let j=0; j<popSize; j++){
switch(sortNum){
case 2:
sortNum = 2;
break;
default: //can't sort by state name, so only population or state number.
sortNum = 1;
break;
}
// let javascript sort the values itself with array index
let popArrayIndex = parseInt(popIndex[j][sortNum]); //sort by state #
innerPopList[popArrayIndex] = popIndex[j];
}
//remove empty elements within arrays:
//https://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript
filteredPop[i] = innerPopList.filter(function(e){return e});
}
}
<file_sep>/archive/archive/art175/art101/project4/proj4/sketch.js
//`data` is the variable holding the json
function preload() {
//most of the json has been handled by the browser through the api script
}
function setup() {
colorMode(HSB);
createCanvas(windowWidth, windowHeight);
background(0);
// noStroke();
}
let sec = 4;
let txt="starting in "
let startDrawing = false;
function draw() {
background('#16161d');
fill(255);
if (frameCount % 60 == 0){
sec--;
if (sec<1){//start after 5 seconds
startDrawing = true;
txt="";
fill(0);
}
txt="starting in "+sec;
}
if (startDrawing)
drawRects();
else
text(txt, width/2, height/2);
}
let prevHeight, prevWidth, rectWidth, rectHeight, elev, fillC;
let distY;
function drawRects(){
for(let i=0; i<data.length; i++){
rectWidth = i*(width/data.length); //map the rect width to available width
rectHeight = map(data[i].distance, maxDistArr[0]/2, maxDistArr[(maxDistArr.length - 1)], 0, height); //map height to distance
if(i!=0){
prevWidth = (i-1)*(width/data.length); //map the rect width to available width
prevHeight = map(data[i-1].distance, maxDistArr[0]/2, maxDistArr[(maxDistArr.length - 1)], 0, height); //map height to distance
}
elev = data[i].elev_high - data[i].elev_low;
fillC = map(elev, maxElevArr[0], maxElevArr[(maxElevArr.length - 1)], 0, 255);
fill(fillC,100,100);
stroke(fillC,100,100);
strokeWeight(4);
if(i!=0){
line(rectWidth, height - rectHeight, prevWidth, height - prevHeight);
}
if ((mouseX > prevWidth) && (mouseX < rectWidth)
){
distY = dist(mouseX, height - rectHeight, mouseX, height - prevHeight);
if(elev > 500)
fill('#e9e9e2');
//rect(mouseX,mouseY,-10,-10);
noStroke();
if (mouseX > width/2)
textAlign(RIGHT);
if (mouseX < width/2)
textAlign(LEFT);
text(prevHeight+"m (distance)",mouseX,height - prevHeight);
text(elev+"m (elevation)",mouseX,mouseY-10);
//frameRate(1);
//console.log(elev);
}
}
}
<file_sep>/archive/archive/art175/chung_paperjs_mod/sketch.js
//inspired by
//http://paperjs.org/examples/rounded-rectangles/
var amount = 100;
var colors = ['red', 'white', 'blue', 'white'];
var increment = 0.1;
function setup(){
rectMode(CENTER);
createCanvas(windowWidth/2, windowHeight/2);
colorMode(HSB);
}
function draw(event) {
background(255);
translate(mouseX,mouseY);
for (let i = 0; i < amount; i+=5) {
var scale = (1 - i / amount) * 500;
rotate(scale);
fill(scale, 100, 100);
rect(0, 0, scale, scale);
}
if (frameCount % 6 == 0){
amount -= increment;
if((amount >= 100)||(amount <= 0))
increment = -increment;
}
/*
for (var i = 0, l = children.length; i < l; i++) {
var item = children[i];
var delta = (mousePoint - item.position) / (i + 5);
item.rotate(Math.sin((event.count + i) / 10) * 7);
if (delta.length > 0.1)
item.position += delta;
}
*/
}
<file_sep>/archive/archive/art175/js/image.js
/////////////////////////////////////////
// This section is for the image modal //
/////////////////////////////////////////
// Get the modal
var modal = document.getElementById("imgModal");
function imageThis(_this){
modal.style.display = "block";
var captionText = document.getElementById("caption");
var modalImg = document.getElementById("img01");
modalImg.src = _this.src;
captionText.innerHTML = _this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("modal")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function(){
modal.style.display = "none";
}
document.onkeydown = function(evt) {
evt = evt || window.event;
if(evt.key === "Escape") {
modal.style.display = "none";
}
//console.log(evt);
};
<file_sep>/archive/archive/art175/cat/animate.js
let cat, cat_sheet;
function preload(){
cat = loadAnimation('img/cat-0.png', 'img/cat-1.png', 'img/cat-2.png', 'img/cat-3.png', 'img/cat-4.png');
//cat = loadAnimation(cat_sheet);
}
function setup(){
createCanvas(windowWidth, windowHeight);
}
function draw(){
animation(cat, 100,100);
}
<file_sep>/archive/README.md
# williamchung.me
my personal site
<file_sep>/archive/archive/art175/art101/project5/Ex8/sketch.js
/*
Shorthand method of writing conditionals.
This...
if (condition)
run code; //the semicolon acts like the closing curled bracket
Is the same thing as this...
if (condition){
run code;
}
The only downside is that it's only limited to one line.
*/
//play / lead to song / color -> note
// Circle code taken and modified from here:
// https://editor.p5js.org/coloringchaos/sketches/SkZVaxF0-
/* ----- Main character ----- */
let cat; // Cat image
let eatCount = 0; // Amount of food eaten
let xpos, ypos; // Position of the cat
/* ----- Sound ----- */
let noteC, noteE, noteG, meow;
// Credits to the meow: Battle cats game created by PONOS
// I do not own the sound effects. They were taken from the link below:
// https://www.youtube.com/watch?v=dd9ALQYYfn4
/* ----- Gyroscope ----- */
let gyro = false; // Checking if gyroscope is going to be used
let a, b, g; // Accelerometer variables
/* ----- Environment ----- */
let bgColor = '#d1d1d1'; // Background color
let circles = []; // Hold the spawned circles.
/* ----- Food properties ----- */
let arrayN = 5; // Total of food to spawn
let foodX = new Array(arrayN); // Store X position of cat food
let foodY = new Array(arrayN); // Store Y position of cat food
let foodH = new Array(arrayN); // Store color value of food
// Preparation for external files
function preload() {
// cat = loadImage('img/cat.svg'); // Spawn the cat!
cat = "cat"; // Spawn the cat!
noteC = loadSound('sound/C.mp3');
noteE = loadSound('sound/E.mp3');
noteG = loadSound('sound/G.mp3');
meow = loadSound('sound/meow.mp3');
}
function setup() {
// Can't play audio without initializing
// https://p5js.org/reference/#/p5.sound/userStartAudio
let myDiv = createDiv('click to start audio');
myDiv.position(0, 0);
userStartAudio().then(function() {
myDiv.remove(); // Remove the message once clicked
});
colorMode(HSB); // I like using HSB
createCanvas(windowWidth, windowHeight); // Fullscreen the canvas!
background(bgColor); // Set the background white
// default values for accelerometer
a = 0;
b = 0;
g = 0;
// Initial position of the cat
xpos = 0;
ypos = 0;
// Initialize the catfood
catFood();
}
// Resize the canvas when the browser window is changed
function windowResized(){
resizeCanvas(windowWidth, windowHeight);
}
function draw() {
background(bgColor); // Set the background color
mX = pmouseX - cat.width; // Offset the cat position to center
mY = pmouseY - cat.height; // Offset cat position to center
// Taken and modified from the kadenze code
let easing = 0.5;
let diffX, diffY;
if (!gyro){ // Use cursor position if gyroscope isn't enabled.
diffX = (mX) - xpos;
diffY = (mY) - ypos;
}
else{ // Use gyroscope if checked
diffX = g - xpos;
diffY = b - ypos;
}
xpos += diffX * easing;
ypos += diffY * easing;
// The code for moving the cat around
//push();
//translate(xpos,ypos);
//image(cat, cat.width/2, cat.height/2); // Offset the cat to be centered
//text(cat, xpos, ypos); // Offset the cat to be centered
text('cat', xpos, ypos); // Offset the cat to be centered
// For visual debugging the collision detection
//fill(50,0.5);
//rect(cat.width/2, cat.height/2,cat.width,cat.height)
//pop();
// Update and display our circles everytime draw loops
for(var i= 0; i<circles.length; i++){
circles[i].update();
circles[i].ellipse();
// If circle has reached it's lifespan, then delete it
if(circles[i].lifespan <= 0){
circles.splice(i, 1);
}
}
catFoodShow(); // Draw the cat food
catEat(); // Constantly check if food is touched
}
// Initialize the cat food
function catFood(){
for (let i=0; i < arrayN; i++) { // Best practice to use `let` instead of `var` (variable scoping)
foodX[i] = round( random(20, width-20) ); // Limit the food from spawning
foodY[i] = round( random(20, height-20) ); // too close to the border
foodH[i] = (random(0, 255)); // Set a random color
fill(foodH[i], 100, 100);
let rectDim = 20; // Setup rectangle dimentions
rect(foodX[i],foodY[i],rectDim,rectDim); // Draw cat food
}
}
// Spawn the cat food (constantly runs)
let rectDim = 20; // We can declare the same variable because of the variable scope using 'let'
function catFoodShow(){
for (let i=0; i < arrayN; i++) {
fill(foodH[i], 100, 100);
rect(foodX[i],foodY[i],rectDim,rectDim);
}
}
// Make sure the cat is able to eat
function catEat(){
// Setup an offset 'coz rectmode is in the corner and cursor is in the center
let detectX = xpos + 0;//cat.width;
let detectY = ypos + 0;//cat.height;
for (var i=0; i < arrayN; i++) {
// Oh boy, the logic below gave me a headache... pseudo detecting the
// overlapping rectangle of the cat and cat food was annoying to write
// if ( (detectX+cat.width/2>foodX[i]) && (detectX-cat.width/2<(foodX[i]+rectDim)) &&
// (detectY+cat.height/2>foodY[i]) && (detectY-cat.height/2<(foodY[i]+rectDim))
// ){
if ( (detectX+0/2>foodX[i]) && (detectX-0/2<(foodX[i]+rectDim)) &&
(detectY+0/2>foodY[i]) && (detectY-0/2<(foodY[i]+rectDim))
){
// Assign a new position once eaten
foodX[i] = round( random(20, width-20) );
foodY[i] = round( random(20, height-20) );
foodH[i] = (random(0, 255));
fill(foodH[i], 100, 100);
rect(foodX[i],foodY[i],rectDim,rectDim);
// For visual debugging
//rect(detectX-cat.width/2,detectY-cat.height/2,cat.width,cat.height);
//console.log("chomp");
// Show circles at where the food spawns
circles.push(new Circle(foodX[i] + rectDim/2, foodY[i] + rectDim/2, random(7, 15), foodH[i]));
circles.push(new Circle(foodX[i] + rectDim/2, foodY[i] + rectDim/2, random(22, 28), foodH[i]));
circles.push(new Circle(foodX[i] + rectDim/2, foodY[i] + rectDim/2, random(36, 43), foodH[i]));
eatCount++; // Increase the count of food eaten
// Play the note according to order of divisible by round(random(7, 10)), 2, 3, 1
if (eatCount % round(random(7, 10)) == 0){
circles.push(new Circle(xpos + 0, ypos + 0, random(7, 15), foodH[i]));
circles.push(new Circle(xpos + 0, ypos + 0, random(22, 28), foodH[i]));
circles.push(new Circle(xpos + 0, ypos + 0, random(36, 43), foodH[i]));
meow.play()
}
else if (eatCount % 2 == 0){
noteE.play()
}
else if (eatCount % 3 == 0){
noteG.play()
}
else if (eatCount % 1 == 0){
noteC.play()
}
}
}
}
// Making the circles
function Circle(x, y, s, h){
//set any properties
this.x = x; //x position
this.y = y; //y position
this.s = s; //circle size
this.h = h; //circle size
//give each circle a lifespan
this.lifespan = 30;
//define methods
//this draws the ellipse
this.ellipse = function(){
// Define visual propoerties of the ellipse
push();
stroke(this.h, 100, 100);
strokeWeight(3);
noFill();
// Draw the ellipse
ellipse(this.x, this.y, this.s);
pop();
}
// This makes it grow
this.update = function(){
this.s = this.s + 3;
this.lifespan--;
}
}
// https://coursescript.com/notes/interactivecomputing/mobile/gyroscope/
// Gyroscope Data
window.addEventListener('deviceorientation', function(e)
{
// Use the gyroscope by default if detected
if ((e.alpha!=null) && (e.beta!=null) && (e.gamma!=null))
gyro = true;
// Map the tilt degree so we don't go too far into the rotation
if (e.alpha!=null)
a = map(e.alpha, -180, 180, -90, 90); // Probably rotation counter/clockwise?
// Over compensate to be able to reach the screen edges without flipping the phone upside down
if (e.beta!=null)
b = map(e.beta, -180, 180, -height/2, height+(height/4)); // Face phone (up/down)
if (e.gamma!=null)
g = map(e.gamma, -180, 180, -width/2, width+(width/4)); // Face phone (tilt left/right)
});
<file_sep>/archive/archive/art175/site2/js/p1.js
/*
This js file assigns a random class to the grid elements and adds a random
column span. It also allows users to scroll horizontally with the vertical
scroll wheel. Lastly, it makes the page expand infinitely as long as the user
continues to scroll
*/
var items = 40;
// click code
// hides the div that is clicked
document.addEventListener('click', function (event) {
if (event.target.className.includes("item") && !(/^([1-9]|10)$/.test(event.target.innerHTML))){
event.target.remove();}
//event.target.style = "display: none;"} //old code that hides as opposed to delete
}, false);
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomInt(max) {
return (Math.floor(Math.random() * Math.floor(max)) + 1);
}
var scrollAmount; // save amount scrolled
// Create a list of images for random generation
var imgList = new Array();
/* Idea + some code taken from here:
https://stackoverflow.com/questions/8810927/showing-an-image-from-an-array-of-images-javascript
*/
imgList[0] = new Image();
imgList[0].src = 'img/bat.jpg';
imgList[0].alt = 'Happy Bat';
imgList[0].title = 'Happy Bat';
imgList[1] = new Image();
imgList[1].src = 'img/broom.jpg';
imgList[1].alt = 'Broom';
imgList[1].title = 'Broom';
imgList[2] = new Image();
imgList[2].src = 'img/candy.png';
imgList[2].alt = 'Inedible Candy';
imgList[2].title = 'Inedible Candy';
imgList[3] = new Image();
imgList[3].src = 'img/ghost.png';
imgList[3].alt = 'Happy Ghost';
imgList[3].title = 'Happy Ghost';
imgList[4] = new Image();
imgList[4].src = 'img/hat.jpg';
imgList[4].alt = 'Witch Hat';
imgList[4].title = 'Witch Hat';
imgList[5] = new Image();
imgList[5].src = 'img/pumpkin.jpg';
imgList[5].alt = 'Happy Pumpkin';
imgList[5].title = 'Happy Pumpkin';
imgList[6] = new Image();
imgList[6].src = 'img/skeleton.jpg';
imgList[6].alt = 'Happy Skeleton';
imgList[6].title = 'Happy Skeleton';
imgList[7] = new Image();
imgList[7].src = 'img/spider.png';
imgList[7].alt = 'Happy Spider';
imgList[7].title = 'Happy Spider';
imgList[8] = new Image();
imgList[8].src = 'img/web.jpg';
imgList[8].alt = 'Spider Web';
imgList[8].title = 'Spider Web';
// End of image list
// side scroll
f = document.getElementById('grid');
f.onwheel = function(e){
f.scrollLeft += e.deltaY * Math.abs(e.deltaY);
scrollAmount = f.scrollLeft;
var scrollProgress = Math.round((scrollAmount / f.scrollWidth) * 100);
//console.log(scrollProgress+"%");
// Choose a random item and clone it to the end of the page
// once you scroll past 40% of the page
if (scrollProgress > 40){
var e = f.children[getRandomInt(10)].cloneNode(true);
items++;
var imgNumber = getRandomInt(8);
e.innerHTML = items + "<img src='"
+ imgList[imgNumber].src
+ "' alt='"
+ imgList[imgNumber].alt
+ "' title='"
+ imgList[imgNumber].title
+ "'>";
f.appendChild(e);
}
}
// Sets a random span for each div item
// return a weird error in forfox for some reason (a bug? imaginary element?)
for (var i = 0; f.children.length; i++){
//console.log(f.children[i]);
var nameOfClass = "span"+getRandomInt(10);
var spanAmount = "grid-column-end: span "+getRandomInt(2)+" ;";
f.children[i].classList.add(nameOfClass);
f.children[i].style = spanAmount;
var imgNumber = getRandomInt(8);
f.children[i].innerHTML = i + "<img src='"
+ imgList[imgNumber].src
+ "' alt='"
+ imgList[imgNumber].alt
+ "' title='"
+ imgList[imgNumber].title
+ "'>";
//console.log(spanAmount);
}
|
436a1c9bb5cc0db12160536a29c11eb789c4b6fe
|
[
"JavaScript",
"HTML",
"Markdown"
] | 15 |
JavaScript
|
mrwm/williamchung.me
|
242a69af8da0eb2d6957b9836f3616556b2949f1
|
6cec0656c6e0f8d77c4c4d862d3428c27a4ae55d
|
refs/heads/master
|
<repo_name>kutsyk/Breakout<file_sep>/breakout.js
var canvas = document.getElementById("404Canvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var mainColor = "#CC424A";
var helpfulColor = "#1F1F1F";
var xSpeed = 3;
var ySpeed = -3;
var speedLimit = 6;
var speedUpTimeout = 100; //milliseconds
var acceleraton = 1.001;
var dx = 0;
var dy = 0;
var paddleHeight = 3;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
var brickRowCount = 25;
var brickColumnCount = 11;
var brickWidth = 30;
var brickHeight = 15;
var brickPadding = 5;
var brickOffsetTop = 70;
var brickOffsetLeft = 30;
var prevScore = 1;
var score = 0;
var lives = 3; //adding lives 5 and max lives will be 10
var bricks = [];
var triged = false;
var briksLeft;
var colors = [
"#FF0000","#FF4000","#FF8000","#FFC100","#FCFF00","#BBFF00","#7BFF00","#3AFF00","#00FF05","#00FF45","#00FF86","#00FFC6","#00F6FF","#00B6FF","#0075FF","#0035FF","#0A00FF","#4B00FF","#8B00FF","#CC00FF","#FF00F1","#FF00B0","#FF0070"
]
var gameMap = [
[0,0,1,0,1,1,1,0,0,0,0,1,1,1,1,1,0,0,0,0,1,0,1,1,1],
[0,1,1,0,1,1,1,0,0,0,1,1,1,1,1,1,0,0,0,1,1,0,1,1,1],
[1,1,1,0,1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1],
[1,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1],
[1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1,0,0,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1,0,0,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1,0,0,1,1,1,1,1,1,1],
[0,0,0,0,1,1,1,0,0,1,1,1,0,1,1,1,0,0,0,0,0,0,1,1,1],
[0,0,0,0,1,1,1,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1],
[0,0,0,0,1,1,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,0],
[0,0,0,0,1,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0],
];
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return colors[Math.floor(Math.random() * 32)];
}
for(var c=0; c<brickColumnCount; c++) {
bricks[c] = [];
for(r=0; r<brickRowCount; r++) {
if(gameMap[c][r] == 1) {
if (Math.floor(Math.random() * 32) < Math.floor(Math.random() * 5)) {
bricks[c][r] = {x: 0, y: 0, status: 1, color: "grey", triged: true};
} else
bricks[c][r] = {x: 0, y: 0, status: 1, color: "grey", triged: false};
}
else
bricks[c][r] = { x: 0, y: 0, status: 0, color: "grey" };
}
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
document.addEventListener("mousemove", mouseMoveHandler, false);
document.addEventListener("mousedown", mouseDownHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}else if(e.keyCode == 32)
mouseDownHandler(e);
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
}
function mouseMoveHandler(e) {
var relativeX = e.clientX - canvas.offsetLeft;
if(relativeX - paddleWidth / 2 > 0 && relativeX + paddleWidth / 2 < canvas.width) {
paddleX = relativeX - paddleWidth / 2;
if(dy == 0)
x = paddleX + paddleWidth / 2;
}
if (relativeX < 0) {
paddleX = 0;
} else if (relativeX > canvas.width) {
paddleX = canvas.width - paddleWidth;
}
}
function mouseDownHandler(e) {
if(y > canvas.height - paddleHeight-ballRadius * 2 - 10)
{
dx = xSpeed;
dy = ySpeed;
}
}
function collisionDetection() {
for(var c = 0; c < brickColumnCount; c++) {
for(var r=0; r < brickRowCount; r++) {
var b = bricks[c][r];
if(b.status == 1) {
if( (x+ballRadius) > b.x && (x-ballRadius) < (b.x + brickWidth)
&&
y > b.y && y < (b.y + brickHeight) ) {
if(!triged)
triged = b.triged;
changeWay(true, b);
return;
}else if( x > b.x && x < (b.x + brickWidth)
&&
(y+ballRadius) > b.y && (y-ballRadius) < (b.y + brickHeight) ) {
if(!triged)
triged = b.triged;
changeWay(false, b);
return;
}
}
}
}
}
function changeWay(isX, b)
{
if(isX)
dx = -dx;
else
dy = -dy;
b.status = 0;
score += b.triged ? 100 : 5;
if(briksLeft == 0)
{
alert("YOU WIN, CONGRATS!");
document.location.reload();
}
}
function drawBall() {
ctx.beginPath();
if(dy == 0)
{
ctx.arc(paddleX + paddleWidth / 2, y, ballRadius, 0, Math.PI * 2);
}else
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = mainColor;
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
if(rightPressed && paddleX < canvas.clientWidth - paddleWidth)
paddleX += 3;
else if(leftPressed && paddleX > 0)
paddleX -= 3;
ctx.rect(paddleX, canvas.height-paddleHeight - 10, paddleWidth, paddleHeight);
if(dy == 0)
x = paddleX + paddleWidth/2;
ctx.fillStyle = "black";
ctx.fill();
ctx.closePath();
}
function drawBricks() {
briksLeft = 0;
for(var c = 0; c < brickColumnCount; c++) {
for(var r = 0; r < brickRowCount; r++) {
if(bricks[c][r].status == 1) {
var brickX = (r*(brickWidth+brickPadding))+brickOffsetLeft;
var brickY = (c*(brickHeight+brickPadding))+brickOffsetTop;
bricks[c][r].x = brickX;
bricks[c][r].y = brickY;
ctx.beginPath();
ctx.rect(brickX, brickY, brickWidth, brickHeight);
ctx.fillStyle = getColor();
ctx.fill();
ctx.closePath();
briksLeft++;
}
}
}
}
var framesCount = 600;
var frames = framesCount;
function getColor(){
if(triged || frames < framesCount){
--frames;
if(frames == 0){
frames = framesCount;
triged = false;
}
return getRandomColor();
}else {
return helpfulColor;
}
}
function drawScore() {
ctx.font = "bold 24px Arial";
ctx.fillStyle = helpfulColor;
//ctx.fillText(/*"SCORE: ",*/ canvas.width - canvas.width/2-25;, 20);
ctx.fillStyle = mainColor;
ctx.fillText(score, canvas.width/2, 20);
}
function drawLives() {
ctx.font = "bold 16px Arial";
ctx.fillStyle = helpfulColor;
ctx.fillText("LIVES:", 9, 20);
for(var i = 0;i < lives;++i)
drawLife(i);
}
function drawLife(i)
{
ctx.beginPath();
ctx.rect( (70 + i * 40), 7, brickWidth, brickHeight);
ctx.fillStyle = mainColor;
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBricks();
drawBall();
drawPaddle();
drawScore();
drawLives();
collisionDetection();
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if(y + dy < ballRadius) {
dy = -dy;
}
else if(y + dy > (canvas.height - ballRadius - 10) ) {
if(x + ballRadius > paddleX && x - ballRadius < paddleX + paddleWidth) {
dy = -dy;
}
else {
lives--;
if(!lives) {
alert("GAME OVER");
document.location.reload();
}
else {
x = canvas.width/2;
y = canvas.height-30;
dx = 0;
dy = 0;
}
}
}
if(rightPressed && paddleX < canvas.width - paddleWidth) {
paddleX += 7;
}
else if(leftPressed && paddleX > 0) {
paddleX -= 7;
}
x += dx;
y += dy;
requestAnimationFrame(draw);
}
function speedUp() {
if (dx == 0 || dy == 0) {
setTimeout(speedUp, speedUpTimeout);
return;
}
if (Math.abs(dx) > speedLimit || Math.abs(dy) > speedLimit) {
setTimeout(speedUp, speedUpTimeout);
return;
}
dx = dx * acceleraton;
dy = dy * acceleraton;
setTimeout(speedUp, speedUpTimeout);
}
draw();
speedUp();
<file_sep>/js/main.js
var Monthes = {Jan: 1, Feb: 2, Mar: 3, Apr: 4, May: 5,
Jun: 6, Jul: 7, Aug: 8, Sep: 9, Oct: 10, Nov: 11, Dec: 12};
// load data
queue()
.defer(d3.json, "/data/oblasti.json")
.defer(d3.json, "/data/dataviz1.json")
.defer(d3.json, "/data/report_1_2013.json")
.defer(d3.json, "/data/report_2_2013.json")
.defer(d3.json, "/data/report_3_2013.json")
.await(ready);
function ready(error, oblasti, dataviz1) {
$("#datepicker").datepicker({
format: "mm-yyyy",
viewMode: "months",
minViewMode: "months",
startDate: '01-2013'
});
$('#datepicker').datepicker('update', new Date(2013, 1, 1));
$("#datepicker").datepicker().on('changeDate', function (e) {
updateMap();
});
// Whenever the brush moves, re-rendering everything.
function renderAll() {
updateMap();
}
function updateMap() {
var month = Monthes[String($("#datepicker").datepicker('getDate')).split(" ")[1]];
console.log(month);
var year = String($("#datepicker").datepicker('getDate')).split(" ")[3];
$.getJSON('/data/report_' + month + '_' + year + '.json', function (data) {
render_map(dataviz1.coordinates, oblasti, data.quantities);
});
}
function render_map(data, borders, quantity) {
//console.log(borders);
var width = 980,
height = 750;
var canvas = d3.select("#chart").node(),
context = canvas.getContext("2d");
// bounding box for Ukraine
var xmax = 40.5; // d3.max(data, function(d){ return d.lon})
var xmin = 22.0; //d3.min(data, function(d){ return d.lon})
var ymax = 53.5; //d3.max(data, function(d){ return d.lat})
var ymin = 44.0; //d3.min(data, function(d){ return d.lat})
// scales
//var cs_x = d3.scale.linear().domain([xmin, xmax]).range([0, width]);
var cs_x = width / (xmax - xmin);
//var cs_y = d3.scale.linear().domain([ymin, ymax]).range([0, height]);
var cs_y = height / (ymax - ymin);
var rad_scale = d3.scale.linear().domain([10, 2600]).range([0.1, 2.6]);
var color = d3.scale.linear()
.domain([-0.8, 0, 0.8])
.range(["#05528e", "silver", "#e0700b"]);
d3.select(canvas)
.attr("width", width)
.attr("height", height)
// clear all
context.fillStyle = "rgba(" + 255 + "," + 255 + "," + 255 + "," + 1 + ")";
context.fillRect(0, 0, width, height);
context.globalAlpha = 0.4;
// draw borders
context.beginPath();
for (var i = 0, l = borders.features.length; i < l; i++) {
var feature = borders.features[i];
var coords = feature.geometry.coordinates;
//cs_x*(p.lon-xmin), height - 40 - cs_y*(p.lat-ymin)
context.moveTo(cs_x * (coords[0][0] - xmin), height - 40 - cs_y * (coords[0][1] - ymin));
for (var i1 = 1, l1 = coords.length; i1 < l1; i1++) {
var pair = coords[i1];
context.lineTo(cs_x * (pair[0] - xmin), height - 40 - cs_y * (pair[1] - ymin));
}
}
context.strokeStyle = "#000";
context.lineWidth = 1;
context.stroke();
// eof draw borders
var i = -1,
n = data.length;
//for(var ovk_num in data){
while (++i < n) {
var p = data[i];
context.fillStyle = "#f8931d";
// draw station as a circle, actually
context.beginPath();
if (quantity == null)
context.arc(cs_x * (p.lon - xmin), height - 40 - cs_y * (p.lat - ymin), 5, 0, 2 * Math.PI, true);
else {
context.arc(cs_x * (p.lon - xmin), height - 40 - cs_y * (p.lat - ymin), quantity[i].qua / 4000, 0, 2 * Math.PI, true);
}
context.fill();
context.fillStyle = "#000000";
//There are several options for setting text
context.font = "bolder 14px Arial";
//textAlign supports: start, end, left, right, center
context.textAlign = "center"
//textBaseline supports: top, hanging, middle, alphabetic, ideographic bottom
if (quantity != null) {
context.textBaseline = "hanging"
context.fillText(quantity[i].qua, cs_x * (p.lon - xmin), height - 40 - cs_y * (p.lat - ymin));
}
context.closePath();
}
}
renderAll();
}<file_sep>/README.md
# Breakout
This project contains simple examples for [Hromadske](https://hromadske.ua/).
Game for 404 result page:

Map visualisation:

Donut visualisation:

|
c6a1e4333af5b29240b1e2621ff11aee0c1368da
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
kutsyk/Breakout
|
e5e28e6d8983302b733873be2388fc67517ba806
|
1bcd970f8270dc3f2501b2dc5f8a06703c3be6f5
|
refs/heads/master
|
<file_sep>import React, {Component} from 'react';
import writerHeader from '../pics/writer-header.jpg';
import profile from '../pics/profile.JPG';
import './header.css';
export default class Header extends Component{
render(){
return(
<div className="header">
<h1 className="header-title">VC Mobile Signing Agent</h1>
<img className="writer-header" src={writerHeader} />
<img className="profile" src={profile} />
<h1 className="name-title"><NAME>, Mobile Signing Agent</h1><br/>
</div>
)
}
}
|
8f0a54d932112f33045a0214ae2d72835e65fec2
|
[
"JavaScript"
] | 1 |
JavaScript
|
andrew23c/notary
|
f438b3b5bfe6f1db861c7447eddab64f1d7c16e6
|
3323c3a292a879365ac7e4d3266166f9fc431c18
|
refs/heads/master
|
<file_sep>package es.sacyl.caza.farmacia.modelo.clases;
// Generated 30-abr-2014 13:00:04 by Hibernate Tools 3.2.1.GA
/**
* Reenvasados generated by hbm2java
*/
public class Reenvasados implements java.io.Serializable {
private Integer idReenvasado;
private String descripcion;
private String principioActivo;
private String lot;
private String caduca;
public Reenvasados() {
}
public Reenvasados(String descripcion) {
this.descripcion = descripcion;
}
public Reenvasados(String descripcion, String principioActivo, String lot, String caduca) {
this.descripcion = descripcion;
this.principioActivo = principioActivo;
this.lot = lot;
this.caduca = caduca;
}
public Integer getIdReenvasado() {
return this.idReenvasado;
}
public void setIdReenvasado(Integer idReenvasado) {
this.idReenvasado = idReenvasado;
}
public String getDescripcion() {
return this.descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getPrincipioActivo() {
return this.principioActivo;
}
public void setPrincipioActivo(String principioActivo) {
this.principioActivo = principioActivo;
}
public String getLot() {
return this.lot;
}
public void setLot(String lot) {
this.lot = lot;
}
public String getCaduca() {
return this.caduca;
}
public void setCaduca(String caduca) {
this.caduca = caduca;
}
}
<file_sep>/*
* 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 es.sacyl.caza.farmacia.vista;
import java.awt.Image;
import java.awt.Toolkit;
/**
*
* @author enrique
*/
public class VentanaPrincipal extends javax.swing.JFrame {
/**
* Creates new form VentanaPrincipal
*/
public VentanaPrincipal() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jDialogAcercaDe = new javax.swing.JDialog();
jPanel3 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jButtonCerrarAcercaDe = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
bntVentanaPrincipalEdicionPMS = new javax.swing.JButton();
btnVentanaPrincipalHojaElaboración = new javax.swing.JButton();
bntVentanaPrincipalSalir = new javax.swing.JButton();
bntVentanaPrincipalReenvasados = new javax.swing.JButton();
jButtonAcercaDe = new javax.swing.JButton();
jDialogAcercaDe.setTitle("Acerca de");
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/images.jpg"))); // NOI18N
jButtonCerrarAcercaDe.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonCerrarAcercaDe.setText("Cerrar");
jButtonCerrarAcercaDe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCerrarAcercaDeActionPerformed(evt);
}
});
jPanel4.setBackground(new java.awt.Color(255, 255, 255));
jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setText("Versión: 1.01");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel2.setText("Farmacotecnia");
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setText("<NAME>");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setText("Hecho por:");
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel4))
.addComponent(jLabel5)))
.addGap(24, 24, 24))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jLabel5)
.addContainerGap())
);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(jButtonCerrarAcercaDe))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 69, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(66, 66, 66)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
.addComponent(jButtonCerrarAcercaDe)
.addGap(44, 44, 44))
);
javax.swing.GroupLayout jDialogAcercaDeLayout = new javax.swing.GroupLayout(jDialogAcercaDe.getContentPane());
jDialogAcercaDe.getContentPane().setLayout(jDialogAcercaDeLayout);
jDialogAcercaDeLayout.setHorizontalGroup(
jDialogAcercaDeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jDialogAcercaDeLayout.setVerticalGroup(
jDialogAcercaDeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Farmacotecnia");
setIconImage(getIconImage());
setResizable(false);
jPanel1.setBackground(new java.awt.Color(204, 204, 204));
jPanel1.setPreferredSize(new java.awt.Dimension(980, 700));
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
bntVentanaPrincipalEdicionPMS.setBackground(new java.awt.Color(204, 204, 255));
bntVentanaPrincipalEdicionPMS.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
bntVentanaPrincipalEdicionPMS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/producto.png"))); // NOI18N
bntVentanaPrincipalEdicionPMS.setMnemonic('P');
bntVentanaPrincipalEdicionPMS.setText("Productos, materiales, etc..");
bntVentanaPrincipalEdicionPMS.setEnabled(false);
bntVentanaPrincipalEdicionPMS.setFocusPainted(false);
bntVentanaPrincipalEdicionPMS.setHideActionText(true);
bntVentanaPrincipalEdicionPMS.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
bntVentanaPrincipalEdicionPMS.setIconTextGap(10);
bntVentanaPrincipalEdicionPMS.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
bntVentanaPrincipalEdicionPMS.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
bntVentanaPrincipalEdicionPMSMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
bntVentanaPrincipalEdicionPMSMouseExited(evt);
}
});
bntVentanaPrincipalEdicionPMS.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bntVentanaPrincipalEdicionPMSActionPerformed(evt);
}
});
btnVentanaPrincipalHojaElaboración.setBackground(new java.awt.Color(250, 120, 120));
btnVentanaPrincipalHojaElaboración.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnVentanaPrincipalHojaElaboración.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/factura.png"))); // NOI18N
btnVentanaPrincipalHojaElaboración.setMnemonic('H');
btnVentanaPrincipalHojaElaboración.setText("Hojas de elaboración");
btnVentanaPrincipalHojaElaboración.setEnabled(false);
btnVentanaPrincipalHojaElaboración.setFocusPainted(false);
btnVentanaPrincipalHojaElaboración.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnVentanaPrincipalHojaElaboración.setMaximumSize(new java.awt.Dimension(199, 83));
btnVentanaPrincipalHojaElaboración.setMinimumSize(new java.awt.Dimension(199, 83));
btnVentanaPrincipalHojaElaboración.setPreferredSize(new java.awt.Dimension(199, 83));
btnVentanaPrincipalHojaElaboración.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnVentanaPrincipalHojaElaboración.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btnVentanaPrincipalHojaElaboraciónMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btnVentanaPrincipalHojaElaboraciónMouseExited(evt);
}
});
btnVentanaPrincipalHojaElaboración.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnVentanaPrincipalHojaElaboraciónActionPerformed(evt);
}
});
bntVentanaPrincipalSalir.setBackground(new java.awt.Color(255, 204, 153));
bntVentanaPrincipalSalir.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
bntVentanaPrincipalSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/etiqueta.png"))); // NOI18N
bntVentanaPrincipalSalir.setMnemonic('E');
bntVentanaPrincipalSalir.setText("Etiquetas");
bntVentanaPrincipalSalir.setEnabled(false);
bntVentanaPrincipalSalir.setFocusPainted(false);
bntVentanaPrincipalSalir.setHideActionText(true);
bntVentanaPrincipalSalir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
bntVentanaPrincipalSalir.setIconTextGap(10);
bntVentanaPrincipalSalir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
bntVentanaPrincipalSalir.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
bntVentanaPrincipalSalirMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
bntVentanaPrincipalSalirMouseExited(evt);
}
});
bntVentanaPrincipalSalir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bntVentanaPrincipalSalirActionPerformed(evt);
}
});
bntVentanaPrincipalReenvasados.setBackground(new java.awt.Color(255, 255, 102));
bntVentanaPrincipalReenvasados.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
bntVentanaPrincipalReenvasados.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/reenvasado.png"))); // NOI18N
bntVentanaPrincipalReenvasados.setMnemonic('R');
bntVentanaPrincipalReenvasados.setText("Reenvasados");
bntVentanaPrincipalReenvasados.setEnabled(false);
bntVentanaPrincipalReenvasados.setFocusPainted(false);
bntVentanaPrincipalReenvasados.setHideActionText(true);
bntVentanaPrincipalReenvasados.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
bntVentanaPrincipalReenvasados.setIconTextGap(10);
bntVentanaPrincipalReenvasados.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
bntVentanaPrincipalReenvasados.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
bntVentanaPrincipalReenvasadosMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
bntVentanaPrincipalReenvasadosMouseExited(evt);
}
});
bntVentanaPrincipalReenvasados.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bntVentanaPrincipalReenvasadosActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(bntVentanaPrincipalReenvasados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(bntVentanaPrincipalEdicionPMS, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(48, 48, 48)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnVentanaPrincipalHojaElaboración, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bntVentanaPrincipalSalir, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(22, 22, 22))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(bntVentanaPrincipalEdicionPMS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnVentanaPrincipalHojaElaboración, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(49, 49, 49)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bntVentanaPrincipalSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bntVentanaPrincipalReenvasados, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21))
);
bntVentanaPrincipalEdicionPMS.getAccessibleContext().setAccessibleDescription("");
jButtonAcercaDe.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/ayuda.png"))); // NOI18N
jButtonAcercaDe.setToolTipText("Acerca de");
jButtonAcercaDe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonAcercaDeActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(30, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButtonAcercaDe, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButtonAcercaDe, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(21, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 567, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 563, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void bntVentanaPrincipalSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntVentanaPrincipalSalirActionPerformed
VentanaEtiquetas.instance.mostrarTodasEtiquetas();
VentanaEtiquetas.instance.setLocationRelativeTo(null);
VentanaEtiquetas.instance.setVisible(true);
}//GEN-LAST:event_bntVentanaPrincipalSalirActionPerformed
private void bntVentanaPrincipalEdicionPMSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntVentanaPrincipalEdicionPMSActionPerformed
// VentanaEdicionPMS.instance;
VentanaEdicionPMS.instance.setLocationRelativeTo(this);
VentanaEdicionPMS.instance.setVisible(true);
}//GEN-LAST:event_bntVentanaPrincipalEdicionPMSActionPerformed
private void btnVentanaPrincipalHojaElaboraciónActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVentanaPrincipalHojaElaboraciónActionPerformed
VentanaHojasElaboracion.instance.setLocationRelativeTo(this);
VentanaHojasElaboracion.instance.setVisible(true);
}//GEN-LAST:event_btnVentanaPrincipalHojaElaboraciónActionPerformed
private void bntVentanaPrincipalEdicionPMSMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntVentanaPrincipalEdicionPMSMouseEntered
if (bntVentanaPrincipalEdicionPMS.isEnabled()) {
bntVentanaPrincipalEdicionPMS.setBackground(new java.awt.Color(145, 145, 187));
}
}//GEN-LAST:event_bntVentanaPrincipalEdicionPMSMouseEntered
private void bntVentanaPrincipalEdicionPMSMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntVentanaPrincipalEdicionPMSMouseExited
bntVentanaPrincipalEdicionPMS.setBackground(new java.awt.Color(204, 204, 255));
}//GEN-LAST:event_bntVentanaPrincipalEdicionPMSMouseExited
private void btnVentanaPrincipalHojaElaboraciónMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnVentanaPrincipalHojaElaboraciónMouseExited
btnVentanaPrincipalHojaElaboración.setBackground(new java.awt.Color(250, 120, 120));
}//GEN-LAST:event_btnVentanaPrincipalHojaElaboraciónMouseExited
private void btnVentanaPrincipalHojaElaboraciónMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnVentanaPrincipalHojaElaboraciónMouseEntered
if (btnVentanaPrincipalHojaElaboración.isEnabled()) {
btnVentanaPrincipalHojaElaboración.setBackground(new java.awt.Color(230, 48, 48));
}
}//GEN-LAST:event_btnVentanaPrincipalHojaElaboraciónMouseEntered
private void bntVentanaPrincipalReenvasadosMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntVentanaPrincipalReenvasadosMouseEntered
if (bntVentanaPrincipalReenvasados.isEnabled()) {
bntVentanaPrincipalReenvasados.setBackground(new java.awt.Color(255, 255, 0));
}
}//GEN-LAST:event_bntVentanaPrincipalReenvasadosMouseEntered
private void bntVentanaPrincipalReenvasadosMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntVentanaPrincipalReenvasadosMouseExited
bntVentanaPrincipalReenvasados.setBackground(new java.awt.Color(255, 255, 102));
}//GEN-LAST:event_bntVentanaPrincipalReenvasadosMouseExited
private void bntVentanaPrincipalSalirMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntVentanaPrincipalSalirMouseExited
bntVentanaPrincipalSalir.setBackground(new java.awt.Color(255, 204, 153));
}//GEN-LAST:event_bntVentanaPrincipalSalirMouseExited
private void bntVentanaPrincipalSalirMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntVentanaPrincipalSalirMouseEntered
if (bntVentanaPrincipalSalir.isEnabled()) {
bntVentanaPrincipalSalir.setBackground(new java.awt.Color(252, 139, 27));
}
}//GEN-LAST:event_bntVentanaPrincipalSalirMouseEntered
private void bntVentanaPrincipalReenvasadosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntVentanaPrincipalReenvasadosActionPerformed
VentanaReenvasados.instance.setLocationRelativeTo(this);
VentanaReenvasados.instance.setVisible(true);
}//GEN-LAST:event_bntVentanaPrincipalReenvasadosActionPerformed
private void jButtonCerrarAcercaDeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCerrarAcercaDeActionPerformed
jDialogAcercaDe.setVisible(false);
}//GEN-LAST:event_jButtonCerrarAcercaDeActionPerformed
private void jButtonAcercaDeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAcercaDeActionPerformed
jDialogAcercaDe.setSize(430, 330);
jDialogAcercaDe.setLocationRelativeTo(null);
jDialogAcercaDe.setVisible(true);
}//GEN-LAST:event_jButtonAcercaDeActionPerformed
public void sesionCargada() {
bntVentanaPrincipalEdicionPMS.setEnabled(true);
bntVentanaPrincipalReenvasados.setEnabled(true);
btnVentanaPrincipalHojaElaboración.setEnabled(true);
bntVentanaPrincipalSalir.setEnabled(true);
}
@Override
public Image getIconImage() {
Image retValue = Toolkit.getDefaultToolkit().
getImage(getClass().getResource("/es/sacyl/caza/farmacia/resources/images.jpg"));
return retValue;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new VentanaPrincipal().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bntVentanaPrincipalEdicionPMS;
private javax.swing.JButton bntVentanaPrincipalReenvasados;
private javax.swing.JButton bntVentanaPrincipalSalir;
private javax.swing.JButton btnVentanaPrincipalHojaElaboración;
private javax.swing.JButton jButtonAcercaDe;
private javax.swing.JButton jButtonCerrarAcercaDe;
private javax.swing.JDialog jDialogAcercaDe;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
// End of variables declaration//GEN-END:variables
}
<file_sep>package es.sacyl.caza.farmacia.modelo.clases;
// Generated 30-abr-2014 13:00:04 by Hibernate Tools 3.2.1.GA
/**
* ProductosUnion generated by hbm2java
*/
public class ProductosUnion implements java.io.Serializable {
private Integer idComponenteUnion;
private Productos productos;
private FichasDeMedicamentos fichasDeMedicamentos;
private String cantidad;
private String unidades;
private String orden;
public ProductosUnion() {
}
public ProductosUnion(Productos productos) {
this.productos = productos;
}
public ProductosUnion(Productos productos, FichasDeMedicamentos fichasDeMedicamentos, String cantidad, String unidades, String orden) {
this.productos = productos;
this.fichasDeMedicamentos = fichasDeMedicamentos;
this.cantidad = cantidad;
this.unidades = unidades;
this.orden = orden;
}
public Integer getIdComponenteUnion() {
return this.idComponenteUnion;
}
public void setIdComponenteUnion(Integer idComponenteUnion) {
this.idComponenteUnion = idComponenteUnion;
}
public Productos getProductos() {
return this.productos;
}
public void setProductos(Productos productos) {
this.productos = productos;
}
public FichasDeMedicamentos getFichasDeMedicamentos() {
return this.fichasDeMedicamentos;
}
public void setFichasDeMedicamentos(FichasDeMedicamentos fichasDeMedicamentos) {
this.fichasDeMedicamentos = fichasDeMedicamentos;
}
public String getCantidad() {
return this.cantidad;
}
public void setCantidad(String cantidad) {
this.cantidad = cantidad;
}
public String getUnidades() {
return this.unidades;
}
public void setUnidades(String unidades) {
this.unidades = unidades;
}
public String getOrden() {
return this.orden;
}
public void setOrden(String orden) {
this.orden = orden;
}
}
<file_sep>package es.sacyl.caza.farmacia;
import es.sacyl.caza.farmacia.vista.VentanaPrincipal;
/**
*
* @author <NAME>
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//TODO: poner pantalla de carga para la inicialización del hibernate
VentanaPrincipal vista= new VentanaPrincipal();
vista.setLocationRelativeTo(null);
vista.setVisible(true);
HiloInicializacionHibernate ini= new HiloInicializacionHibernate(vista);
ini.start();
}
}
<file_sep>
package es.sacyl.caza.farmacia.modelo;
import org.hibernate.Session;
/**
*
* @author <NAME>
*/
public class DAO {
//Abrir sesion de hibernate
public Session abrirSesion(){
Session sesion = NewHibernateUtil.getSessionFactory().openSession();
return sesion;
}
//Cerrar una sesion de hibernate
public void cerrarSesion(Session sesion){
sesion.close();
}
//Primera sesion
public void primeraSesion() throws Exception{
Session sesion = abrirSesion();
cerrarSesion(sesion);
}
}
<file_sep>/*
* 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 es.sacyl.caza.farmacia.vista;
import es.sacyl.caza.farmacia.controlador.ControladorFichasDeMedicamentos;
import es.sacyl.caza.farmacia.controlador.ControladorMaquinaria;
import es.sacyl.caza.farmacia.controlador.ControladorMaterialElaborar;
import es.sacyl.caza.farmacia.controlador.ControladorMaterialEnvasar;
import es.sacyl.caza.farmacia.controlador.ControladorProductos;
import java.awt.Image;
import java.awt.Toolkit;
/**
*
* @author enrique
*/
public class VentanaHojasElaboracion extends javax.swing.JFrame {
ControladorFichasDeMedicamentos control;
public PanelMaquinaria panelAddMaquinaria;
public ControladorMaquinaria controlMaquinaria;
public PanelMaterialElaboracion panelAddMaterialElaboracion;
public ControladorMaterialElaborar controlMaterialElaborar;
public PanelMaterialEnvasar panelAddMaterialEnvasar;
public ControladorMaterialEnvasar controlMaterialEnvasar;
public PanelProductos panelAddProductos;
public ControladorProductos controlProductos;
public final static VentanaHojasElaboracion instance= new VentanaHojasElaboracion(null, false);
/**
* Creates new form VentanaHojasElaboracion
*/
private VentanaHojasElaboracion(java.awt.Frame parent, boolean modal) {
super("Hojas de elaboración");
initComponents();
addPanelesADialog();
controlMaquinaria = new ControladorMaquinaria(panelAddMaquinaria);
controlMaterialElaborar = new ControladorMaterialElaborar(panelAddMaterialElaboracion);
controlMaterialEnvasar = new ControladorMaterialEnvasar(panelAddMaterialEnvasar);
controlProductos = new ControladorProductos(panelAddProductos);
//Cambiar la cantidad que se mueve el scroll al girar la rueda del ratón
jScrollPane1.getVerticalScrollBar().setUnitIncrement(20);
control = new ControladorFichasDeMedicamentos(this);
// jButtonAceptarFichasDeMedicamentos.setVisible(false);
// jButtonCancelarFichasDeMedicamentos.setVisible(false);
jPanelAceptarCancelar.setVisible(false);
jPanelAceptarCancelar.setBackground(new java.awt.Color(245,83,83,200));
}
//Añade los paneles correspondientes a cada JDialog
private void addPanelesADialog() {
//Panel maquinaria
panelAddMaquinaria = new PanelMaquinaria(true);
javax.swing.GroupLayout jDialogAddMaquinariaLayout = new javax.swing.GroupLayout(jDialogAddMaquinaria.getContentPane());
jDialogAddMaquinaria.getContentPane().setLayout(jDialogAddMaquinariaLayout);
jDialogAddMaquinariaLayout.setHorizontalGroup(
jDialogAddMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 975, Short.MAX_VALUE)
.addGroup(jDialogAddMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jDialogAddMaquinariaLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(panelAddMaquinaria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
jDialogAddMaquinariaLayout.setVerticalGroup(
jDialogAddMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 575, Short.MAX_VALUE)
.addGroup(jDialogAddMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jDialogAddMaquinariaLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(panelAddMaquinaria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
//Panel material elaboracion
panelAddMaterialElaboracion = new PanelMaterialElaboracion(true);
javax.swing.GroupLayout jDialogAddMaterialElaborarLayout = new javax.swing.GroupLayout(jDialogAddMaterialElaborar.getContentPane());
jDialogAddMaterialElaborar.getContentPane().setLayout(jDialogAddMaterialElaborarLayout);
jDialogAddMaterialElaborarLayout.setHorizontalGroup(
jDialogAddMaterialElaborarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 975, Short.MAX_VALUE)
.addGroup(jDialogAddMaterialElaborarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jDialogAddMaterialElaborarLayout.createSequentialGroup()
.addComponent(panelAddMaterialElaboracion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
jDialogAddMaterialElaborarLayout.setVerticalGroup(
jDialogAddMaterialElaborarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 600, Short.MAX_VALUE)
.addGroup(jDialogAddMaterialElaborarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelAddMaterialElaboracion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
//Panel material para envasar
panelAddMaterialEnvasar = new PanelMaterialEnvasar(true);
javax.swing.GroupLayout jDialogAddMaterialEnvasarLayout = new javax.swing.GroupLayout(jDialogAddMaterialEnvasar.getContentPane());
jDialogAddMaterialEnvasar.getContentPane().setLayout(jDialogAddMaterialEnvasarLayout);
jDialogAddMaterialEnvasarLayout.setHorizontalGroup(
jDialogAddMaterialEnvasarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 975, Short.MAX_VALUE)
.addGroup(jDialogAddMaterialEnvasarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jDialogAddMaterialEnvasarLayout.createSequentialGroup()
.addComponent(panelAddMaterialEnvasar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
jDialogAddMaterialEnvasarLayout.setVerticalGroup(
jDialogAddMaterialEnvasarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 600, Short.MAX_VALUE)
.addGroup(jDialogAddMaterialEnvasarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelAddMaterialEnvasar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
//Panel productos
panelAddProductos = new PanelProductos(true);
javax.swing.GroupLayout jDialogAddProductosLayout = new javax.swing.GroupLayout(jDialogAddProducto.getContentPane());
jDialogAddProducto.getContentPane().setLayout(jDialogAddProductosLayout);
jDialogAddProductosLayout.setHorizontalGroup(
jDialogAddProductosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 975, Short.MAX_VALUE)
.addGroup(jDialogAddProductosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jDialogAddProductosLayout.createSequentialGroup()
.addComponent(panelAddProductos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
jDialogAddProductosLayout.setVerticalGroup(
jDialogAddProductosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 600, Short.MAX_VALUE)
.addGroup(jDialogAddProductosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelAddProductos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}
@Override
public Image getIconImage() {
Image retValue = Toolkit.getDefaultToolkit().
getImage(getClass().getResource("/es/sacyl/caza/farmacia/resources/images.jpg"));
return retValue;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jDialogAddMaquinaria = new javax.swing.JDialog();
jDialogAddMaterialElaborar = new javax.swing.JDialog();
jDialogAddMaterialEnvasar = new javax.swing.JDialog();
jDialogAddProducto = new javax.swing.JDialog();
jDialogModificarProducto = new javax.swing.JDialog();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jComboBoxDialogModificarProductoUnidades = new javax.swing.JComboBox();
jButtonDialogModificarProductoAceptar = new javax.swing.JButton();
jLabelDialogModificarProductoProductos = new javax.swing.JLabel();
jButtonDialogModificarProductoCancelar = new javax.swing.JButton();
jTextFieldDialogModificarProductoCantidad = new javax.swing.JTextField();
jLabel18 = new javax.swing.JLabel();
jLabel20 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
jCheckBoxCSP = new javax.swing.JCheckBox();
jDialogEtiquetas = new javax.swing.JDialog();
jPanel5 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jLabel19 = new javax.swing.JLabel();
jButtonDialogEtiquetasVolver = new javax.swing.JButton();
jButtonDialogEtiquetasNuevaEtiqueta = new javax.swing.JButton();
jButtonDialogEtiquetasVerEtiquetas = new javax.swing.JButton();
jPopupMenuCopiarPegar = new javax.swing.JPopupMenu();
jMenuItemCopiar = new javax.swing.JMenuItem();
jMenuItemPegar = new javax.swing.JMenuItem();
jToolBarProductos = new javax.swing.JToolBar();
jButtonPrimeroFichasDeMedicamentos = new javax.swing.JButton();
jButtonAtrasFichasDeMedicamentos = new javax.swing.JButton();
jSeparator3 = new javax.swing.JToolBar.Separator();
jLabelPosicionFichasDeMedicamentos = new javax.swing.JLabel();
jSeparator4 = new javax.swing.JToolBar.Separator();
jButtonSiguienteFichasDeMedicamentos = new javax.swing.JButton();
jButtonUltimoFichasDeMedicamentos = new javax.swing.JButton();
jSeparator2 = new javax.swing.JToolBar.Separator();
jButtonNuevoFichasDeMedicamentos = new javax.swing.JButton();
jButtonModificarFichasDeMedicamentos = new javax.swing.JButton();
jButtonEliminarFichasDeMedicamentos = new javax.swing.JButton();
jButtonMostrarEtiqueta = new javax.swing.JButton();
jButtonImprimir = new javax.swing.JButton();
jLayeredPane1 = new javax.swing.JLayeredPane();
jPanelAceptarCancelar = new javax.swing.JPanel();
jButtonAceptarFichasDeMedicamentos = new javax.swing.JButton();
jButtonCancelarFichasDeMedicamentos = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
jPanelListaFichasDeMedicamentos = new javax.swing.JPanel();
jScrollPaneListaMedicamentos = new javax.swing.JScrollPane();
jListFichasDeMedicamentos = new javax.swing.JList();
jPanelEdicionDatosFichasDeMedicamentos = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jScrollPane4 = new javax.swing.JScrollPane();
jTextAreaMedicamento = new javax.swing.JTextArea();
jLabelIdFichasDeMedicamentos = new javax.swing.JLabel();
jComboBoxVeredicto = new javax.swing.JComboBox();
jTextFieldObservacionesVeredicto = new javax.swing.JTextField();
jScrollPane3 = new javax.swing.JScrollPane();
jTextAreaProcedimiento = new javax.swing.JTextArea();
jScrollPane5 = new javax.swing.JScrollPane();
jTextAreaObservaciones = new javax.swing.JTextArea();
jScrollPane6 = new javax.swing.JScrollPane();
jTextAreaEstabilidad = new javax.swing.JTextArea();
jComboBoxViaAdministracion = new javax.swing.JComboBox();
jTextFieldDatosOrganolepsis = new javax.swing.JTextField();
jScrollPane8 = new javax.swing.JScrollPane();
jTextAreaParaEtiqueta = new javax.swing.JTextArea();
jScrollPane7 = new javax.swing.JScrollPane();
jTextAreaObservacionesElaboracion = new javax.swing.JTextArea();
jScrollPane9 = new javax.swing.JScrollPane();
jTextAreaOrigen = new javax.swing.JTextArea();
jComboBoxEDO = new javax.swing.JComboBox();
jComboBoxTipo = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
jComboBoxElaboradoPor = new javax.swing.JComboBox();
jPanelProductosBuscar = new javax.swing.JPanel();
jLabel16 = new javax.swing.JLabel();
jComboBoxBuscarFichasDeMedicamentos = new javax.swing.JComboBox();
jTextFieldBuscarFichasDeMedicamentos = new javax.swing.JTextField();
jButtonBuscarFichasDeMedicamentos = new javax.swing.JButton();
jButtonQuitarBuscarFichasDeMedicamentos = new javax.swing.JButton();
jCheckBoxMostrarTodo = new javax.swing.JCheckBox();
jPanelMaquinaria = new javax.swing.JPanel();
jScrollPane10 = new javax.swing.JScrollPane();
jTableMaquinaria = new javax.swing.JTable();
jButtonAddMaquinaria = new javax.swing.JButton();
jButtonEliminarMaquinaria = new javax.swing.JButton();
jPanelMaterialEnvasar = new javax.swing.JPanel();
jScrollPane11 = new javax.swing.JScrollPane();
jTableMaterialEnvasar = new javax.swing.JTable();
jButtonAddMaterialEnvasar = new javax.swing.JButton();
jButtonEliminarMaterialEnvasar = new javax.swing.JButton();
jPanelMaterialElaborar = new javax.swing.JPanel();
jScrollPane12 = new javax.swing.JScrollPane();
jTableMaterialElaborar = new javax.swing.JTable();
jButtonAddMaterialElaborar = new javax.swing.JButton();
jButtonEliminarMaterialElaborar = new javax.swing.JButton();
jPanelProductos = new javax.swing.JPanel();
jScrollPane13 = new javax.swing.JScrollPane();
jTableProductos = new javax.swing.JTable();
jButtonAddProducto = new javax.swing.JButton();
jButtonModificarProducto = new javax.swing.JButton();
jButtonEliminarProducto = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItemArchivoNuevo = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
jMenuItemArchivoSalir = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItemEditarModificar = new javax.swing.JMenuItem();
jMenuItemEditarEliminar = new javax.swing.JMenuItem();
jSeparator15 = new javax.swing.JPopupMenu.Separator();
jMenuItemAddMaquinaria = new javax.swing.JMenuItem();
jMenuItemAddMaterialElaborar = new javax.swing.JMenuItem();
jMenuItemAddMaterialEnvasar = new javax.swing.JMenuItem();
jMenuItemAddProducto = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItemVerPrimero = new javax.swing.JMenuItem();
jMenuItemVerAnterior = new javax.swing.JMenuItem();
jSeparator14 = new javax.swing.JPopupMenu.Separator();
jMenuItemVerSiguiente = new javax.swing.JMenuItem();
jMenuItemVerUltimo = new javax.swing.JMenuItem();
jDialogAddMaquinaria.setTitle("Farmacotecnia->Hojas de elaboración->Añadir maquinaria");
jDialogAddMaquinaria.setAlwaysOnTop(true);
jDialogAddMaquinaria.setModal(true);
jDialogAddMaquinaria.setResizable(false);
javax.swing.GroupLayout jDialogAddMaquinariaLayout = new javax.swing.GroupLayout(jDialogAddMaquinaria.getContentPane());
jDialogAddMaquinaria.getContentPane().setLayout(jDialogAddMaquinariaLayout);
jDialogAddMaquinariaLayout.setHorizontalGroup(
jDialogAddMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialogAddMaquinariaLayout.setVerticalGroup(
jDialogAddMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
jDialogAddMaterialElaborar.setTitle("Farmacotecnia->Hojas de elaboración->Añadir material elaboración");
jDialogAddMaterialElaborar.setAlwaysOnTop(true);
jDialogAddMaterialElaborar.setModal(true);
javax.swing.GroupLayout jDialogAddMaterialElaborarLayout = new javax.swing.GroupLayout(jDialogAddMaterialElaborar.getContentPane());
jDialogAddMaterialElaborar.getContentPane().setLayout(jDialogAddMaterialElaborarLayout);
jDialogAddMaterialElaborarLayout.setHorizontalGroup(
jDialogAddMaterialElaborarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 975, Short.MAX_VALUE)
);
jDialogAddMaterialElaborarLayout.setVerticalGroup(
jDialogAddMaterialElaborarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 600, Short.MAX_VALUE)
);
jDialogAddMaterialEnvasar.setTitle("Farmacotecnia->Hojas de elaboración->Añadir material para envasar");
jDialogAddMaterialEnvasar.setAlwaysOnTop(true);
jDialogAddMaterialEnvasar.setModal(true);
javax.swing.GroupLayout jDialogAddMaterialEnvasarLayout = new javax.swing.GroupLayout(jDialogAddMaterialEnvasar.getContentPane());
jDialogAddMaterialEnvasar.getContentPane().setLayout(jDialogAddMaterialEnvasarLayout);
jDialogAddMaterialEnvasarLayout.setHorizontalGroup(
jDialogAddMaterialEnvasarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialogAddMaterialEnvasarLayout.setVerticalGroup(
jDialogAddMaterialEnvasarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
jDialogAddProducto.setTitle("Farmacotecnia->Hojas de elaboración->Añadir producto");
jDialogAddProducto.setAlwaysOnTop(true);
jDialogAddProducto.setModal(true);
javax.swing.GroupLayout jDialogAddProductoLayout = new javax.swing.GroupLayout(jDialogAddProducto.getContentPane());
jDialogAddProducto.getContentPane().setLayout(jDialogAddProductoLayout);
jDialogAddProductoLayout.setHorizontalGroup(
jDialogAddProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialogAddProductoLayout.setVerticalGroup(
jDialogAddProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
jDialogModificarProducto.setAlwaysOnTop(true);
jDialogModificarProducto.setModal(true);
jPanel2.setBackground(new java.awt.Color(255, 223, 204));
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 255), 2), "Modificar producto"));
jComboBoxDialogModificarProductoUnidades.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jComboBoxDialogModificarProductoUnidades.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ML", "MG", "L", "GR", "gotas", "bolsas", "vial", "comp", "cápsulas", "frasco", "ampollas" }));
jButtonDialogModificarProductoAceptar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonDialogModificarProductoAceptar.setText("Aceptar");
jLabelDialogModificarProductoProductos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabelDialogModificarProductoProductos.setText("jLabel21");
jButtonDialogModificarProductoCancelar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonDialogModificarProductoCancelar.setText("Cancelar");
jTextFieldDialogModificarProductoCantidad.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTextFieldDialogModificarProductoCantidad.setText("jTextField2");
jLabel18.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel18.setText("Unidades:");
jLabel20.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel20.setText("Cantidad:");
jLabel17.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel17.setText("Producto:");
jCheckBoxCSP.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jCheckBoxCSP.setText("C.S.P. (cantidad suficiente para)");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBoxCSP)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel17)
.addGap(18, 18, 18)
.addComponent(jLabelDialogModificarProductoProductos))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel20)
.addGap(18, 18, 18)
.addComponent(jTextFieldDialogModificarProductoCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jButtonDialogModificarProductoAceptar)
.addGap(18, 18, 18)
.addComponent(jButtonDialogModificarProductoCancelar))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel18)
.addGap(18, 18, 18)
.addComponent(jComboBoxDialogModificarProductoUnidades, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(27, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel17)
.addComponent(jLabelDialogModificarProductoProductos))
.addGap(18, 18, 18)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel20)
.addComponent(jTextFieldDialogModificarProductoCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jCheckBoxCSP)
.addGap(18, 18, 18)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(jComboBoxDialogModificarProductoUnidades, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonDialogModificarProductoAceptar)
.addComponent(jButtonDialogModificarProductoCancelar))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(30, 30, 30))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(33, Short.MAX_VALUE))
);
javax.swing.GroupLayout jDialogModificarProductoLayout = new javax.swing.GroupLayout(jDialogModificarProducto.getContentPane());
jDialogModificarProducto.getContentPane().setLayout(jDialogModificarProductoLayout);
jDialogModificarProductoLayout.setHorizontalGroup(
jDialogModificarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jDialogModificarProductoLayout.setVerticalGroup(
jDialogModificarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jDialogEtiquetas.setAlwaysOnTop(true);
jDialogEtiquetas.setModal(true);
jPanel5.setBackground(new java.awt.Color(255, 223, 204));
jPanel4.setBackground(new java.awt.Color(251, 250, 250));
jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 255), 2));
jLabel19.setBackground(new java.awt.Color(255, 255, 255));
jLabel19.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel19.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel19.setText("¿Qué desea hacer con el medicamento seleccionado?");
jButtonDialogEtiquetasVolver.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonDialogEtiquetasVolver.setText("Volver");
jButtonDialogEtiquetasNuevaEtiqueta.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonDialogEtiquetasNuevaEtiqueta.setText("Crear una nueva etiqueta relacionada con este medicamento");
jButtonDialogEtiquetasNuevaEtiqueta.setToolTipText("");
jButtonDialogEtiquetasVerEtiquetas.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonDialogEtiquetasVerEtiquetas.setText("Ver las etiquetas relacionadas con este medicamento");
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButtonDialogEtiquetasVerEtiquetas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonDialogEtiquetasNuevaEtiqueta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonDialogEtiquetasVolver, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel19, javax.swing.GroupLayout.PREFERRED_SIZE, 463, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel19)
.addGap(18, 18, 18)
.addComponent(jButtonDialogEtiquetasVerEtiquetas)
.addGap(18, 18, 18)
.addComponent(jButtonDialogEtiquetasNuevaEtiqueta)
.addGap(18, 18, 18)
.addComponent(jButtonDialogEtiquetasVolver)
.addContainerGap())
);
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(39, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(39, Short.MAX_VALUE))
);
javax.swing.GroupLayout jDialogEtiquetasLayout = new javax.swing.GroupLayout(jDialogEtiquetas.getContentPane());
jDialogEtiquetas.getContentPane().setLayout(jDialogEtiquetasLayout);
jDialogEtiquetasLayout.setHorizontalGroup(
jDialogEtiquetasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jDialogEtiquetasLayout.setVerticalGroup(
jDialogEtiquetasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jMenuItemCopiar.setText("Copiar (Ctlr+C)");
jPopupMenuCopiarPegar.add(jMenuItemCopiar);
jMenuItemPegar.setText("Pegar (Ctlr+V)");
jPopupMenuCopiarPegar.add(jMenuItemPegar);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Farmacotecnia->Hojas de elaboración");
setIconImage(getIconImage());
setMinimumSize(new java.awt.Dimension(900, 600));
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jToolBarProductos.setBackground(new java.awt.Color(193, 115, 115));
jToolBarProductos.setFloatable(false);
jToolBarProductos.setRollover(true);
jButtonPrimeroFichasDeMedicamentos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/flechaPrimero.png"))); // NOI18N
jButtonPrimeroFichasDeMedicamentos.setToolTipText("Se coloca en el primer medicamento");
jButtonPrimeroFichasDeMedicamentos.setEnabled(false);
jButtonPrimeroFichasDeMedicamentos.setFocusable(false);
jButtonPrimeroFichasDeMedicamentos.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonPrimeroFichasDeMedicamentos.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarProductos.add(jButtonPrimeroFichasDeMedicamentos);
jButtonAtrasFichasDeMedicamentos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/flechaIzquierda.png"))); // NOI18N
jButtonAtrasFichasDeMedicamentos.setToolTipText("Se coloca en el medicamento anterior");
jButtonAtrasFichasDeMedicamentos.setEnabled(false);
jButtonAtrasFichasDeMedicamentos.setFocusable(false);
jButtonAtrasFichasDeMedicamentos.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonAtrasFichasDeMedicamentos.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarProductos.add(jButtonAtrasFichasDeMedicamentos);
jToolBarProductos.add(jSeparator3);
jLabelPosicionFichasDeMedicamentos.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabelPosicionFichasDeMedicamentos.setForeground(new java.awt.Color(255, 255, 255));
jLabelPosicionFichasDeMedicamentos.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabelPosicionFichasDeMedicamentos.setText("Producto 200 de 300");
jLabelPosicionFichasDeMedicamentos.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jToolBarProductos.add(jLabelPosicionFichasDeMedicamentos);
jToolBarProductos.add(jSeparator4);
jButtonSiguienteFichasDeMedicamentos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/flechaDerecha.png"))); // NOI18N
jButtonSiguienteFichasDeMedicamentos.setToolTipText("Se coloca en el medicamento siguiente");
jButtonSiguienteFichasDeMedicamentos.setFocusable(false);
jButtonSiguienteFichasDeMedicamentos.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonSiguienteFichasDeMedicamentos.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarProductos.add(jButtonSiguienteFichasDeMedicamentos);
jButtonUltimoFichasDeMedicamentos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/flechaUltimo.png"))); // NOI18N
jButtonUltimoFichasDeMedicamentos.setToolTipText("Se coloca en el último medicamento");
jButtonUltimoFichasDeMedicamentos.setFocusable(false);
jButtonUltimoFichasDeMedicamentos.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonUltimoFichasDeMedicamentos.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarProductos.add(jButtonUltimoFichasDeMedicamentos);
jSeparator2.setBackground(new java.awt.Color(0, 0, 0));
jSeparator2.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
jSeparator2.setPreferredSize(new java.awt.Dimension(6, 1));
jToolBarProductos.add(jSeparator2);
jButtonNuevoFichasDeMedicamentos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/facturaAgregar.png"))); // NOI18N
jButtonNuevoFichasDeMedicamentos.setToolTipText("Crea un nuevo medicamento");
jButtonNuevoFichasDeMedicamentos.setFocusable(false);
jButtonNuevoFichasDeMedicamentos.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonNuevoFichasDeMedicamentos.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarProductos.add(jButtonNuevoFichasDeMedicamentos);
jButtonModificarFichasDeMedicamentos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/facturaEditar.png"))); // NOI18N
jButtonModificarFichasDeMedicamentos.setToolTipText("Permite modificar el medicamento actual, pulsar los botones de aceptar o cancelar situados al final de la sección datos medicamento para salir del modo de edición");
jButtonModificarFichasDeMedicamentos.setFocusable(false);
jButtonModificarFichasDeMedicamentos.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonModificarFichasDeMedicamentos.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarProductos.add(jButtonModificarFichasDeMedicamentos);
jButtonEliminarFichasDeMedicamentos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/facturaBorrar.png"))); // NOI18N
jButtonEliminarFichasDeMedicamentos.setToolTipText("Elimina el medicamento actual");
jButtonEliminarFichasDeMedicamentos.setFocusable(false);
jButtonEliminarFichasDeMedicamentos.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonEliminarFichasDeMedicamentos.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarProductos.add(jButtonEliminarFichasDeMedicamentos);
jButtonMostrarEtiqueta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/etiqueta.png"))); // NOI18N
jButtonMostrarEtiqueta.setToolTipText("Muestra las etiqueta relacionadas con este medicamento o crea una nueva etiqueta para este medicamento");
jButtonMostrarEtiqueta.setFocusable(false);
jButtonMostrarEtiqueta.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonMostrarEtiqueta.setMaximumSize(new java.awt.Dimension(55, 55));
jButtonMostrarEtiqueta.setMinimumSize(new java.awt.Dimension(55, 55));
jButtonMostrarEtiqueta.setPreferredSize(new java.awt.Dimension(55, 55));
jButtonMostrarEtiqueta.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarProductos.add(jButtonMostrarEtiqueta);
jButtonImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/facturaImprimir.png"))); // NOI18N
jButtonImprimir.setToolTipText("Imprime la hoja de elaboración del medicamento actual");
jButtonImprimir.setFocusable(false);
jButtonImprimir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonImprimir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarProductos.add(jButtonImprimir);
jLayeredPane1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanelAceptarCancelar.setBackground(new java.awt.Color(245, 83, 83));
jButtonAceptarFichasDeMedicamentos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonAceptarFichasDeMedicamentos.setMnemonic('A');
jButtonAceptarFichasDeMedicamentos.setText("Aceptar");
jButtonCancelarFichasDeMedicamentos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonCancelarFichasDeMedicamentos.setMnemonic('C');
jButtonCancelarFichasDeMedicamentos.setText("Cancelar");
javax.swing.GroupLayout jPanelAceptarCancelarLayout = new javax.swing.GroupLayout(jPanelAceptarCancelar);
jPanelAceptarCancelar.setLayout(jPanelAceptarCancelarLayout);
jPanelAceptarCancelarLayout.setHorizontalGroup(
jPanelAceptarCancelarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelAceptarCancelarLayout.createSequentialGroup()
.addGap(52, 52, 52)
.addComponent(jButtonAceptarFichasDeMedicamentos)
.addGap(52, 52, 52)
.addComponent(jButtonCancelarFichasDeMedicamentos)
.addContainerGap(42, Short.MAX_VALUE))
);
jPanelAceptarCancelarLayout.setVerticalGroup(
jPanelAceptarCancelarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelAceptarCancelarLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelAceptarCancelarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonAceptarFichasDeMedicamentos)
.addComponent(jButtonCancelarFichasDeMedicamentos))
.addContainerGap(14, Short.MAX_VALUE))
);
jLayeredPane1.add(jPanelAceptarCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 530, 310, 50));
jLayeredPane1.setLayer(jPanelAceptarCancelar, javax.swing.JLayeredPane.DRAG_LAYER);
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane1.setPreferredSize(new java.awt.Dimension(951, 2050));
jPanel1.setBackground(new java.awt.Color(255, 223, 204));
jPanel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jPanel1.setPreferredSize(new java.awt.Dimension(932, 2050));
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanelListaFichasDeMedicamentos.setBackground(new java.awt.Color(255, 255, 255));
jPanelListaFichasDeMedicamentos.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 255), 2), "Lista Medicamentos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14), java.awt.Color.black)); // NOI18N
jListFichasDeMedicamentos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jListFichasDeMedicamentos.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPaneListaMedicamentos.setViewportView(jListFichasDeMedicamentos);
javax.swing.GroupLayout jPanelListaFichasDeMedicamentosLayout = new javax.swing.GroupLayout(jPanelListaFichasDeMedicamentos);
jPanelListaFichasDeMedicamentos.setLayout(jPanelListaFichasDeMedicamentosLayout);
jPanelListaFichasDeMedicamentosLayout.setHorizontalGroup(
jPanelListaFichasDeMedicamentosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelListaFichasDeMedicamentosLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jScrollPaneListaMedicamentos, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(27, Short.MAX_VALUE))
);
jPanelListaFichasDeMedicamentosLayout.setVerticalGroup(
jPanelListaFichasDeMedicamentosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelListaFichasDeMedicamentosLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPaneListaMedicamentos, javax.swing.GroupLayout.PREFERRED_SIZE, 420, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1.add(jPanelListaFichasDeMedicamentos, new org.netbeans.lib.awtextra.AbsoluteConstraints(26, 77, -1, -1));
jPanelEdicionDatosFichasDeMedicamentos.setBackground(new java.awt.Color(255, 255, 255));
jPanelEdicionDatosFichasDeMedicamentos.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.lightGray, 2), "Datos medicamento", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N
jPanelEdicionDatosFichasDeMedicamentos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jPanelEdicionDatosFichasDeMedicamentos.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setText("Id:");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 30, -1, -1));
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setText("Medicamento:");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 65, -1, -1));
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setText("Veredicto:");
jLabel4.setToolTipText("1, para hacer; 0, no se hace");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 155, -1, -1));
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setText("Observaciones veredicto:");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 193, -1, -1));
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel6.setText("Procedimiento:");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 298, -1, -1));
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel7.setText("Observaciones personales:");
jLabel7.setToolTipText("No salen en la hoja de elaboración");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 1136, -1, -1));
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel8.setText("Estabilidad:");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 656, -1, -1));
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel9.setText("Via de administración:");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 780, -1, -1));
jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel10.setText("Datos organolepsis:");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(46, 847, -1, -1));
jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel11.setText("Tipo:");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(46, 888, -1, -1));
jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel12.setText("E.D.O.");
jLabel12.setToolTipText("¿Tiene algún excipiente de declaración obligatoria?");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(46, 944, -1, -1));
jLabel13.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel13.setText("Para etiqueta:");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 982, -1, -1));
jLabel14.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel14.setText("Observaciones para elaboración:");
jLabel14.setToolTipText("Para que salga en las observaciones de la hoja de elaboración");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 502, -1, -1));
jLabel15.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel15.setText("Origen:");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 1307, -1, -1));
jScrollPane4.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jTextAreaMedicamento.setEditable(false);
jTextAreaMedicamento.setColumns(20);
jTextAreaMedicamento.setFont(new java.awt.Font("Monospaced", 0, 14)); // NOI18N
jTextAreaMedicamento.setLineWrap(true);
jTextAreaMedicamento.setRows(2);
jTextAreaMedicamento.setText("\n");
jTextAreaMedicamento.setWrapStyleWord(true);
jTextAreaMedicamento.setComponentPopupMenu(jPopupMenuCopiarPegar);
jScrollPane4.setViewportView(jTextAreaMedicamento);
jPanelEdicionDatosFichasDeMedicamentos.add(jScrollPane4, new org.netbeans.lib.awtextra.AbsoluteConstraints(56, 88, 354, -1));
jLabelIdFichasDeMedicamentos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabelIdFichasDeMedicamentos.setText("jLabel1");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabelIdFichasDeMedicamentos, new org.netbeans.lib.awtextra.AbsoluteConstraints(71, 30, -1, -1));
jComboBoxVeredicto.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jComboBoxVeredicto.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "1" }));
jComboBoxVeredicto.setToolTipText("1, para hacer; 0, no se hace");
jComboBoxVeredicto.setEnabled(false);
jPanelEdicionDatosFichasDeMedicamentos.add(jComboBoxVeredicto, new org.netbeans.lib.awtextra.AbsoluteConstraints(116, 152, 75, -1));
jTextFieldObservacionesVeredicto.setEditable(false);
jTextFieldObservacionesVeredicto.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTextFieldObservacionesVeredicto.setText("jTextField1");
jPanelEdicionDatosFichasDeMedicamentos.add(jTextFieldObservacionesVeredicto, new org.netbeans.lib.awtextra.AbsoluteConstraints(56, 216, 354, -1));
jScrollPane3.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane3.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jTextAreaProcedimiento.setEditable(false);
jTextAreaProcedimiento.setColumns(20);
jTextAreaProcedimiento.setFont(new java.awt.Font("Monospaced", 0, 14)); // NOI18N
jTextAreaProcedimiento.setLineWrap(true);
jTextAreaProcedimiento.setRows(7);
jTextAreaProcedimiento.setText(" 1.- Se pesa la cantidad correspondiente de ác. tánico.\n\n 2.- Se mezcla con 500 ml de B.\n\n 3.- Se agita con agitador mecánico.\n\n 4.- Se filtra.\n\n 5.- Se envasa con el resto de B.");
jTextAreaProcedimiento.setWrapStyleWord(true);
jTextAreaProcedimiento.setComponentPopupMenu(jPopupMenuCopiarPegar);
jScrollPane3.setViewportView(jTextAreaProcedimiento);
jPanelEdicionDatosFichasDeMedicamentos.add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(56, 321, 354, -1));
jScrollPane5.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane5.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jTextAreaObservaciones.setEditable(false);
jTextAreaObservaciones.setColumns(20);
jTextAreaObservaciones.setFont(new java.awt.Font("Monospaced", 0, 14)); // NOI18N
jTextAreaObservaciones.setLineWrap(true);
jTextAreaObservaciones.setRows(6);
jTextAreaObservaciones.setToolTipText("No salen en la hoja de elaboración");
jTextAreaObservaciones.setWrapStyleWord(true);
jTextAreaObservaciones.setComponentPopupMenu(jPopupMenuCopiarPegar);
jScrollPane5.setViewportView(jTextAreaObservaciones);
jPanelEdicionDatosFichasDeMedicamentos.add(jScrollPane5, new org.netbeans.lib.awtextra.AbsoluteConstraints(46, 1159, 364, -1));
jScrollPane6.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane6.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jTextAreaEstabilidad.setEditable(false);
jTextAreaEstabilidad.setColumns(20);
jTextAreaEstabilidad.setFont(new java.awt.Font("Monospaced", 0, 14)); // NOI18N
jTextAreaEstabilidad.setLineWrap(true);
jTextAreaEstabilidad.setRows(3);
jTextAreaEstabilidad.setWrapStyleWord(true);
jTextAreaEstabilidad.setComponentPopupMenu(jPopupMenuCopiarPegar);
jScrollPane6.setViewportView(jTextAreaEstabilidad);
jPanelEdicionDatosFichasDeMedicamentos.add(jScrollPane6, new org.netbeans.lib.awtextra.AbsoluteConstraints(56, 679, 354, -1));
jComboBoxViaAdministracion.setEditable(true);
jComboBoxViaAdministracion.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jComboBoxViaAdministracion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "tópica", "oral", "bucal", "rectal", "oftalmica", "epidural", "subcutánea", "intradural", "inhalatoria", "vesical", "intracamerular", "intravítrea", "subconjuntival", "desoclusion catéter hemodiálisis", "intradérmica" }));
jComboBoxViaAdministracion.setEnabled(false);
jPanelEdicionDatosFichasDeMedicamentos.add(jComboBoxViaAdministracion, new org.netbeans.lib.awtextra.AbsoluteConstraints(56, 803, 354, -1));
jTextFieldDatosOrganolepsis.setEditable(false);
jTextFieldDatosOrganolepsis.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTextFieldDatosOrganolepsis.setText("cuasi preparado oficinal");
jPanelEdicionDatosFichasDeMedicamentos.add(jTextFieldDatosOrganolepsis, new org.netbeans.lib.awtextra.AbsoluteConstraints(184, 844, 226, -1));
jScrollPane8.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane8.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jTextAreaParaEtiqueta.setEditable(false);
jTextAreaParaEtiqueta.setColumns(20);
jTextAreaParaEtiqueta.setLineWrap(true);
jTextAreaParaEtiqueta.setRows(5);
jTextAreaParaEtiqueta.setWrapStyleWord(true);
jTextAreaParaEtiqueta.setComponentPopupMenu(jPopupMenuCopiarPegar);
jScrollPane8.setViewportView(jTextAreaParaEtiqueta);
jPanelEdicionDatosFichasDeMedicamentos.add(jScrollPane8, new org.netbeans.lib.awtextra.AbsoluteConstraints(46, 1005, 364, -1));
jScrollPane7.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane7.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jTextAreaObservacionesElaboracion.setEditable(false);
jTextAreaObservacionesElaboracion.setColumns(20);
jTextAreaObservacionesElaboracion.setLineWrap(true);
jTextAreaObservacionesElaboracion.setRows(5);
jTextAreaObservacionesElaboracion.setToolTipText("Para que salga en las observaciones de la hoja de elaboración");
jTextAreaObservacionesElaboracion.setWrapStyleWord(true);
jTextAreaObservacionesElaboracion.setComponentPopupMenu(jPopupMenuCopiarPegar);
jScrollPane7.setViewportView(jTextAreaObservacionesElaboracion);
jPanelEdicionDatosFichasDeMedicamentos.add(jScrollPane7, new org.netbeans.lib.awtextra.AbsoluteConstraints(56, 525, 354, -1));
jScrollPane9.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane9.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jTextAreaOrigen.setEditable(false);
jTextAreaOrigen.setColumns(20);
jTextAreaOrigen.setFont(new java.awt.Font("Monospaced", 0, 14)); // NOI18N
jTextAreaOrigen.setLineWrap(true);
jTextAreaOrigen.setRows(5);
jTextAreaOrigen.setWrapStyleWord(true);
jTextAreaOrigen.setComponentPopupMenu(jPopupMenuCopiarPegar);
jScrollPane9.setViewportView(jTextAreaOrigen);
jPanelEdicionDatosFichasDeMedicamentos.add(jScrollPane9, new org.netbeans.lib.awtextra.AbsoluteConstraints(46, 1330, 364, -1));
jComboBoxEDO.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jComboBoxEDO.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "cloruro de benzalconio", "deriv del ac. Borico", "lidocaina", "glute", "butilhidroxianisol", "alcohol bencílico", "lactosa", "cremofor (ac ricino polietoxilado)", "almidón de trigo", "sacarosa", "butilhidroxitolueno", "sulfitos", "tartracina", "glucosa", "fructosa", "aspartamo", "alcohol etílico (etanol)", "sales de fenilmercurio", "deriv del ac. Benzoico" }));
jComboBoxEDO.setToolTipText("¿Tiene algún excipiente de declaración obligatoria?");
jComboBoxEDO.setEnabled(false);
jPanelEdicionDatosFichasDeMedicamentos.add(jComboBoxEDO, new org.netbeans.lib.awtextra.AbsoluteConstraints(104, 941, 306, -1));
jComboBoxTipo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jComboBoxTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "preparado oficinal", "F.M Tipificada", "F.M", "cuasi FMT", "cuasi F.M", "solo para etiq", "para laboratorio", "antisepticos", "cuasi preparado oficinal" }));
jComboBoxTipo.setEnabled(false);
jPanelEdicionDatosFichasDeMedicamentos.add(jComboBoxTipo, new org.netbeans.lib.awtextra.AbsoluteConstraints(95, 885, 315, -1));
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel1.setText("Elaborado por:");
jPanelEdicionDatosFichasDeMedicamentos.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 260, -1, -1));
jComboBoxElaboradoPor.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jComboBoxElaboradoPor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "famaceutico", "auxiliar", "enfermera" }));
jComboBoxElaboradoPor.setEnabled(false);
jPanelEdicionDatosFichasDeMedicamentos.add(jComboBoxElaboradoPor, new org.netbeans.lib.awtextra.AbsoluteConstraints(145, 257, 265, -1));
jPanel1.add(jPanelEdicionDatosFichasDeMedicamentos, new org.netbeans.lib.awtextra.AbsoluteConstraints(451, 77, 446, 1532));
jPanelProductosBuscar.setBackground(new java.awt.Color(255, 255, 255));
jPanelProductosBuscar.setMaximumSize(new java.awt.Dimension(733, 48));
jLabel16.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel16.setText("Buscar por:");
jComboBoxBuscarFichasDeMedicamentos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jComboBoxBuscarFichasDeMedicamentos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nombre", "Producto que contiene" }));
jComboBoxBuscarFichasDeMedicamentos.setToolTipText("Seleccionar por que criterio buscar");
jTextFieldBuscarFichasDeMedicamentos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTextFieldBuscarFichasDeMedicamentos.setToolTipText("Introducir el texto de guia para buscar");
jButtonBuscarFichasDeMedicamentos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonBuscarFichasDeMedicamentos.setMnemonic('B');
jButtonBuscarFichasDeMedicamentos.setText("Buscar");
jButtonBuscarFichasDeMedicamentos.setToolTipText("Buscar productos que coincidan con los criterios elegidos");
jButtonQuitarBuscarFichasDeMedicamentos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonQuitarBuscarFichasDeMedicamentos.setMnemonic('Q');
jButtonQuitarBuscarFichasDeMedicamentos.setText("Quitar búsqueda");
jButtonQuitarBuscarFichasDeMedicamentos.setToolTipText("Volver a mostrar todos los datos");
jCheckBoxMostrarTodo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jCheckBoxMostrarTodo.setText("Mostrar todo");
jCheckBoxMostrarTodo.setToolTipText("Si se selecciona muestra todas las fichas de medicamentos, sino sólo se muestran las que tengan veredicto 1");
javax.swing.GroupLayout jPanelProductosBuscarLayout = new javax.swing.GroupLayout(jPanelProductosBuscar);
jPanelProductosBuscar.setLayout(jPanelProductosBuscarLayout);
jPanelProductosBuscarLayout.setHorizontalGroup(
jPanelProductosBuscarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelProductosBuscarLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxBuscarFichasDeMedicamentos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextFieldBuscarFichasDeMedicamentos, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonBuscarFichasDeMedicamentos, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonQuitarBuscarFichasDeMedicamentos)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCheckBoxMostrarTodo)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelProductosBuscarLayout.setVerticalGroup(
jPanelProductosBuscarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelProductosBuscarLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelProductosBuscarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
.addComponent(jComboBoxBuscarFichasDeMedicamentos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldBuscarFichasDeMedicamentos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonBuscarFichasDeMedicamentos)
.addComponent(jButtonQuitarBuscarFichasDeMedicamentos)
.addComponent(jCheckBoxMostrarTodo))
.addContainerGap())
);
jPanel1.add(jPanelProductosBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(26, 11, 871, -1));
jPanelMaquinaria.setBackground(new java.awt.Color(255, 255, 255));
jPanelMaquinaria.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.lightGray, 2), "Maquinaria", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N
jTableMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTableMaquinaria.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane10.setViewportView(jTableMaquinaria);
jButtonAddMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonAddMaquinaria.setText("Añadir");
jButtonEliminarMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonEliminarMaquinaria.setText("Eliminar");
javax.swing.GroupLayout jPanelMaquinariaLayout = new javax.swing.GroupLayout(jPanelMaquinaria);
jPanelMaquinaria.setLayout(jPanelMaquinariaLayout);
jPanelMaquinariaLayout.setHorizontalGroup(
jPanelMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMaquinariaLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelMaquinariaLayout.createSequentialGroup()
.addComponent(jButtonAddMaquinaria)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonEliminarMaquinaria)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelMaquinariaLayout.setVerticalGroup(
jPanelMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMaquinariaLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
.addGroup(jPanelMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonAddMaquinaria)
.addComponent(jButtonEliminarMaquinaria))
.addGap(25, 25, 25))
);
jPanel1.add(jPanelMaquinaria, new org.netbeans.lib.awtextra.AbsoluteConstraints(26, 601, 398, -1));
jPanelMaterialEnvasar.setBackground(new java.awt.Color(255, 255, 255));
jPanelMaterialEnvasar.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.lightGray, 2), "Material para envasar", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N
jPanelMaterialEnvasar.setPreferredSize(new java.awt.Dimension(390, 279));
jTableMaterialEnvasar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTableMaterialEnvasar.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane11.setViewportView(jTableMaterialEnvasar);
jButtonAddMaterialEnvasar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonAddMaterialEnvasar.setText("Añadir");
jButtonEliminarMaterialEnvasar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonEliminarMaterialEnvasar.setText("Eliminar");
javax.swing.GroupLayout jPanelMaterialEnvasarLayout = new javax.swing.GroupLayout(jPanelMaterialEnvasar);
jPanelMaterialEnvasar.setLayout(jPanelMaterialEnvasarLayout);
jPanelMaterialEnvasarLayout.setHorizontalGroup(
jPanelMaterialEnvasarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMaterialEnvasarLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelMaterialEnvasarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane11, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelMaterialEnvasarLayout.createSequentialGroup()
.addComponent(jButtonAddMaterialEnvasar)
.addGap(18, 18, 18)
.addComponent(jButtonEliminarMaterialEnvasar)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelMaterialEnvasarLayout.setVerticalGroup(
jPanelMaterialEnvasarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMaterialEnvasarLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane11, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
.addGroup(jPanelMaterialEnvasarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonAddMaterialEnvasar)
.addComponent(jButtonEliminarMaterialEnvasar))
.addGap(26, 26, 26))
);
jPanel1.add(jPanelMaterialEnvasar, new org.netbeans.lib.awtextra.AbsoluteConstraints(26, 947, 398, -1));
jPanelMaterialElaborar.setBackground(new java.awt.Color(255, 255, 255));
jPanelMaterialElaborar.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.lightGray, 2), "Material para elaborar", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N
jPanelMaterialElaborar.setPreferredSize(new java.awt.Dimension(390, 279));
jTableMaterialElaborar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTableMaterialElaborar.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"null"
}
) {
boolean[] canEdit = new boolean [] {
false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTableMaterialElaborar.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane12.setViewportView(jTableMaterialElaborar);
jButtonAddMaterialElaborar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonAddMaterialElaborar.setText("Añadir");
jButtonEliminarMaterialElaborar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonEliminarMaterialElaborar.setText("Eliminar");
javax.swing.GroupLayout jPanelMaterialElaborarLayout = new javax.swing.GroupLayout(jPanelMaterialElaborar);
jPanelMaterialElaborar.setLayout(jPanelMaterialElaborarLayout);
jPanelMaterialElaborarLayout.setHorizontalGroup(
jPanelMaterialElaborarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMaterialElaborarLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelMaterialElaborarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane12, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelMaterialElaborarLayout.createSequentialGroup()
.addComponent(jButtonAddMaterialElaborar)
.addGap(18, 18, 18)
.addComponent(jButtonEliminarMaterialElaborar)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelMaterialElaborarLayout.setVerticalGroup(
jPanelMaterialElaborarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMaterialElaborarLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addGroup(jPanelMaterialElaborarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonAddMaterialElaborar)
.addComponent(jButtonEliminarMaterialElaborar))
.addGap(27, 27, 27))
);
jPanel1.add(jPanelMaterialElaborar, new org.netbeans.lib.awtextra.AbsoluteConstraints(26, 1300, 398, 309));
jPanelProductos.setBackground(new java.awt.Color(255, 255, 255));
jPanelProductos.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.lightGray, 2), "Productos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N
jTableProductos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTableProductos.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null}
},
new String [] {
"", "Productos", "Codigo referencia", "Cantidad", "Unidad", "Proveedor", "Lote", "Caducidad"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Float.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTableProductos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jTableProductos.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTableProductosKeyReleased(evt);
}
});
jScrollPane13.setViewportView(jTableProductos);
if (jTableProductos.getColumnModel().getColumnCount() > 0) {
jTableProductos.getColumnModel().getColumn(1).setPreferredWidth(200);
jTableProductos.getColumnModel().getColumn(2).setPreferredWidth(50);
}
jButtonAddProducto.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonAddProducto.setText("Añadir");
jButtonModificarProducto.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonModificarProducto.setText("Modificar");
jButtonEliminarProducto.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonEliminarProducto.setText("Eliminar");
javax.swing.GroupLayout jPanelProductosLayout = new javax.swing.GroupLayout(jPanelProductos);
jPanelProductos.setLayout(jPanelProductosLayout);
jPanelProductosLayout.setHorizontalGroup(
jPanelProductosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelProductosLayout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(jPanelProductosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelProductosLayout.createSequentialGroup()
.addComponent(jButtonAddProducto)
.addGap(18, 18, 18)
.addComponent(jButtonModificarProducto)
.addGap(18, 18, 18)
.addComponent(jButtonEliminarProducto))
.addComponent(jScrollPane13, javax.swing.GroupLayout.PREFERRED_SIZE, 805, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelProductosLayout.setVerticalGroup(
jPanelProductosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelProductosLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane13, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addGroup(jPanelProductosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonAddProducto)
.addComponent(jButtonModificarProducto)
.addComponent(jButtonEliminarProducto))
.addContainerGap(49, Short.MAX_VALUE))
);
jPanel1.add(jPanelProductos, new org.netbeans.lib.awtextra.AbsoluteConstraints(26, 1673, 871, -1));
jScrollPane1.setViewportView(jPanel1);
jLayeredPane1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 953, 579));
jMenu1.setText("Archivo");
jMenuItemArchivoNuevo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemArchivoNuevo.setText("Nuevo");
jMenu1.add(jMenuItemArchivoNuevo);
jMenu1.add(jSeparator1);
jMenuItemArchivoSalir.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
jMenuItemArchivoSalir.setText("Salir");
jMenu1.add(jMenuItemArchivoSalir);
jMenuBar1.add(jMenu1);
jMenu2.setText("Editar");
jMenuItemEditarModificar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemEditarModificar.setText("Modificar");
jMenu2.add(jMenuItemEditarModificar);
jMenuItemEditarEliminar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemEditarEliminar.setText("Eliminar");
jMenu2.add(jMenuItemEditarEliminar);
jMenu2.add(jSeparator15);
jMenuItemAddMaquinaria.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemAddMaquinaria.setText("Añadir maquinaria");
jMenu2.add(jMenuItemAddMaquinaria);
jMenuItemAddMaterialElaborar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_J, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemAddMaterialElaborar.setText("Añadir material para elaborar");
jMenu2.add(jMenuItemAddMaterialElaborar);
jMenuItemAddMaterialEnvasar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemAddMaterialEnvasar.setText("Añadir material para envasar");
jMenu2.add(jMenuItemAddMaterialEnvasar);
jMenuItemAddProducto.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemAddProducto.setText("Añadir producto");
jMenu2.add(jMenuItemAddProducto);
jMenuBar1.add(jMenu2);
jMenu3.setText("Ver");
jMenuItemVerPrimero.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_1, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemVerPrimero.setText("Primero");
jMenu3.add(jMenuItemVerPrimero);
jMenuItemVerAnterior.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_2, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemVerAnterior.setText("Anterior");
jMenu3.add(jMenuItemVerAnterior);
jMenu3.add(jSeparator14);
jMenuItemVerSiguiente.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_3, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemVerSiguiente.setText("Siguiente");
jMenu3.add(jMenuItemVerSiguiente);
jMenuItemVerUltimo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_4, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemVerUltimo.setText("Último");
jMenu3.add(jMenuItemVerUltimo);
jMenuBar1.add(jMenu3);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToolBarProductos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLayeredPane1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jToolBarProductos, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTableProductosKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableProductosKeyReleased
// System.out.println("jj");
}//GEN-LAST:event_jTableProductosKeyReleased
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
}//GEN-LAST:event_formWindowOpened
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
/*
*/
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
VentanaHojasElaboracion dialog = new VentanaHojasElaboracion(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JButton jButtonAceptarFichasDeMedicamentos;
public javax.swing.JButton jButtonAddMaquinaria;
public javax.swing.JButton jButtonAddMaterialElaborar;
public javax.swing.JButton jButtonAddMaterialEnvasar;
public javax.swing.JButton jButtonAddProducto;
public javax.swing.JButton jButtonAtrasFichasDeMedicamentos;
public javax.swing.JButton jButtonBuscarFichasDeMedicamentos;
public javax.swing.JButton jButtonCancelarFichasDeMedicamentos;
public javax.swing.JButton jButtonDialogEtiquetasNuevaEtiqueta;
public javax.swing.JButton jButtonDialogEtiquetasVerEtiquetas;
public javax.swing.JButton jButtonDialogEtiquetasVolver;
public javax.swing.JButton jButtonDialogModificarProductoAceptar;
public javax.swing.JButton jButtonDialogModificarProductoCancelar;
public javax.swing.JButton jButtonEliminarFichasDeMedicamentos;
public javax.swing.JButton jButtonEliminarMaquinaria;
public javax.swing.JButton jButtonEliminarMaterialElaborar;
public javax.swing.JButton jButtonEliminarMaterialEnvasar;
public javax.swing.JButton jButtonEliminarProducto;
public javax.swing.JButton jButtonImprimir;
public javax.swing.JButton jButtonModificarFichasDeMedicamentos;
public javax.swing.JButton jButtonModificarProducto;
public javax.swing.JButton jButtonMostrarEtiqueta;
public javax.swing.JButton jButtonNuevoFichasDeMedicamentos;
public javax.swing.JButton jButtonPrimeroFichasDeMedicamentos;
public javax.swing.JButton jButtonQuitarBuscarFichasDeMedicamentos;
public javax.swing.JButton jButtonSiguienteFichasDeMedicamentos;
public javax.swing.JButton jButtonUltimoFichasDeMedicamentos;
public javax.swing.JCheckBox jCheckBoxCSP;
public javax.swing.JCheckBox jCheckBoxMostrarTodo;
public javax.swing.JComboBox jComboBoxBuscarFichasDeMedicamentos;
public javax.swing.JComboBox jComboBoxDialogModificarProductoUnidades;
public javax.swing.JComboBox jComboBoxEDO;
public javax.swing.JComboBox jComboBoxElaboradoPor;
public javax.swing.JComboBox jComboBoxTipo;
public javax.swing.JComboBox jComboBoxVeredicto;
public javax.swing.JComboBox jComboBoxViaAdministracion;
public javax.swing.JDialog jDialogAddMaquinaria;
public javax.swing.JDialog jDialogAddMaterialElaborar;
public javax.swing.JDialog jDialogAddMaterialEnvasar;
public javax.swing.JDialog jDialogAddProducto;
public javax.swing.JDialog jDialogEtiquetas;
public javax.swing.JDialog jDialogModificarProducto;
public javax.swing.JLabel jLabel1;
public javax.swing.JLabel jLabel10;
public javax.swing.JLabel jLabel11;
public javax.swing.JLabel jLabel12;
public javax.swing.JLabel jLabel13;
public javax.swing.JLabel jLabel14;
public javax.swing.JLabel jLabel15;
public javax.swing.JLabel jLabel16;
public javax.swing.JLabel jLabel17;
public javax.swing.JLabel jLabel18;
public javax.swing.JLabel jLabel19;
public javax.swing.JLabel jLabel2;
public javax.swing.JLabel jLabel20;
public javax.swing.JLabel jLabel3;
public javax.swing.JLabel jLabel4;
public javax.swing.JLabel jLabel5;
public javax.swing.JLabel jLabel6;
public javax.swing.JLabel jLabel7;
public javax.swing.JLabel jLabel8;
public javax.swing.JLabel jLabel9;
public javax.swing.JLabel jLabelDialogModificarProductoProductos;
public javax.swing.JLabel jLabelIdFichasDeMedicamentos;
public javax.swing.JLabel jLabelPosicionFichasDeMedicamentos;
public javax.swing.JLayeredPane jLayeredPane1;
public javax.swing.JList jListFichasDeMedicamentos;
public javax.swing.JMenu jMenu1;
public javax.swing.JMenu jMenu2;
public javax.swing.JMenu jMenu3;
public javax.swing.JMenuBar jMenuBar1;
public javax.swing.JMenuItem jMenuItemAddMaquinaria;
public javax.swing.JMenuItem jMenuItemAddMaterialElaborar;
public javax.swing.JMenuItem jMenuItemAddMaterialEnvasar;
public javax.swing.JMenuItem jMenuItemAddProducto;
public javax.swing.JMenuItem jMenuItemArchivoNuevo;
public javax.swing.JMenuItem jMenuItemArchivoSalir;
public javax.swing.JMenuItem jMenuItemCopiar;
public javax.swing.JMenuItem jMenuItemEditarEliminar;
public javax.swing.JMenuItem jMenuItemEditarModificar;
public javax.swing.JMenuItem jMenuItemPegar;
public javax.swing.JMenuItem jMenuItemVerAnterior;
public javax.swing.JMenuItem jMenuItemVerPrimero;
public javax.swing.JMenuItem jMenuItemVerSiguiente;
public javax.swing.JMenuItem jMenuItemVerUltimo;
public javax.swing.JPanel jPanel1;
public javax.swing.JPanel jPanel2;
public javax.swing.JPanel jPanel3;
public javax.swing.JPanel jPanel4;
public javax.swing.JPanel jPanel5;
public javax.swing.JPanel jPanelAceptarCancelar;
public javax.swing.JPanel jPanelEdicionDatosFichasDeMedicamentos;
public javax.swing.JPanel jPanelListaFichasDeMedicamentos;
public javax.swing.JPanel jPanelMaquinaria;
public javax.swing.JPanel jPanelMaterialElaborar;
public javax.swing.JPanel jPanelMaterialEnvasar;
public javax.swing.JPanel jPanelProductos;
public javax.swing.JPanel jPanelProductosBuscar;
public javax.swing.JPopupMenu jPopupMenuCopiarPegar;
public javax.swing.JScrollPane jScrollPane1;
public javax.swing.JScrollPane jScrollPane10;
public javax.swing.JScrollPane jScrollPane11;
public javax.swing.JScrollPane jScrollPane12;
public javax.swing.JScrollPane jScrollPane13;
public javax.swing.JScrollPane jScrollPane3;
public javax.swing.JScrollPane jScrollPane4;
public javax.swing.JScrollPane jScrollPane5;
public javax.swing.JScrollPane jScrollPane6;
public javax.swing.JScrollPane jScrollPane7;
public javax.swing.JScrollPane jScrollPane8;
public javax.swing.JScrollPane jScrollPane9;
public javax.swing.JScrollPane jScrollPaneListaMedicamentos;
public javax.swing.JPopupMenu.Separator jSeparator1;
public javax.swing.JPopupMenu.Separator jSeparator14;
public javax.swing.JPopupMenu.Separator jSeparator15;
public javax.swing.JToolBar.Separator jSeparator2;
public javax.swing.JToolBar.Separator jSeparator3;
public javax.swing.JToolBar.Separator jSeparator4;
public javax.swing.JTable jTableMaquinaria;
public javax.swing.JTable jTableMaterialElaborar;
public javax.swing.JTable jTableMaterialEnvasar;
public javax.swing.JTable jTableProductos;
public javax.swing.JTextArea jTextAreaEstabilidad;
public javax.swing.JTextArea jTextAreaMedicamento;
public javax.swing.JTextArea jTextAreaObservaciones;
public javax.swing.JTextArea jTextAreaObservacionesElaboracion;
public javax.swing.JTextArea jTextAreaOrigen;
public javax.swing.JTextArea jTextAreaParaEtiqueta;
public javax.swing.JTextArea jTextAreaProcedimiento;
public javax.swing.JTextField jTextFieldBuscarFichasDeMedicamentos;
public javax.swing.JTextField jTextFieldDatosOrganolepsis;
public javax.swing.JTextField jTextFieldDialogModificarProductoCantidad;
public javax.swing.JTextField jTextFieldObservacionesVeredicto;
public javax.swing.JToolBar jToolBarProductos;
// End of variables declaration//GEN-END:variables
}
<file_sep>package es.sacyl.caza.farmacia.modelo.clases;
// Generated 30-abr-2014 13:00:04 by Hibernate Tools 3.2.1.GA
import java.util.HashSet;
import java.util.Set;
/**
* MaterialParaElaborar generated by hbm2java
*/
public class MaterialParaElaborar implements java.io.Serializable {
private Integer idMaterial;
private String material;
private boolean tenemos;
private Set materialParaElaborarUnions = new HashSet(0);
public MaterialParaElaborar() {
}
public MaterialParaElaborar(String material, boolean tenemos) {
this.material = material;
this.tenemos = tenemos;
}
public MaterialParaElaborar(String material, boolean tenemos, Set materialParaElaborarUnions) {
this.material = material;
this.tenemos = tenemos;
this.materialParaElaborarUnions = materialParaElaborarUnions;
}
public Integer getIdMaterial() {
return this.idMaterial;
}
public void setIdMaterial(Integer idMaterial) {
this.idMaterial = idMaterial;
}
public String getMaterial() {
return this.material;
}
public void setMaterial(String material) {
this.material = material;
}
public boolean isTenemos() {
return this.tenemos;
}
public void setTenemos(boolean tenemos) {
this.tenemos = tenemos;
}
public Set getMaterialParaElaborarUnions() {
return this.materialParaElaborarUnions;
}
public void setMaterialParaElaborarUnions(Set materialParaElaborarUnions) {
this.materialParaElaborarUnions = materialParaElaborarUnions;
}
}
<file_sep>package es.sacyl.caza.farmacia.controlador;
import es.sacyl.caza.farmacia.modelo.EtiquetasDAO;
import es.sacyl.caza.farmacia.modelo.EtiquetasDataSource;
import es.sacyl.caza.farmacia.modelo.FichasDeMedicamentosDAO;
import es.sacyl.caza.farmacia.modelo.clases.Etiquetas;
import es.sacyl.caza.farmacia.modelo.clases.FichasDeMedicamentos;
import es.sacyl.caza.farmacia.vista.VentanaEtiquetas;
import java.awt.Frame;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import org.hibernate.exception.ConstraintViolationException;
/**
*
* @author <NAME>
*/
public class ControladorEtiquetas {
private VentanaEtiquetas vista;
private ArrayList<Etiquetas> listaEtiquetas;
private ArrayList<FichasDeMedicamentos> listaFichaMedicamentos;
private String[] maquinariaJList;
private EtiquetasDAO modelo;
private boolean nuevoPulsado = false;
//TODO: modificar los reportes para mostrar o no el lote
public ControladorEtiquetas(VentanaEtiquetas vista) {
this.vista = vista;
init();
initListeners();
}
//muestra la ventana con los datos de las etiquetas relacionadas con un medicamento o crea una nueva etiqueta relacionada con ese medicamento
public ControladorEtiquetas(VentanaEtiquetas vista, String nombreMedicamento, boolean nuevaEtiqueta) {
this.vista = vista;
if (!nuevaEtiqueta) {
initConMedicamento(nombreMedicamento);
} else {
init();
}
initListeners();
if (nuevaEtiqueta) {
pulsarBotonNuevaEtiquetas();
vista.jButtonAceptarEtiquetas.setVisible(true);
vista.jButtonCancelarEtiquetas.setVisible(true);
vista.jComboBoxMedicamento.setSelectedItem(nombreMedicamento);
vista.jComboBoxMedicamento.transferFocusBackward();
}
}
public void cargarTodasEtiquetas() {
init();
initListeners();
}
public void cargarEtiquetaDeMedicamento(String nombreMedicamento, boolean nuevaEtiqueta) {
if (!nuevaEtiqueta) {
initConMedicamento(nombreMedicamento);
} else {
init();
}
initListeners();
if (nuevaEtiqueta) {
pulsarBotonNuevaEtiquetas();
vista.jButtonAceptarEtiquetas.setVisible(true);
vista.jButtonCancelarEtiquetas.setVisible(true);
vista.jComboBoxMedicamento.setSelectedItem(nombreMedicamento);
vista.jComboBoxMedicamento.transferFocusBackward();
}
}
//Inicialización de los objetos necesarios para acceder y mostrar los datos
private void init() {
modelo = new EtiquetasDAO();
listaEtiquetas = modelo.selectAllEtiquetas();
rellenarJListEtiquetas();
rellenarComboBoxMedicamentos();
vista.jListEtiquetas.setSelectedIndex(0);
actualizarPosicion();
mostrarDatosEtiquetas();
soloEscribirNumerosJTextField(vista.jTextFieldEtiquetasLibroRecetario);
}
//Inicializacion de los objetos necesarios para acceder y mostrar los datos de un medicamento en concreto
private void initConMedicamento(String nombreMedicamento) {
modelo = new EtiquetasDAO();
listaEtiquetas = modelo.selectEtiquetasPorFichaDeMedicamento(nombreMedicamento);
rellenarJListEtiquetas();
rellenarComboBoxMedicamentos();
vista.jListEtiquetas.setSelectedIndex(0);
if (listaEtiquetas.size() < 1) {
JOptionPane.showMessageDialog(vista, "No hay etiquetas relacionadas con el medicamento seleccionado", "Información", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(vista, "Se mostrarán todas las etiquetas que existen", "Información", JOptionPane.INFORMATION_MESSAGE);
recargarDatosQuitarBuscar();
} else {
JOptionPane.showMessageDialog(vista, "Se han encontrado " + listaEtiquetas.size() + " etiquetas", "Información", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(vista, "Púlse el botón de quitar búsqueda si quiere ver todas las etiquetas", "Información", JOptionPane.INFORMATION_MESSAGE);
}
actualizarPosicion();
mostrarDatosEtiquetas();
soloEscribirNumerosJTextField(vista.jTextFieldEtiquetasLibroRecetario);
}
//Rellena un comboBox con los medicamentos
private void rellenarComboBoxMedicamentos() {
FichasDeMedicamentosDAO fichasDao = new FichasDeMedicamentosDAO();
listaFichaMedicamentos = fichasDao.selectAllMedicamentos();
String[] nombresMedicamentos = new String[listaFichaMedicamentos.size()];
nombresMedicamentos[0] = "";
for (int i = 1; i < listaFichaMedicamentos.size(); i++) {
nombresMedicamentos[i] = listaFichaMedicamentos.get(i).getMedicamento();
}
vista.jComboBoxMedicamento.setModel(new DefaultComboBoxModel(nombresMedicamentos));
}
//Añade los listener de los eventos a los componentes
private void initListeners() {
vista.jListEtiquetas.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
cambiarPosicionJListEtiquetas();
}
});
vista.jButtonSiguienteEtiquetas.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseSiguiente();
}
});
vista.jButtonAtrasEtiquetas.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseAnterior();
}
});
vista.jButtonPrimeroEtiquetas.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoversePrimero();
}
});
vista.jButtonUltimoEtiquetas.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseUltimo();
}
});
vista.jButtonModificarEtiquetas.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonModificarEtiquetas();
}
});
vista.jButtonAceptarEtiquetas.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonAceptarPulsado();
}
});
vista.jButtonCancelarEtiquetas.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonCancelarPulsado();
}
});
vista.jButtonNuevoEtiquetas.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonNuevaEtiquetas();
}
});
vista.jButtonBuscarEtiquetas.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonBuscar();
}
});
vista.jButtonQuitarBuscarEtiquetas.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
recargarDatosQuitarBuscar();
}
});
vista.jButtonEliminarEtiquetas.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEliminarEtiquetas();
}
});
vista.jMenuItemArchivoSalir.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
vista.dispose();
}
});
vista.jMenuItemArchivoNuevo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonNuevaEtiquetas();
}
});
vista.jMenuItemEditarEliminar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEliminarEtiquetas();
}
});
vista.jMenuItemEditarModificar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonModificarEtiquetas();
}
});
vista.jMenuItemVerAnterior.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseAnterior();
}
});
vista.jMenuItemVerPrimero.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoversePrimero();
}
});
vista.jMenuItemVerSiguiente.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseSiguiente();
}
});
vista.jMenuItemVerUltimo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseUltimo();
}
});
vista.jButtonImprimirEtiqueta.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonDialogImprimir();
}
});
vista.jButtonDialogImprimirPreview.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonDialogImprimirPreview();
}
});
vista.jButtonDialogImprimirVolver.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
vista.jDialogImprimirEtiquetas.setVisible(false);
}
});
vista.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
vista.dispose();
}
});
vista.jTextFieldBuscarEtiquetas.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
botonBuscar();
}
}
});
vista.jCheckBoxNombrePaciente.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarCheckBoxDatosPaciente();
}
});
vista.jButtonDialogImprimirVolverPaciente.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
vista.jDialogImprimirEtiquetasPaciente.setVisible(false);
}
});
vista.jButtonDialogImprimirPreviewPaciente.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarVistaPreviaPaciente();
}
});
vista.jMenuItemCopiar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
copiar();
}
});
vista.jMenuItemPegar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pegar();
}
});
}
public void copiar() {
if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaEtiquetasConservacion)) {
vista.jTextAreaEtiquetasConservacion.copy();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaEtiquetasMedicamento)) {
vista.jTextAreaEtiquetasMedicamento.copy();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaEtiquetasReferenciaBibliografica)) {
vista.jTextAreaEtiquetasReferenciaBibliografica.copy();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaEtiquetasReferenciaCaducidad)) {
vista.jTextAreaEtiquetasReferenciaCaducidad.copy();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaEtiquetasUtilizacion)) {
vista.jTextAreaEtiquetasUtilizacion.copy();
}
}
//Acción de pegar
public void pegar() {
//solo se puede pegar si se estan editando los datos
if (vista.jButtonAceptarEtiquetas.isVisible()) {
//Para pegar hacer un switch con todos los componentes en donde se puede pegar
if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaEtiquetasConservacion)) {
vista.jTextAreaEtiquetasConservacion.paste();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaEtiquetasMedicamento)) {
vista.jTextAreaEtiquetasMedicamento.paste();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaEtiquetasReferenciaBibliografica)) {
vista.jTextAreaEtiquetasReferenciaBibliografica.paste();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaEtiquetasReferenciaCaducidad)) {
vista.jTextAreaEtiquetasReferenciaCaducidad.paste();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaEtiquetasUtilizacion)) {
vista.jTextAreaEtiquetasUtilizacion.paste();
}
} else {
JOptionPane.showMessageDialog(vista, "Para poder pegar hay que pulsar antes el botón de modificar los datos", "Error", JOptionPane.ERROR_MESSAGE);
}
}
//Llena el JListEtiquetas con la descripcion de la etiquetas existentes en la base de datos
private void rellenarJListEtiquetas() {
maquinariaJList = new String[listaEtiquetas.size()];
for (int i = 0; i < maquinariaJList.length; i++) {
maquinariaJList[i] = listaEtiquetas.get(i).getTipoEtiqueta() + " - " + listaEtiquetas.get(i).getDescripcion();
}
vista.jListEtiquetas.setModel(new javax.swing.AbstractListModel() {
@Override
public int getSize() {
return maquinariaJList.length;
}
@Override
public Object getElementAt(int i) {
return maquinariaJList[i];
}
});
}
//Posición de la etiqueta en el que estamos situados
private void actualizarPosicion() {
String pos = "Etiquetas " + (vista.jListEtiquetas.getSelectedIndex() + 1) + " de " + maquinariaJList.length;
vista.jLabelPosicionEtiquetas.setText(pos);
}
//Mostrar los datos del elemento seleccionado del jListEtiquetas
private void mostrarDatosEtiquetas() {
if (vista.jListEtiquetas.getSelectedIndex() > -1) {
vista.jLabelIdFichasDeMedicamentos.setText("" + listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getIdEtiqueta());
vista.jTextAreaEtiquetasConservacion.setText(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConservacion());
vista.jTextAreaEtiquetasMedicamento.setText(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getDescripcion());
vista.jTextAreaEtiquetasReferenciaBibliografica.setText(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getReferenciaBiblio());
vista.jTextAreaEtiquetasReferenciaCaducidad.setText(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getReferenciaCaducidad());
vista.jTextAreaEtiquetasUtilizacion.setText(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getUtilizacion());
vista.jTextFieldEtiquetasCaducidad.setText(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getCaducidad());
vista.jTextFieldEtiquetasConcentracion.setText(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion());
if (listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getNumLibroRecetario() != null) {
vista.jTextFieldEtiquetasLibroRecetario.setText("" + listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getNumLibroRecetario());
} else {
vista.jTextFieldEtiquetasLibroRecetario.setText("");
}
vista.jTextFieldEtiquetasStockMinimo.setText(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getStockMinimo());
if (!nuevoPulsado) {
if (!modelo.selectNombreFichaDeMedicamento(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())).equals("?")) {
vista.jComboBoxMedicamento.setSelectedItem(modelo.selectNombreFichaDeMedicamento(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())));
} else {
vista.jComboBoxMedicamento.setSelectedIndex(0);
}
if (listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getQuienLoElabora() != null) {
//si no es A E o F entonces se cuenta como si no tubiera nada
if (!listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getQuienLoElabora().equals("A") || !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getQuienLoElabora().equals("E") || !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getQuienLoElabora().equals("F")) {
vista.jComboBoxEtiquetasElaboradoPor.setSelectedItem(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getQuienLoElabora());
} else {
vista.jComboBoxEtiquetasElaboradoPor.setSelectedIndex(0);
}
} else {
vista.jComboBoxEtiquetasElaboradoPor.setSelectedIndex(0);
}
if (listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getTipoEtiqueta() != null) {
vista.jComboBoxEtiquetasTipoEtiqueta.setSelectedItem(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getTipoEtiqueta());
} else {
vista.jComboBoxEtiquetasTipoEtiqueta.setSelectedIndex(0);
}
} else {
vista.jComboBoxEtiquetasElaboradoPor.setSelectedIndex(0);
vista.jComboBoxEtiquetasTipoEtiqueta.setSelectedIndex(0);
vista.jComboBoxMedicamento.setSelectedIndex(0);
}
}
}
//Recoger los datos de los controloes en el elemento seleccionado del jListEtiquetas
private void recogerDatosEtiquetas() {
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setConservacion(vista.jTextAreaEtiquetasConservacion.getText());
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setDescripcion(vista.jTextAreaEtiquetasMedicamento.getText());
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setReferenciaBiblio(vista.jTextAreaEtiquetasReferenciaBibliografica.getText());
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setReferenciaCaducidad(vista.jTextAreaEtiquetasReferenciaCaducidad.getText());
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setUtilizacion(vista.jTextAreaEtiquetasUtilizacion.getText());
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setCaducidad(vista.jTextFieldEtiquetasCaducidad.getText());
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setConcentracion(vista.jTextFieldEtiquetasConcentracion.getText());
if (!vista.jTextFieldEtiquetasLibroRecetario.getText().equals("")) {
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setNumLibroRecetario(Integer.valueOf(vista.jTextFieldEtiquetasLibroRecetario.getText()));
} else {
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setNumLibroRecetario(null);
}
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setStockMinimo(vista.jTextFieldEtiquetasStockMinimo.getText());
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setQuienLoElabora(vista.jComboBoxEtiquetasElaboradoPor.getSelectedItem().toString());
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setTipoEtiqueta(vista.jComboBoxEtiquetasTipoEtiqueta.getSelectedItem().toString());
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setFichasDeMedicamentos(listaFichaMedicamentos.get(vista.jComboBoxMedicamento.getSelectedIndex()));
}
// Evento al cambiar de posición en el jListEtiquetas
private void cambiarPosicionJListEtiquetas() {
actualizarPosicion();
controlarBotonesMoverse();
mostrarDatosEtiquetas();
}
// Activar/desactivar botones de siguiente,anterior,primero,último
private void controlarBotonesMoverse() {
if (vista.jListEtiquetas.getSelectedIndex() == 0) {
vista.jButtonAtrasEtiquetas.setEnabled(false);
vista.jButtonPrimeroEtiquetas.setEnabled(false);
} else {
vista.jButtonAtrasEtiquetas.setEnabled(true);
vista.jButtonPrimeroEtiquetas.setEnabled(true);
}
if (vista.jListEtiquetas.getSelectedIndex() == listaEtiquetas.size() - 1) {
vista.jButtonSiguienteEtiquetas.setEnabled(false);
vista.jButtonUltimoEtiquetas.setEnabled(false);
} else {
vista.jButtonSiguienteEtiquetas.setEnabled(true);
vista.jButtonUltimoEtiquetas.setEnabled(true);
}
}
//Moverse a la siguiente etiqueta de la lista
protected void botonMoverseSiguiente() {
vista.jListEtiquetas.setSelectedIndex(vista.jListEtiquetas.getSelectedIndex() + 1);
if (vista.jScrollPaneListaEtiquetas.getVerticalScrollBar().getValue() - (vista.jListEtiquetas.getSelectedIndex() * 19) < -361) {
vista.jScrollPaneListaEtiquetas.getVerticalScrollBar().setValue(((vista.jListEtiquetas.getSelectedIndex() * 19) - 361));
}
}
//Moverse a la anterior etiqueta de la lista
protected void botonMoverseAnterior() {
vista.jListEtiquetas.setSelectedIndex(vista.jListEtiquetas.getSelectedIndex() - 1);
if (vista.jScrollPaneListaEtiquetas.getVerticalScrollBar().getValue() - (vista.jListEtiquetas.getSelectedIndex() * 19) > 0) {
vista.jScrollPaneListaEtiquetas.getVerticalScrollBar().setValue(((vista.jListEtiquetas.getSelectedIndex() * 19)));
}
}
//Moverse a la primer etiqueta de la lista
protected void botonMoversePrimero() {
vista.jListEtiquetas.setSelectedIndex(0);
vista.jScrollPaneListaEtiquetas.getVerticalScrollBar().setValue(0);
}
//Moverse a la última etiqueta de la lista
protected void botonMoverseUltimo() {
vista.jListEtiquetas.setSelectedIndex(listaEtiquetas.size() - 1);
vista.jScrollPaneListaEtiquetas.getVerticalScrollBar().setValue(((vista.jListEtiquetas.getSelectedIndex() * 22) - 308));
}
//Modificar una etiqueta
protected void pulsarBotonModificarEtiquetas() {
comenzarEdicion();
nuevoPulsado = false;
}
//Nueva etiqueta
protected void pulsarBotonNuevaEtiquetas() {
nuevoPulsado = true;
Etiquetas maq = new Etiquetas();
listaEtiquetas.add(maq);
rellenarJListEtiquetas();
vista.jListEtiquetas.setSelectedIndex(listaEtiquetas.size() - 1);
comenzarEdicion();
}
//Eliminar etiqueta
protected void pulsarBotonEliminarEtiquetas() {
if (JOptionPane.showConfirmDialog(vista, "¿Desea eliminar la etiqueta actual?", "Eliminar", JOptionPane.YES_NO_OPTION) == 0) {
if (listaEtiquetas.size() < 2) {
JOptionPane.showMessageDialog(vista, "No se pueden eliminar todas las etiqueta visibles. \nPruebe a quitar algún filtro de busqueda", "Aviso", JOptionPane.WARNING_MESSAGE);
} else {
modelo.eliminarEtiquetas(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()));
listaEtiquetas.remove(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()));
rellenarJListEtiquetas();
vista.jListEtiquetas.setSelectedIndex(0);
}
}
}
// Habilitar controles para permitir la edición de los datos de una etiqueta
private void comenzarEdicion() {
vista.jTextAreaEtiquetasConservacion.setEditable(true);
vista.jTextAreaEtiquetasMedicamento.setEditable(true);
vista.jTextAreaEtiquetasReferenciaBibliografica.setEditable(true);
vista.jTextAreaEtiquetasReferenciaCaducidad.setEditable(true);
vista.jTextAreaEtiquetasUtilizacion.setEditable(true);
vista.jTextFieldEtiquetasCaducidad.setEditable(true);
vista.jTextFieldEtiquetasConcentracion.setEditable(true);
vista.jTextFieldEtiquetasLibroRecetario.setEditable(true);
vista.jTextFieldEtiquetasStockMinimo.setEditable(true);
vista.jComboBoxEtiquetasElaboradoPor.setEnabled(true);
vista.jComboBoxEtiquetasTipoEtiqueta.setEnabled(true);
vista.jComboBoxMedicamento.setEnabled(true);
//deshabilitar el JList y los botones de la barra de herramientas para evitar errores
vista.jListEtiquetas.setEnabled(false);
vista.jButtonAtrasEtiquetas.setEnabled(false);
vista.jButtonEliminarEtiquetas.setEnabled(false);
vista.jButtonNuevoEtiquetas.setEnabled(false);
vista.jButtonPrimeroEtiquetas.setEnabled(false);
vista.jButtonSiguienteEtiquetas.setEnabled(false);
vista.jButtonUltimoEtiquetas.setEnabled(false);
vista.jButtonBuscarEtiquetas.setEnabled(false);
vista.jButtonQuitarBuscarEtiquetas.setEnabled(false);
vista.jTextFieldBuscarEtiquetas.setEnabled(false);
vista.jButtonImprimirEtiqueta.setEnabled(false);
//cambiar el color de los paneles para resaltar
vista.jPanelEdicionDatosEtiquetas.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 255), 2, true), "Edición de datos"));
vista.jPanelListaEtiquetas.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 2, true), "Lista de etiquetas"));
//mostrar botones de aceptar-cancelar para terminar la edición
vista.jPanelAceptarCancelar.setVisible(true);
//Da el foco al primer componente editable
vista.jComboBoxMedicamento.transferFocusBackward();
}
// lo contrario de comenzarEdicion()
private void acabarEdicion() {
vista.jTextAreaEtiquetasConservacion.setEditable(false);
vista.jTextAreaEtiquetasMedicamento.setEditable(false);
vista.jTextAreaEtiquetasReferenciaBibliografica.setEditable(false);
vista.jTextAreaEtiquetasReferenciaCaducidad.setEditable(false);
vista.jTextAreaEtiquetasUtilizacion.setEditable(false);
vista.jTextFieldEtiquetasCaducidad.setEditable(false);
vista.jTextFieldEtiquetasConcentracion.setEditable(false);
vista.jTextFieldEtiquetasLibroRecetario.setEditable(false);
vista.jTextFieldEtiquetasStockMinimo.setEditable(false);
vista.jComboBoxEtiquetasElaboradoPor.setEnabled(false);
vista.jComboBoxEtiquetasTipoEtiqueta.setEnabled(false);
vista.jComboBoxMedicamento.setEnabled(false);
//deshabilitar el JList y los botones de la barra de herramientas para evitar errores
vista.jListEtiquetas.setEnabled(true);
vista.jButtonAtrasEtiquetas.setEnabled(true);
vista.jButtonEliminarEtiquetas.setEnabled(true);
vista.jButtonNuevoEtiquetas.setEnabled(true);
vista.jButtonPrimeroEtiquetas.setEnabled(true);
vista.jButtonSiguienteEtiquetas.setEnabled(true);
vista.jButtonUltimoEtiquetas.setEnabled(true);
vista.jButtonBuscarEtiquetas.setEnabled(true);
vista.jButtonQuitarBuscarEtiquetas.setEnabled(true);
vista.jTextFieldBuscarEtiquetas.setEnabled(true);
vista.jButtonImprimirEtiqueta.setEnabled(true);
//cambiar el color de los paneles para resaltar
vista.jPanelEdicionDatosEtiquetas.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 2, true), "Edición de datos"));
vista.jPanelListaEtiquetas.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 255), 2, true), "Lista de etiquetas"));
//mostrar botones de aceptar-cancelar para terminar la edición
vista.jPanelAceptarCancelar.setVisible(false);
}
//Pulsar boton de aceptar
public void botonAceptarPulsado() {
if (comprobarCamposObligatorios()) {
try {
if (nuevoPulsado) {
recogerDatosEtiquetas();
modelo.nuevoEtiquetas(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()));
acabarEdicion();
rellenarJListEtiquetas();
vista.jListEtiquetas.setSelectedIndex(listaEtiquetas.size() - 1);
} else {
recogerDatosEtiquetas();
modelo.modificarEtiquetas(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()));
int posicion = vista.jListEtiquetas.getSelectedIndex();
acabarEdicion();
rellenarJListEtiquetas();
vista.jListEtiquetas.setSelectedIndex(posicion);
}
} catch (org.hibernate.exception.DataException e) {
JOptionPane.showMessageDialog(vista, "El nombre de la etiqueta es demasiado larga, por favor hágalo más corto.", "Error", JOptionPane.WARNING_MESSAGE);
} catch (ConstraintViolationException e) {
JOptionPane.showMessageDialog(vista, "La etiqueta introducida ya existe, introduza otra", "Error", JOptionPane.WARNING_MESSAGE);
}
}
}
//Comprobar que los campos obligatorios no están vacios
public boolean comprobarCamposObligatorios() {
if (vista.jTextAreaEtiquetasMedicamento.getText().equals("")) {
JOptionPane.showMessageDialog(vista, "Los siguiente campos son obligatorios \n\t-Descripción", "Aviso", JOptionPane.WARNING_MESSAGE);
return false;
}
return true;
}
//Pulsar boton de cancelar
public void botonCancelarPulsado() {
if (nuevoPulsado) {
listaEtiquetas.remove(listaEtiquetas.size() - 1);
acabarEdicion();
rellenarJListEtiquetas();
vista.jListEtiquetas.setSelectedIndex(0);
} else {
acabarEdicion();
controlarBotonesMoverse();
mostrarDatosEtiquetas();
}
}
//Realizar búsquedas
public void botonBuscar() {
if (vista.jComboBoxBuscarEtiquetas.getSelectedIndex() == 0) {
listaEtiquetas = modelo.selectEtiquetasPorNombre(vista.jTextFieldBuscarEtiquetas.getText());
} else if (vista.jComboBoxBuscarEtiquetas.getSelectedIndex() == 1) {
listaEtiquetas = modelo.selectEtiquetasPorTipoEtiqueta(vista.jTextFieldBuscarEtiquetas.getText());
}
rellenarJListEtiquetas();
vista.jListEtiquetas.setSelectedIndex(0);
if (listaEtiquetas.size() < 1) {
JOptionPane.showMessageDialog(vista, "No hay etiquetas que cumplan las condiciones de la búsqueda", "Información", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(vista, "Se han reestablecido las condiciones de búsqueda", "Información", JOptionPane.INFORMATION_MESSAGE);
recargarDatosQuitarBuscar();
} else {
JOptionPane.showMessageDialog(vista, "Se han encontrado " + listaEtiquetas.size() + " etiquetas", "Información", JOptionPane.INFORMATION_MESSAGE);
}
}
//Quitar el filtro de las búsquedas también usado al entrar en esta pestaña
public void recargarDatosQuitarBuscar() {
vista.jTextFieldBuscarEtiquetas.setText("");
recargarDatos();
}
// Recarga los datos de la base de datos
public void recargarDatos() {
listaEtiquetas = modelo.selectAllEtiquetas();
rellenarJListEtiquetas();
vista.jListEtiquetas.setSelectedIndex(0);
}
//Devuelve la etiqueta escogida
public Etiquetas getEtiquetasElegida() {
return listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex());
}
//Se usa para permitir únicamente la escritura de número en el jTextField que se requiera
public void soloEscribirNumerosJTextField(JTextField textField) {
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
char caracter = e.getKeyChar();
if (!Character.isDigit(caracter)) {
e.consume();
}
}
});
}
//Muestra un diálogo que permite elegir el formato de etiqueta que queremos mostrar
public void pulsarBotonDialogImprimir() {
java.util.Date hoy = new java.util.Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
if (modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()))) {
vista.jDialogImprimirEtiquetasPaciente.setSize(580, 470);
vista.jDialogImprimirEtiquetasPaciente.setLocationRelativeTo(null);
vista.jTextFieldNombrePaciente.setText("");
vista.jRadioButton3.setSelected(true);
vista.jFormattedTextFieldFechaElaboracionPaciente.setText(formatter.format(hoy));
if (listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getTipoEtiqueta().equalsIgnoreCase("A")) {
vista.jRadioButtonDialogImprimirTipoAPaciente.setSelected(true);
} else if (listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getTipoEtiqueta().equalsIgnoreCase("B")) {
vista.jRadioButtonDialogImprimirTipoBPaciente.setSelected(true);
} else {
vista.jRadioButtonDialogImprimirTipoCPaciente.setSelected(true);
}
vista.jDialogImprimirEtiquetasPaciente.setVisible(true);
} else {
vista.jDialogImprimirEtiquetas.setSize(580, 350);
vista.jDialogImprimirEtiquetas.setLocationRelativeTo(null);
if (listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getTipoEtiqueta().equalsIgnoreCase("A")) {
vista.jRadioButtonDialogImprimirTipoA.setSelected(true);
} else if (listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getTipoEtiqueta().equalsIgnoreCase("B")) {
vista.jRadioButtonDialogImprimirTipoB.setSelected(true);
} else {
vista.jRadioButtonDialogImprimirTipoC.setSelected(true);
}
vista.jRadioButton2.setSelected(true);
vista.jFormattedTextFieldFechaElaboracion.setText(formatter.format(hoy));
vista.jDialogImprimirEtiquetas.setVisible(true);
}
}
//habilita y deshabilita la opción de introducir el nombre del cliente y un número específico de etiquetas
public void pulsarCheckBoxDatosPaciente() {
if (vista.jCheckBoxNombrePaciente.isSelected()) {
vista.jTextFieldNombrePaciente.setEnabled(true);
vista.jSpinnerNumeroEtiquetas.setEnabled(true);
} else {
vista.jTextFieldNombrePaciente.setEnabled(false);
vista.jSpinnerNumeroEtiquetas.setEnabled(false);
}
}
//Determina cual es el formato de la etiqueta elegido por el usuario cuando se pulsa el boton de vista previa
//y muestra un reporte de acuerdo con ese formato
public void pulsarBotonDialogImprimirPreview() {
String nombreReporte = "";
//Puede que haya una forma más eficiente de comprobar todas estas cosas
if (vista.jRadioButtonDialogImprimirTipoA.isSelected()) {
if (!vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& !vista.jRadioButtonDialogImprimirFormatoApli.isSelected()
&& !modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())) && !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("")) {
nombreReporte = "reportEtiqADpe.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& !vista.jRadioButtonDialogImprimirFormatoApli.isSelected()
&& !modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())) && !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("")) {
nombreReporte = "reportEtiqAUtilizacion.jasper";
} else if (!vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& !vista.jRadioButtonDialogImprimirFormatoApli.isSelected()
&& !modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())) && listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("")) {
nombreReporte = "reportEtiqADpeNoConcentracion.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& !vista.jRadioButtonDialogImprimirFormatoApli.isSelected()
&& !modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())) && listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("")) {
nombreReporte = "reportEtiqAUtilizacionNoConcentracion.jasper";
} else if (vista.jRadioButtonDialogImprimirFormatoApli.isSelected()) {
nombreReporte = "reportEtiquetaApli.jasper";
mostrarReporte(nombreReporte, 14);
return;
}
} else if (vista.jRadioButtonDialogImprimirTipoB.isSelected()) {
if (!vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& !vista.jRadioButtonDialogImprimirFormatoApli.isSelected()
&& !modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())) && !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("")) {
nombreReporte = "reportEtiqBDpe.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& !vista.jRadioButtonDialogImprimirFormatoApli.isSelected()
&& !modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())) && !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("")) {
nombreReporte = "reportEtiqBUtilizacion.jasper";
} else if (!vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& !vista.jRadioButtonDialogImprimirFormatoApli.isSelected()
&& !modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())) && listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("")) {
nombreReporte = "reportEtiqBDpeNoConcentracion.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& !vista.jRadioButtonDialogImprimirFormatoApli.isSelected()
&& !modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())) && listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("")) {
nombreReporte = "reportEtiqBUtilizacionNoConcentracion.jasper";
} else if (vista.jRadioButtonDialogImprimirFormatoApli.isSelected()) {
nombreReporte = "reportEtiquetaApli.jasper";
mostrarReporte(nombreReporte, 14);
return;
}
} else if (vista.jRadioButtonDialogImprimirTipoC.isSelected()) {
if (!vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& !vista.jRadioButtonDialogImprimirFormatoApli.isSelected()
&& !modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())) && !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("")) {
nombreReporte = "reportEtiqCDpe.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& !vista.jRadioButtonDialogImprimirFormatoApli.isSelected()
&& !modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())) && !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("")) {
nombreReporte = "reportEtiqCUtilizacion.jasper";
} else if (!vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& !vista.jRadioButtonDialogImprimirFormatoApli.isSelected()
&& !modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())) && listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("")) {
nombreReporte = "reportEtiqCDpeNoConcentracion.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& !vista.jRadioButtonDialogImprimirFormatoApli.isSelected()
&& !modelo.esFormulaMagistral(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex())) && listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("")) {
nombreReporte = "reportEtiqCUtilizacionNoConcentracion.jasper";
} else if (vista.jRadioButtonDialogImprimirFormatoApli.isSelected()) {
nombreReporte = "reportEtiquetaApli.jasper";
mostrarReporte(nombreReporte, 14);
return;
}
}
mostrarReporte(nombreReporte);
}
public void pulsarVistaPreviaPaciente() {
String nombreReporte = "";
if (vista.jRadioButtonDialogImprimirTipoAPaciente.isSelected()) {
if (!vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && !vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqAFM.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && !vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqAFMUtilizacion.jasper";
} else if (!vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && !vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqAFMNoConcentracion.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && !vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqAFMUtilizacionNoConcentracion.jasper";
} else if (!vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqAFMPaciente.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqAFMUtilizacionPaciente.jasper";
} else if (!vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqAFMNoConcentracionPaciente.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqAFMUtilizacionNoConcentracionPaciente.jasper";
}
} else if (vista.jRadioButtonDialogImprimirTipoBPaciente.isSelected()) {
if (!vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && !vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqBFM.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && !vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "report4EtiqbFMUtilizacion.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && !vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "report4EtiqbFMUtilizacionNoConcentracion.jasper";
} else if (!vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && !vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqBFMNoConcentracion.jasper";
} else if (!vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqBFMPaciente.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "report4EtiqbFMUtilizacionPaciente.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "report4EtiqbFMUtilizacionNoConcentracionPaciente.jasper";
} else if (!vista.jCheckBoxDialogImprimirUtilizacion.isSelected()
&& listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqBFmNoConcentracionPaciente.jasper";
}
} else if (vista.jRadioButtonDialogImprimirTipoCPaciente.isSelected()) {
if (!vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && !vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqCFM.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && !vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqCFMUtilizacion.jasper";
} else if (!vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && !vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqCFMNoConcentracion.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && !vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqCFMUtilizacionNoConcentracion.jasper";
} else if (!vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqCFMPaciente.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& !listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqCFMUtilizacionPaciente.jasper";
} else if (!vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqCFMNoConcentracionPaciente.jasper";
} else if (vista.jCheckBoxDialogImprimirUtilizacionPaciente.isSelected()
&& listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).getConcentracion().equals("") && vista.jCheckBoxNombrePaciente.isSelected()) {
nombreReporte = "reportEtiqCFMUtilizacionNoCocentracionPaciente.jasper";
}
}
if (vista.jRadioButtonDialogImprimirFormatoApliPaciente.isSelected()) {
nombreReporte = "reportEtiquetaApli.jasper";
mostrarReporteFormulaMagistral(nombreReporte, 14);
return;
}
mostrarReporteFormulaMagistral(nombreReporte);
}
//Muestra el tipo de reporte elegido de la etiqueta seleccionada
public void mostrarReporte(String nombreReporte) {
ArrayList<Etiquetas> etiqImprimir = new ArrayList<>();
//Llenar la hoja de etiquetas
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setFechaDeElaboracion(vista.jFormattedTextFieldFechaElaboracion.getText());
etiqImprimir.add(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()));
EtiquetasDataSource datasource = new EtiquetasDataSource(etiqImprimir);
JasperReport reporte;
try {
reporte = (JasperReport) JRLoader.loadObjectFromFile(nombreReporte);
JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, datasource);
JasperViewer jviewer = new JasperViewer(jasperPrint, false);
// jviewer.setAlwaysOnTop(true);
vista.jDialogImprimirEtiquetas.setVisible(false);
jviewer.setTitle("Imprimir");
jviewer.setVisible(true);
jviewer.setExtendedState(Frame.MAXIMIZED_BOTH);
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setFechaDeElaboracion("");
} catch (JRException e1) {
JOptionPane.showMessageDialog(vista, "Error al inicializar el reporte", "Fallo", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
}
//Muestra el tipo de reporte elegido de la etiqueta seleccionada
public void mostrarReporte(String nombreReporte, int repeticion) {
ArrayList<Etiquetas> etiqImprimir = new ArrayList<>();
//Llenar la hoja de etiquetas
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setFechaDeElaboracion(vista.jFormattedTextFieldFechaElaboracion.getText());
for (int i = 0; i < repeticion; i++) {
etiqImprimir.add(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()));
}
EtiquetasDataSource datasource = new EtiquetasDataSource(etiqImprimir);
JasperReport reporte;
try {
reporte = (JasperReport) JRLoader.loadObjectFromFile(nombreReporte);
JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, datasource);
JasperViewer jviewer = new JasperViewer(jasperPrint, false);
// jviewer.setAlwaysOnTop(true);
vista.jDialogImprimirEtiquetas.setVisible(false);
jviewer.setTitle("Imprimir");
jviewer.setVisible(true);
jviewer.setExtendedState(Frame.MAXIMIZED_BOTH);
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setFechaDeElaboracion("");
} catch (JRException e1) {
JOptionPane.showMessageDialog(vista, "Error al inicializar el reporte", "Fallo", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
}
//Muestra el tipo de reporte de formulas magistrales elegido de la etiqueta seleccionada
public void mostrarReporteFormulaMagistral(String nombreReporte) {
ArrayList<Etiquetas> etiqImprimir = new ArrayList<>();
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setNombreDelPaciente(vista.jTextFieldNombrePaciente.getText());
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setFechaDeElaboracion(vista.jFormattedTextFieldFechaElaboracionPaciente.getText());
//Llenar la hoja de etiquetas
for (int i = 0; i < Integer.valueOf(vista.jSpinnerNumeroEtiquetas.getValue().toString()); i++) {
etiqImprimir.add(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()));
}
EtiquetasDataSource datasource = new EtiquetasDataSource(etiqImprimir);
JasperReport reporte;
try {
reporte = (JasperReport) JRLoader.loadObjectFromFile(nombreReporte);
JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, datasource);
JasperViewer jviewer = new JasperViewer(jasperPrint, false);
// jviewer.setAlwaysOnTop(true);
vista.jDialogImprimirEtiquetasPaciente.setVisible(false);
jviewer.setTitle("Imprimir");
jviewer.setVisible(true);
jviewer.setExtendedState(Frame.MAXIMIZED_BOTH);
//no interesa guardar el nombre del paciente en la base de datos
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setNombreDelPaciente("");
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setFechaDeElaboracion("");
} catch (JRException e1) {
JOptionPane.showMessageDialog(vista, "Error al inicializar el reporte", "Fallo", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
}
//Muestra el tipo de reporte de formulas magistrales elegido de la etiqueta seleccionada
public void mostrarReporteFormulaMagistral(String nombreReporte, int repeticion) {
ArrayList<Etiquetas> etiqImprimir = new ArrayList<>();
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setNombreDelPaciente(vista.jTextFieldNombrePaciente.getText());
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setFechaDeElaboracion(vista.jFormattedTextFieldFechaElaboracionPaciente.getText());
//Llenar la hoja de etiquetas
for (int i = 0; i < repeticion; i++) {
etiqImprimir.add(listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()));
}
EtiquetasDataSource datasource = new EtiquetasDataSource(etiqImprimir);
JasperReport reporte;
try {
reporte = (JasperReport) JRLoader.loadObjectFromFile(nombreReporte);
JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, datasource);
JasperViewer jviewer = new JasperViewer(jasperPrint, false);
// jviewer.setAlwaysOnTop(true);
vista.jDialogImprimirEtiquetasPaciente.setVisible(false);
jviewer.setTitle("Imprimir");
jviewer.setVisible(true);
jviewer.setExtendedState(Frame.MAXIMIZED_BOTH);
//no interesa guardar el nombre del paciente en la base de datos
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setNombreDelPaciente("");
listaEtiquetas.get(vista.jListEtiquetas.getSelectedIndex()).setFechaDeElaboracion("");
} catch (JRException e1) {
JOptionPane.showMessageDialog(vista, "Error al inicializar el reporte", "Fallo", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
}
}
<file_sep>package es.sacyl.caza.farmacia.controlador;
import es.sacyl.caza.farmacia.modelo.ProductosDAO;
import es.sacyl.caza.farmacia.modelo.clases.Productos;
import es.sacyl.caza.farmacia.vista.PanelProductos;
import es.sacyl.caza.farmacia.vista.VentanaEdicionPMS;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import org.hibernate.exception.ConstraintViolationException;
/**
*
* @author <NAME>
*
* Maneja los eventos relacionados con la pestaña productos de la
* VentanaEdicionPMS
*/
public class ControladorProductos {
private PanelProductos vista;
private ArrayList<Productos> listaProductos;
private String[] productosJList;
private ProductosDAO modelo;
private boolean nuevoPulsado = false;
private VentanaEdicionPMS ventanaPms;
public ControladorProductos(PanelProductos vista) {
this.vista = vista;
init();
initListeners();
}
public ControladorProductos(PanelProductos vista, VentanaEdicionPMS ventanaEdicionPMS) {
this.vista = vista;
this.ventanaPms = ventanaEdicionPMS;
init();
initListeners();
}
//Inicialización de los objetos necesarios para acceder y mostrar los datos
private void init() {
modelo = new ProductosDAO();
listaProductos = modelo.selectAllProducto();
rellenarJListProductos();
vista.jListProductos.setSelectedIndex(0);
actualizarPosicion();
mostrarDatosProductos();
acabarEdicion();
}
//Añade los listener de los eventos a los componentes
private void initListeners() {
vista.jListProductos.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
cambiarPosicionJListProductos();
}
});
vista.jButtonSiguienteProductos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseSiguiente();
}
});
vista.jButtonAtrasProductos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseAnterior();
}
});
vista.jButtonPrimeroProductos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoversePrimero();
}
});
vista.jButtonUltimoProductos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseUltimo();
}
});
vista.jButtonModificarProductos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonModificarProducto();
}
});
vista.jButtonAceptarProductos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonAceptarPulsado();
}
});
vista.jButtonCancelarProductos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonCancelarPulsado();
}
});
vista.jButtonNuevoProductos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonNuevoProducto();
}
});
vista.jButtonBuscarProductos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonBuscar();
}
});
vista.jButtonQuitarBuscarProductos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
recargarDatosQuitarBuscar();
}
});
vista.jButtonEliminarProductos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEliminarProducto();
}
});
vista.jTextFieldBuscarProductos.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
botonBuscar();
}
}
});
}
//Llena el JListProductos con los nombres de los productos existentes en la base de datos
private void rellenarJListProductos() {
productosJList = new String[listaProductos.size()];
for (int i = 0; i < productosJList.length; i++) {
productosJList[i] = listaProductos.get(i).getReferencia() + " - " + listaProductos.get(i).getComponente();
}
vista.jListProductos.setModel(new javax.swing.AbstractListModel() {
@Override
public int getSize() {
return productosJList.length;
}
@Override
public Object getElementAt(int i) {
return productosJList[i];
}
});
}
//Posición del producto en el que estamos situados
private void actualizarPosicion() {
String pos = "Producto " + (vista.jListProductos.getSelectedIndex() + 1) + " de " + productosJList.length;
vista.jLabelPosicionProducto.setText(pos);
}
//Mostrar los datos del elemento seleccionado del jListProductos
private void mostrarDatosProductos() {
if (vista.jListProductos.getSelectedIndex() > -1) {
vista.jTextAreaComponenteProductos.setText(listaProductos.get(vista.jListProductos.getSelectedIndex()).getComponente());
vista.jLabelIdProductos.setText(listaProductos.get(vista.jListProductos.getSelectedIndex()).getIdComponente() + "");
vista.jTextAreaObservacionesProductos.setText(listaProductos.get(vista.jListProductos.getSelectedIndex()).getObservaciones());
vista.jTextFieldEstanteProductos.setText(listaProductos.get(vista.jListProductos.getSelectedIndex()).getEstante());
vista.jTextFieldReferenciaProductos.setText(listaProductos.get(vista.jListProductos.getSelectedIndex()).getReferencia());
if (!nuevoPulsado) {
if (listaProductos.get(vista.jListProductos.getSelectedIndex()).getActivo()) {
vista.jComboBoxActivoProductos.setSelectedIndex(1);
} else {
vista.jComboBoxActivoProductos.setSelectedIndex(0);
}
}
}
}
//Recoger los datos de los controloes en el elemento seleccionado del jListProductos
private void recogerDatosProductos() {
listaProductos.get(vista.jListProductos.getSelectedIndex()).setComponente(vista.jTextAreaComponenteProductos.getText());
listaProductos.get(vista.jListProductos.getSelectedIndex()).setEstante(vista.jTextFieldEstanteProductos.getText());
listaProductos.get(vista.jListProductos.getSelectedIndex()).setObservaciones(vista.jTextAreaObservacionesProductos.getText());
listaProductos.get(vista.jListProductos.getSelectedIndex()).setReferencia(vista.jTextFieldReferenciaProductos.getText());
if (vista.jComboBoxActivoProductos.getSelectedIndex() == 0) {
listaProductos.get(vista.jListProductos.getSelectedIndex()).setActivo(false);
} else {
listaProductos.get(vista.jListProductos.getSelectedIndex()).setActivo(true);
}
}
// Activar/desactivar botones de siguiente,anterior,primero,último
private void controlarBotonesMoverse() {
if (vista.jListProductos.getSelectedIndex() == 0) {
vista.jButtonAtrasProductos.setEnabled(false);
vista.jButtonPrimeroProductos.setEnabled(false);
} else {
vista.jButtonAtrasProductos.setEnabled(true);
vista.jButtonPrimeroProductos.setEnabled(true);
}
if (vista.jListProductos.getSelectedIndex() == listaProductos.size() - 1) {
vista.jButtonSiguienteProductos.setEnabled(false);
vista.jButtonUltimoProductos.setEnabled(false);
} else {
vista.jButtonSiguienteProductos.setEnabled(true);
vista.jButtonUltimoProductos.setEnabled(true);
}
}
// Evento al cambiar de posición en el jListProductos
private void cambiarPosicionJListProductos() {
actualizarPosicion();
controlarBotonesMoverse();
mostrarDatosProductos();
}
//Moverse al siguiente producto de la lista
protected void botonMoverseSiguiente() {
vista.jListProductos.setSelectedIndex(vista.jListProductos.getSelectedIndex() + 1);
if (vista.jScrollPaneListaProducto.getVerticalScrollBar().getValue() - (vista.jListProductos.getSelectedIndex() * 22) < -308) {
vista.jScrollPaneListaProducto.getVerticalScrollBar().setValue(((vista.jListProductos.getSelectedIndex() * 22) - 308));
}
}
//Moverse al anterior producto de la lista
protected void botonMoverseAnterior() {
vista.jListProductos.setSelectedIndex(vista.jListProductos.getSelectedIndex() - 1);
if (vista.jScrollPaneListaProducto.getVerticalScrollBar().getValue() - (vista.jListProductos.getSelectedIndex() * 22) > 0) {
vista.jScrollPaneListaProducto.getVerticalScrollBar().setValue(((vista.jListProductos.getSelectedIndex() * 22)));
}
}
//Moverse al primer producto de la lista
protected void botonMoversePrimero() {
vista.jListProductos.setSelectedIndex(0);
vista.jScrollPaneListaProducto.getVerticalScrollBar().setValue(0);
}
//Moverse al último producto de la lista
protected void botonMoverseUltimo() {
vista.jListProductos.setSelectedIndex(listaProductos.size() - 1);
vista.jScrollPaneListaProducto.getVerticalScrollBar().setValue(((vista.jListProductos.getSelectedIndex() * 22) - 308));
}
//Modificar un producto
protected void pulsarBotonModificarProducto() {
comenzarEdicion();
nuevoPulsado = false;
}
//Nuevo producto
protected void pulsarBotonNuevoProducto() {
nuevoPulsado = true;
Productos producto = new Productos();
listaProductos.add(producto);
rellenarJListProductos();
vista.jListProductos.setSelectedIndex(listaProductos.size() - 1);
comenzarEdicion();
}
//Eliminar producto
protected void pulsarBotonEliminarProducto() {
if (JOptionPane.showConfirmDialog(vista, "¿Desea eliminar el producto actual?", "Eliminar", JOptionPane.YES_NO_OPTION) == 0) {
if (listaProductos.size() < 2) {
JOptionPane.showMessageDialog(vista, "No se pueden eliminar todos los productos visibles. \nPruebe a quitar algún filtro de busqueda", "Aviso", JOptionPane.WARNING_MESSAGE);
} else {
modelo.eliminarProducto(listaProductos.get(vista.jListProductos.getSelectedIndex()));
listaProductos.remove(listaProductos.get(vista.jListProductos.getSelectedIndex()));
rellenarJListProductos();
vista.jListProductos.setSelectedIndex(0);
}
}
}
// Habilitar controles para permitir la edición de los datos de un producto
private void comenzarEdicion() {
vista.jTextAreaComponenteProductos.setEditable(true);
vista.jTextAreaObservacionesProductos.setEditable(true);
vista.jTextFieldEstanteProductos.setEditable(true);
vista.jTextFieldReferenciaProductos.setEditable(true);
vista.jComboBoxActivoProductos.setEnabled(true);
//deshabilitar el JList y los botones de la barra de herramientas para evitar errores
vista.jListProductos.setEnabled(false);
vista.jButtonAtrasProductos.setEnabled(false);
vista.jButtonEliminarProductos.setEnabled(false);
vista.jButtonNuevoProductos.setEnabled(false);
vista.jButtonPrimeroProductos.setEnabled(false);
vista.jButtonSiguienteProductos.setEnabled(false);
vista.jButtonUltimoProductos.setEnabled(false);
//deshabilita el resto de pestañas
if (ventanaPms != null) {
ventanaPms.jTabbedPaneEdicionPMS.setEnabledAt(1, false);
ventanaPms.jTabbedPaneEdicionPMS.setEnabledAt(2, false);
ventanaPms.jTabbedPaneEdicionPMS.setEnabledAt(3, false);
}
vista.jButtonBuscarProductos.setEnabled(false);
vista.jButtonQuitarBuscarProductos.setEnabled(false);
vista.jTextFieldBuscarProductos.setEnabled(false);
//cambiar el color de los paneles para resaltar
vista.jPanelEdicionDatosProductos.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 102, 51), 2, true), "Edición de datos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14)));
vista.jPanelListaProductos.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 2, true), "Lista de productos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14)));
//mostrar botones de aceptar-cancelar para terminar la edición
vista.jButtonAceptarProductos.setVisible(true);
vista.jButtonCancelarProductos.setVisible(true);
//da el focus a la primera opción editable
vista.jTextFieldReferenciaProductos.transferFocusBackward();
}
//Pasos contrarios a comenzarEdicion()
private void acabarEdicion() {
vista.jTextAreaComponenteProductos.setEditable(false);
vista.jTextAreaObservacionesProductos.setEditable(false);
vista.jTextFieldEstanteProductos.setEditable(false);
vista.jTextFieldReferenciaProductos.setEditable(false);
vista.jComboBoxActivoProductos.setEnabled(false);
//deshabilitar el JList y los botones de la barra de herramientas para evitar errores
vista.jListProductos.setEnabled(true);
vista.jButtonAtrasProductos.setEnabled(true);
vista.jButtonEliminarProductos.setEnabled(true);
vista.jButtonNuevoProductos.setEnabled(true);
vista.jButtonPrimeroProductos.setEnabled(true);
vista.jButtonSiguienteProductos.setEnabled(true);
vista.jButtonUltimoProductos.setEnabled(true);
if (ventanaPms != null) {
ventanaPms.jTabbedPaneEdicionPMS.setEnabledAt(1, true);
ventanaPms.jTabbedPaneEdicionPMS.setEnabledAt(2, true);
ventanaPms.jTabbedPaneEdicionPMS.setEnabledAt(3, true);
}
vista.jButtonBuscarProductos.setEnabled(true);
vista.jButtonQuitarBuscarProductos.setEnabled(true);
vista.jTextFieldBuscarProductos.setEnabled(true);
//cambiar el color de los paneles para resaltar
vista.jPanelEdicionDatosProductos.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 2, true), "Edición de datos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14)));
vista.jPanelListaProductos.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 102, 51), 2, true), "Lista de productos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14)));
//mostrar botones de aceptar-cancelar para terminar la edición
vista.jButtonAceptarProductos.setVisible(false);
vista.jButtonCancelarProductos.setVisible(false);
}
//Pulsar boton de aceptar
public void botonAceptarPulsado() {
if (comprobarCamposObligatorios()) {
try {
if (nuevoPulsado) {
recogerDatosProductos();
modelo.nuevoProducto(listaProductos.get(vista.jListProductos.getSelectedIndex()));
acabarEdicion();
rellenarJListProductos();
vista.jListProductos.setSelectedIndex(listaProductos.size() - 1);
} else {
recogerDatosProductos();
modelo.modificarProducto(listaProductos.get(vista.jListProductos.getSelectedIndex()));
int posicion = vista.jListProductos.getSelectedIndex();
acabarEdicion();
rellenarJListProductos();
vista.jListProductos.setSelectedIndex(posicion);
}
} catch (org.hibernate.exception.DataException e) {
JOptionPane.showMessageDialog(vista, "Uno de los campos es demasiado largo, por favor hágalo más corto.", "Error", JOptionPane.WARNING_MESSAGE);
} catch (ConstraintViolationException e) {
JOptionPane.showMessageDialog(vista, "La referencia introducida ya existe, introduza otra", "Error", JOptionPane.WARNING_MESSAGE);
}
}
}
//Pulsar boton de cancelar
public void botonCancelarPulsado() {
if (nuevoPulsado) {
listaProductos.remove(listaProductos.size() - 1);
acabarEdicion();
rellenarJListProductos();
vista.jListProductos.setSelectedIndex(0);
} else {
acabarEdicion();
controlarBotonesMoverse();
mostrarDatosProductos();
}
}
//Comprobar que los campos obligatorios no están vacios y que la referencia sea válida
public boolean comprobarCamposObligatorios() {
if (vista.jTextAreaComponenteProductos.getText().equals("")) {
JOptionPane.showMessageDialog(vista, "Los siguiente campos son obligatorios \n\t-Componente\n\t-Referencia", "Aviso", JOptionPane.WARNING_MESSAGE);
return false;
} else if (vista.jTextFieldReferenciaProductos.getText().equals("")) {
JOptionPane.showMessageDialog(vista, "Los siguiente campos son obligatorios \n\t-Componente\n\t-Referencia", "Aviso", JOptionPane.WARNING_MESSAGE);
return false;
} else if (!(vista.jTextFieldReferenciaProductos.getText().startsWith("s") || vista.jTextFieldReferenciaProductos.getText().startsWith("S")
|| vista.jTextFieldReferenciaProductos.getText().startsWith("l") || vista.jTextFieldReferenciaProductos.getText().startsWith("L")
|| vista.jTextFieldReferenciaProductos.getText().startsWith("c") || vista.jTextFieldReferenciaProductos.getText().startsWith("C")
|| vista.jTextFieldReferenciaProductos.getText().startsWith("#"))) {
JOptionPane.showMessageDialog(vista, "El campo referencia debe empezar por 'S','L','C' o '#' ", "Aviso", JOptionPane.WARNING_MESSAGE);
return false;
}
return true;
}
//Realizar búsquedas
public void botonBuscar() {
if (vista.jComboBoxBuscarProductos.getSelectedIndex() == 0) {
listaProductos = modelo.selectProductosPorComponente(vista.jTextFieldBuscarProductos.getText());
} else if (vista.jComboBoxBuscarProductos.getSelectedIndex() == 1) {
listaProductos = modelo.selectProductosPorReferencia(vista.jTextFieldBuscarProductos.getText());
} else if (vista.jComboBoxBuscarProductos.getSelectedIndex() == 2) {
if (vista.jTextFieldBuscarProductos.getText().equals("1")) {
listaProductos = modelo.selectProductosActivos(true);
} else if (vista.jTextFieldBuscarProductos.getText().equals("0")) {
listaProductos = modelo.selectProductosActivos(false);
}
}
rellenarJListProductos();
vista.jListProductos.setSelectedIndex(0);
if (listaProductos.size() < 1) {
JOptionPane.showMessageDialog(vista, "No hay productos que cumplan las condiciones de la búsqueda", "Información", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(vista, "Se han reestablecido las condiciones de búsqueda", "Información", JOptionPane.INFORMATION_MESSAGE);
recargarDatosQuitarBuscar();
} else {
JOptionPane.showMessageDialog(vista, "Se han encontrado " + listaProductos.size() + " productos", "Información", JOptionPane.INFORMATION_MESSAGE);
}
}
//Quitar el filtro de las busqudas
public void recargarDatosQuitarBuscar() {
vista.jTextFieldBuscarProductos.setText("");
recargarDatos();
}
// Recarga los datos de la base de datos
public void recargarDatos() {
listaProductos = modelo.selectAllProducto();
rellenarJListProductos();
vista.jListProductos.setSelectedIndex(0);
}
//Devuelve el producto seleccionado actualmente
public Productos getProducto() {
return listaProductos.get(vista.jListProductos.getSelectedIndex());
}
}
<file_sep>package es.sacyl.caza.farmacia.controlador;
import es.sacyl.caza.farmacia.modelo.ReenvasadosDAO;
import es.sacyl.caza.farmacia.modelo.ReenvasadosDataSource;
import es.sacyl.caza.farmacia.modelo.clases.Reenvasados;
import es.sacyl.caza.farmacia.vista.VentanaReenvasados;
import java.awt.Frame;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import org.hibernate.exception.ConstraintViolationException;
/**
* Maneja los eventos de la ventanaReenvasados
*
* @author <NAME>
*/
public class ControladorReenvasados {
private VentanaReenvasados vista;
private ArrayList<Reenvasados> listaReenvasados;
private String[] reenvasadosJList;
private ReenvasadosDAO modelo;
private boolean nuevoPulsado = false;
public ControladorReenvasados(VentanaReenvasados vista) {
this.vista = vista;
init();
initListeners();
}
//Inicialización de los objetos necesarios para acceder y mostrar los datos
private void init() {
modelo = new ReenvasadosDAO();
listaReenvasados = modelo.selectAllReenvasados();
rellenarJListReenvasados();
vista.jListReenvasados.setSelectedIndex(0);
actualizarPosicion();
mostrarDatosReenvasados();
acabarEdicion();
}
//Añade los listener de los eventos a los componentes
private void initListeners() {
vista.jListReenvasados.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
cambiarPosicionJListReenvasados();
}
});
vista.jButtonSiguienteReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseSiguiente();
}
});
vista.jButtonAtrasReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseAnterior();
}
});
vista.jButtonPrimeroReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoversePrimero();
}
});
vista.jButtonUltimoReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseUltimo();
}
});
vista.jButtonModificarReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonModificarReenvasados();
}
});
vista.jButtonAceptarReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonAceptarPulsado();
}
});
vista.jButtonCancelarReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonCancelarPulsado();
}
});
vista.jButtonNuevoReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonNuevoReenvasados();
}
});
vista.jButtonBuscarReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonBuscar();
}
});
vista.jButtonQuitarBuscarReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
recargarDatosQuitarBuscar();
}
});
vista.jButtonEliminarReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEliminarReenvasados();
}
});
vista.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
cerrarVentana();
}
});
vista.jMenuItemArchivoSalir.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
cerrarVentana();
}
});
vista.jMenuItemArchivoNuevo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonNuevoReenvasados();
}
});
vista.jMenuItemEditarEliminar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEliminarReenvasados();
}
});
vista.jMenuItemEditarModificar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonModificarReenvasados();
}
});
vista.jMenuItemVerAnterior.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseAnterior();
}
});
vista.jMenuItemVerPrimero.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoversePrimero();
}
});
vista.jMenuItemVerSiguiente.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseSiguiente();
}
});
vista.jMenuItemVerUltimo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseUltimo();
}
});
vista.jButtonImprimirReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonImprimir();
}
});
vista.jButtonVistaPreviaReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonVistaPrevia();
}
});
vista.jButtonVolverReenvasados.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
vista.jDialogImprimirReenvasados.setVisible(false);
}
});
vista.jMenuItemCopiar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
copiar();
}
});
vista.jMenuItemPegar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pegar();
}
});
vista.jTextFieldBuscarReenvasados.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
botonBuscar();
}
}
});
}
//Acción de copiar
public void copiar() {
if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaDescripcionReenvasados)) {
vista.jTextAreaDescripcionReenvasados.copy();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaPrincipioActivoReenvasados)) {
vista.jTextAreaPrincipioActivoReenvasados.copy();
}
}
//Acción de pegar
public void pegar() {
//solo se puede pegar si se estan editando los datos
if (vista.jButtonAceptarReenvasados.isVisible()) {
//Para pegar hacer un switch con todos los componentes en donde se puede pegar
if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaDescripcionReenvasados)) {
vista.jTextAreaDescripcionReenvasados.paste();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaPrincipioActivoReenvasados)) {
vista.jTextAreaPrincipioActivoReenvasados.paste();
}
} else {
JOptionPane.showMessageDialog(vista, "Para poder pegar hay que pulsar antes el botón de modificar los datos", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void cerrarVentana() {
vista.dispose();
}
//Llena el JListReenvasados con los nombres de los materiales para envasar existentes en la base de datos
private void rellenarJListReenvasados() {
reenvasadosJList = new String[listaReenvasados.size()];
for (int i = 0; i < reenvasadosJList.length; i++) {
reenvasadosJList[i] = listaReenvasados.get(i).getDescripcion();
}
vista.jListReenvasados.setModel(new javax.swing.AbstractListModel() {
@Override
public int getSize() {
return reenvasadosJList.length;
}
@Override
public Object getElementAt(int i) {
return reenvasadosJList[i];
}
});
}
//Posición del material para envasar en el que estamos situados
private void actualizarPosicion() {
String pos = "Reenvasado " + (vista.jListReenvasados.getSelectedIndex() + 1) + " de " + reenvasadosJList.length;
vista.jLabelPosicionReenvasados.setText(pos);
}
//Mostrar los datos del elemento seleccionado del jListReenvasados
private void mostrarDatosReenvasados() {
if (vista.jListReenvasados.getSelectedIndex() > -1) {
vista.jTextAreaDescripcionReenvasados.setText(listaReenvasados.get(vista.jListReenvasados.getSelectedIndex()).getDescripcion());
vista.jLabelIdReenvasados.setText(listaReenvasados.get(vista.jListReenvasados.getSelectedIndex()).getIdReenvasado() + "");
vista.jTextAreaPrincipioActivoReenvasados.setText(listaReenvasados.get(vista.jListReenvasados.getSelectedIndex()).getPrincipioActivo());
}
}
//Recoger los datos de los controloes en el elemento seleccionado del jListReenvasados
private void recogerDatosReenvasados() {
listaReenvasados.get(vista.jListReenvasados.getSelectedIndex()).setDescripcion(vista.jTextAreaDescripcionReenvasados.getText());
listaReenvasados.get(vista.jListReenvasados.getSelectedIndex()).setPrincipioActivo(vista.jTextAreaPrincipioActivoReenvasados.getText());
}
// Evento al cambiar de posición en el jListReenvasados
private void cambiarPosicionJListReenvasados() {
actualizarPosicion();
controlarBotonesMoverse();
mostrarDatosReenvasados();
}
// Activar/desactivar botones de siguiente,anterior,primero,último
private void controlarBotonesMoverse() {
if (vista.jListReenvasados.getSelectedIndex() == 0) {
vista.jButtonAtrasReenvasados.setEnabled(false);
vista.jButtonPrimeroReenvasados.setEnabled(false);
} else {
vista.jButtonAtrasReenvasados.setEnabled(true);
vista.jButtonPrimeroReenvasados.setEnabled(true);
}
if (vista.jListReenvasados.getSelectedIndex() == listaReenvasados.size() - 1) {
vista.jButtonSiguienteReenvasados.setEnabled(false);
vista.jButtonUltimoReenvasados.setEnabled(false);
} else {
vista.jButtonSiguienteReenvasados.setEnabled(true);
vista.jButtonUltimoReenvasados.setEnabled(true);
}
}
//Moverse al siguiente material para envasar de la lista
protected void botonMoverseSiguiente() {
vista.jListReenvasados.setSelectedIndex(vista.jListReenvasados.getSelectedIndex() + 1);
if (vista.jScrollPaneListaMaterial.getVerticalScrollBar().getValue() - (vista.jListReenvasados.getSelectedIndex() * 22) < -308) {
vista.jScrollPaneListaMaterial.getVerticalScrollBar().setValue(((vista.jListReenvasados.getSelectedIndex() * 22) - 308));
}
}
//Moverse al anterior material para envasar de la lista
protected void botonMoverseAnterior() {
vista.jListReenvasados.setSelectedIndex(vista.jListReenvasados.getSelectedIndex() - 1);
if (vista.jScrollPaneListaMaterial.getVerticalScrollBar().getValue() - (vista.jListReenvasados.getSelectedIndex() * 22) > 0) {
vista.jScrollPaneListaMaterial.getVerticalScrollBar().setValue(((vista.jListReenvasados.getSelectedIndex() * 22)));
}
}
//Moverse al primer material para envasar de la lista
protected void botonMoversePrimero() {
vista.jListReenvasados.setSelectedIndex(0);
vista.jScrollPaneListaMaterial.getVerticalScrollBar().setValue(0);
}
//Moverse al última material para envasar de la lista
protected void botonMoverseUltimo() {
vista.jListReenvasados.setSelectedIndex(listaReenvasados.size() - 1);
vista.jScrollPaneListaMaterial.getVerticalScrollBar().setValue(((vista.jListReenvasados.getSelectedIndex() * 22) - 308));
}
//Modificar un material para envasar
protected void pulsarBotonModificarReenvasados() {
comenzarEdicion();
nuevoPulsado = false;
}
//Nuevo material para envasar
protected void pulsarBotonNuevoReenvasados() {
nuevoPulsado = true;
Reenvasados reenv = new Reenvasados();
listaReenvasados.add(reenv);
rellenarJListReenvasados();
vista.jListReenvasados.setSelectedIndex(listaReenvasados.size() - 1);
comenzarEdicion();
}
//Eliminar material para envasar
protected void pulsarBotonEliminarReenvasados() {
if (JOptionPane.showConfirmDialog(vista, "¿Desea eliminar el reenvasado actual?", "Eliminar", JOptionPane.YES_NO_OPTION) == 0) {
if (listaReenvasados.size() < 2) {
JOptionPane.showMessageDialog(vista, "No se pueden eliminar todos los reenvasados visibles. \nPruebe a quitar algún filtro de busqueda", "Aviso", JOptionPane.WARNING_MESSAGE);
} else {
modelo.eliminarReenvasados(listaReenvasados.get(vista.jListReenvasados.getSelectedIndex()));
listaReenvasados.remove(listaReenvasados.get(vista.jListReenvasados.getSelectedIndex()));
rellenarJListReenvasados();
vista.jListReenvasados.setSelectedIndex(0);
}
}
}
// Habilitar controles para permitir la edición de los datos de un material para envasar
private void comenzarEdicion() {
vista.jTextAreaDescripcionReenvasados.setEditable(true);
vista.jTextAreaPrincipioActivoReenvasados.setEditable(true);
//deshabilitar el JList y los botones de la barra de herramientas para evitar errores
vista.jListReenvasados.setEnabled(false);
vista.jButtonAtrasReenvasados.setEnabled(false);
vista.jButtonEliminarReenvasados.setEnabled(false);
vista.jButtonNuevoReenvasados.setEnabled(false);
vista.jButtonPrimeroReenvasados.setEnabled(false);
vista.jButtonSiguienteReenvasados.setEnabled(false);
vista.jButtonUltimoReenvasados.setEnabled(false);
vista.jButtonBuscarReenvasados.setEnabled(false);
vista.jButtonQuitarBuscarReenvasados.setEnabled(false);
vista.jTextFieldBuscarReenvasados.setEnabled(false);
vista.jButtonImprimirReenvasados.setEnabled(false);
//cambiar el color de los paneles para resaltar
vista.jPanelEdicionDatosReenvasados.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 102, 51), 2, true), "Edición de datos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14)));
vista.jPanelListaReenvasados.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 2, true), "Lista de materiales", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14)));
//mostrar botones de aceptar-cancelar para terminar la edición
vista.jButtonAceptarReenvasados.setVisible(true);
vista.jButtonCancelarReenvasados.setVisible(true);
//Da el foco al primer componente editable
vista.jTextAreaPrincipioActivoReenvasados.transferFocusBackward();
}
// lo contrario de comenzarEdicion()
private void acabarEdicion() {
vista.jTextAreaDescripcionReenvasados.setEditable(false);
vista.jTextAreaPrincipioActivoReenvasados.setEditable(false);
//deshabilitar el JList y los botones de la barra de herramientas para evitar errores
vista.jListReenvasados.setEnabled(true);
vista.jButtonAtrasReenvasados.setEnabled(true);
vista.jButtonEliminarReenvasados.setEnabled(true);
vista.jButtonNuevoReenvasados.setEnabled(true);
vista.jButtonPrimeroReenvasados.setEnabled(true);
vista.jButtonSiguienteReenvasados.setEnabled(true);
vista.jButtonUltimoReenvasados.setEnabled(true);
vista.jButtonBuscarReenvasados.setEnabled(true);
vista.jButtonQuitarBuscarReenvasados.setEnabled(true);
vista.jTextFieldBuscarReenvasados.setEnabled(true);
vista.jButtonImprimirReenvasados.setEnabled(true);
//cambiar el color de los paneles para resaltar
vista.jPanelEdicionDatosReenvasados.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 2, true), "Edición de datos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14)));
vista.jPanelListaReenvasados.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 102, 51), 2, true), "Lista de materiales", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14)));
//mostrar botones de aceptar-cancelar para terminar la edición
vista.jButtonAceptarReenvasados.setVisible(false);
vista.jButtonCancelarReenvasados.setVisible(false);
}
//Pulsar boton de aceptar
public void botonAceptarPulsado() {
if (comprobarCamposObligatorios()) {
try {
if (nuevoPulsado) {
recogerDatosReenvasados();
modelo.nuevoReenvasados(listaReenvasados.get(vista.jListReenvasados.getSelectedIndex()));
acabarEdicion();
rellenarJListReenvasados();
vista.jListReenvasados.setSelectedIndex(listaReenvasados.size() - 1);
} else {
recogerDatosReenvasados();
modelo.modificarReenvasados(listaReenvasados.get(vista.jListReenvasados.getSelectedIndex()));
int posicion = vista.jListReenvasados.getSelectedIndex();
acabarEdicion();
rellenarJListReenvasados();
vista.jListReenvasados.setSelectedIndex(posicion);
}
} catch (org.hibernate.exception.DataException e) {
if (e.getCause().toString().contains("DESCRIPCION")) {
JOptionPane.showMessageDialog(vista, "La descripción del reenvasado es demasiado larga, el máximo son 25 caracteres para que quepa en la etiqueta", "Error", JOptionPane.WARNING_MESSAGE);
} else {
JOptionPane.showMessageDialog(vista, "Los datos extra del reenvasado son demasiado largos, el máximo son 25 caracteres para que quepan en la etiqueta", "Error", JOptionPane.WARNING_MESSAGE);
}
} catch (ConstraintViolationException e) {
JOptionPane.showMessageDialog(vista, "El reenvasado introducido ya existe, introduzca otro", "Error", JOptionPane.WARNING_MESSAGE);
}
}
}
//Comprobar que los campos obligatorios no están vacios
public boolean comprobarCamposObligatorios() {
if (vista.jTextAreaDescripcionReenvasados.getText().equals("")) {
JOptionPane.showMessageDialog(vista, "Los siguiente campos son obligatorios \n\t-Descripción", "Aviso", JOptionPane.WARNING_MESSAGE);
return false;
}
return true;
}
//Pulsar boton de cancelar
public void botonCancelarPulsado() {
if (nuevoPulsado) {
listaReenvasados.remove(listaReenvasados.size() - 1);
acabarEdicion();
rellenarJListReenvasados();
vista.jListReenvasados.setSelectedIndex(0);
} else {
acabarEdicion();
controlarBotonesMoverse();
mostrarDatosReenvasados();
}
}
//Realizar búsquedas
public void botonBuscar() {
if (vista.jComboBoxBuscarReenvasados.getSelectedIndex() == 0) {
listaReenvasados = modelo.selectReenvasadosPorDescripcion(vista.jTextFieldBuscarReenvasados.getText());
} else if (vista.jComboBoxBuscarReenvasados.getSelectedIndex() == 1) {
listaReenvasados = modelo.selectReenvasadosPorPrincipioActivo(vista.jTextFieldBuscarReenvasados.getText());
}
rellenarJListReenvasados();
vista.jListReenvasados.setSelectedIndex(0);
if (listaReenvasados.size() < 1) {
JOptionPane.showMessageDialog(vista, "No hay reenvasados que cumplan las condiciones de la búsqueda", "Información", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(vista, "Se han reestablecido las condiciones de búsqueda", "Información", JOptionPane.INFORMATION_MESSAGE);
recargarDatosQuitarBuscar();
} else {
JOptionPane.showMessageDialog(vista, "Se han encontrado " + listaReenvasados.size() + " reenvasados", "Información", JOptionPane.INFORMATION_MESSAGE);
}
}
//Quitar el filtro de las búsquedas
public void recargarDatosQuitarBuscar() {
vista.jTextFieldBuscarReenvasados.setText("");
recargarDatos();
}
// Recarga los datos de la base de datos
public void recargarDatos() {
listaReenvasados = modelo.selectAllReenvasados();
rellenarJListReenvasados();
vista.jListReenvasados.setSelectedIndex(0);
}
//Muestra un diálogo en el que se pide el lote y la fecha de caducidad del reenvasado
public void pulsarBotonImprimir() {
//En principio se le da una caducidad de un año desde el día que se reenvasa
java.util.Date hoy = new java.util.Date();
Date fecha = addDaysToDate(hoy, 365);
SimpleDateFormat formatter = new SimpleDateFormat("MM/yy");
vista.jFormattedTextFieldFechaCaducidadReenvasados.setText(formatter.format(fecha));
vista.jTextFieldLoteReenvasados.setText("");
vista.jDialogImprimirReenvasados.setSize(510, 350);
vista.jDialogImprimirReenvasados.setLocationRelativeTo(null);
vista.jDialogImprimirReenvasados.setVisible(true);
}
//Añade a la fecha que se le pase el número de dias que se le pase
public Date addDaysToDate(final Date date, int noOfDays) {
Date newDate = new Date(date.getTime());
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(newDate);
calendar.add(Calendar.DATE, noOfDays);
newDate.setTime(calendar.getTime().getTime());
return newDate;
}
//Comprueba los datos introducidos y muestra un reporte del reenvasado seleccionado
public void pulsarBotonVistaPrevia() {
//Mostrar el reporte solo si los campos de lote y fecha han sido rellenados
if (!vista.jTextFieldLoteReenvasados.getText().trim().equals("") && !vista.jFormattedTextFieldFechaCaducidadReenvasados.getText().equals("")) {
listaReenvasados.get(vista.jListReenvasados.getSelectedIndex()).setCaduca(vista.jFormattedTextFieldFechaCaducidadReenvasados.getText());
listaReenvasados.get(vista.jListReenvasados.getSelectedIndex()).setLot(vista.jTextFieldLoteReenvasados.getText());
if (vista.jCheckBoxDatosExtra.isSelected()) {
mostrarReporte(14, "reportReenvasadosPrincipioActivo.jasper");
} else {
mostrarReporte(14, "reportReenvasados.jasper");
}
} else {
JOptionPane.showMessageDialog(vista.jDialogImprimirReenvasados, "Han de rellenarse los datos del lote y de la fecha de caducidad", "Error", JOptionPane.WARNING_MESSAGE);
}
}
//muestra el reporte eligiendo el nombre y el número de filas que va a tener
public void mostrarReporte(int filas, String nombreReporte) {
ArrayList<Reenvasados> reenvImprimir = new ArrayList<>();
//Llenar la hoja de etiquetas
for (int i = 0; i < filas; i++) {
reenvImprimir.add(listaReenvasados.get(vista.jListReenvasados.getSelectedIndex()));
}
ReenvasadosDataSource datasource = new ReenvasadosDataSource(reenvImprimir);
JasperReport reporte;
try {
reporte = (JasperReport) JRLoader.loadObjectFromFile(nombreReporte);
JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, datasource);
JasperViewer jviewer = new JasperViewer(jasperPrint, false);
// jviewer.setAlwaysOnTop(true);
jviewer.setTitle("Imprimir");
vista.jDialogImprimirReenvasados.setVisible(false);
jviewer.setVisible(true);
jviewer.setExtendedState(Frame.MAXIMIZED_BOTH);
} catch (JRException e1) {
JOptionPane.showMessageDialog(vista.jDialogImprimirReenvasados, "Error al inicializar el reporte", "Fallo", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
}
}
<file_sep>/*
* 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 es.sacyl.caza.farmacia.vista;
/**
*
* @author enrique
*/
public class PanelMaquinaria extends javax.swing.JPanel {
/**
*
* @param add true para que se vean los botones de añadir y cancelar el añadir
*/
public PanelMaquinaria(boolean add) {
initComponents();
jButtonAceptarMaquinaria.setVisible(false);
jButtonCancelarMaquinaria.setVisible(false);
jButtonAddMaquinaria.setVisible(add);
jButtonCancelarAddMaquinaria.setVisible(add);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanelMaquinaria = new javax.swing.JPanel();
jToolBarMaquinaria = new javax.swing.JToolBar();
jButtonPrimeroMaquinaria = new javax.swing.JButton();
jButtonAtrasMaquinaria = new javax.swing.JButton();
jSeparator5 = new javax.swing.JToolBar.Separator();
jLabelPosicionMaquinaria = new javax.swing.JLabel();
jSeparator6 = new javax.swing.JToolBar.Separator();
jButtonSiguienteMaquinaria = new javax.swing.JButton();
jButtonUltimoMaquinaria = new javax.swing.JButton();
jSeparator7 = new javax.swing.JToolBar.Separator();
jButtonNuevoMaquinaria = new javax.swing.JButton();
jButtonModificarMaquinaria = new javax.swing.JButton();
jButtonEliminarMaquinaria = new javax.swing.JButton();
jPanelProductosBuscar1 = new javax.swing.JPanel();
jLabel9 = new javax.swing.JLabel();
jComboBoxBuscarMaquinaria = new javax.swing.JComboBox();
jTextFieldBuscarMaquinaria = new javax.swing.JTextField();
jButtonBuscarMaquinaria = new javax.swing.JButton();
jButtonQuitarBuscarMaquinaria = new javax.swing.JButton();
jPanelListaMaquinaria = new javax.swing.JPanel();
jScrollPaneListaMaquinaria = new javax.swing.JScrollPane();
jListMaquinaria = new javax.swing.JList();
jLabel10 = new javax.swing.JLabel();
jPanelEdicionDatosMaquinaria = new javax.swing.JPanel();
jLabel11 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jButtonCancelarMaquinaria = new javax.swing.JButton();
jButtonAceptarMaquinaria = new javax.swing.JButton();
jLabelIdMaquinaria = new javax.swing.JLabel();
jScrollPane5 = new javax.swing.JScrollPane();
jTextAreaMaquinaria = new javax.swing.JTextArea();
jCheckBoxTenemosMaquinaria = new javax.swing.JCheckBox();
jButtonAddMaquinaria = new javax.swing.JButton();
jButtonCancelarAddMaquinaria = new javax.swing.JButton();
setPreferredSize(new java.awt.Dimension(975, 605));
jPanelMaquinaria.setBackground(new java.awt.Color(255, 255, 255));
jPanelMaquinaria.setPreferredSize(new java.awt.Dimension(975, 605));
jToolBarMaquinaria.setBackground(new java.awt.Color(237, 255, 255));
jToolBarMaquinaria.setFloatable(false);
jToolBarMaquinaria.setRollover(true);
jButtonPrimeroMaquinaria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/flechaPrimero.png"))); // NOI18N
jButtonPrimeroMaquinaria.setToolTipText("Se coloca en la primera maquinaria");
jButtonPrimeroMaquinaria.setEnabled(false);
jButtonPrimeroMaquinaria.setFocusable(false);
jButtonPrimeroMaquinaria.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonPrimeroMaquinaria.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarMaquinaria.add(jButtonPrimeroMaquinaria);
jButtonAtrasMaquinaria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/flechaIzquierda.png"))); // NOI18N
jButtonAtrasMaquinaria.setToolTipText("Se coloca en la maquinaria anterior");
jButtonAtrasMaquinaria.setEnabled(false);
jButtonAtrasMaquinaria.setFocusable(false);
jButtonAtrasMaquinaria.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonAtrasMaquinaria.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarMaquinaria.add(jButtonAtrasMaquinaria);
jToolBarMaquinaria.add(jSeparator5);
jLabelPosicionMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabelPosicionMaquinaria.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabelPosicionMaquinaria.setText("Maquinaria 200 de 300");
jLabelPosicionMaquinaria.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jToolBarMaquinaria.add(jLabelPosicionMaquinaria);
jToolBarMaquinaria.add(jSeparator6);
jButtonSiguienteMaquinaria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/flechaDerecha.png"))); // NOI18N
jButtonSiguienteMaquinaria.setToolTipText("Se coloca en la maquinaria siguiente");
jButtonSiguienteMaquinaria.setFocusable(false);
jButtonSiguienteMaquinaria.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonSiguienteMaquinaria.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarMaquinaria.add(jButtonSiguienteMaquinaria);
jButtonUltimoMaquinaria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/flechaUltimo.png"))); // NOI18N
jButtonUltimoMaquinaria.setToolTipText("Se coloca en la última maquinaria");
jButtonUltimoMaquinaria.setFocusable(false);
jButtonUltimoMaquinaria.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonUltimoMaquinaria.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarMaquinaria.add(jButtonUltimoMaquinaria);
jSeparator7.setBackground(new java.awt.Color(0, 0, 0));
jSeparator7.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
jSeparator7.setPreferredSize(new java.awt.Dimension(6, 1));
jToolBarMaquinaria.add(jSeparator7);
jButtonNuevoMaquinaria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/productoAgregar.png"))); // NOI18N
jButtonNuevoMaquinaria.setToolTipText("Crea un nueva maquinaria");
jButtonNuevoMaquinaria.setFocusable(false);
jButtonNuevoMaquinaria.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonNuevoMaquinaria.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarMaquinaria.add(jButtonNuevoMaquinaria);
jButtonModificarMaquinaria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/productoEditar.png"))); // NOI18N
jButtonModificarMaquinaria.setToolTipText("Permite modificar la maquinaria actual");
jButtonModificarMaquinaria.setFocusable(false);
jButtonModificarMaquinaria.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonModificarMaquinaria.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarMaquinaria.add(jButtonModificarMaquinaria);
jButtonEliminarMaquinaria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/sacyl/caza/farmacia/resources/productoBorrar.png"))); // NOI18N
jButtonEliminarMaquinaria.setToolTipText("Elimina la maquinaria actual");
jButtonEliminarMaquinaria.setFocusable(false);
jButtonEliminarMaquinaria.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonEliminarMaquinaria.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBarMaquinaria.add(jButtonEliminarMaquinaria);
jPanelProductosBuscar1.setBackground(new java.awt.Color(255, 255, 255));
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel9.setText("Buscar por:");
jComboBoxBuscarMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jComboBoxBuscarMaquinaria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Maquinaria", "Tenemos" }));
jComboBoxBuscarMaquinaria.setToolTipText("Seleccionar por que criterio buscar");
jTextFieldBuscarMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTextFieldBuscarMaquinaria.setToolTipText("Introducir el texto de guia para buscar");
jButtonBuscarMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonBuscarMaquinaria.setMnemonic('B');
jButtonBuscarMaquinaria.setText("Buscar");
jButtonBuscarMaquinaria.setToolTipText("Buscar productos que coincidan con los criterios elegidos");
jButtonQuitarBuscarMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonQuitarBuscarMaquinaria.setMnemonic('Q');
jButtonQuitarBuscarMaquinaria.setText("Quitar búsqueda");
jButtonQuitarBuscarMaquinaria.setToolTipText("Volver a mostrar todos los datos");
javax.swing.GroupLayout jPanelProductosBuscar1Layout = new javax.swing.GroupLayout(jPanelProductosBuscar1);
jPanelProductosBuscar1.setLayout(jPanelProductosBuscar1Layout);
jPanelProductosBuscar1Layout.setHorizontalGroup(
jPanelProductosBuscar1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelProductosBuscar1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxBuscarMaquinaria, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldBuscarMaquinaria, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonBuscarMaquinaria, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonQuitarBuscarMaquinaria)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelProductosBuscar1Layout.setVerticalGroup(
jPanelProductosBuscar1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelProductosBuscar1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelProductosBuscar1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
.addComponent(jComboBoxBuscarMaquinaria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldBuscarMaquinaria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonBuscarMaquinaria)
.addComponent(jButtonQuitarBuscarMaquinaria))
.addContainerGap())
);
jPanelListaMaquinaria.setBackground(new java.awt.Color(255, 255, 255));
jPanelListaMaquinaria.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 102, 51), 2, true), "Lista de maquinaria", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N
jListMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jListMaquinaria.setToolTipText("Si se selecciona una maquinaria se verán sus datos a la derecha");
jScrollPaneListaMaquinaria.setViewportView(jListMaquinaria);
jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel10.setText("¿Tenemos?- Maquinaria");
javax.swing.GroupLayout jPanelListaMaquinariaLayout = new javax.swing.GroupLayout(jPanelListaMaquinaria);
jPanelListaMaquinaria.setLayout(jPanelListaMaquinariaLayout);
jPanelListaMaquinariaLayout.setHorizontalGroup(
jPanelListaMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelListaMaquinariaLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelListaMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPaneListaMaquinaria, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10))
.addContainerGap(22, Short.MAX_VALUE))
);
jPanelListaMaquinariaLayout.setVerticalGroup(
jPanelListaMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelListaMaquinariaLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPaneListaMaquinaria)
.addContainerGap())
);
jPanelEdicionDatosMaquinaria.setBackground(new java.awt.Color(255, 255, 255));
jPanelEdicionDatosMaquinaria.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 2, true), "Edición de datos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N
jPanelEdicionDatosMaquinaria.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel11.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabel11.setText("ID:");
jPanelEdicionDatosMaquinaria.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 70, -1, -1));
jLabel13.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabel13.setText("Maquinaria:");
jPanelEdicionDatosMaquinaria.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 150, -1, -1));
jLabel16.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabel16.setText("Tenemos:");
jPanelEdicionDatosMaquinaria.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 260, -1, -1));
jButtonCancelarMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jButtonCancelarMaquinaria.setMnemonic('C');
jButtonCancelarMaquinaria.setText("Cancelar");
jPanelEdicionDatosMaquinaria.add(jButtonCancelarMaquinaria, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 350, -1, -1));
jButtonAceptarMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jButtonAceptarMaquinaria.setMnemonic('A');
jButtonAceptarMaquinaria.setText("Aceptar");
jPanelEdicionDatosMaquinaria.add(jButtonAceptarMaquinaria, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 350, -1, -1));
jLabelIdMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabelIdMaquinaria.setText("44");
jPanelEdicionDatosMaquinaria.add(jLabelIdMaquinaria, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 70, 60, -1));
jTextAreaMaquinaria.setEditable(false);
jTextAreaMaquinaria.setColumns(20);
jTextAreaMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jTextAreaMaquinaria.setLineWrap(true);
jTextAreaMaquinaria.setRows(5);
jTextAreaMaquinaria.setToolTipText("Nombre de la maquinaria");
jScrollPane5.setViewportView(jTextAreaMaquinaria);
jPanelEdicionDatosMaquinaria.add(jScrollPane5, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 150, 290, 60));
jCheckBoxTenemosMaquinaria.setBackground(new java.awt.Color(255, 255, 255));
jCheckBoxTenemosMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jCheckBoxTenemosMaquinaria.setText("Sí");
jCheckBoxTenemosMaquinaria.setToolTipText("");
jCheckBoxTenemosMaquinaria.setEnabled(false);
jPanelEdicionDatosMaquinaria.add(jCheckBoxTenemosMaquinaria, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 255, -1, -1));
jButtonAddMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jButtonAddMaquinaria.setText("Añadir");
jButtonCancelarAddMaquinaria.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jButtonCancelarAddMaquinaria.setText("Cancelar");
javax.swing.GroupLayout jPanelMaquinariaLayout = new javax.swing.GroupLayout(jPanelMaquinaria);
jPanelMaquinaria.setLayout(jPanelMaquinariaLayout);
jPanelMaquinariaLayout.setHorizontalGroup(
jPanelMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToolBarMaquinaria, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelMaquinariaLayout.createSequentialGroup()
.addGap(59, 59, 59)
.addGroup(jPanelMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanelProductosBuscar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelMaquinariaLayout.createSequentialGroup()
.addComponent(jPanelListaMaquinaria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMaquinariaLayout.createSequentialGroup()
.addComponent(jButtonAddMaquinaria)
.addGap(18, 18, 18)
.addComponent(jButtonCancelarAddMaquinaria))
.addComponent(jPanelEdicionDatosMaquinaria, javax.swing.GroupLayout.PREFERRED_SIZE, 546, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(65, Short.MAX_VALUE))
);
jPanelMaquinariaLayout.setVerticalGroup(
jPanelMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMaquinariaLayout.createSequentialGroup()
.addComponent(jToolBarMaquinaria, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(11, 11, 11)
.addComponent(jPanelProductosBuscar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanelEdicionDatosMaquinaria, javax.swing.GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE)
.addComponent(jPanelListaMaquinaria, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelMaquinariaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonAddMaquinaria)
.addComponent(jButtonCancelarAddMaquinaria))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 975, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanelMaquinaria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 611, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanelMaquinaria, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
.addContainerGap()))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JButton jButtonAceptarMaquinaria;
public javax.swing.JButton jButtonAddMaquinaria;
public javax.swing.JButton jButtonAtrasMaquinaria;
public javax.swing.JButton jButtonBuscarMaquinaria;
public javax.swing.JButton jButtonCancelarAddMaquinaria;
public javax.swing.JButton jButtonCancelarMaquinaria;
public javax.swing.JButton jButtonEliminarMaquinaria;
public javax.swing.JButton jButtonModificarMaquinaria;
public javax.swing.JButton jButtonNuevoMaquinaria;
public javax.swing.JButton jButtonPrimeroMaquinaria;
public javax.swing.JButton jButtonQuitarBuscarMaquinaria;
public javax.swing.JButton jButtonSiguienteMaquinaria;
public javax.swing.JButton jButtonUltimoMaquinaria;
public javax.swing.JCheckBox jCheckBoxTenemosMaquinaria;
public javax.swing.JComboBox jComboBoxBuscarMaquinaria;
public javax.swing.JLabel jLabel10;
public javax.swing.JLabel jLabel11;
public javax.swing.JLabel jLabel13;
public javax.swing.JLabel jLabel16;
public javax.swing.JLabel jLabel9;
public javax.swing.JLabel jLabelIdMaquinaria;
public javax.swing.JLabel jLabelPosicionMaquinaria;
public javax.swing.JList jListMaquinaria;
public javax.swing.JPanel jPanelEdicionDatosMaquinaria;
public javax.swing.JPanel jPanelListaMaquinaria;
public javax.swing.JPanel jPanelMaquinaria;
public javax.swing.JPanel jPanelProductosBuscar1;
public javax.swing.JScrollPane jScrollPane5;
public javax.swing.JScrollPane jScrollPaneListaMaquinaria;
public javax.swing.JToolBar.Separator jSeparator5;
public javax.swing.JToolBar.Separator jSeparator6;
public javax.swing.JToolBar.Separator jSeparator7;
public javax.swing.JTextArea jTextAreaMaquinaria;
public javax.swing.JTextField jTextFieldBuscarMaquinaria;
public javax.swing.JToolBar jToolBarMaquinaria;
// End of variables declaration//GEN-END:variables
}
<file_sep>package es.sacyl.caza.farmacia.modelo.clases;
// Generated 30-abr-2014 13:00:04 by Hibernate Tools 3.2.1.GA
import java.util.HashSet;
import java.util.Set;
/**
* Productos generated by hbm2java
*/
public class Productos implements java.io.Serializable {
private Integer idComponente;
private String componente;
private String referencia;
private Boolean activo;
private String observaciones;
private String estante;
private Set productosUnions = new HashSet(0);
public Productos() {
}
public Productos(String componente, String referencia, Boolean activo, String observaciones, String estante, Set productosUnions) {
this.componente = componente;
this.referencia = referencia;
this.activo = activo;
this.observaciones = observaciones;
this.estante = estante;
this.productosUnions = productosUnions;
}
public Integer getIdComponente() {
return this.idComponente;
}
public void setIdComponente(Integer idComponente) {
this.idComponente = idComponente;
}
public String getComponente() {
return this.componente;
}
public void setComponente(String componente) {
this.componente = componente;
}
public String getReferencia() {
return this.referencia;
}
public void setReferencia(String referencia) {
this.referencia = referencia;
}
public Boolean getActivo() {
return this.activo;
}
public void setActivo(Boolean activo) {
this.activo = activo;
}
public String getObservaciones() {
return this.observaciones;
}
public void setObservaciones(String observaciones) {
this.observaciones = observaciones;
}
public String getEstante() {
return this.estante;
}
public void setEstante(String estante) {
this.estante = estante;
}
public Set getProductosUnions() {
return this.productosUnions;
}
public void setProductosUnions(Set productosUnions) {
this.productosUnions = productosUnions;
}
}
<file_sep>
package es.sacyl.caza.farmacia.modelo;
import es.sacyl.caza.farmacia.modelo.clases.MaquinariaUnion;
import java.util.ArrayList;
import java.util.List;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
/**
*Clase usada para pasar datos a los reportes
* @author <NAME>
*/
public class MaquinariaDataSource implements JRDataSource {
private int indiceMaquinariaActual = -1;
private List<MaquinariaUnion> maquinaria = new ArrayList<MaquinariaUnion>();
public MaquinariaDataSource(List<MaquinariaUnion> maquinaria) {
this.maquinaria= maquinaria;
}
@Override
public Object getFieldValue(JRField jrField) throws JRException {
Object valor = null;
if ("maquinaria".equals(jrField.getName())) {
valor = maquinaria.get(indiceMaquinariaActual).getMaquinaria().getMaquinaria();
}
return valor;
}
@Override
public boolean next() throws JRException {
return ++indiceMaquinariaActual < maquinaria.size();
}
}
<file_sep>package es.sacyl.caza.farmacia.controlador;
import es.sacyl.caza.farmacia.modelo.MaterialEnvasarDAO;
import es.sacyl.caza.farmacia.modelo.clases.MaterialDeEnvasado;
import es.sacyl.caza.farmacia.vista.PanelMaterialEnvasar;
import es.sacyl.caza.farmacia.vista.VentanaEdicionPMS;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import org.hibernate.exception.ConstraintViolationException;
/**
*
* @author <NAME>
*
* Maneja los eventos de la pestaña material envasar de la VentanaEdicionPMS
*/
public class ControladorMaterialEnvasar {
private VentanaEdicionPMS ventanaPms;
private ArrayList<MaterialDeEnvasado> listaMaterialEnvasar;
private String[] MaterialEnvasarJList;
private MaterialEnvasarDAO modelo;
private boolean nuevoPulsado = false;
private PanelMaterialEnvasar vista;
public ControladorMaterialEnvasar(PanelMaterialEnvasar vista) {
this.vista = vista;
init();
initListeners();
}
public ControladorMaterialEnvasar(PanelMaterialEnvasar vista, VentanaEdicionPMS ventanaEdicionPMS) {
this.vista = vista;
this.ventanaPms = ventanaEdicionPMS;
init();
initListeners();
}
//Inicialización de los objetos necesarios para acceder y mostrar los datos
private void init() {
modelo = new MaterialEnvasarDAO();
listaMaterialEnvasar = modelo.selectAllMaterialDeEnvasado();
rellenarJListMaterialEnvasar();
vista.jListMaterialEnvasar.setSelectedIndex(0);
actualizarPosicion();
mostrarDatosMaterialEnvasar();
pulsarCheckboxTenemos();
acabarEdicion();
}
//Añade los listener de los eventos a los componentes
private void initListeners() {
vista.jListMaterialEnvasar.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
cambiarPosicionJListMaterialEnvasar();
}
});
vista.jButtonSiguienteMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseSiguiente();
}
});
vista.jButtonAtrasMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseAnterior();
}
});
vista.jButtonPrimeroMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoversePrimero();
}
});
vista.jButtonUltimoMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseUltimo();
}
});
vista.jButtonModificarMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonModificarMaterialEnvasar();
}
});
vista.jButtonAceptarMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonAceptarPulsado();
}
});
vista.jButtonCancelarMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonCancelarPulsado();
}
});
vista.jButtonNuevoMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonNuevoMaterialEnvasar();
}
});
vista.jButtonBuscarMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonBuscar();
}
});
vista.jButtonQuitarBuscarMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
recargarDatosQuitarBuscar();
}
});
vista.jButtonEliminarMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEliminarMaterialEnvasar();
}
});
vista.jCheckBoxTenemosMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarCheckboxTenemos();
}
});
vista.jTextFieldBuscarMaterialEnvasar.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
botonBuscar();
}
}
});
}
//Llena el JListMaterialEnvasar con los nombres de los materiales para envasar existentes en la base de datos
private void rellenarJListMaterialEnvasar() {
MaterialEnvasarJList = new String[listaMaterialEnvasar.size()];
for (int i = 0; i < MaterialEnvasarJList.length; i++) {
if (listaMaterialEnvasar.get(i).isTenemos()) {
MaterialEnvasarJList[i] = "Sí - " + listaMaterialEnvasar.get(i).getParaEnvasar();
} else {
MaterialEnvasarJList[i] = "No - " + listaMaterialEnvasar.get(i).getParaEnvasar();
}
}
vista.jListMaterialEnvasar.setModel(new javax.swing.AbstractListModel() {
@Override
public int getSize() {
return MaterialEnvasarJList.length;
}
@Override
public Object getElementAt(int i) {
return MaterialEnvasarJList[i];
}
});
}
//Posición del material para envasar en el que estamos situados
private void actualizarPosicion() {
String pos = "Material para envasar " + (vista.jListMaterialEnvasar.getSelectedIndex() + 1) + " de " + MaterialEnvasarJList.length;
vista.jLabelPosicionMaterialEnvasar.setText(pos);
}
//Mostrar los datos del elemento seleccionado del jListMaterialEnvasar
private void mostrarDatosMaterialEnvasar() {
if (vista.jListMaterialEnvasar.getSelectedIndex() > -1) {
vista.jTextAreaMaterialEnvasar.setText(listaMaterialEnvasar.get(vista.jListMaterialEnvasar.getSelectedIndex()).getParaEnvasar());
vista.jLabelIdMaterialEnvasar.setText(listaMaterialEnvasar.get(vista.jListMaterialEnvasar.getSelectedIndex()).getIdParaEnvasar() + "");
if (!nuevoPulsado) {
if (listaMaterialEnvasar.get(vista.jListMaterialEnvasar.getSelectedIndex()).isTenemos()) {
vista.jCheckBoxTenemosMaterialEnvasar.setSelected(true);
} else {
vista.jCheckBoxTenemosMaterialEnvasar.setSelected(false);
}
}
}
}
//Recoger los datos de los controloes en el elemento seleccionado del jListMaterialEnvasar
private void recogerDatosMaterialEnvasar() {
listaMaterialEnvasar.get(vista.jListMaterialEnvasar.getSelectedIndex()).setParaEnvasar(vista.jTextAreaMaterialEnvasar.getText());
if (vista.jCheckBoxTenemosMaterialEnvasar.isSelected()) {
listaMaterialEnvasar.get(vista.jListMaterialEnvasar.getSelectedIndex()).setTenemos(true);
} else {
listaMaterialEnvasar.get(vista.jListMaterialEnvasar.getSelectedIndex()).setTenemos(false);
}
}
// Evento al cambiar de posición en el jListMaterialEnvasar
private void cambiarPosicionJListMaterialEnvasar() {
actualizarPosicion();
controlarBotonesMoverse();
mostrarDatosMaterialEnvasar();
pulsarCheckboxTenemos();
}
// Activar/desactivar botones de siguiente,anterior,primero,último
private void controlarBotonesMoverse() {
if (vista.jListMaterialEnvasar.getSelectedIndex() == 0) {
vista.jButtonAtrasMaterialEnvasar.setEnabled(false);
vista.jButtonPrimeroMaterialEnvasar.setEnabled(false);
} else {
vista.jButtonAtrasMaterialEnvasar.setEnabled(true);
vista.jButtonPrimeroMaterialEnvasar.setEnabled(true);
}
if (vista.jListMaterialEnvasar.getSelectedIndex() == listaMaterialEnvasar.size() - 1) {
vista.jButtonSiguienteMaterialEnvasar.setEnabled(false);
vista.jButtonUltimoMaterialEnvasar.setEnabled(false);
} else {
vista.jButtonSiguienteMaterialEnvasar.setEnabled(true);
vista.jButtonUltimoMaterialEnvasar.setEnabled(true);
}
}
//Poner si/no en el checkbox de tenemos dependiendo de si está o no seleccionado
private void pulsarCheckboxTenemos() {
if (vista.jCheckBoxTenemosMaterialEnvasar.isSelected()) {
vista.jCheckBoxTenemosMaterialEnvasar.setText("Sí");
} else {
vista.jCheckBoxTenemosMaterialEnvasar.setText("No");
}
}
//Moverse al siguiente material para envasar de la lista
protected void botonMoverseSiguiente() {
vista.jListMaterialEnvasar.setSelectedIndex(vista.jListMaterialEnvasar.getSelectedIndex() + 1);
if (vista.jScrollPaneListaMaterial.getVerticalScrollBar().getValue() - (vista.jListMaterialEnvasar.getSelectedIndex() * 22) < -308) {
vista.jScrollPaneListaMaterial.getVerticalScrollBar().setValue(((vista.jListMaterialEnvasar.getSelectedIndex() * 22) - 308));
}
}
//Moverse al anterior material para envasar de la lista
protected void botonMoverseAnterior() {
vista.jListMaterialEnvasar.setSelectedIndex(vista.jListMaterialEnvasar.getSelectedIndex() - 1);
if (vista.jScrollPaneListaMaterial.getVerticalScrollBar().getValue() - (vista.jListMaterialEnvasar.getSelectedIndex() * 22) > 0) {
vista.jScrollPaneListaMaterial.getVerticalScrollBar().setValue(((vista.jListMaterialEnvasar.getSelectedIndex() * 22)));
}
}
//Moverse al primer material para envasar de la lista
protected void botonMoversePrimero() {
vista.jListMaterialEnvasar.setSelectedIndex(0);
vista.jScrollPaneListaMaterial.getVerticalScrollBar().setValue(0);
}
//Moverse al última material para envasar de la lista
protected void botonMoverseUltimo() {
vista.jListMaterialEnvasar.setSelectedIndex(listaMaterialEnvasar.size() - 1);
vista.jScrollPaneListaMaterial.getVerticalScrollBar().setValue(((vista.jListMaterialEnvasar.getSelectedIndex() * 22) - 308));
}
//Modificar un material para envasar
protected void pulsarBotonModificarMaterialEnvasar() {
comenzarEdicion();
nuevoPulsado = false;
}
//Nuevo material para envasar
protected void pulsarBotonNuevoMaterialEnvasar() {
nuevoPulsado = true;
MaterialDeEnvasado maq = new MaterialDeEnvasado();
listaMaterialEnvasar.add(maq);
rellenarJListMaterialEnvasar();
vista.jListMaterialEnvasar.setSelectedIndex(listaMaterialEnvasar.size() - 1);
comenzarEdicion();
}
//Eliminar material para envasar
protected void pulsarBotonEliminarMaterialEnvasar() {
if (JOptionPane.showConfirmDialog(vista, "¿Desea eliminar el material para envasar actual?", "Eliminar", JOptionPane.YES_NO_OPTION) == 0) {
if (listaMaterialEnvasar.size() < 2) {
JOptionPane.showMessageDialog(vista, "No se pueden eliminar todos los materiales visibles. \nPruebe a quitar algún filtro de busqueda", "Aviso", JOptionPane.WARNING_MESSAGE);
} else {
modelo.eliminarMaterialDeEnvasado(listaMaterialEnvasar.get(vista.jListMaterialEnvasar.getSelectedIndex()));
listaMaterialEnvasar.remove(listaMaterialEnvasar.get(vista.jListMaterialEnvasar.getSelectedIndex()));
rellenarJListMaterialEnvasar();
vista.jListMaterialEnvasar.setSelectedIndex(0);
}
}
}
// Habilitar controles para permitir la edición de los datos de un material para envasar
private void comenzarEdicion() {
vista.jTextAreaMaterialEnvasar.setEditable(true);
vista.jCheckBoxTenemosMaterialEnvasar.setEnabled(true);
//deshabilitar el JList y los botones de la barra de herramientas para evitar errores
vista.jListMaterialEnvasar.setEnabled(false);
vista.jButtonAtrasMaterialEnvasar.setEnabled(false);
vista.jButtonEliminarMaterialEnvasar.setEnabled(false);
vista.jButtonNuevoMaterialEnvasar.setEnabled(false);
vista.jButtonPrimeroMaterialEnvasar.setEnabled(false);
vista.jButtonSiguienteMaterialEnvasar.setEnabled(false);
vista.jButtonUltimoMaterialEnvasar.setEnabled(false);
//deshabilita el resto de pestañas
if (ventanaPms != null) {
ventanaPms.jTabbedPaneEdicionPMS.setEnabledAt(0, false);
ventanaPms.jTabbedPaneEdicionPMS.setEnabledAt(1, false);
ventanaPms.jTabbedPaneEdicionPMS.setEnabledAt(3, false);
}
vista.jButtonBuscarMaterialEnvasar.setEnabled(false);
vista.jButtonQuitarBuscarMaterialEnvasar.setEnabled(false);
vista.jTextFieldBuscarMaterialEnvasar.setEnabled(false);
//cambiar el color de los paneles para resaltar
vista.jPanelEdicionDatosMaterialEnvasar.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 102, 51), 2, true), "Edición de datos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14)));
vista.jPanelListaMaterialEnvasar.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 2, true), "Lista de materiales", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14)));
//mostrar botones de aceptar-cancelar para terminar la edición
vista.jButtonAceptarMaterialEnvasar.setVisible(true);
vista.jButtonCancelarMaterialEnvasar.setVisible(true);
//Da el foco al primer componente editable
vista.jCheckBoxTenemosMaterialEnvasar.transferFocusBackward();
}
// lo contrario de comenzarEdicion()
private void acabarEdicion() {
vista.jTextAreaMaterialEnvasar.setEditable(false);
vista.jCheckBoxTenemosMaterialEnvasar.setEnabled(false);
//deshabilitar el JList y los botones de la barra de herramientas para evitar errores
vista.jListMaterialEnvasar.setEnabled(true);
vista.jButtonAtrasMaterialEnvasar.setEnabled(true);
vista.jButtonEliminarMaterialEnvasar.setEnabled(true);
vista.jButtonNuevoMaterialEnvasar.setEnabled(true);
vista.jButtonPrimeroMaterialEnvasar.setEnabled(true);
vista.jButtonSiguienteMaterialEnvasar.setEnabled(true);
vista.jButtonUltimoMaterialEnvasar.setEnabled(true);
//deshabilita el resto de pestañas
if (ventanaPms != null) {
ventanaPms.jTabbedPaneEdicionPMS.setEnabledAt(0, true);
ventanaPms.jTabbedPaneEdicionPMS.setEnabledAt(1, true);
ventanaPms.jTabbedPaneEdicionPMS.setEnabledAt(3, true);
}
vista.jButtonBuscarMaterialEnvasar.setEnabled(true);
vista.jButtonQuitarBuscarMaterialEnvasar.setEnabled(true);
vista.jTextFieldBuscarMaterialEnvasar.setEnabled(true);
//cambiar el color de los paneles para resaltar
vista.jPanelEdicionDatosMaterialEnvasar.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 2, true), "Edición de datos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14)));
vista.jPanelListaMaterialEnvasar.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 102, 51), 2, true), "Lista de materiales", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14)));
//mostrar botones de aceptar-cancelar para terminar la edición
vista.jButtonAceptarMaterialEnvasar.setVisible(false);
vista.jButtonCancelarMaterialEnvasar.setVisible(false);
}
//Pulsar boton de aceptar
public void botonAceptarPulsado() {
if (comprobarCamposObligatorios()) {
try {
if (nuevoPulsado) {
recogerDatosMaterialEnvasar();
modelo.nuevoMaterialDeEnvasado(listaMaterialEnvasar.get(vista.jListMaterialEnvasar.getSelectedIndex()));
acabarEdicion();
rellenarJListMaterialEnvasar();
vista.jListMaterialEnvasar.setSelectedIndex(listaMaterialEnvasar.size() - 1);
} else {
recogerDatosMaterialEnvasar();
modelo.modificarMaterialDeEnvasado(listaMaterialEnvasar.get(vista.jListMaterialEnvasar.getSelectedIndex()));
int posicion = vista.jListMaterialEnvasar.getSelectedIndex();
acabarEdicion();
rellenarJListMaterialEnvasar();
vista.jListMaterialEnvasar.setSelectedIndex(posicion);
}
} catch (org.hibernate.exception.DataException e) {
JOptionPane.showMessageDialog(vista, "El nombre del material para envasar es demasiado largo, por favor hágalo más corto.", "Error", JOptionPane.WARNING_MESSAGE);
} catch (ConstraintViolationException e) {
JOptionPane.showMessageDialog(vista, "El material para envasar introducido ya existe, introduza otro", "Error", JOptionPane.WARNING_MESSAGE);
}
}
}
//Comprobar que los campos obligatorios no están vacios
public boolean comprobarCamposObligatorios() {
if (vista.jTextAreaMaterialEnvasar.getText().equals("")) {
JOptionPane.showMessageDialog(vista, "Los siguiente campos son obligatorios \n\t-Material envasar\n\t-Tenemos", "Aviso", JOptionPane.WARNING_MESSAGE);
return false;
}
return true;
}
//Pulsar boton de cancelar
public void botonCancelarPulsado() {
if (nuevoPulsado) {
listaMaterialEnvasar.remove(listaMaterialEnvasar.size() - 1);
acabarEdicion();
rellenarJListMaterialEnvasar();
vista.jListMaterialEnvasar.setSelectedIndex(0);
} else {
acabarEdicion();
controlarBotonesMoverse();
mostrarDatosMaterialEnvasar();
}
}
//Realizar búsquedas
public void botonBuscar() {
if (vista.jComboBoxBuscarMaterialEnvasar.getSelectedIndex() == 0) {
listaMaterialEnvasar = modelo.selectMaterialDeEnvasadoPorNombre(vista.jTextFieldBuscarMaterialEnvasar.getText());
} else if (vista.jComboBoxBuscarMaterialEnvasar.getSelectedIndex() == 1) {
if (vista.jTextFieldBuscarMaterialEnvasar.getText().toLowerCase().equals("sí") || vista.jTextFieldBuscarMaterialEnvasar.getText().toLowerCase().equals("si")) {
listaMaterialEnvasar = modelo.selectMaterialDeEnvasadoTenemos(true);
} else if (vista.jTextFieldBuscarMaterialEnvasar.getText().toLowerCase().equals("no")) {
listaMaterialEnvasar = modelo.selectMaterialDeEnvasadoTenemos(false);
}
}
rellenarJListMaterialEnvasar();
vista.jListMaterialEnvasar.setSelectedIndex(0);
if (listaMaterialEnvasar.size() < 1) {
JOptionPane.showMessageDialog(vista, "No hay materiales para envasar que cumplan las condiciones de la búsqueda", "Información", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(vista, "Se han reestablecido las condiciones de búsqueda", "Información", JOptionPane.INFORMATION_MESSAGE);
recargarDatosQuitarBuscar();
} else {
JOptionPane.showMessageDialog(vista, "Se han encontrado " + listaMaterialEnvasar.size() + " materiales para envasar", "Información", JOptionPane.INFORMATION_MESSAGE);
}
}
//Quitar el filtro de las búsquedas
public void recargarDatosQuitarBuscar() {
vista.jTextFieldBuscarMaterialEnvasar.setText("");
recargarDatos();
}
// Recarga los datos de la base de datos
public void recargarDatos() {
listaMaterialEnvasar = modelo.selectAllMaterialDeEnvasado();
rellenarJListMaterialEnvasar();
vista.jListMaterialEnvasar.setSelectedIndex(0);
}
//Devuelve el material de envasar seleccionado actualmente
public MaterialDeEnvasado getMaterialEnvasado() {
return listaMaterialEnvasar.get(vista.jListMaterialEnvasar.getSelectedIndex());
}
}
<file_sep>package es.sacyl.caza.farmacia.modelo.clases;
// Generated 30-abr-2014 13:00:04 by Hibernate Tools 3.2.1.GA
/**
* MaterialParaElaborarUnion generated by hbm2java
*/
public class MaterialParaElaborarUnion implements java.io.Serializable {
private Integer idMaterialUnion;
private MaterialParaElaborar materialParaElaborar;
private FichasDeMedicamentos fichasDeMedicamentos;
public MaterialParaElaborarUnion() {
}
public MaterialParaElaborarUnion(MaterialParaElaborar materialParaElaborar, FichasDeMedicamentos fichasDeMedicamentos) {
this.materialParaElaborar = materialParaElaborar;
this.fichasDeMedicamentos = fichasDeMedicamentos;
}
public Integer getIdMaterialUnion() {
return this.idMaterialUnion;
}
public void setIdMaterialUnion(Integer idMaterialUnion) {
this.idMaterialUnion = idMaterialUnion;
}
public MaterialParaElaborar getMaterialParaElaborar() {
return this.materialParaElaborar;
}
public void setMaterialParaElaborar(MaterialParaElaborar materialParaElaborar) {
this.materialParaElaborar = materialParaElaborar;
}
public FichasDeMedicamentos getFichasDeMedicamentos() {
return this.fichasDeMedicamentos;
}
public void setFichasDeMedicamentos(FichasDeMedicamentos fichasDeMedicamentos) {
this.fichasDeMedicamentos = fichasDeMedicamentos;
}
}
<file_sep>package es.sacyl.caza.farmacia.controlador;
import es.sacyl.caza.farmacia.modelo.FichasDeMedicamentosDAO;
import es.sacyl.caza.farmacia.modelo.FichasDeMedicamentosDataSource;
import es.sacyl.caza.farmacia.modelo.clases.FichasDeMedicamentos;
import es.sacyl.caza.farmacia.modelo.clases.MaquinariaUnion;
import es.sacyl.caza.farmacia.modelo.clases.MaterialDeEnvasadoUnion;
import es.sacyl.caza.farmacia.modelo.clases.MaterialParaElaborarUnion;
import es.sacyl.caza.farmacia.modelo.clases.ProductosUnion;
import es.sacyl.caza.farmacia.vista.VentanaEtiquetas;
import es.sacyl.caza.farmacia.vista.VentanaHojasElaboracion;
import java.awt.Frame;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import org.hibernate.Session;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
/**
*
* @author <NAME>
*/
public class ControladorFichasDeMedicamentos {
private VentanaHojasElaboracion vista;
private ArrayList<FichasDeMedicamentos> listaFichasDeMedicamentos;
private ArrayList<MaquinariaUnion> listaMaquinariaMedicamento;
private ArrayList<MaterialDeEnvasadoUnion> listaMaterialEnvasadoMedicamento;
private ArrayList<MaterialParaElaborarUnion> listaMaterialElaborarMedicamento;
private ArrayList<ProductosUnion> listaProductosMedicamento;
private String[] fichasDeMedicamentosJList;
private FichasDeMedicamentosDAO modelo;
private boolean nuevoPulsado = false;
private boolean nuevoProducto = false;
private boolean rellenando = false;
public ControladorFichasDeMedicamentos(VentanaHojasElaboracion vista) {
this.vista = vista;
init();
initListeners();
}
//Inicialización de los objetos necesarios para acceder y mostrar los datos
private void init() {
soloEscribirNumerosJTextField(vista.jTextFieldDialogModificarProductoCantidad);
modelo = new FichasDeMedicamentosDAO();
listaFichasDeMedicamentos = modelo.selectAllMedicamentosVeredicto();
//Hay que rellenar las tablas con la sesion todavia abierta para evitar un LazyInitialitationError
Session sesion = modelo.abrirSesion();
listaMaterialElaborarMedicamento = modelo.selectMaterialElaborarDeMedicamento(listaFichasDeMedicamentos.get(0).getIdMedicamento(), sesion);
listaMaquinariaMedicamento = modelo.selectMaquinariaDeMedicamento(listaFichasDeMedicamentos.get(0).getIdMedicamento(), sesion);
listaMaterialEnvasadoMedicamento = modelo.selectMaterialEnvasarDeMedicamento(listaFichasDeMedicamentos.get(0).getIdMedicamento(), sesion);
listaProductosMedicamento = modelo.selectProductosDeMedicamento(listaFichasDeMedicamentos.get(0).getIdMedicamento(), sesion);
rellenarJListFichasDeMedicamentos();
vista.jListFichasDeMedicamentos.setSelectedIndex(0);
actualizarPosicion();
mostrarDatosFichasDeMedicamentos();
rellenarTablaMaterialElaborar();
rellenarTablaMaquinaria();
rellenarTablaMaterialEnvasar();
rellenarTablaProductos();
modelo.cerrarSesion(sesion);
}
//Añade los listener de los eventos a los componentes
private void initListeners() {
vista.jListFichasDeMedicamentos.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
cambiarPosicionJListFichasDeMedicamentos();
}
});
vista.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
cerrarVentana();
}
});
vista.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
cerrarVentana();
}
});
vista.jMenuItemArchivoSalir.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
cerrarVentana();
}
});
vista.jMenuItemArchivoNuevo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonNuevoMedicamento();
}
});
vista.jMenuItemEditarEliminar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEliminarMedicamento();
}
});
vista.jMenuItemEditarModificar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonModificarMedicamento();
}
});
vista.jMenuItemVerAnterior.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseAnterior();
}
});
vista.jMenuItemVerPrimero.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoversePrimero();
}
});
vista.jMenuItemVerSiguiente.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseSiguiente();
}
});
vista.jMenuItemVerUltimo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseUltimo();
}
});
vista.jMenuItemAddMaquinaria.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarAddMaquinaria();
}
});
vista.jMenuItemAddMaterialElaborar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarAddMaterialElaborar();
}
});
vista.jMenuItemAddMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarAddMaterialEnvasar();
}
});
vista.jMenuItemAddProducto.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarAddProductos();
}
});
vista.jButtonSiguienteFichasDeMedicamentos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseSiguiente();
}
});
vista.jButtonAtrasFichasDeMedicamentos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseAnterior();
}
});
vista.jButtonPrimeroFichasDeMedicamentos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoversePrimero();
}
});
vista.jButtonUltimoFichasDeMedicamentos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonMoverseUltimo();
}
});
vista.jButtonModificarFichasDeMedicamentos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonModificarMedicamento();
}
});
vista.jButtonAceptarFichasDeMedicamentos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonAceptarPulsado();
}
});
vista.jButtonCancelarFichasDeMedicamentos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonCancelarPulsado();
}
});
vista.jButtonNuevoFichasDeMedicamentos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonNuevoMedicamento();
}
});
vista.jButtonBuscarFichasDeMedicamentos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonBuscar();
}
});
vista.jButtonQuitarBuscarFichasDeMedicamentos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
recargarDatosQuitarBuscar();
}
});
vista.jButtonEliminarFichasDeMedicamentos.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEliminarMedicamento();
}
});
vista.jButtonAddMaquinaria.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarAddMaquinaria();
}
});
vista.panelAddMaquinaria.jButtonAddMaquinaria.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
addMaquinariaMedicamento();
}
});
vista.panelAddMaquinaria.jButtonCancelarAddMaquinaria.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
vista.jDialogAddMaquinaria.setVisible(false);
}
});
vista.jButtonAddMaterialElaborar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarAddMaterialElaborar();
}
});
vista.panelAddMaterialElaboracion.jButtonAddMaterialElaborar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
addMaterialElaborarMedicamento();
}
});
vista.panelAddMaterialElaboracion.jButtonCancelarAddMaterialElaborar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
vista.jDialogAddMaterialElaborar.setVisible(false);
}
});
vista.jButtonAddMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarAddMaterialEnvasar();
}
});
vista.panelAddMaterialEnvasar.jButtonAddMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
addMaterialEnvasarMedicamento();
}
});
vista.panelAddMaterialEnvasar.jButtonCancelarAddMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
vista.jDialogAddMaterialEnvasar.setVisible(false);
}
});
vista.jButtonAddProducto.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarAddProductos();
}
});
vista.panelAddProductos.jButtonAddProducto.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
addProductosMedicamento();
}
});
vista.panelAddProductos.jButtonCancelarAddProducto.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
vista.jDialogAddProducto.setVisible(false);
}
});
vista.jButtonDialogModificarProductoCancelar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
vista.jDialogModificarProducto.setVisible(false);
}
});
vista.jButtonDialogModificarProductoAceptar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
modificarProductoMedicamento();
}
});
vista.jButtonModificarProducto.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonModificarProducto();
}
});
vista.jButtonEliminarMaquinaria.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEliminarMaquinaria();
}
});
vista.jButtonEliminarMaterialElaborar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEliminarMaterialElaborar();
}
});
vista.jButtonEliminarMaterialEnvasar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEliminarMaterialEnvasar();
}
});
vista.jButtonEliminarProducto.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEliminarProducto();
}
});
vista.jTableProductos.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
pulsarBotonEliminarProducto();
}
}
});
vista.jTableMaquinaria.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
pulsarBotonEliminarMaquinaria();
}
}
});
vista.jTableMaterialElaborar.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
pulsarBotonEliminarMaterialElaborar();
}
}
});
vista.jTableMaterialEnvasar.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
pulsarBotonEliminarMaterialEnvasar();
}
}
});
vista.jButtonMostrarEtiqueta.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonEtiquetas();
}
});
vista.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
cerrarVentana();
}
});
vista.jButtonDialogEtiquetasNuevaEtiqueta.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonDialogEtiquetasNuevaEtiqueta();
}
});
vista.jButtonDialogEtiquetasVerEtiquetas.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonDialogEtiquetasVerEtiqueta();
}
});
vista.jButtonDialogEtiquetasVolver.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
vista.jDialogEtiquetas.setVisible(false);
}
});
vista.jButtonImprimir.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarBotonImprimir();
}
});
vista.jCheckBoxMostrarTodo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pulsarCheckMostrarTodo();
}
});
vista.jTextFieldBuscarFichasDeMedicamentos.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
botonBuscar();
}
}
});
vista.jMenuItemCopiar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
copiar();
}
});
vista.jMenuItemPegar.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
pegar();
}
});
}
public void copiar() {
if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaEstabilidad)) {
vista.jTextAreaEstabilidad.copy();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaMedicamento)) {
vista.jTextAreaMedicamento.copy();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaObservaciones)) {
vista.jTextAreaObservaciones.copy();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaObservacionesElaboracion)) {
vista.jTextAreaObservacionesElaboracion.copy();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaOrigen)) {
vista.jTextAreaOrigen.copy();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaParaEtiqueta)) {
vista.jTextAreaParaEtiqueta.copy();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaProcedimiento)) {
vista.jTextAreaProcedimiento.copy();
}
}
//Acción de pegar
public void pegar() {
//solo se puede pegar si se estan editando los datos
if (vista.jButtonAceptarFichasDeMedicamentos.isVisible()) {
//Para pegar hacer un switch con todos los componentes en donde se puede pegar
if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaEstabilidad)) {
vista.jTextAreaEstabilidad.paste();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaMedicamento)) {
vista.jTextAreaMedicamento.paste();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaObservaciones)) {
vista.jTextAreaObservaciones.paste();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaObservacionesElaboracion)) {
vista.jTextAreaObservacionesElaboracion.paste();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaOrigen)) {
vista.jTextAreaOrigen.paste();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaParaEtiqueta)) {
vista.jTextAreaParaEtiqueta.paste();
} else if (vista.jPopupMenuCopiarPegar.getInvoker().equals(vista.jTextAreaProcedimiento)) {
vista.jTextAreaProcedimiento.paste();
}
} else {
JOptionPane.showMessageDialog(vista, "Para poder pegar hay que pulsar antes el botón de modificar los datos", "Error", JOptionPane.ERROR_MESSAGE);
}
}
//Vacia la memoria antes de cerrar la ventana
public void cerrarVentana() {
vista.dispose();
}
//Se usa para permitir únicamente la escritura de número en el jTextField que se requiera
public void soloEscribirNumerosJTextField(JTextField textField) {
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
char caracter = e.getKeyChar();
if (!Character.isDigit(caracter)) {
e.consume();
}
}
});
}
//usado para rellenar la tabla del material para elaborar
public void rellenarTablaMaterialElaborar() {
String[][] lista = new String[listaMaterialElaborarMedicamento.size()][1];
for (int i = 0; i < listaMaterialElaborarMedicamento.size(); i++) {
lista[i][0] = listaMaterialElaborarMedicamento.get(i).getMaterialParaElaborar().getMaterial();
}
vista.jTableMaterialElaborar.setModel(new javax.swing.table.DefaultTableModel(
lista,
new String[]{
"Material para elaborar"
}
) {
boolean[] canEdit = new boolean[]{
false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
});
}
//usado para rellenar la tabla del material para envasar
public void rellenarTablaMaterialEnvasar() {
String[][] lista = new String[listaMaterialEnvasadoMedicamento.size()][1];
for (int i = 0; i < listaMaterialEnvasadoMedicamento.size(); i++) {
lista[i][0] = listaMaterialEnvasadoMedicamento.get(i).getMaterialDeEnvasado().getParaEnvasar();
}
vista.jTableMaterialEnvasar.setModel(new javax.swing.table.DefaultTableModel(
lista,
new String[]{
"Material para envasar"
}
) {
boolean[] canEdit = new boolean[]{
false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
});
}
//usado para rellenar la tabla de la maquinaria
public void rellenarTablaMaquinaria() {
String[][] lista = new String[listaMaquinariaMedicamento.size()][1];
for (int i = 0; i < listaMaquinariaMedicamento.size(); i++) {
lista[i][0] = listaMaquinariaMedicamento.get(i).getMaquinaria().getMaquinaria();
}
vista.jTableMaquinaria.setModel(new javax.swing.table.DefaultTableModel(
lista,
new String[]{
"Maquinaria"
}
) {
boolean[] canEdit = new boolean[]{
false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
});
}
//Usado para rellenar la tabla de productos
private void rellenarTablaProductos() {
String[][] lista = new String[listaProductosMedicamento.size()][7];
for (int i = 0; i < listaProductosMedicamento.size(); i++) {
lista[i][0] = listaProductosMedicamento.get(i).getOrden();
lista[i][1] = listaProductosMedicamento.get(i).getProductos().getComponente();
lista[i][2] = listaProductosMedicamento.get(i).getProductos().getReferencia();
lista[i][3] = listaProductosMedicamento.get(i).getCantidad();
lista[i][4] = listaProductosMedicamento.get(i).getUnidades();
}
vista.jTableProductos.setModel(new javax.swing.table.DefaultTableModel(
lista,
new String[]{
"Orden", "Productos", "Código referencia", "Cantidad", "Unidad", "Proveedor", "Lote", "Caducidad"
}
) {
Class[] types = new Class[]{
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean[]{
false, false, false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
});
if (vista.jTableProductos.getColumnModel().getColumnCount() > 0) {
vista.jTableProductos.getColumnModel().getColumn(0).setPreferredWidth(50);
vista.jTableProductos.getColumnModel().getColumn(1).setPreferredWidth(225);
vista.jTableProductos.getColumnModel().getColumn(2).setPreferredWidth(100);
}
}
//Llena el JListFichasDeMedicamentos con los nombres de los FichasDeMedicamentos existentes en la base de datos
private void rellenarJListFichasDeMedicamentos() {
rellenando = true;
fichasDeMedicamentosJList = new String[listaFichasDeMedicamentos.size()];
for (int i = 0; i < fichasDeMedicamentosJList.length; i++) {
fichasDeMedicamentosJList[i] = listaFichasDeMedicamentos.get(i).getMedicamento();
}
vista.jListFichasDeMedicamentos.setModel(new javax.swing.AbstractListModel() {
@Override
public int getSize() {
return fichasDeMedicamentosJList.length;
}
@Override
public Object getElementAt(int i) {
return fichasDeMedicamentosJList[i];
}
});
rellenando = false;
}
//Posición del medicamentos en el que estamos situados
private void actualizarPosicion() {
String pos = "Medicamento " + (vista.jListFichasDeMedicamentos.getSelectedIndex() + 1) + " de " + fichasDeMedicamentosJList.length;
vista.jLabelPosicionFichasDeMedicamentos.setText(pos);
}
//Mostrar los datos del elemento seleccionado del jListFichasDeMedicamentos
private void mostrarDatosFichasDeMedicamentos() {
if (vista.jListFichasDeMedicamentos.getSelectedIndex() > -1) {
vista.jLabelIdFichasDeMedicamentos.setText(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento() + "");
vista.jTextAreaMedicamento.setText(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getMedicamento());
vista.jTextAreaEstabilidad.setText(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getEstabilidad());
vista.jTextAreaObservacionesElaboracion.setText(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getObservacParaElaboracion());
vista.jTextAreaObservaciones.setText(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getObservaciones());
vista.jTextFieldDatosOrganolepsis.setText(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getOrganolepsisDatos());
vista.jTextAreaOrigen.setText(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getOrigen());
vista.jTextAreaParaEtiqueta.setText(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getParaEtiqueta());
vista.jTextAreaProcedimiento.setText(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getProcedimiento());
vista.jTextFieldObservacionesVeredicto.setText(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getVeredObservac());
if (!nuevoPulsado) {
if (listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getVeredicto() == 1) {
vista.jComboBoxVeredicto.setSelectedIndex(1);
} else {
vista.jComboBoxVeredicto.setSelectedIndex(0);
}
//Los campos de los combobox que no tienen datos necesitan un tratamiento especial para poder mostrarse adecuadamente
if (listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getAlgunEdo().length() > 1) {
vista.jComboBoxEDO.setSelectedItem(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getAlgunEdo());
} else {
vista.jComboBoxEDO.setSelectedIndex(0);
}
if (listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getElaboradoPor().length() > 1) {
vista.jComboBoxElaboradoPor.setSelectedItem(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getElaboradoPor());
} else {
vista.jComboBoxElaboradoPor.setSelectedIndex(0);
}
if (listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getTipo().length() > 1) {
vista.jComboBoxTipo.setSelectedItem(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getTipo());
} else {
vista.jComboBoxTipo.setSelectedIndex(0);
}
if (listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getViaDeAdmon().length() > 1) {
vista.jComboBoxViaAdministracion.setSelectedItem(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getViaDeAdmon());
} else {
vista.jComboBoxViaAdministracion.setSelectedIndex(0);
}
} else {
//poner los combos sin nada seleccionado
vista.jComboBoxVeredicto.setSelectedIndex(1);
vista.jComboBoxEDO.setSelectedIndex(0);
vista.jComboBoxElaboradoPor.setSelectedIndex(0);
vista.jComboBoxTipo.setSelectedIndex(0);
vista.jComboBoxViaAdministracion.setSelectedIndex(0);
}
}
}
//Recoger los datos de los controloes en el elemento seleccionado del jListFichasDeMedicamentos
private void recogerDatosFichasDeMedicamentos() {
if (vista.jComboBoxEDO.getSelectedItem() != null) {
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setAlgunEdo(vista.jComboBoxEDO.getSelectedItem().toString());
} else {
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setAlgunEdo(" ");
}
if (vista.jComboBoxElaboradoPor.getSelectedItem() != null) {
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setElaboradoPor(vista.jComboBoxElaboradoPor.getSelectedItem().toString());
} else {
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setElaboradoPor(" ");
}
if (vista.jComboBoxTipo.getSelectedItem() != null) {
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setTipo(vista.jComboBoxTipo.getSelectedItem().toString());
} else {
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setTipo(" ");
}
if (vista.jComboBoxViaAdministracion.getSelectedItem() != null) {
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setViaDeAdmon(vista.jComboBoxViaAdministracion.getSelectedItem().toString());
} else {
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setViaDeAdmon(" ");
}
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setEstabilidad(vista.jTextAreaEstabilidad.getText());
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setMedicamento(vista.jTextAreaMedicamento.getText());
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setObservacParaElaboracion(vista.jTextAreaObservacionesElaboracion.getText());
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setObservaciones(vista.jTextAreaObservaciones.getText());
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setOrganolepsisDatos(vista.jTextFieldDatosOrganolepsis.getText());
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setOrigen(vista.jTextAreaOrigen.getText());
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setParaEtiqueta(vista.jTextAreaParaEtiqueta.getText());
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setProcedimiento(vista.jTextAreaProcedimiento.getText());
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setVeredObservac(vista.jTextFieldObservacionesVeredicto.getText());
if (vista.jComboBoxVeredicto.getSelectedIndex() == 0) {
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setVeredicto(0);
} else {
listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).setVeredicto(1);
}
}
// Activar/desactivar botones de siguiente,anterior,primero,último
private void controlarBotonesMoverse() {
if (vista.jListFichasDeMedicamentos.getSelectedIndex() == 0) {
vista.jButtonAtrasFichasDeMedicamentos.setEnabled(false);
vista.jButtonPrimeroFichasDeMedicamentos.setEnabled(false);
} else {
vista.jButtonAtrasFichasDeMedicamentos.setEnabled(true);
vista.jButtonPrimeroFichasDeMedicamentos.setEnabled(true);
}
if (vista.jListFichasDeMedicamentos.getSelectedIndex() == listaFichasDeMedicamentos.size() - 1) {
vista.jButtonSiguienteFichasDeMedicamentos.setEnabled(false);
vista.jButtonUltimoFichasDeMedicamentos.setEnabled(false);
} else {
vista.jButtonSiguienteFichasDeMedicamentos.setEnabled(true);
vista.jButtonUltimoFichasDeMedicamentos.setEnabled(true);
}
}
// Evento al cambiar de posición en el jListFichasDeMedicamentos
private void cambiarPosicionJListFichasDeMedicamentos() {
actualizarPosicion();
controlarBotonesMoverse();
mostrarDatosFichasDeMedicamentos();
//Hay que rellenar las tablas con la sesion todavia abierta para evitar un LazyInitialitationError
if (!rellenando) {
Session sesion = modelo.abrirSesion();
listaMaterialElaborarMedicamento = modelo.selectMaterialElaborarDeMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento(), sesion);
listaMaquinariaMedicamento = modelo.selectMaquinariaDeMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento(), sesion);
listaMaterialEnvasadoMedicamento = modelo.selectMaterialEnvasarDeMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento(), sesion);
listaProductosMedicamento = modelo.selectProductosDeMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento(), sesion);
rellenarTablaMaterialElaborar();
rellenarTablaMaquinaria();
rellenarTablaMaterialEnvasar();
rellenarTablaProductos();
modelo.cerrarSesion(sesion);
}
}
//Moverse al siguiente medicamento de la lista
protected void botonMoverseSiguiente() {
vista.jListFichasDeMedicamentos.setSelectedIndex(vista.jListFichasDeMedicamentos.getSelectedIndex() + 1);
if (vista.jScrollPaneListaMedicamentos.getVerticalScrollBar().getValue() - (vista.jListFichasDeMedicamentos.getSelectedIndex() * 19) < -380) {
vista.jScrollPaneListaMedicamentos.getVerticalScrollBar().setValue(((vista.jListFichasDeMedicamentos.getSelectedIndex() * 19) - 380));
}
}
//Moverse al anterior medicamento de la lista
protected void botonMoverseAnterior() {
vista.jListFichasDeMedicamentos.setSelectedIndex(vista.jListFichasDeMedicamentos.getSelectedIndex() - 1);
if (vista.jScrollPaneListaMedicamentos.getVerticalScrollBar().getValue() - (vista.jListFichasDeMedicamentos.getSelectedIndex() * 19) > 0) {
vista.jScrollPaneListaMedicamentos.getVerticalScrollBar().setValue(((vista.jListFichasDeMedicamentos.getSelectedIndex() * 19)));
}
}
//Moverse al primer medicamento de la lista
protected void botonMoversePrimero() {
vista.jListFichasDeMedicamentos.setSelectedIndex(0);
vista.jScrollPaneListaMedicamentos.getVerticalScrollBar().setValue(0);
}
//Moverse al último medicamento de la lista
protected void botonMoverseUltimo() {
vista.jListFichasDeMedicamentos.setSelectedIndex(listaFichasDeMedicamentos.size() - 1);
vista.jScrollPaneListaMedicamentos.getVerticalScrollBar().setValue(vista.jListFichasDeMedicamentos.getSelectedIndex() * 19);
}
//Modificar un medicamento
protected void pulsarBotonModificarMedicamento() {
comenzarEdicion();
nuevoPulsado = false;
}
//Nuevo medicamento
protected void pulsarBotonNuevoMedicamento() {
nuevoPulsado = true;
FichasDeMedicamentos producto = new FichasDeMedicamentos();
//ya se encarga el auto_increment de asignarle el id correcto
producto.setIdMedicamento(0);
listaFichasDeMedicamentos.add(producto);
rellenarJListFichasDeMedicamentos();
vista.jListFichasDeMedicamentos.setSelectedIndex(listaFichasDeMedicamentos.size() - 1);
comenzarEdicion();
}
//Eliminar medicamento
protected void pulsarBotonEliminarMedicamento() {
if (JOptionPane.showConfirmDialog(vista, "¿Desea eliminar el medicamento actual?", "Eliminar", JOptionPane.YES_NO_OPTION) == 0) {
if (listaFichasDeMedicamentos.size() < 2) {
JOptionPane.showMessageDialog(vista, "No se pueden eliminar todos los medicamentos visibles. \nPruebe a quitar algún filtro de busqueda", "Aviso", JOptionPane.WARNING_MESSAGE);
} else {
modelo.eliminarMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()));
listaFichasDeMedicamentos.remove(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()));
rellenarJListFichasDeMedicamentos();
vista.jListFichasDeMedicamentos.setSelectedIndex(0);
}
}
}
// Habilitar controles para permitir la edición de los datos de un medicamento
private void comenzarEdicion() {
vista.jTextAreaMedicamento.setEditable(true);
vista.jTextAreaEstabilidad.setEditable(true);
vista.jTextAreaObservacionesElaboracion.setEditable(true);
vista.jTextAreaObservaciones.setEditable(true);
vista.jTextFieldDatosOrganolepsis.setEditable(true);
vista.jTextAreaOrigen.setEditable(true);
vista.jTextAreaParaEtiqueta.setEditable(true);
vista.jTextAreaProcedimiento.setEditable(true);
vista.jTextFieldObservacionesVeredicto.setEditable(true);
vista.jComboBoxViaAdministracion.setEnabled(true);
vista.jComboBoxVeredicto.setEnabled(true);
vista.jComboBoxEDO.setEnabled(true);
vista.jComboBoxElaboradoPor.setEnabled(true);
vista.jComboBoxTipo.setEnabled(true);
//No dejar manipular las cosas de otras tablas hasta que se termine de crear el nuevo medicamento o de modificar el actual
vista.jButtonAddMaquinaria.setEnabled(false);
vista.jButtonAddMaterialElaborar.setEnabled(false);
vista.jButtonAddMaterialEnvasar.setEnabled(false);
vista.jButtonAddProducto.setEnabled(false);
vista.jButtonEliminarMaquinaria.setEnabled(false);
vista.jButtonEliminarMaterialElaborar.setEnabled(false);
vista.jButtonEliminarMaterialEnvasar.setEnabled(false);
vista.jButtonEliminarProducto.setEnabled(false);
vista.jButtonModificarProducto.setEnabled(false);
//deshabilitar el JList y los botones de la barra de herramientas para evitar errores
vista.jListFichasDeMedicamentos.setEnabled(false);
vista.jButtonAtrasFichasDeMedicamentos.setEnabled(false);
vista.jButtonEliminarFichasDeMedicamentos.setEnabled(false);
vista.jButtonNuevoFichasDeMedicamentos.setEnabled(false);
vista.jButtonPrimeroFichasDeMedicamentos.setEnabled(false);
vista.jButtonSiguienteFichasDeMedicamentos.setEnabled(false);
vista.jButtonUltimoFichasDeMedicamentos.setEnabled(false);
vista.jButtonBuscarFichasDeMedicamentos.setEnabled(false);
vista.jButtonQuitarBuscarFichasDeMedicamentos.setEnabled(false);
vista.jTextFieldBuscarFichasDeMedicamentos.setEnabled(false);
vista.jButtonImprimir.setEnabled(false);
vista.jButtonMostrarEtiqueta.setEnabled(false);
//cambiar el color de los paneles para resaltar
vista.jPanelEdicionDatosFichasDeMedicamentos.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 255), 2, true), "Datos medicamento"));
vista.jPanelListaFichasDeMedicamentos.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(java.awt.Color.lightGray, 2, true), "Lista de medicamentos"));
//mostrar botones de aceptar-cancelar para terminar la edición
vista.jPanelAceptarCancelar.setVisible(true);
//da el focus a la primera opción editable
vista.jComboBoxVeredicto.transferFocusBackward();
}
//Pasos contrarios a comenzarEdicion()
private void acabarEdicion() {
vista.jTextAreaMedicamento.setEditable(false);
vista.jTextAreaEstabilidad.setEditable(false);
vista.jTextAreaObservacionesElaboracion.setEditable(false);
vista.jTextAreaObservaciones.setEditable(false);
vista.jTextFieldDatosOrganolepsis.setEditable(false);
vista.jTextAreaOrigen.setEditable(false);
vista.jTextAreaParaEtiqueta.setEditable(false);
vista.jTextAreaProcedimiento.setEditable(false);
vista.jTextFieldObservacionesVeredicto.setEditable(false);
vista.jComboBoxViaAdministracion.setEnabled(false);
vista.jComboBoxVeredicto.setEnabled(false);
vista.jComboBoxEDO.setEnabled(false);
vista.jComboBoxElaboradoPor.setEnabled(false);
vista.jComboBoxTipo.setEnabled(false);
vista.jButtonAddMaquinaria.setEnabled(true);
vista.jButtonAddMaterialElaborar.setEnabled(true);
vista.jButtonAddMaterialEnvasar.setEnabled(true);
vista.jButtonAddProducto.setEnabled(true);
vista.jButtonEliminarMaquinaria.setEnabled(true);
vista.jButtonEliminarMaterialElaborar.setEnabled(true);
vista.jButtonEliminarMaterialEnvasar.setEnabled(true);
vista.jButtonEliminarProducto.setEnabled(true);
vista.jButtonModificarProducto.setEnabled(true);
//deshabilitar el JList y los botones de la barra de herramientas para evitar errores
vista.jListFichasDeMedicamentos.setEnabled(true);
vista.jButtonAtrasFichasDeMedicamentos.setEnabled(true);
vista.jButtonEliminarFichasDeMedicamentos.setEnabled(true);
vista.jButtonNuevoFichasDeMedicamentos.setEnabled(true);
vista.jButtonPrimeroFichasDeMedicamentos.setEnabled(true);
vista.jButtonSiguienteFichasDeMedicamentos.setEnabled(true);
vista.jButtonUltimoFichasDeMedicamentos.setEnabled(true);
vista.jButtonBuscarFichasDeMedicamentos.setEnabled(true);
vista.jButtonQuitarBuscarFichasDeMedicamentos.setEnabled(true);
vista.jTextFieldBuscarFichasDeMedicamentos.setEnabled(true);
vista.jButtonImprimir.setEnabled(true);
vista.jButtonMostrarEtiqueta.setEnabled(true);
//cambiar el color de los paneles para resaltar
vista.jPanelEdicionDatosFichasDeMedicamentos.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(java.awt.Color.lightGray, 2, true), "Datos medicamento"));
vista.jPanelListaFichasDeMedicamentos.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 255), 2, true), "Lista de medicamentos"));
//mostrar botones de aceptar-cancelar para terminar la edición
vista.jPanelAceptarCancelar.setVisible(false);
}
//Pulsar boton de aceptar
public void botonAceptarPulsado() {
if (comprobarCamposObligatorios()) {
try {
if (nuevoPulsado) {
recogerDatosFichasDeMedicamentos();
modelo.nuevoMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()));
acabarEdicion();
rellenarJListFichasDeMedicamentos();
vista.jListFichasDeMedicamentos.setSelectedIndex(listaFichasDeMedicamentos.size() - 1);
} else {
recogerDatosFichasDeMedicamentos();
modelo.modificarMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()));
acabarEdicion();
int posicion = vista.jListFichasDeMedicamentos.getSelectedIndex();
rellenarJListFichasDeMedicamentos();
vista.jListFichasDeMedicamentos.setSelectedIndex(posicion);
}
} catch (org.hibernate.exception.DataException e) {
JOptionPane.showMessageDialog(vista, "Uno de los campos es demasiado largo, por favor hágalo más corto.", "Error", JOptionPane.WARNING_MESSAGE);
} catch (ConstraintViolationException e) {
JOptionPane.showMessageDialog(vista, "El medicamento introducido ya existe, introduza otro", "Error", JOptionPane.WARNING_MESSAGE);
}
nuevoPulsado = false;
}
}
//Pulsar boton de cancelar
public void botonCancelarPulsado() {
if (nuevoPulsado) {
listaFichasDeMedicamentos.remove(listaFichasDeMedicamentos.size() - 1);
acabarEdicion();
rellenarJListFichasDeMedicamentos();
vista.jListFichasDeMedicamentos.setSelectedIndex(0);
} else {
acabarEdicion();
controlarBotonesMoverse();
mostrarDatosFichasDeMedicamentos();
}
nuevoPulsado = false;
}
//Comprobar que los campos obligatorios no están vacios
public boolean comprobarCamposObligatorios() {
if (vista.jTextAreaMedicamento.getText().equals("")) {
JOptionPane.showMessageDialog(vista, "Los siguiente campos son obligatorios \n\t-Medicamento", "Aviso", JOptionPane.WARNING_MESSAGE);
return false;
}
return true;
}
//Realizar búsquedas
public void botonBuscar() {
if (vista.jComboBoxBuscarFichasDeMedicamentos.getSelectedIndex() == 0) {
if (vista.jCheckBoxMostrarTodo.isSelected()) {
listaFichasDeMedicamentos = modelo.selectMedicamentoPorNombre(vista.jTextFieldBuscarFichasDeMedicamentos.getText());
} else {
listaFichasDeMedicamentos = modelo.selectMedicamentoPorNombreVeredicto(vista.jTextFieldBuscarFichasDeMedicamentos.getText());
}
} else if (vista.jComboBoxBuscarFichasDeMedicamentos.getSelectedIndex() == 1) {
if (vista.jCheckBoxMostrarTodo.isSelected()) {
listaFichasDeMedicamentos = modelo.selectMedicamentoPorNombreProducto(vista.jTextFieldBuscarFichasDeMedicamentos.getText());
} else {
listaFichasDeMedicamentos = modelo.selectMedicamentoPorNombreProductoVeredicto(vista.jTextFieldBuscarFichasDeMedicamentos.getText());
}
}
rellenarJListFichasDeMedicamentos();
vista.jListFichasDeMedicamentos.setSelectedIndex(0);
if (listaFichasDeMedicamentos.size() < 1) {
JOptionPane.showMessageDialog(vista, "No hay medicamentos que cumplan las condiciones de la búsqueda", "Información", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(vista, "Se han reestablecido las condiciones de búsqueda", "Información", JOptionPane.INFORMATION_MESSAGE);
recargarDatosQuitarBuscar();
} else {
JOptionPane.showMessageDialog(vista, "Se han encontrado " + listaFichasDeMedicamentos.size() + " medicamentos", "Información", JOptionPane.INFORMATION_MESSAGE);
}
}
//Quitar el filtro de las busqudas
public void recargarDatosQuitarBuscar() {
vista.jTextFieldBuscarFichasDeMedicamentos.setText("");
recargarDatos();
}
// Recarga los datos de la base de datos
public void recargarDatos() {
if (vista.jCheckBoxMostrarTodo.isSelected()) {
listaFichasDeMedicamentos = modelo.selectAllMedicamentos();
} else {
listaFichasDeMedicamentos = modelo.selectAllMedicamentosVeredicto();
}
rellenarJListFichasDeMedicamentos();
vista.jListFichasDeMedicamentos.setSelectedIndex(0);
}
// Pulsar el boton de añadir maquinaria
public void pulsarAddMaquinaria() {
vista.jDialogAddMaquinaria.setSize(975, 640);
vista.jDialogAddMaquinaria.setLocationRelativeTo(null);
vista.jDialogAddMaquinaria.setVisible(true);
}
//Añadir una maquinaria a un medicamento
public void addMaquinariaMedicamento() {
MaquinariaUnion maquinaria = new MaquinariaUnion();
maquinaria.setMaquinaria(vista.controlMaquinaria.getMaquinariaElegida());
maquinaria.setFichasDeMedicamentos(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()));
try {
modelo.nuevoMaquinariaUnion(maquinaria);
vista.jDialogAddMaquinaria.setVisible(false);
int id = listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento();
//recargarDatos
listaFichasDeMedicamentos.set(vista.jListFichasDeMedicamentos.getSelectedIndex(), modelo.selectMedicamentoPorID(id));
cambiarPosicionJListFichasDeMedicamentos();
} catch (ConstraintViolationException e) {
JOptionPane.showMessageDialog(vista.jDialogAddMaquinaria, "Esa maquinaria ya esta añadida, no se pueden añadir dos maquinarias iguales", "Error", JOptionPane.WARNING_MESSAGE);
}
}
// Pulsar el boton de añadir material para elaborar
public void pulsarAddMaterialElaborar() {
vista.jDialogAddMaterialElaborar.setSize(975, 640);
vista.jDialogAddMaterialElaborar.setLocationRelativeTo(null);
vista.jDialogAddMaterialElaborar.setVisible(true);
}
//Añadir un material para elaborar a un medicamento
public void addMaterialElaborarMedicamento() {
MaterialParaElaborarUnion material = new MaterialParaElaborarUnion();
material.setMaterialParaElaborar(vista.controlMaterialElaborar.getMaterialParaElaborar());
material.setFichasDeMedicamentos(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()));
modelo.nuevoMaterialElaborarUnion(material);
vista.jDialogAddMaterialElaborar.setVisible(false);
int id = listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento();
//recargarDatos
listaFichasDeMedicamentos.set(vista.jListFichasDeMedicamentos.getSelectedIndex(), modelo.selectMedicamentoPorID(id));
cambiarPosicionJListFichasDeMedicamentos();
}
// Pulsar el boton de añadir material para envasar
public void pulsarAddMaterialEnvasar() {
vista.jDialogAddMaterialEnvasar.setSize(975, 640);
vista.jDialogAddMaterialEnvasar.setLocationRelativeTo(null);
vista.jDialogAddMaterialEnvasar.setVisible(true);
}
//Añadir un material para envasar a un medicamento
public void addMaterialEnvasarMedicamento() {
MaterialDeEnvasadoUnion material = new MaterialDeEnvasadoUnion();
material.setMaterialDeEnvasado(vista.controlMaterialEnvasar.getMaterialEnvasado());
material.setFichasDeMedicamentos(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()));
modelo.nuevoMaterialEnvasarUnion(material);
vista.jDialogAddMaterialEnvasar.setVisible(false);
int id = listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento();
//recargarDatos
listaFichasDeMedicamentos.set(vista.jListFichasDeMedicamentos.getSelectedIndex(), modelo.selectMedicamentoPorID(id));
cambiarPosicionJListFichasDeMedicamentos();
}
// Pulsar el boton de añadir producto
public void pulsarAddProductos() {
vista.jDialogAddProducto.setSize(975, 640);
vista.jDialogAddProducto.setLocationRelativeTo(null);
vista.jDialogAddProducto.setVisible(true);
}
//Añadir un producto a un medicamento
public void addProductosMedicamento() {
ProductosUnion producto = new ProductosUnion();
producto.setProductos(vista.controlProductos.getProducto());
producto.setFichasDeMedicamentos(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()));
asignarOrdenProducto(producto);
modelo.nuevoProductoUnion(producto);
vista.jDialogAddProducto.setVisible(false);
int id = listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento();
//recargarDatos
listaFichasDeMedicamentos.set(vista.jListFichasDeMedicamentos.getSelectedIndex(), modelo.selectMedicamentoPorID(id));
cambiarPosicionJListFichasDeMedicamentos();
nuevoProducto = true;
mostrarDatosProducto(listaProductosMedicamento.size() - 1);
vista.jDialogModificarProducto.setSize(450, 330);
vista.jDialogModificarProducto.setLocationRelativeTo(null);
vista.jDialogModificarProducto.setVisible(true);
}
//pulsar el boton de modificar los datos de un producto perteneciente a un medicamento
public void pulsarBotonModificarProducto() {
if (vista.jTableProductos.getSelectedRow() != -1) {
mostrarDatosProducto(vista.jTableProductos.getSelectedRow());
vista.jDialogModificarProducto.setSize(450, 330);
vista.jDialogModificarProducto.setLocationRelativeTo(null);
vista.jDialogModificarProducto.setVisible(true);
} else {
JOptionPane.showMessageDialog(vista, "Debe seleccionar un producto de la tabla para poder modificarlo", "Advertencia", JOptionPane.WARNING_MESSAGE);
}
}
//mostrar los datos de un producto en el dialogo de modificar productos
public void mostrarDatosProducto(int posicion) {
vista.jLabelDialogModificarProductoProductos.setText(vista.jTableProductos.getValueAt(posicion, 1).toString());
if (!nuevoProducto && listaProductosMedicamento.get(posicion).getCantidad() != null) {
if (listaProductosMedicamento.get(posicion).getCantidad().contains("C.S.P.")) {
vista.jTextFieldDialogModificarProductoCantidad.setText(listaProductosMedicamento.get(posicion).getCantidad().substring(7));
vista.jCheckBoxCSP.setSelected(true);
} else {
vista.jTextFieldDialogModificarProductoCantidad.setText(listaProductosMedicamento.get(posicion).getCantidad());
vista.jCheckBoxCSP.setSelected(false);
}
vista.jComboBoxDialogModificarProductoUnidades.setSelectedItem(listaProductosMedicamento.get(posicion).getUnidades());
} else {
vista.jTextFieldDialogModificarProductoCantidad.setText("");
vista.jComboBoxDialogModificarProductoUnidades.setSelectedItem("");
vista.jCheckBoxCSP.setSelected(false);
}
}
//modificar los datos de un medicamento perteneciente a un medicamento
public void modificarProductoMedicamento() {
try {
if (!vista.jTextFieldDialogModificarProductoCantidad.getText().equals("") && vista.jComboBoxDialogModificarProductoUnidades.getSelectedIndex() != -1) {
if (!nuevoProducto) {
listaProductosMedicamento.get(vista.jTableProductos.getSelectedRow()).setUnidades(vista.jComboBoxDialogModificarProductoUnidades.getSelectedItem().toString());
if (vista.jCheckBoxCSP.isSelected()) {
listaProductosMedicamento.get(vista.jTableProductos.getSelectedRow()).setCantidad("C.S.P. " + vista.jTextFieldDialogModificarProductoCantidad.getText());
} else {
listaProductosMedicamento.get(vista.jTableProductos.getSelectedRow()).setCantidad(vista.jTextFieldDialogModificarProductoCantidad.getText());
}
modelo.modificarProductoUnion(listaProductosMedicamento.get(vista.jTableProductos.getSelectedRow()));
} else {
listaProductosMedicamento.get(listaProductosMedicamento.size() - 1).setUnidades(vista.jComboBoxDialogModificarProductoUnidades.getSelectedItem().toString());
if (vista.jCheckBoxCSP.isSelected()) {
listaProductosMedicamento.get(listaProductosMedicamento.size() - 1).setCantidad("C.S.P. " + vista.jTextFieldDialogModificarProductoCantidad.getText());
} else {
listaProductosMedicamento.get(listaProductosMedicamento.size() - 1).setCantidad(vista.jTextFieldDialogModificarProductoCantidad.getText());
}
modelo.modificarProductoUnion(listaProductosMedicamento.get(listaProductosMedicamento.size() - 1));
}
nuevoProducto = false;
int id = listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento();
//recargarDatos
listaFichasDeMedicamentos.set(vista.jListFichasDeMedicamentos.getSelectedIndex(), modelo.selectMedicamentoPorID(id));
cambiarPosicionJListFichasDeMedicamentos();
vista.jDialogModificarProducto.setVisible(false);
} else {
JOptionPane.showMessageDialog(vista.jDialogModificarProducto, "La cantidad y las unidades tienen que tener algún valor para poder modificar los datos", "Error", JOptionPane.WARNING_MESSAGE);
}
} catch (DataException e) {
JOptionPane.showMessageDialog(vista.jDialogModificarProducto, "El producto no se ha podido modificar debido a que la cantidad introducida es demasiado alta", "Aviso", JOptionPane.WARNING_MESSAGE);
}
}
//da el siguiente orden a un producto nuevo
public void asignarOrdenProducto(ProductosUnion producto) {
String anterior = modelo.maxOrden(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento());
if (anterior != null) {
char siguiente = (char) ((int) anterior.charAt(0) + 1);
producto.setOrden(String.valueOf(siguiente));
} else {
producto.setOrden(String.valueOf("a"));
}
}
//Eliminar una maquinaria
public void pulsarBotonEliminarMaquinaria() {
if (vista.jTableMaquinaria.getSelectedRow() != -1) {
if (JOptionPane.showConfirmDialog(vista, "¿Desea eliminar la maquinaria seleccionada?", "Eliminar", JOptionPane.YES_NO_OPTION) == 0) {
modelo.eliminarMaquinariaUnion(listaMaquinariaMedicamento.get(vista.jTableMaquinaria.getSelectedRow()));
int id = listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento();
//recargarDatos
listaFichasDeMedicamentos.set(vista.jListFichasDeMedicamentos.getSelectedIndex(), modelo.selectMedicamentoPorID(id));
cambiarPosicionJListFichasDeMedicamentos();
}
} else {
JOptionPane.showMessageDialog(vista, "Debe seleccionar una maquinaria de la tabla para poder eliminarla", "Advertencia", JOptionPane.WARNING_MESSAGE);
}
}
//Eliminar una maquinaria
public void pulsarBotonEliminarMaterialElaborar() {
if (vista.jTableMaterialElaborar.getSelectedRow() != -1) {
if (JOptionPane.showConfirmDialog(vista, "¿Desea eliminar el material para elaborar seleccionado?", "Eliminar", JOptionPane.YES_NO_OPTION) == 0) {
modelo.eliminarMaterialElaborarUnion(listaMaterialElaborarMedicamento.get(vista.jTableMaterialElaborar.getSelectedRow()));
int id = listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento();
//recargarDatos
listaFichasDeMedicamentos.set(vista.jListFichasDeMedicamentos.getSelectedIndex(), modelo.selectMedicamentoPorID(id));
cambiarPosicionJListFichasDeMedicamentos();
}
} else {
JOptionPane.showMessageDialog(vista, "Debe seleccionar un material para elaborar de la tabla para poder eliminarlo", "Advertencia", JOptionPane.WARNING_MESSAGE);
}
}
//Eliminar una maquinaria
public void pulsarBotonEliminarMaterialEnvasar() {
if (vista.jTableMaterialEnvasar.getSelectedRow() != -1) {
if (JOptionPane.showConfirmDialog(vista, "¿Desea eliminar el material para envasar seleccionado?", "Eliminar", JOptionPane.YES_NO_OPTION) == 0) {
modelo.eliminarMaterialEnvasarUnion(listaMaterialEnvasadoMedicamento.get(vista.jTableMaterialEnvasar.getSelectedRow()));
int id = listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento();
//recargarDatos
listaFichasDeMedicamentos.set(vista.jListFichasDeMedicamentos.getSelectedIndex(), modelo.selectMedicamentoPorID(id));
cambiarPosicionJListFichasDeMedicamentos();
}
} else {
JOptionPane.showMessageDialog(vista, "Debe seleccionar un material para envasar de la tabla para poder eliminarlo", "Advertencia", JOptionPane.WARNING_MESSAGE);
}
}
//Eliminar una maquinaria
public void pulsarBotonEliminarProducto() {
if (vista.jTableProductos.getSelectedRow() != -1) {
if (JOptionPane.showConfirmDialog(vista, "¿Desea eliminar el producto seleccionado?", "Eliminar", JOptionPane.YES_NO_OPTION) == 0) {
modelo.eliminarProductoUnion(listaProductosMedicamento.get(vista.jTableProductos.getSelectedRow()));
int id = listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento();
//recargarDatos
listaFichasDeMedicamentos.set(vista.jListFichasDeMedicamentos.getSelectedIndex(), modelo.selectMedicamentoPorID(id));
cambiarPosicionJListFichasDeMedicamentos();
}
} else {
JOptionPane.showMessageDialog(vista, "Debe seleccionar un producto de la tabla para poder eliminarlo", "Advertencia", JOptionPane.WARNING_MESSAGE);
}
}
//Pulsar botón de mostrar etiquetas
public void pulsarBotonDialogEtiquetasVerEtiqueta() {
vista.jDialogEtiquetas.setVisible(false);
VentanaEtiquetas.instance.mostrarEtiquetaDeMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getMedicamento(), false);
VentanaEtiquetas.instance.setLocationRelativeTo(null);
VentanaEtiquetas.instance.setVisible(true);
}
//Pulsar botón de nueva etiqueta
public void pulsarBotonDialogEtiquetasNuevaEtiqueta() {
vista.jDialogEtiquetas.setVisible(false);
VentanaEtiquetas.instance.mostrarEtiquetaDeMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getMedicamento(), true);
VentanaEtiquetas.instance.setLocationRelativeTo(null);
VentanaEtiquetas.instance.setVisible(true);
}
//Pulsar el botón que abre el diálogo de las etiquetas
public void pulsarBotonEtiquetas() {
vista.jDialogEtiquetas.setSize(580, 300);
vista.jDialogEtiquetas.setLocationRelativeTo(null);
vista.jDialogEtiquetas.setVisible(true);
}
//Pulsar el botón de imprimir
public void pulsarBotonImprimir() {
Session sesion = modelo.abrirSesion();
listaMaterialElaborarMedicamento = modelo.selectMaterialElaborarDeMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento(), sesion);
listaMaquinariaMedicamento = modelo.selectMaquinariaDeMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento(), sesion);
listaMaterialEnvasadoMedicamento = modelo.selectMaterialEnvasarDeMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento(), sesion);
listaProductosMedicamento = modelo.selectProductosDeMedicamento(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()).getIdMedicamento(), sesion);
ArrayList<FichasDeMedicamentos> fichaMedicamentoImprimir = new ArrayList<>();
fichaMedicamentoImprimir.add(listaFichasDeMedicamentos.get(vista.jListFichasDeMedicamentos.getSelectedIndex()));
FichasDeMedicamentosDataSource datasource = new FichasDeMedicamentosDataSource(fichaMedicamentoImprimir, listaMaquinariaMedicamento, listaMaterialElaborarMedicamento, listaMaterialEnvasadoMedicamento, listaProductosMedicamento);
JasperReport reporte;
try {
reporte = (JasperReport) JRLoader.loadObjectFromFile("reportSub.jasper");
JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, datasource);
JasperViewer jviewer = new JasperViewer(jasperPrint, false);
// jviewer.setAlwaysOnTop(true);
jviewer.setTitle("Imprimir");
jviewer.setVisible(true);
jviewer.setExtendedState(Frame.MAXIMIZED_BOTH);
} catch (JRException e1) {
JOptionPane.showMessageDialog(vista, "Error al inicializar el reporte", "Fallo", JOptionPane.ERROR_MESSAGE);
}
modelo.cerrarSesion(sesion);
}
public void pulsarCheckMostrarTodo() {
if (vista.jCheckBoxMostrarTodo.isSelected()) {
listaFichasDeMedicamentos = modelo.selectAllMedicamentos();
} else {
listaFichasDeMedicamentos = modelo.selectAllMedicamentosVeredicto();
}
rellenarJListFichasDeMedicamentos();
vista.jListFichasDeMedicamentos.setSelectedIndex(0);
}
}
<file_sep>package es.sacyl.caza.farmacia.modelo;
import es.sacyl.caza.farmacia.modelo.clases.Productos;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;
/**
*
* @author <NAME>
*/
public class ProductosDAO extends DAO {
//Añadir un nuevo producto a la tabla productos
public void nuevoProducto(Productos producto) throws org.hibernate.exception.DataException{
Session sesion = abrirSesion();
Transaction tx = sesion.beginTransaction();
try{
sesion.save(producto);
tx.commit();
}catch(ConstraintViolationException e){
throw e;
}finally{
cerrarSesion(sesion);
}
}
//Modificar un producto ya existente de la tabla productos
public void modificarProducto(Productos producto) throws org.hibernate.exception.DataException {
Session sesion = abrirSesion();
Transaction tx = sesion.beginTransaction();
try{
sesion.update(producto);
tx.commit();
}catch(ConstraintViolationException e){
throw e;
}finally{
cerrarSesion(sesion);
}
}
//Eliminar un producto existente de la tabla productos
public void eliminarProducto(Productos producto){
Session sesion = abrirSesion();
Transaction tx = sesion.beginTransaction();
sesion.delete(producto);
tx.commit();
cerrarSesion(sesion);
}
//Obtener todos los productos de la tabla productos
public ArrayList<Productos> selectAllProducto(){
Session sesion = abrirSesion();
ArrayList<Productos> listaProductos = new ArrayList<>();
Query q = sesion.createQuery("from Productos order by componente");
List<Productos> lista = q.list();
Iterator iter = lista.iterator();
while (iter.hasNext()) {
// extraer el objeto
Productos producto = (Productos) iter.next();
listaProductos.add(producto);
}
cerrarSesion(sesion);
return listaProductos;
}
//Obtener los productos que cumplan la condición
public ArrayList<Productos> selectProductosPorComponente(String componente){
Session sesion = abrirSesion();
ArrayList<Productos> listaProductos = new ArrayList<>();
Query q = sesion.createQuery("from Productos as p where p.componente like ? order by componente");
componente=componente+"%";
q.setString(0, componente);
List<Productos> lista = q.list();
Iterator iter = lista.iterator();
while (iter.hasNext()) {
// extraer el objeto
Productos producto = (Productos) iter.next();
listaProductos.add(producto);
}
cerrarSesion(sesion);
return listaProductos;
}
//Obtener productos por referencia
public ArrayList<Productos> selectProductosPorReferencia(String referencia){
Session sesion = abrirSesion();
ArrayList<Productos> listaProductos = new ArrayList<>();
Query q = sesion.createQuery("from Productos as p where p.referencia like ? order by referencia");
referencia=referencia+"%";
q.setString(0, referencia);
List<Productos> lista = q.list();
Iterator iter = lista.iterator();
while (iter.hasNext()) {
// extraer el objeto
Productos producto = (Productos) iter.next();
listaProductos.add(producto);
}
cerrarSesion(sesion);
return listaProductos;
}
//Obtener productos activos/no activos
public ArrayList<Productos> selectProductosActivos(boolean activo){
Session sesion = abrirSesion();
ArrayList<Productos> listaProductos = new ArrayList<>();
Query q = sesion.createQuery("from Productos as p where p.activo = ? order by componente");
q.setBoolean(0, activo);
List<Productos> lista = q.list();
Iterator iter = lista.iterator();
while (iter.hasNext()) {
// extraer el objeto
Productos producto = (Productos) iter.next();
listaProductos.add(producto);
}
cerrarSesion(sesion);
return listaProductos;
}
}
|
0e547af53399dfe4998547bee16ea5c8f9d09817
|
[
"Java"
] | 17 |
Java
|
enrique24/FarmacotecniaCAZA
|
0c250e9bd21a87218fd543951eb9eb33acf22d62
|
f0a03a53688fad1f36f2f0a5b26ded5bb6d4698e
|
refs/heads/master
|
<file_sep>'use strict';
const
Joi = require('joi'),
Api = require('../../lib/api'),
Service = require('./service'),
Model = require('./model'),
Routes = require('../../config').Routes;
const ApiConfig = {
USER_DEVICE: {
validate: {
payload: {
[Model.UserDevice.DEVICE_ID]: Joi.string().required(),
[Model.UserDevice.USER_ID]: Joi.number().required()
},
failAction: Api.invalidParams
}
}
};
module.exports = [
{
method: 'GET',
path: Routes.USER,
config: {},
handler: Service.find
},
{
method: 'POST',
path: Routes.USER_DEVICE,
config: ApiConfig.USER_DEVICE,
handler: Service.addDevice
}
];<file_sep>'use strict';
const
Model = require('./model').User;
module.exports = {
getUserObj: (params) => {
return {
[Model.USERNAME]: params.username,
[Model.EMAIL]: params.email,
[Model.FIRST_NAME]: params.firstName,
[Model.LAST_NAME]: params.lastName,
[Model.PHOTO_URL]: params.photoUrl,
[Model.FB_ID]: params.fbId,
[Model.IS_ADMIN]: false,
};
}
};<file_sep>'use strict';
module.exports = {
_Params: {
FB_TOKEN: 'fb_token',
TOKEN: 'token'
}
};<file_sep>'use strict';
const Path = require('path');
const BLIPP_OPTIONS = {
showAuth: true
};
const GOOD_OPTIONS = {
reporters: {
console: [{
module: 'good-squeeze',
name: 'Squeeze',
args: [{
response: '*',
log: '*'
}]
}, {
module: 'good-console'
}, 'stdout']
}
};
module.exports = [
{
plugin: {
register: 'inert',
options: {}
}
},
{
plugin: {
register: 'bell',
options: {}
}
},
{
plugin: {
register: 'hapi-auth-jwt2',
options: {}
}
},
{
plugin: {
register: 'blipp',
options: BLIPP_OPTIONS
}
},
{
plugin: {
register: 'good',
options: GOOD_OPTIONS
}
},
{
plugin: {
register: Path.join(__dirname, 'modules/auth/plugin'),
options: {}
}
},
{
plugin: {
register: 'hapi-router',
options: {
routes: './app/modules/**/routes.js'
}
}
}
];<file_sep>'use strict';
const Winston = require('winston');
const Cfg = require('../config');
const logger = new Winston.Logger({
transports: [
new (Winston.transports.Console)(),
new (Winston.transports.File)({
name: "info-file",
filename: Cfg.LOG_PATH + "info.log",
level: 'info'
}),
new (Winston.transports.File)({
name: "warn-file",
filename: Cfg.LOG_PATH + "warn.log",
level: 'warn'
}),
new (Winston.transports.File)({
name: "error-file",
filename: Cfg.LOG_PATH + "error.log",
level: 'error'
})
]
});
module.exports = {
info: (message, metadata) => {
logger.log('info', message, metadata);
},
warn: (message, metadata) => {
logger.log('warn', message, metadata);
},
error: (message, metadata) => {
logger.log('error', message, metadata);
},
};<file_sep>'use strict';
module.exports = {
Errors: {
INVALID_PARAMS: "Request parameters are invalid",
NOT_MODIFIED: "Resource not modified",
FB_AUTH_FAILED: "Facebook authentication failed",
}
};<file_sep>'use strict';
const
Config = require('../../config'),
Jwt = require('../../lib/jwt');
const registerAuth = server => {
server.auth.strategy('facebook', 'bell', {
provider: 'facebook',
password: '<PASSWORD>',
isSecure: false,
clientId: Config.FB_CLIENT_ID,
clientSecret: Config.FB_CLIENT_SECRET,
location: server.info.uri
});
server.auth.strategy('jwt', 'jwt', {
key: Config.APP_SECRET,
validateFunc: Jwt.verify,
verifyOptions: {algorithms: ['HS256']},
tokenType: 'Bearer'
});
server.auth.default('jwt');
};
exports.register = (server, options, next) => {
registerAuth(server);
next();
};
exports.register.attributes = {
name: 'Auth',
version: '1.0.0'
};<file_sep>'use strict';
const
Promise = require('bluebird'),
Log = require('../../lib/log'),
DB = require('../../db'),
Api = require('../../lib/api'),
Model = require('./model'),
DBUtil = require('../../lib/util').Db,
Repo = require('./repo')(DB);
const getMatchParams = req => {
let obj = {};
let fromTS = req.query[Model._Params.FROM];
if (fromTS) {
obj[Model._Params.FROM] = DBUtil.formatDBTime(fromTS);
}
return obj;
};
const getMatchByIdParams = req => {
return {
[Model._Params.ID]: req.params[Model._Params.ID] || 0
}
};
const getMatchPayload = req => {
const params = {};
[
Model.DESCRIPTION,
Model.LOCATION,
Model.LAT,
Model.LNG,
Model.MAX_PLAYERS,
Model.MIN_PLAYERS,
Model.Team.TEAM1_NAME,
Model.Team.TEAM2_NAME,
Model.Team.TEAM1_COLOR_HEX,
Model.Team.TEAM2_COLOR_HEX,
].map(key => {
params[key] = req.payload[key];
});
params[Model.DUE_DATE] = DBUtil.formatDBTime(req.payload[Model.DUE_DATE]);
return params;
};
module.exports = {
/**
* Find match by id
* @param request
* @param reply
*/
findById: (request, reply) => {
return new Promise((resolve, reject) => {
let params = getMatchByIdParams(request);
Repo.findById(params).then(res => {
Api.write(reply, res, {omitMetadata: true});
}).catch(err => {
Api.badRequest(reply, err);
});
});
},
/**
* Find filtered matches
* @param request
* @param reply
*/
find: (request, reply) => {
return new Promise((resolve, reject) => {
let params = getMatchParams(request);
Repo.find(params).then(res => {
Api.write(reply, res, Api.DEFAULTS);
}).catch(err => {
Api.badRequest(reply, err);
});
});
},
/**
* Add a match
* @param request
* @param reply
*/
add: (request, reply) => {
return new Promise((resolve, reject) => {
let params = getMatchPayload(request);
Repo.add(params).then(res => {
if (res.rowCount) {
Api.success(reply, res);
} else {
Api.notModified(reply);
}
}).catch(err => {
Api.badRequest(reply, err);
});
});
},
/**
* Remove a match
* @param request
* @param reply
*/
remove: (request, reply) => {
return new Promise((resolve, reject) => {
let params = getMatchByIdParams(request);
Repo.remove(params).then(res => {
if (res.rowCount) {
Api.success(reply, res);
} else {
Api.notModified(reply);
}
}).catch(err => {
Api.badRequest(reply, err);
});
});
}
};<file_sep># ttfu
TeamTheFuckUp Server & Dashboard
<file_sep>'use strict';
const Promise = require('bluebird');
const Cfg = require('./config');
const options = {
promiseLib: Promise
};
let pgp = require('pg-promise')(options);
let db = pgp(Cfg.DB_STRING);
module.exports = db;<file_sep>'use strict';
module.exports = {
MATCH_ID: 'match_id',
DUE_DATE: 'due_date',
DESCRIPTION: 'description',
LOCATION: 'location',
LAT: 'lat',
LNG: 'lng',
MAX_PLAYERS: 'max_players',
MIN_PLAYERS: 'min_players',
TEAMS: 'teams',
UPDATED_AT: 'updated_at',
CREATED_AT: 'created_at',
DELETED_AT: 'deleted_at',
Team: {
TEAM1_NAME: 'team1_name',
TEAM2_NAME: 'team2_name',
TEAM1_COLOR_HEX: 'team1_color_hex',
TEAM2_COLOR_HEX: 'team2_color_hex'
},
_Params: {
ID: 'id',
FROM: 'from'
}
};<file_sep>'use strict';
const
Promise = require('bluebird'),
DB = require('../../db'),
Api = require('../../lib/api'),
Repo = require('./repo')(DB),
Models = require('./model'),
UserModel = Models.User,
UserDeviceModel = Models.UserDevice,
Jwt = require('../../lib/jwt');
const getUserDeviceData = req => {
return {
[UserDeviceModel.USER_ID]: req.payload[UserDeviceModel.USER_ID],
[UserDeviceModel.DEVICE_ID]: req.payload[UserDeviceModel.DEVICE_ID],
[UserDeviceModel.CREATED_AT]: new Date(),
[UserDeviceModel.ACTIVE]: true
};
};
module.exports = {
/**
* Query user from facebook
* @param request
* @param reply
* @param data
*/
findByFacebookId: (request, reply, data) => {
return new Promise((resolve, reject) => {
Repo.findByFacebookId(data).then(res => {
resolve(res);
}).catch(err => {
reject(err);
});
});
},
/**
* Get user from user_id stored in token
* @param request
* @param reply
*/
find: (request, reply) => {
return new Promise((resolve, reject) => {
let tokenPayload = Jwt.getTokenPayload(request);
const query = {
[Models.User.USER_ID]: tokenPayload[Models.User.USER_ID]
};
Repo.find(query).then(res => {
Api.write(reply, res, Api.DEFAULTS);
}).catch(err => {
Api.badRequest(reply, err);
});
})
},
/**
* Adds a user
* @param request
* @param reply
* @param data
*/
add: (request, reply, data) => {
return new Promise((resolve, reject) => {
Repo.add(data).then(res => {
resolve(res);
}).catch(err => {
reject(err);
});
});
},
/**
* Adds a user device
* @param request
* @param reply
*/
addDevice: (request, reply) => {
return new Promise((resolve, reject) => {
let userDeviceData = getUserDeviceData(request);
Repo.addDevice(userDeviceData).then(res => {
Api.write(reply, res, Api.DEFAULTS);
}).catch(err => {
Api.badRequest(reply, err);
});
});
}
};<file_sep>'use strict';
const Boom = require('boom');
const Log = require('./log');
const Cfg = require('../config');
module.exports = {
write: (reply, res) => {
return reply(res.data || res);
},
redirect: (reply, url) => {
return reply.redirect(url);
},
success: (reply) => {
return reply({success: 1});
},
notModified: (reply) => {
return reply(Boom.badRequest(Cfg.Strings.Errors.NOT_MODIFIED));
},
badRequest: (reply, err) => {
Log.error(err.message, err);
return reply(Boom.badRequest(err.message, err));
},
invalidParams: (request, reply, source, err) => {
Log.error(err.message, err);
return reply(Boom.badRequest(Cfg.Strings.Errors.INVALID_PARAMS, err));
},
};<file_sep>up:
@echo "Starting ..."
docker-compose up -d
@$(MAKE) --no-print-directory status
build:
@echo "Building ..."
docker-compose build
status:
@echo "Status ..."
@docker-compose ps<file_sep>'use strict';
module.exports = {
default: (request, reply) => {
reply.file('client/index.html');
},
error404: (request, reply) => {
reply.file('app/views/404.html');
}
};<file_sep>'use strict';
require('dotenv').config();
const _ = require('lodash');
const Routes = require('./routes');
const Strings = require('./strings');
const API_URL = '/api/v1/';
const MILLIS = Math.floor(Date.now() / 1000);
const CONFIG_KEYS = [
'HOST',
'PORT',
'APP_SECRET',
'DB_STRING',
'FB_CLIENT_ID',
'FB_CLIENT_SECRET',
'LOG_PATH',
];
let CommonConfig = {
Routes: Routes(API_URL),
Strings: Strings
};
CONFIG_KEYS.forEach(key => {
CommonConfig[key] = process.env[key];
});
const EnvConfig = {
development: {
TOKEN_EXPIRATION_TIME: MILLIS + (60 * 60) //1Hour
},
production: {
TOKEN_EXPIRATION_TIME: MILLIS + (24 * 60 * 60) //24Hour
}
};
let Config = EnvConfig[process.env.ENVIRONMENT] || {};
_.extend(Config, CommonConfig);
module.exports = Config;<file_sep>const Glue = require('glue');
const Log = require('./lib/log');
const Config = require('./config');
const Plugins = require('./plugins');
const MANIFEST = {
connections: [{port: Config.PORT}],
registrations: Plugins,
};
const OPTIONS = {};
const start = () => {
Glue.compose(MANIFEST, OPTIONS, (err, server) => {
server.start((err) => {
if (err) {
Log.error(err.message, err);
}
Log.info('Server started @' + Config.HOST + ':' + Config.PORT);
});
});
};
module.exports = {
start: start
};<file_sep>'use strict';
const Code = require('code');
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const Cfg = require('../app/config');
const Jwt = require('../app/lib/jwt');
const Log = require('../app/lib/log');
const expect = Code.expect;
const JWT_REGEX = /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/;
lab.experiment('Auth', () => {
lab.test('Generate Token Key', (done) => {
Jwt.generate({user_id: 1}).then((token) => {
Log.info("Token generated: ", token);
expect(token).to.match(JWT_REGEX);
done();
}).catch((err) => {
Log.error(err.message);
done();
});
})
});
|
6091854b045627e43cb7e8042e9457fb7e0e94af
|
[
"JavaScript",
"Makefile",
"Markdown"
] | 18 |
JavaScript
|
kostandinang/ttfu
|
d151cb59dd9378ea24dd8d3a59129f08c900468f
|
9afee57f73c45fbd0ffd7179ad308644cbe1d0a1
|
refs/heads/main
|
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXCHAR 1000
void Tester(int o,int Out[],int In[],int i);
int InstructionType(char c);
void WriteAInstruction(int num,int final[]);
void WriteCInstruction(char instruction[],int final[]);
void WriteComp(int instruction_out[],int Comp_input[]);
void WriteDest(int instruction_out[],int Dest_input[]);
void WriteJump(int instruction_out[],int Jump_input[]);
int getInstructionType(char instruction[],int n);
int main()
{
int Instruction[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
FILE *fp;
char str[MAXCHAR];
char* filename = "test.txt";
fp = fopen(filename, "r");
FILE *out_file = fopen("hack.txt", "w"); // write only
if (fp == NULL){
printf("Could not open file %s",filename);
return 1;
}
/*
while (fgets(str, MAXCHAR, fp) != NULL)
printf("%s", str);*/
while (fgets(str, MAXCHAR, fp) != NULL){
if(InstructionType(str[0])==0){
str[0]='0';
int val=atoi(str);
WriteAInstruction(val,Instruction);
/*Write inctruction to file here*/
//printf alal A instrcution here yes
//printf("ins : %s : ",str);
int i;
for(i=0;i<16;++i){
//printf("%d",Instruction[i]);
fprintf(out_file, "%d",Instruction[i]);
}
fprintf(out_file, "\n");
}else{
int sz=strlen(str);
//printf("%s\t : C-Instruction : %d\n", str,getInstructionType(str,sz));
WriteCInstruction(str,Instruction);
int a;
for(a=0;a<16;++a){
fprintf(out_file, "%d",Instruction[a]);
}
fprintf(out_file, "\n");
}
}
printf("Done successfully !!!\n");
printf("Check output_file\n");
fclose(fp);
fclose(out_file);
return 0;
}
void Tester(int o,int Out[],int In[],int i){
printf("IN below : \n");
int j;
for(j=0;j<i;++j){
printf("%d",In[j]);
}
printf("\n\nOut below\n");
for(j=0;j<o;++j){
printf("%d",Out[j]);
}
printf("\n");
}
void WriteAInstruction(int num,int final[]){
int i,res,bin;
for(i=0;i<16;++i){
final[i]=0;
}
res=num;
bin=15;
while(res!=0){
final[bin]=res%2;
//printf("## %d\n",res%2);
--bin;
res=res/2;
}
//printf("Done now yeah\n");
}
int InstructionType(char c){
if(c=='@'){
return 0; //0 means its an A-Instruction
}else{
return 1;
}
}
/*
Comp : receives an instruction as argument and fills the comp part with the comp_input
//Tested and tried
*/
void WriteComp(int instruction_out[],int Comp_input[]){
int i;
for(i=0;i<7;++i){
instruction_out[i+3]=Comp_input[i];
//Tester(16,instruction_out,Comp_input,7);
}
//Tester(16,instruction_out,Comp_input,7);
}
void WriteDest(int instruction_out[],int Dest_input[]){
int i;
for(i=0;i<3;++i){
instruction_out[i+10]=Dest_input[i];
}
//Tester(16,instruction_out,Dest_input,3);
}
void WriteJump(int instruction_out[],int Jump_input[]){
int i;
for(i=0;i<3;++i){
instruction_out[i+13]=Jump_input[i];
}
Tester(16,instruction_out,Jump_input,3);
}
/*
WriteCInstruction: writes a C instrcution be calling the utility functions
//
*/
void WriteCInstruction(char instruction[],int final[]){
int i;
int sz=strlen(instruction);
int instType=getInstructionType(instruction,sz);
char dest_literal[5]="";
char comp_literal[5]="";
char jump_literal[5]="";
//get it done yeah
//result values here
int dest_value[3]={0,0,0};
int jump_value[3]={0,0,0};
int comp_value[7]={0,0,0,0,0,0,0};
if(instType==1){
int k=0;
int i=0;
while(instruction[i]!='='){
dest_literal[k]=instruction[i];
++i;
++k;
}
++i;
k=0;
while(instruction[i]!=';'){
comp_literal[k]=instruction[i];
++i;
++k;
}
++i;
k=0;
while(instruction[i]!='\n'){
jump_literal[k]=instruction[i];
i++;
++k;
}
}else if(instType==2){
int k=0;
int i=0;
while(instruction[i]!='='){
dest_literal[k]=instruction[i];
++i;
++k;
}
//printf("test i : %d",i);
++i;
k=0;
while(instruction[i]!='\n'){
comp_literal[k]=instruction[i];
++i;
++k;
}
//printf("here type 2 \n");
}else if(instType==3){
int k=0;
int i=0;
while(instruction[i]!=';'){
comp_literal[k]=instruction[i];
++i;
++k;
}
++i;
k=0;
while(instruction[i]!='\n'){
jump_literal[k]=instruction[i];
++i;
++k;
}
}else{
printf("Invalid instruction heyyy\n");
}
//printf("dest : %s\n",dest_literal);
//printf("comp : %s\n",comp_literal);
//printf("jump : %s\n",jump_literal);
//Firstly set the Destination
//Stage 1 : destination setting
if(strcmp(dest_literal,"M")==0){
dest_value[0]=0;dest_value[1]=0;dest_value[2]=1;
}else if(strcmp(dest_literal,"D")==0){
dest_value[0]=0;dest_value[1]=1;dest_value[2]=0;
}else if(strcmp(dest_literal,"MD")==0){
dest_value[0]=0;dest_value[1]=1;dest_value[2]=1;
}else if(strcmp(dest_literal,"A")==0){
dest_value[0]=1;dest_value[1]=0;dest_value[2]=0;
}else if(strcmp(dest_literal,"AM")==0){
dest_value[0]=1;dest_value[1]=0;dest_value[2]=1;
}else if(strcmp(dest_literal,"AD")==0){
dest_value[0]=1;dest_value[1]=1;dest_value[2]=0;
}else if(strcmp(dest_literal,"AMD")==0){
dest_value[0]=1;dest_value[1]=1;dest_value[2]=1;
}else if(strcmp(dest_literal,"")==0){
dest_value[0]=0;dest_value[1]=0;dest_value[2]=0;
}else{
printf("Error here : Stage 1 : destination setting \n");
printf("inst : %s\n",instruction);
}
//stage 2 jump : setting
if(strcmp(jump_literal,"JGT")==0){
jump_value[0]=0;jump_value[1]=0;jump_value[2]=1;
}else if(strcmp(jump_literal,"JEQ")==0){
jump_value[0]=0;jump_value[1]=1;jump_value[2]=0;
}else if(strcmp(jump_literal,"JGE")==0){
jump_value[0]=0;jump_value[1]=1;jump_value[2]=1;
}else if(strcmp(jump_literal,"JLT")==0){
jump_value[0]=1;jump_value[1]=0;jump_value[2]=0;
}else if(strcmp(jump_literal,"JNE")==0){
jump_value[0]=1;jump_value[1]=0;jump_value[2]=1;
}else if(strcmp(jump_literal,"JLE")==0){
jump_value[0]=1;jump_value[1]=1;jump_value[2]=0;
}else if(strcmp(jump_literal,"JMP")==0){
jump_value[0]=1;jump_value[1]=1;jump_value[2]=1;
}else if(strcmp(jump_literal,"")==0){
jump_value[0]=0;jump_value[1]=0;jump_value[2]=0;
}else{
printf("Erorr here >> stage 2 jump : setting ");
printf("inst : %s\n",jump_literal);
}
//stage 3 part : setting comp , a=0
if(strcmp(comp_literal,"0")==0){
comp_value[0]=0;
comp_value[1]=1; comp_value[2]=0; comp_value[3]=1;
comp_value[4]=0; comp_value[5]=1; comp_value[6]=0;
}else if(strcmp(comp_literal,"1")==0){
comp_value[0]=0;
comp_value[1]=1; comp_value[2]=1; comp_value[3]=1;
comp_value[4]=1; comp_value[5]=1; comp_value[6]=1;
}else if(strcmp(comp_literal,"-1")==0){
comp_value[0]=0;
comp_value[1]=1; comp_value[2]=1; comp_value[3]=1;
comp_value[4]=0; comp_value[5]=1; comp_value[6]=0;
}else if(strcmp(comp_literal,"D")==0){
comp_value[0]=0;
comp_value[1]=0; comp_value[2]=0; comp_value[3]=1;
comp_value[4]=1; comp_value[5]=0; comp_value[6]=0;
}else if(strcmp(comp_literal,"!D")==0){
comp_value[0]=0;
comp_value[1]=0; comp_value[2]=0; comp_value[3]=1;
comp_value[4]=1; comp_value[5]=0; comp_value[6]=1;
}else if(strcmp(comp_literal,"-D")==0){
comp_value[0]=0;
comp_value[1]=0; comp_value[2]=0; comp_value[3]=1;
comp_value[4]=1; comp_value[5]=1; comp_value[6]=1;
}else if(strcmp(comp_literal,"D+1")==0){
comp_value[0]=0;
comp_value[1]=0; comp_value[2]=1; comp_value[3]=1;
comp_value[4]=1; comp_value[5]=1; comp_value[6]=1;
}else if(strcmp(comp_literal,"D-1")==0){
comp_value[0]=0;
comp_value[1]=0; comp_value[2]=0; comp_value[3]=1;
comp_value[4]=1; comp_value[5]=1; comp_value[6]=0;
}else if((strcmp(comp_literal,"A")==0) || (strcmp(comp_literal,"M")==0)){
//Check if a=0
if(strcmp(comp_literal,"A")==0){
comp_value[0]=0;
comp_value[1]=1; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=0; comp_value[6]=0;
}
//Check if a=1
if(strcmp(comp_literal,"M")==0){
comp_value[0]=1;
comp_value[1]=1; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=0; comp_value[6]=0;
}
}else if((strcmp(comp_literal,"!A")==0) || (strcmp(comp_literal,"!M")==0)){
//Check if a=0
if(strcmp(comp_literal,"!A")==0){
comp_value[0]=0;
comp_value[1]=1; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=0; comp_value[6]=1;
}
//Check if a=1
if(strcmp(comp_literal,"!M")==0){
comp_value[0]=1;
comp_value[1]=1; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=0; comp_value[6]=1;
}
}else if((strcmp(comp_literal,"-A")==0) || (strcmp(comp_literal,"-M")==0)){
//Check if a=0
if(strcmp(comp_literal,"-A")==0){
comp_value[0]=0;
comp_value[1]=1; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=1; comp_value[6]=1;
}
//Check if a=1
if(strcmp(comp_literal,"-M")==0){
comp_value[0]=1;
comp_value[1]=1; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=1; comp_value[6]=1;
}
}else if((strcmp(comp_literal,"A+1")==0) || (strcmp(comp_literal,"M+1")==0)){
//Check if a=0
if(strcmp(comp_literal,"A+1")==0){
comp_value[0]=0;
comp_value[1]=1; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=1; comp_value[5]=1; comp_value[6]=1;
}
//Check if a=1
if(strcmp(comp_literal,"M+1")==0){
comp_value[0]=1;
comp_value[1]=1; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=1; comp_value[5]=1; comp_value[6]=1;
}
}else if((strcmp(comp_literal,"A-1")==0) || (strcmp(comp_literal,"M-1")==0)){
//Check if a=0
if(strcmp(comp_literal,"A-1")==0){
comp_value[0]=0;
comp_value[1]=1; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=1; comp_value[6]=0;
}
//Check if a=1
if(strcmp(comp_literal,"M-1")==0){
comp_value[0]=1;
comp_value[1]=1; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=1; comp_value[6]=0;
}
}else if((strcmp(comp_literal,"D+A")==0) || (strcmp(comp_literal,"D+M")==0)){
//Check if a=0
if(strcmp(comp_literal,"D+A")==0){
comp_value[0]=0;
comp_value[1]=0; comp_value[2]=0; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=1; comp_value[6]=0;
}
//Check if a=1
if(strcmp(comp_literal,"D+M")==0){
comp_value[0]=1;
comp_value[1]=0; comp_value[2]=0; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=1; comp_value[6]=0;
}
}else if((strcmp(comp_literal,"D-A")==0) || (strcmp(comp_literal,"D-M")==0)){
//Check if a=0
if(strcmp(comp_literal,"D-A")==0){
comp_value[0]=0;
comp_value[1]=0; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=1; comp_value[6]=1;
}
//Check if a=1
if(strcmp(comp_literal,"D-M")==0){
comp_value[0]=1;
comp_value[1]=0; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=1; comp_value[6]=1;
}
}else if((strcmp(comp_literal,"A-D")==0) || (strcmp(comp_literal,"M-D")==0)){
//Check if a=0
if(strcmp(comp_literal,"A-D")==0){
comp_value[0]=0;
comp_value[1]=0; comp_value[2]=0; comp_value[3]=0;
comp_value[4]=1; comp_value[5]=1; comp_value[6]=1;
}
//Check if a=1
if(strcmp(comp_literal,"M-D")==0){
comp_value[0]=1;
comp_value[1]=0; comp_value[2]=0; comp_value[3]=0;
comp_value[4]=1; comp_value[5]=1; comp_value[6]=1;
}
}else if((strcmp(comp_literal,"D&A")==0) || (strcmp(comp_literal,"D&M")==0)){
//Check if a=0
if(strcmp(comp_literal,"D&A")==0){
comp_value[0]=0;
comp_value[1]=0; comp_value[2]=0; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=0; comp_value[6]=0;
}
//Check if a=1
if(strcmp(comp_literal,"D&M")==0){
comp_value[0]=1;
comp_value[1]=0; comp_value[2]=0; comp_value[3]=0;
comp_value[4]=0; comp_value[5]=0; comp_value[6]=0;
}
}else if((strcmp(comp_literal,"D|A")==0) || (strcmp(comp_literal,"D|M")==0)){
//Check if a=0
if(strcmp(comp_literal,"D|A")==0){
comp_value[0]=0;
comp_value[1]=0; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=1; comp_value[5]=0; comp_value[6]=1;
}
//Check if a=1
if(strcmp(comp_literal,"D|M")==0){
comp_value[0]=1;
comp_value[1]=0; comp_value[2]=1; comp_value[3]=0;
comp_value[4]=1; comp_value[5]=0; comp_value[6]=1;
}
}else{
//there is a mistake in provided machine code ...
printf("There is an error shame : stage 3 part 1: setting comp , a=0\n");
printf("inst : %s\n",instruction);
}
//set the final ,Array of instruction yes yes
final[0]=1;final[1]=1;final[2]=1;
//set comp first
int a;
for(a=0;a<7;++a){
final[a+3]=comp_value[a];
}
//set dest second
int b;
for(b=0;b<3;++b){
final[b+10]=dest_value[b];
}
int c;
for(c=0;c<3;++c){
final[c+13]=jump_value[c];
}
//Done this function returns nothing yes yes
//function that does magic here ...yeah yeah yeah
}
/*
getInstructionType : returns type
//Determine instruction type
//type 1 dest=comp;jump
//type 2 dest=comp
//type 3 comp;jump
*/
int getInstructionType(char instruction[],int n){
int i,nequal,ncolon;
nequal=ncolon=0;
for(i=0;i<n;++i){
if(instruction[i]=='='){
++nequal;
}
if(instruction[i]==';'){
++ncolon;
}
}//end of for(){} ....
if(nequal==1 && ncolon==1){
return 1;
}else if(nequal==1 && ncolon==0){
return 2;
}else if(nequal==0 && ncolon==1){
return 3;
}else{
return 0;
}//end of if.;l
}
<file_sep># Hack-Assembler
An assembler for the hack machine language
|
688b9a3a5f233c6d63298adbbbb702459c115f16
|
[
"Markdown",
"C"
] | 2 |
C
|
brianzhou139/Hack-Assembler
|
b500706f2a7c083e8a922c4c6afaf0c7d6e500d5
|
1ee9406ca8b4e4565d742b8c03a66dcead11752b
|
refs/heads/master
|
<repo_name>anasjaber/tesseract<file_sep>/Tesseract.Tests/EngineTests.cs
using System;
using NUnit.Framework;
namespace Tesseract.Tests
{
[TestFixture]
public class EngineTests
{
[Test]
public void Initialise_ShouldStartEngine()
{
using(var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default)) {
}
}
[Test]
public void CanParseText()
{
using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default)) {
using(var img = Pix.LoadFromFile("./phototest.tiff")) {
using(var page = engine.Process(img)) {
var text = page.GetText();
Assert.That(text, Is.EqualTo(""));
}
}
}
}
}
}
|
94771390ccaefaf35b043a72556718ab420e903b
|
[
"C#"
] | 1 |
C#
|
anasjaber/tesseract
|
3c074bda1b1cab27defc173e62eace45c2ff8680
|
a1366d3088aa9b7fa76835818886dbff62641f89
|
refs/heads/master
|
<file_sep>class Listing
attr_accessor :city
@@all = []
def initialize(city)
@city=city
@@all << self
end
def trips
Trip.all.select{|trip| trip.listing==self}
end
def guests
trips.map{|trip| trip.guest}.uniq
end
def trip_count
trips.count
end
def self.all
@@all
end
def self.find_all_by_city(city)
@@all.select{|listing| listing.city==city}
end
def self.most_popular
@@all.max{|listinga, listingb| listinga.trip_count <=> listingb.trip_count}
end
end
class Guest
attr_accessor :name
@@all = []
def initialize(name)
@name=name
@@all << self
end
def listings
trips.map{|trip| trip.listing}.uniq
end
def trips
Trip.all.select{|trip| trip.guest==self}
end
def trip_count
trips.count
end
def self.all
@@all
end
def self.pro_traveler
@@all.each_with_object([]) do |guest, pro_array|
if guest.trip_count>1
pro_array << guest
end
end
end
def self.find_all_by_name(name)
@@all.select{|guest| guest.name==name}
end
end
class Trip
attr_accessor :guest, :listing
@@all = []
def initialize(guest, listing)
@guest=guest
@listing=listing
@@all << self
end
def self.all
@@all
end
end<file_sep>require_relative '../config/environment.rb'
def reload
load 'config/environment.rb'
end
#Airbnb
# nyc1=Listing.new("New York")
# nyc2=Listing.new("New York")
# cali=Listing.new("San Diego")
# james=Guest.new("James")
# jeanne=Guest.new("Jeanne")
# ada=Guest.new("Ada")
# soren=Guest.new("Soren")
# james2=Guest.new("James")
# trip1=Trip.new(james, nyc1)
# trip2=Trip.new(james, cali)
# trip3=Trip.new(jeanne, nyc2)
# trip4=Trip.new(jeanne, nyc2)
# trip5=Trip.new(ada, cali)
# trip6=Trip.new(soren, nyc2)
# bakery
# bakery1=Bakery.new("Sunshine")
# bakery2=Bakery.new("By the Way")
# bakery3=Bakery.new("Cakes and More")
# cake1=Dessert.new("Chocolate Cake", bakery1)
# cake2=Dessert.new("Lemon Cake", bakery1)
# cake3=Dessert.new("Coconut Cake", bakery2)
# cake4=Dessert.new("Banana Cake", bakery3)
# flour1=Ingredient.new("Flour", 150, cake1)
# flour2=Ingredient.new("Flour", 150, cake2)
# flour3=Ingredient.new("Flour", 150, cake3)
# flour4=Ingredient.new("Flour", 150, cake4)
# oil1=Ingredient.new("Coconut Oil", 300, cake3)
# oil2=Ingredient.new("Olive Oil", 250, cake2)
# egg=Ingredient.new("Eggs", 310, cake3)
# sugar=Ingredient.new("Sugar", 100, cake4)
# lyft
# pass1=Passenger.new("James")
# pass2=Passenger.new("Jeanne")
# pass3=Passenger.new("Ada")
# pass4=Passenger.new("Soren")
# driv1=Driver.new("Aleks")
# driv2=Driver.new("Teddy")
# driv3=Driver.new("Ginny")
# driv4=Driver.new("David")
# trip1=Ride.new(pass1, driv2, 14.3)
# trip2=Ride.new(pass2, driv2, 117.3)
# trip3=Ride.new(pass3, driv1, 35.8)
# trip4=Ride.new(pass4, driv3, 44.4)
# trip5=Ride.new(pass4, driv3, 450.1)
# trip6=Ride.new(pass4, driv4, 3.8)
# imdb
# actor1=Actor.new("<NAME>")
# actor2=Actor.new("<NAME>")
# actor3=Actor.new("<NAME>")
# actor4=Actor.new("<NAME>")
# actor5=Actor.new("<NAME>")
# actor6=Actor.new("<NAME>")
# actor7=Actor.new("<NAME>")
# movie1=Movie.new("Avengers")
# movie2=Movie.new("Rom Com")
# show1=Show.new("Avengers")
# show2=Show.new("Game of Thrones")
# show3=Show.new("The Good Place")
# char1=Character.new("Iron Man", actor2)
# char2=Character.new("The Thing", actor3)
# char3=Character.new("Thanos", actor4)
# char4=Character.new("Captain America", actor5)
# char5=Character.new("<NAME>", actor1)
# char6=Character.new("<NAME>", actor6)
# char7=Character.new("Roger", actor7)
# char8=Character.new("Dean", actor2)
# char9=Character.new("Tyrian", actor2)
# char10=Character.new("<NAME>", actor5)
# char11=Character.new("Arya", actor1)
# char12=Character.new("Michael", actor3)
# char13=Character.new("Spiderman", actor7)
# app1=Appearance.new(char1, movie1)
# app2=Appearance.new(char2, movie1)
# app3=Appearance.new(char3, movie1)
# app4=Appearance.new(char4, movie1)
# app5=Appearance.new(char5, movie1)
# app6=Appearance.new(char6, movie1)
# app7=Appearance.new(char7, movie2)
# app8=Appearance.new(char8, movie2)
# app9=Appearance.new(char1, show1)
# app10=Appearance.new(char4, show1)
# app11=Appearance.new(char5, show1)
# app12=Appearance.new(char13, show1)
# app13=Appearance.new(char9, show2)
# app14=Appearance.new(char10, show2)
# app15=Appearance.new(char11, show2)
# app16=Appearance.new(char12, show3)
# app17=Appearance.new(char1, show2)
# crowdfund
# user1=User.new("James")
# user2=User.new("Jeanne")
# user3=User.new("Ada")
# user4=User.new("Soren")
# user5=User.new("Nika")
# user6=User.new("David")
# user7=User.new("Ginny")
# project1=Project.new("Album", user1, 10000)
# project2=Project.new("Movie", user4, 100000)
# project3=Project.new("Software", user2, 300000)
# project4=Project.new("Invention", user5, 400000)
# pledge1=Pledge.new(user2, project1, 6000)
# pledge2=Pledge.new(user5, project1, 7000)
# pledge3=Pledge.new(user1, project2, 15000)
# pledge4=Pledge.new(user1, project3, 15001)
# pledge5=Pledge.new(user3, project2, 8000)
# pledge6=Pledge.new(user4, project3, 65)
# pledge7=Pledge.new(user2, project2, 100)
# gym
gym1=Location.new("Downtown")
gym2=Location.new("Uptown")
gym3=Location.new("Westchester")
client1=Client.new("Carl")
client2=Client.new("Cara")
client3=Client.new("Clarissa")
client4=Client.new("Clarke")
client5=Client.new("Connor")
client6=Client.new("Colin")
trainer1=Trainer.new("Tom")
trainer2=Trainer.new("Tracy")
trainer3=Trainer.new("Tara")
trainer4=Trainer.new("Timothy")
trainer1.start_training(client1)
trainer1.start_training(client2)
trainer1.start_training(client3)
trainer2.start_training(client4)
trainer3.start_training(client5)
trainer4.start_training(client6)
trainer1.works_at(gym1)
trainer2.works_at(gym2)
trainer3.works_at(gym3)
trainer4.works_at(gym2)
Pry.start
0<file_sep>class User
attr_accessor :name
@@all = []
def initialize(name)
@name=name
@@all << self
end
def pledges
Pledge.all.select{|pledge| pledge.user==self}
end
def backed_projects
pledges.map{|pledge| pledge.project}.uniq
end
def created_projects
Project.all.select{|project| project.creator==self}
end
def self.all
@@all
end
def self.highest_pledge
Pledge.all.max{|pledge1, pledge2| pledge1.amount <=> pledge2.amount}.user
end
def self.multi_pledger
@@all.select{|user| user.pledges.length>1}
end
def self.project_creator
@@all.select{|user| user.created_projects.length>=1}
end
end
class Project
attr_accessor :name, :creator, :goal
@@all = []
def initialize(name, creator, goal)
@name=name
@creator=creator
@goal=goal
@@all << self
end
def pledges
Pledge.all.select{|pledge| pledge.project==self}
end
def backers
pledges.map{|pledge| pledge.user}.uniq
end
def self.all
@@all
end
def pledge_value
pledges.reduce(0){|total, pledge| total+=pledge.amount}
end
def self.no_pledges
@@all.select{|project| project.pledges.length==0}
end
def self.above_goal
@@all.select{|project| project.pledge_value>=project.goal}
end
def self.most_backers
@@all.max{|project1, project2| project1.backers.length <=> project2.backers.length}
end
end
class Pledge
attr_accessor :user, :project, :amount
@@all = []
def initialize(user, project, amount)
@user=user
@project=project
@amount=amount
@@all << self
end
def self.all
@@all
end
end<file_sep>class Bakery
attr_accessor :name
@@all = []
def initialize(name)
@name=name
@@all << self
end
def desserts
Dessert.all.select{|dessert| dessert.bakery==self}
end
def ingredients
desserts.map{|dessert| dessert.ingredients}.flatten
end
def average_calories #is this violating single purpose principle?
total=desserts.reduce(0){|total, dessert| total+=dessert.calories}
total/desserts.length
end
def shopping_list
ingredients.map{|ingredient| ingredient.name}
end
def self.all
@@all
end
end
class Dessert
attr_accessor :name, :bakery
@@all = []
def initialize(name, bakery)
@name=name
@bakery=bakery
@@all << self
end
def ingredients
Ingredient.all.select{|ingredient| ingredient.dessert==self}
end
def calories
ingredients.reduce(0){|total, ingredient| total+=ingredient.calories}
end
def self.all
@@all
end
end
class Ingredient
attr_accessor :name, :dessert, :calories
@@all = []
def initialize(name, calories, dessert)
@name=name
@calories=calories
@dessert=dessert
@@all << self
end
def bakery
dessert.bakery
end
def self.all
@@all
end
def self.find_all_by_name(ingredient_name) ## contains string, not exact match
@@all.select{|ingredient| ingredient.name.include?(ingredient_name)}
end
end<file_sep>## I think I'm having some logic flaws regarding relationships between client and Location, and how to calculate which location has the least clients
class Trainer
attr_reader :name
@@all = []
def initialize(name)
@name=name
@@all << self
end
def start_training(client)
client.assign_trainer(self)
end
def clients
Client.all.select{|client| client.trainer==self}
end
def worksites
WorkSite.all.select{|worksite| worksite.trainer==self}
end
def locations
worksites.map{|worksite| worksite.location}.uniq
end
def works_at(location)
WorkSite.new(self, location)
end
def self.all
@@all
end
def self.most_clients
@@all.max{|trainer1, trainer2| trainer1.clients.length <=> trainer2.clients.length}
end
end
class Location
attr_reader :name
@@all = []
def initialize(name)
@name=name
@@all << self
end
def worksites
WorkSite.all.select{|worksite| worksite.location==self}
end
def trainers
worksites.map{|worksite| worksite.trainer}.uniq
end
def self.all
@@all
end
def clients
trainers.map{|trainer| trainer.clients}.flatten
end
def self.least_clients
@@all.min{|loc1, loc2|loc1.clients.length <=> loc2.clients.length}
end
end
class WorkSite # joiner class for Trainer and Location
attr_reader :trainer, :location
@@all = []
def initialize(trainer, location)
@trainer=trainer
@location=location
@@all << self
end
def self.all
@@all
end
end
class Client
attr_reader :name, :trainer
@@all = []
def initialize(name)
@name=name
@@all << self
end
def assign_trainer(trainer)
@trainer=trainer
end
def self.all
@@all
end
end
<file_sep>class Movie
attr_accessor :name
@@all=[]
def initialize(name)
@name=name
@@all << self
end
def self.all
@@all
end
def appearances # returns all the appearances for this show
Appearance.all.select{|app| app.project==self}
end
def characters # returns all the characters in the movie
appearances.map{|app| app.character}
end
def actors # returns all the actors in a movie
characters.map{|character| character.actor}
end
def self.most_actors
@@all.max{|movie1, movie2| movie1.actors.length <=> movie2.actors.length}
end
end
class Show #basically same as Movie class with different requested methods
attr_accessor :name
@@all=[]
def initialize(name)
@name=name
@@all << self
end
def self.all
@@all
end
def appearances # returns all the appearances for this show
Appearance.all.select{|app| app.project==self}
end
def characters # returns all the characters in the movie
appearances.map{|app| app.character}.uniq
end
def actors # returns all the actors in a movie
characters.map{|character| character.actor}
end
def self.most_actors
@@all.max{|movie1, movie2| movie1.actors.length <=> movie2.actors.length}
end
def on_the_big_screen
Movie.all.select{|movie| movie.name==self.name}
end
end
class Character
attr_accessor :name, :actor
@@all = []
def initialize(name, actor)
@name=name
@actor=actor
@@all << self
end
def appearances # returns all movies+shows in array
Appearance.all.select{|appearance| appearance.character==self}
end
def self.most_appearances
@@all.max{|character1, character2| character1.appearances.length <=> character2.appearances.length}
end
def self.all
@@all
end
end
class Appearance #joiner class bringing together Movie/Show and Character
attr_accessor :name, :character, :project
@@all = []
def initialize(character, project)
@character=character
@project=project
@@all << self
end
def self.all
@@all
end
end
class Actor
attr_accessor :name
@@all = []
def initialize(name)
@name=name
@@all << self
end
def characters # all characters portrayed by actor
Character.all.select{|character| character.actor==self}
end
def self.all
@@all
end
def self.most_characters
@@all.max{|actor1, actor2| actor1.characters.length <=> actor2.characters.length}
end
end
<file_sep>class Passenger
attr_accessor :name
@@all = []
def initialize(name)
@name=name
@@all << self
end
def rides
Ride.all.select{|ride| ride.passenger==self}
end
def drivers
rides.map {|ride| ride.driver}.uniq
end
def total_distance
rides.reduce(0) {|distance, ride| distance+=ride.distance}
end
def self.all
@@all
end
def self.premium_members
@@all.select {|passenger| passenger.total_distance>100.0}
end
end
class Driver
attr_accessor :name
@@all = []
def initialize(name)
@name=name
@@all << self
end
def rides
Ride.all.select{|ride| ride.driver==self}
end
def passengers
rides.map{|ride| ride.passenger}.uniq
end
def self.all
@@all
end
def total_distance
rides.reduce(0){|distance, ride| distance+=ride.distance}
end
def self.mileage_cap(distance)
@@all.select{|driver| driver.total_distance>distance}
end
end
class Ride
attr_accessor :distance, :driver, :passenger
@@all = []
def initialize(passenger, driver, distance)
@passenger=passenger
@driver=driver
@distance=distance
@@all << self
end
def self.average_distance
@@all.reduce(0){|total, ride| total+=ride.distance}/@@all.length
end
def self.all
@@all
end
end
|
c6849714c35594d292f319fb67a83c6cb970a02b
|
[
"Ruby"
] | 7 |
Ruby
|
edensongjbs/ruby-oo-practice-relationships-domains-yale-web-yss-052520
|
a68deaef4fa0847fa4962b09e708892457c73d86
|
5c937b979097cc0c19aa88a3226920acf7b1729b
|
refs/heads/master
|
<file_sep># exercise_5.rb
require 'net/http'
require 'open-uri'
require 'nokogiri'
require 'hpricot'
TEST_EXPRESSION = /\bthe\b/i
PAGE_URL = "http://satishtalim.github.com/webruby/chapter3.html"
def count_matches(text_to_match)
text_to_match.scan(TEST_EXPRESSION).size
end
def output_expression_matches(text, library)
count = count_matches(text)
puts "Lbrary #{library} gives #{count} matches."
end
def using_uri
url = URI.parse(PAGE_URL)
Net::HTTP.start(url.host, url.port) do |http|
req = Net::HTTP::Get.new(url.path)
text = http.request(req).body
output_expression_matches(text, "URI")
end
end
def using_open_uri
f = open(PAGE_URL)
output_expression_matches(f.readlines.join, "Open-URI")
end
def using_hpricot
page = Hpricot(open(PAGE_URL))
output_expression_matches(page.inner_text, "Hpricot")
end
def using_nokogiri
doc = Nokogiri::HTML(open(PAGE_URL))
output_expression_matches(doc.inner_text, "Nokogiri")
end
using_uri
using_open_uri
using_hpricot
using_nokogiri<file_sep># nethpcot.rb
require 'open-uri'
require 'hpricot'
page = Hpricot(open('http://rubylearning.com'))
puts "Page title is: #{page.at(:title).inner_html}"
|
1b6d18ad652a121106570297f51e17f6b40afc97
|
[
"Ruby"
] | 2 |
Ruby
|
kryptykphysh/my_ruby_programs
|
8aff3ff1bae752aefbf23d2bc7ab498cc3c92acf
|
2cc0c588bdaa0e526c4c3c2707bd8ae1d11bbeea
|
refs/heads/main
|
<repo_name>rchlkr/restaurant-page<file_sep>/src/showMenu.js
const showMenu = () => {
let infoDiv = document.getElementById("infodiv");
let contactTab = document.getElementById("contact");
let tabDiv = document.getElementById("tabdiv");
let contentDiv = document.getElementById("contentdiv");
const menuDiv = document.createElement("div");
const menuContent = document.createElement("div");
infoDiv.appendChild(menuDiv);
menuDiv.appendChild(menuContent);
menuDiv.id = "menudiv";
contentDiv.style.backgroundColor = "hsla(0, 0%, 0%, 0.6)";
infoDiv.style.backgroundColor = "hsla(0, 0%, 0%, 0)";
contentDiv.style.zIndex = "10";
contentDiv.style.position = "relative";
infoDiv.style.top = "0";
infoDiv.style.paddingTop = "2.5rem";
menuDiv.style.display = "flex";
menuDiv.style.width = "100%";
menuDiv.style.height = "72%";
menuDiv.style.position = "fixed";
menuDiv.style.bottom = "2.3rem";
menuDiv.style.justifyContent = "center";
menuDiv.style.alignItems = "center";
menuDiv.style.backgroundColor = "transparent";
menuContent.style.backgroundColor = "white";
menuContent.style.width = "30%";
menuContent.style.height = "60%";
menuContent.style.overflow = "scroll";
menuContent.style.fontFamily = "Staatliches";
menuContent.style.color = "hsla(0, 0%, 20%, 1)";
menuContent.style.fontSize = "2rem";
menuContent.style.textAlign = "center";
menuContent.style.padding = "1rem 6rem 1rem 6rem";
menuContent.innerHTML =
"dinner salads<br><br><p style='font-size:1.2rem'>the standard</p><p style='font-family:raleway;font-size:0.8rem'>garbanzo beans, adzuki beans, alfalfa sprouts, sunflower seeds & heirloom tomatoes on a bed of leafy romaine & tossed in a lemon herb vinaigrette</p><br><p style='font-size:1.2rem'>the chef</p><p style='font-family:raleway;font-size:0.8rem'>hard-boiled egg, heirloom tomato, hemp hearts, artichoke hearts & avocado on a bed of spring mix & tossed in a creamy poppyseed dressing</p><br><p style='font-size:1.2rem'>the taco</p><p style='font-family:raleway;font-size:0.8rem'>black beans, kidney beans, white corn, flax seeds & gaucamole on a bed of romaine hearts & tossed in a zesty southwest vinaigrette</p>";
let menuTab = document.getElementById("menu");
tabDiv.style.backgroundColor = "hsla(0, 0%, 0%, 0)";
menuTab.style.backgroundColor = "hsla(0, 0%, 0%, 0.7)";
contactTab.style.backgroundColor = "hsla(0, 0%, 0%, 0)";
};
export default showMenu;
<file_sep>/src/index.js
import populatePage from "./populatePage";
import showMenu from "./showMenu";
import showContact from "./showContact";
window.onLoad = populatePage();
let toggleMenu = document.getElementById("menu");
let toggleContact = document.getElementById("contact");
let infoDiv = document.getElementById("infodiv");
toggleMenu.addEventListener("click", function () {
infoDiv.removeChild(infoDiv.childNodes[1]);
showMenu();
});
toggleContact.addEventListener("click", function () {
infoDiv.removeChild(infoDiv.childNodes[1]);
showContact();
});
/*
window.onLoad = populatePage();
let toggleMenu = document.getElementById("menu");
let toggleContact = document.getElementById("contact");
let infoDiv = document.getElementById("infodiv");
toggleMenu.addEventListener("click", function () {
infoDiv.removeChild(infoDiv.childNodes[1]);
showMenu();
});
toggleContact.addEventListener("click", function () {
infoDiv.removeChild(infoDiv.childNodes[1]);
showContact();
});
*/
<file_sep>/src/populatePage.js
const populatePage = () => {
document.body.style.margin = "0";
document.body.style.padding = "0";
document.body.style.height = "100vh";
document.body.style.fontSize = "16px";
document.body.style.boxSizing = "border-box";
document.body.style.backgroundImage =
"url('https://images.pexels.com/photos/2615407/pexels-photo-2615407.jpeg')";
document.body.style.backgroundSize = "100% auto";
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundPosition = "center bottom 30%";
const contentDiv = document.getElementById("content");
const infoDiv = document.createElement("div");
const header = document.createElement("header");
const blurb = document.createElement("article");
contentDiv.appendChild(infoDiv);
infoDiv.appendChild(header);
infoDiv.appendChild(blurb);
contentDiv.id = "contentdiv";
infoDiv.id = "infodiv";
header.id = "header";
blurb.id = "blurb";
contentDiv.style.clear = "both";
contentDiv.style.position = "relative";
contentDiv.style.zIndex = "10";
contentDiv.style.height = "calc(100% - 2.3rem)";
contentDiv.style.marginBottom = "2rem";
infoDiv.style.backgroundColor = "hsla(0, 0%, 0%, 0.5)";
infoDiv.style.paddingTop = "2.5rem";
infoDiv.style.paddingBottom = "1rem";
infoDiv.style.width = "100%";
header.style.fontFamily = "Staatliches";
header.style.position = "relative";
header.style.color = "white";
header.style.fontSize = "5rem";
header.style.textAlign = "center";
header.style.overflow = "hidden";
header.style.height = "auto";
blurb.style.fontFamily = "Raleway";
blurb.style.fontWeight = "500";
blurb.style.color = "white";
blurb.style.fontSize = "1.2rem";
blurb.style.textAlign = "center";
header.textContent = "leaf garden cafe";
blurb.innerHTML =
"ultra healthy power salads overflowing<br>with interesting ingredients sourced from local farms";
const tabDiv = document.createElement("div");
const menuTab = document.createElement("button");
const menuTabText = document.createTextNode("menu");
const contactTab = document.createElement("button");
const contactTabText = document.createTextNode("contact");
document.body.appendChild(tabDiv);
menuTab.appendChild(menuTabText);
tabDiv.appendChild(menuTab);
contactTab.appendChild(contactTabText);
tabDiv.appendChild(contactTab);
tabDiv.style.display = "inline-block";
tabDiv.style.backgroundColor = "hsla(0, 0%, 0%, 0.5)";
tabDiv.style.zIndex = "20";
tabDiv.style.position = "fixed";
tabDiv.style.bottom = "0";
tabDiv.style.width = "100%";
tabDiv.style.textAlign = "center";
tabDiv.id = "tabdiv";
menuTab.style.border = "none";
menuTab.style.background = "none";
menuTab.style.fontFamily = "Staatliches";
menuTab.style.fontSize = "1.5rem";
menuTab.style.color = "white";
menuTab.style.padding = "0.45rem 1rem 0 1rem";
menuTab.style.cursor = "pointer";
menuTab.id = "menu";
contactTab.style.border = "none";
contactTab.style.background = "none";
contactTab.style.fontFamily = "Staatliches";
contactTab.style.fontSize = "1.5rem";
contactTab.style.color = "white";
contactTab.style.padding = "0.45rem 1rem 0 1rem";
contactTab.style.cursor = "pointer";
contactTab.id = "contact";
};
export default populatePage;
<file_sep>/src/showContact.js
const showContact = () => {
let infoDiv = document.getElementById("infodiv");
let menuTab = document.getElementById("menu");
let tabDiv = document.getElementById("tabdiv");
let contentDiv = document.getElementById("contentdiv");
const contactDiv = document.createElement("div");
const contactContent = document.createElement("div");
infoDiv.appendChild(contactDiv);
contactDiv.appendChild(contactContent);
contactDiv.id = "contactdiv";
contentDiv.style.backgroundColor = "hsla(0, 0%, 0%, 0.6)";
infoDiv.style.backgroundColor = "hsla(0, 0%, 0%, 0)";
contentDiv.style.zIndex = "10";
contentDiv.style.position = "relative";
infoDiv.style.top = "0";
infoDiv.style.paddingTop = "2.5rem";
contactDiv.style.display = "flex";
contactDiv.style.width = "100%";
contactDiv.style.height = "72%";
contactDiv.style.position = "fixed";
contactDiv.style.bottom = "2.3rem";
contactDiv.style.justifyContent = "center";
contactDiv.style.alignItems = "center";
contactDiv.style.backgroundColor = "transparent";
contactContent.style.backgroundColor = "white";
contactContent.style.width = "30%";
contactContent.style.height = "60%";
contactContent.style.overflow = "scroll";
contactContent.style.fontFamily = "Staatliches";
contactContent.style.color = "hsla(0, 0%, 20%, 1)";
contactContent.style.fontSize = "2rem";
contactContent.style.textAlign = "center";
contactContent.style.padding = "1rem 6rem 1rem 6rem";
contactContent.innerHTML =
"location<br><p style=font-family:raleway;font-size:1.2rem>15 Shropshire Ln<br>Milbridge, ME 04658<br>(222) 214-3590</p><img src='media/map.jpg'>";
let contactTab = document.getElementById("contact");
tabDiv.style.backgroundColor = "hsla(0, 0%, 0%, 0)";
contactTab.style.backgroundColor = "hsla(0, 0%, 0%, 0.7)";
menuTab.style.backgroundColor = "hsla(0, 0%, 0%, 0)";
};
export default showContact;
<file_sep>/README.md
# a mock restaurant page
### using ES6 modules, webpack & npm
each tab is a stand-alone module imported into the main JS file.
the main JS file only contains event listeners for tab-switching functionality.
created entirely in JavaScript, including styling _(not fun)_
|
32fecca2007bc9e79439656cd33ac2f4be7bcafb
|
[
"JavaScript",
"Markdown"
] | 5 |
JavaScript
|
rchlkr/restaurant-page
|
d88c83777237a5bfea28fc6e034cfbabf5014ebf
|
afef90027f7a5535b850b76322ea7deeee97dd23
|
refs/heads/master
|
<file_sep>import { Component } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import {TranslateService} from '@ngx-translate/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
title = 'CNAMproject';
color = 'primary';
mode = 'determinate';
value = 50;
constructor(private translate: TranslateService) {
translate.setDefaultLang('fr');
}
}
|
d4cb07fcd0b54ac5ffc02b6397c85a34a89e663a
|
[
"TypeScript"
] | 1 |
TypeScript
|
SkillsAreImba/Frontend
|
6c090e68409132f335518b08b3a491f1b43aa83c
|
0718d159e29c6d664d7e10b3a27c4c23a6501cae
|
refs/heads/master
|
<repo_name>phantacix/go-xserver<file_sep>/wsl.sh
#!/bin/bash
set -e
CUR_DIR=$PWD
SRC_DIR=$PWD
BIN_DIR=$PWD/bin
CONF_DIR=$PWD/config
case $1 in
"start")
mkdir -p $CONF_DIR
ln -sf $SRC_DIR/common/config/framework.toml $CONF_DIR/
ln -sf $SRC_DIR/default_plugins/login/login.toml $CONF_DIR/
cd $BIN_DIR
mkdir -p $BIN_DIR/logs
mkdir -p $BIN_DIR/logs.back
if [[ `ls -l ./logs | wc -l` > 1 ]]; then
mv -f ./logs/* ./logs.back/
fi
nohup ./go-xserver --app mgr --network-port '0,31000' --common-logflushinterval 200 > /dev/null 2>&1 &
nohup ./go-xserver --app login --network-port '7200,0' --common-logflushinterval 200 --suffix 1 > /dev/null 2>&1 &
nohup ./go-xserver --app login --network-port '7201,0' --common-logflushinterval 200 --suffix 2 > /dev/null 2>&1 &
nohup ./go-xserver --app login --network-port '7202,0' --common-logflushinterval 200 --suffix 3 > /dev/null 2>&1 &
nohup ./go-xserver --app gateway --network-port '7300,33000' --common-logflushinterval 200 --suffix 1 > /dev/null 2>&1 &
nohup ./go-xserver --app gateway --network-port '7301,33001' --common-logflushinterval 200 --suffix 2 > /dev/null 2>&1 &
nohup ./go-xserver --app gateway --network-port '7302,33002' --common-logflushinterval 200 --suffix 3 > /dev/null 2>&1 &
nohup ./go-xserver --app lobby --network-port '0,0' --common-logflushinterval 200 --suffix 1 > /dev/null 2>&1 &
nohup ./go-xserver --app lobby --network-port '0,0' --common-logflushinterval 200 --suffix 2 > /dev/null 2>&1 &
nohup ./go-xserver --app lobby --network-port '0,0' --common-logflushinterval 200 --suffix 3 > /dev/null 2>&1 &
nohup ./go-xserver --app match --network-port '0,0' --common-logflushinterval 200 --suffix 1 > /dev/null 2>&1 &
sleep 1s
ps -ux | grep go-xserver
exit 0
;;
"stop")
pkill go-xserver
sleep 5s
ps -ux | grep go-xserver
exit 0
;;
esac
echo "Usage:"
echo " wsl.sh start"
echo " wsl.sh stop"
cd $CUR_DIR
exit 0
<file_sep>/README.md
# go-xserver
**go-xserver 是一个 Golang 服务器框架(go-x.v2)**
致力于实现 1 个高可用、高易用的 Golang 服务器框架
并以插件的方式,来丰富框架内容
## 编译
- [安装 golang 1.12+](https://golang.google.cn/dl/)
- [安装 docker](https://docs.docker.com/install/linux/docker-ce/centos/)
- 编译执行以下语句即可:
```shell
./make.sh
```
- 【非必须】 Windows 10 下开发,请参考[在 Win10 中 Linux 环境搭建](doc/WIKI-在Win10中Linux环境搭建.md)
## 运行
- 安装 Redis ,并修改 config/config.toml 相关配置
- All In One 例子
```shell
./make.sh start
./make.sh stop
```
- Run In WSL 例子
```shell
./wsl.sh start
./wsl.sh stop
```
wsl 目前`监听同一个端口不报错`,详细请参考 issue : https://github.com/Microsoft/WSL/issues/2915
因此 wsl.sh 脚本中具体指定下 --network-port 参数
## 测试客户端
- [pyclient](https://github.com/fananchong/go-xclient/tree/master/pyclient)
## 缺省插件
- [go-xserver-plugins](https://github.com/fananchong/go-xserver-plugins)
- mgr
- login
- gateway
## v0.1
- 管理服务器
- 登陆服务器
- 网关服务器
- 客户端消息中继
- 服务器组内消息中继
- 大厅服务器
- 获取角色列表(登录大厅服务)
- 创建角色
- 获取角色详细信息(进入游戏)
- 登出游戏
- 角色聊天(世界聊天、私聊)
## v0.2
- 参考 micro/go-micro 改造框架层代码
- 服务发现重做,参考 micro/go-micro 提炼 接口,并默认支持 mdns
## WIKI
- [主体框架](doc/规范-代码框架.md)
- 配置模块
- [框架层配置](doc/规范-配置文件_框架层.md)
- [逻辑层配置](doc/规范-配置文件_逻辑层.md)
- [服务发现](doc/框架层功能-服务发现.md)
- [登陆模块](doc/框架层功能-登陆模块.md)
- [闲置连接处理](doc/框架层功能-闲置连接处理.md)
- [登出模块](doc/框架层功能-登出模块.md)
- [服务器组内互联](doc/规范-服务器架构.md)
## ISSUE
- [插件工程独立建库问题](doc/ISSUE-插件工程独立建库问题.md)
## 将要实现的功能
- 框架层功能
- 灰度更新
- 服务器健康监测
- 逻辑层功能
- 匹配服务
- 房间服务
- 压测工具
|
ce91de20d035eb40b6eeaa202b3c9881f6dc93d7
|
[
"Markdown",
"Shell"
] | 2 |
Shell
|
phantacix/go-xserver
|
1d597a0edd38dbb3dc80a4ede8af2229a0b22018
|
75b92da7f80c3747f6a406176f414151cefe1484
|
refs/heads/master
|
<file_sep>import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import library_functions as lf
except ModuleNotFoundError:
import project.library_functions as lf
def get_wiki_plots_figure():
pages_distribution = make_subplots(
rows=4,
cols=1,
subplot_titles=(
"Page Length (N. of Characters)",
"Amount of Links per Page",
"Amount of Synonyms (redirects) per Page",
"Amount of Categories per Page",
),
)
pages_distribution.add_trace(
go.Histogram(
x=lf.get_page_lengths(),
xbins_end=10000,
xbins_size=500,
hovertemplate=f"Length (N. of Characters): %{{x}} <br>Number of pages: %{{y}}",
),
row=1,
col=1,
)
# pages_distribution.update_xaxes(, row=1, col=1)
pages_distribution.add_trace(
go.Histogram(
x=lf.get_number_of_links(),
xbins_end=15,
hovertemplate=f"Amount of Links: %{{x}} <br>Number of pages: %{{y}}",
),
row=2,
col=1,
)
pages_distribution.add_trace(
go.Histogram(
x=lf.get_number_of_synonyms(),
xbins_end=20,
xbins_size=1,
hovertemplate=f"Amount of Synonyms (redirects): %{{x}} <br>Number of pages: %{{y}}",
),
row=3,
col=1,
)
pages_distribution.add_trace(
go.Histogram(
x=lf.get_number_of_categories(),
xbins_end=15,
xbins_size=1,
hovertemplate=f"Amount of Categories: %{{x}} <br>Number of pages: %{{y}}",
),
row=4,
col=1,
)
pages_distribution.update_layout(
margin={"l": 10, "r": 10, "t": 25, "b": 10},
xaxis={},
yaxis={},
showlegend=False,
clickmode="event+select",
height=650,
)
for annotation in pages_distribution.layout.annotations:
annotation.update(x=0.025, xanchor="left")
return pages_distribution
def get_reddit_plots_figure():
posts_distribution = make_subplots(
rows=2,
cols=1,
subplot_titles=(
"Post Length (N. of Characters)",
"Amount of Nootropics Mentions per Post",
),
)
posts_distribution.add_trace(
go.Histogram(
x=lf.get_post_lengths(),
xbins_end=2000,
hovertemplate=f"Length (N. of Characters): %{{x}} <br>Number of posts: %{{y}}",
),
row=1,
col=1,
)
# pages_distribution.update_xaxes(, row=1, col=1)
posts_distribution.add_trace(
go.Histogram(
x=lf.get_n_of_matches_per_post(),
xbins_end=15,
xbins_size=1,
hovertemplate=f"Amount of mentions: %{{x}} <br>Number of posts: %{{y}}",
),
row=2,
col=1,
)
posts_distribution.update_layout(
# margin={"l": 20, "r": 20, "t": 25, "b": 25},
xaxis={},
yaxis={},
showlegend=False,
clickmode="event+select",
height=650,
)
for annotation in posts_distribution.layout.annotations:
annotation.update(x=0.025, xanchor="left")
return posts_distribution<file_sep>import networkx as nx
import numpy as np
def shortest_path_length_distribution(G: nx.Graph,
as_probability_distribution=False):
all_shortest_path_lengths_dict = dict(nx.shortest_path_length(G))
number_of_nodes = G.number_of_nodes()
# Preallocate
shortest_path_lengths = np.zeros(number_of_nodes * (number_of_nodes - 1),
dtype=int)
index = 0
for target_node, shortest_path_from_source_dict \
in all_shortest_path_lengths_dict.items():
for source_node, shortest_path_length \
in shortest_path_from_source_dict.items():
if target_node != source_node:
shortest_path_lengths[index] = shortest_path_length
index += 1
bins = range(0, np.max(shortest_path_lengths) + 1)
path_length = bins[:-1]
distribution, _ = np.histogram(shortest_path_lengths, bins=bins)
if as_probability_distribution:
distribution = distribution / np.sum(distribution)
return path_length, distribution
<file_sep>from nltk import FreqDist
import numpy as np
from typing import Any
def term_frequency(terms: Any,
document: list,
type: str = 'raw count',
K=0.5):
return_dict = True
if terms is None:
terms = set(document)
elif isinstance(terms, str):
return_dict = False
terms = [terms]
if type.lower() == 'binary':
document_set = set(document)
result = {term: term in document_set
for term in terms}
else:
fd = FreqDist(document)
n_terms = fd.N()
if type.lower() == 'raw count':
result = {term: fd[term] for term in fd}
elif type.lower() == 'frequency':
result = {term: fd[term] / n_terms for term in terms}
elif type.lower() == 'log normalized':
result = {term: np.log10(1 + fd[term]) for term in terms}
elif type.lower() == 'double normalized K':
count_max_term = np.max(fd.values())
result = {term: K + (1 - K) * fd[term] / count_max_term
for term in terms}
else:
raise Exception('Unknown type: "' + type + '".')
if not return_dict:
result = result[terms[0]]
return result
<file_sep>import networkx as nx
import numpy as np
def betweenness(G: nx.Graph):
betweenness = nx.betweenness_centrality(G)
return np.fromiter(dict(betweenness).values(), dtype=float)
<file_sep>import nltk
def stress(pronunciation: nltk.Text):
return [character
for phoneme in pronunciation
for character in phoneme
if character.isdigit()]
<file_sep>from typing import List, Any, Union
from pathlib import Path
from tqdm.auto import tqdm
try:
import library_functions as lf
except ModuleNotFoundError:
import project.library_functions as lf
import networkx as nx
import numpy as np
import wojciech as w
def create_graph_reddit(
max_drugs_in_post: Union[int, np.int] = np.inf,
min_edge_occurrences_to_link: Union[int, np.int] = 1,
min_content_length_in_characters: Union[int, np.int] = 0,
conditional_functions_dict: Union[dict, Path] = None,
include_node_contents: bool = False,
include_link_contents: bool = False,
alternative_path: Union[str, Path] = None,
show_progress_bars: bool = False,
):
"""
Args:
max_drugs_in_post (int): a limit of the number of drugs in a post.
Posts containing more drugs will be
disregarded.
min_edge_occurrences_to_link (int): a limit describing the minimum
number times a link needs to appear
in order to be considered valid.
The links that occur less times will
be disregarded.
min_content_length_in_characters (int): a limit describing the minimum
length of the content of the
Reddit post. Posts with shorter
content will be disregarded.
conditional_functions_dict (dict): a dictionary keyed by attribute names
whose values are functions that
represent conditions for those
attributes, e.g.
{'polarity': lambda x: x > 0.1}
include_node_contents (bool): A boolean determining whether to assign
the content of the posts containing a
drug as a node attribute.
include_link_contents (bool): A boolean determining whether to assign
the content of the posts containing the
linked drugs as an edge attribute.
show_progress_bars (): A boolean deciding whether to show progress bars.
Returns:
Examples:
>>> g_reddit = create_graph_reddit(
>>> max_drugs_in_post=10,
>>> min_edge_occurrences_to_link=3,
>>> min_content_length_in_characters=25,
>>> conditional_functions_dict={'polarity': lambda x: x > 0.1},
>>> alternative_path=None,
>>> include_node_contents=False,
>>> include_link_contents=False
>>> )
"""
# Make sure that conditional_functions_dict is a dict
if conditional_functions_dict is None:
conditional_functions_dict = dict()
# Load the clean Reddit and Wiki data
drug_database_reddit = lf.load_data_reddit(alternative_path)
wiki_data = lf.load_data_wiki()
substance_names = lf.load_substance_names()
# Initialize graphs
g_reddit = nx.Graph()
g_reddit.add_nodes_from(substance_names)
# Assign node properties. Note thad we use drug names as nodes, and that
# the drug names are taken from Wikipedia
for index_drug, drug in enumerate(wiki_data["name"]):
if drug in g_reddit.nodes:
g_reddit.nodes[drug]["count"] = 0
g_reddit.nodes[drug]["polarity"] = []
g_reddit.nodes[drug]["subjectivity"] = []
g_reddit.nodes[drug]["contents"] = []
g_reddit.nodes[drug]["ids"] = []
g_reddit.nodes[drug]["categories"] = wiki_data["categories"][index_drug]
# Link drugs that appear in the same post
for post_id, reddit_post in tqdm(
list(drug_database_reddit.items()), disable=not show_progress_bars
):
# Disregard the post if the length of its content does not
# surpass the threshold
if len(reddit_post["content"]) < min_content_length_in_characters:
continue
# Link the drugs and assign link attributes
link_drugs(
G=g_reddit,
list_of_drugs=reddit_post["matches"],
polarity=reddit_post["polarity"],
subjectivity=reddit_post["subjectivity"],
text=reddit_post["title"] + " " + reddit_post["content"],
max_drugs_in_post=max_drugs_in_post,
conditional_functions_dict=conditional_functions_dict,
include_link_contents=include_link_contents,
include_node_contents=include_node_contents,
post_id=post_id,
)
# Remove the edges that occur fewer times than the threshold
if min_edge_occurrences_to_link > 1:
def occurring_to_seldom(edge_attributes):
return edge_attributes["count"] < min_edge_occurrences_to_link
edges_to_remove = w.graph.get_edges_by_conditions(g_reddit, occurring_to_seldom)
g_reddit.remove_edges_from(edges_to_remove)
# Weight the parameters
attributes_to_weight = ["polarity", "subjectivity"]
for edge in tqdm(g_reddit.edges, disable=not show_progress_bars):
for attribute in attributes_to_weight:
g_reddit.edges[edge][attribute + "_weighted"] = weigh_attribute(
attribute, g_reddit.edges[edge]
)
return g_reddit
def link_drugs(
G: nx.Graph,
list_of_drugs: List[str],
polarity: float,
subjectivity: float,
post_id: str,
text: str,
max_drugs_in_post: int,
conditional_functions_dict,
include_node_contents: bool = False,
include_link_contents: bool = False,
):
# Discard posts where the number of mentioned substances exceeds the limit
if (len(list_of_drugs) < 1) or (len(list_of_drugs) > max_drugs_in_post):
return
# Discard posts that do NOT meet the polarity criteria
if "polarity" in conditional_functions_dict.keys():
condition = conditional_functions_dict["polarity"]
if not condition(polarity):
return
# Discard posts that do NOT meet the subjectivity criteria
if "subjectivity" in conditional_functions_dict.keys():
condition = conditional_functions_dict["subjectivity"]
if not condition(subjectivity):
return
# Assign the node attributes.
for drug in list_of_drugs:
if drug in G.nodes:
G.nodes[drug]["count"] += 1
G.nodes[drug]["polarity"].append(polarity)
G.nodes[drug]["subjectivity"].append(subjectivity)
G.nodes[drug]["ids"].append(post_id)
if include_node_contents:
G.nodes[drug]["contents"].append(text)
# Stop here if there is only one drug
if len(list_of_drugs) == 1:
return
# Assign the edge attributes.
for index in range(len(list_of_drugs)):
drug = list_of_drugs[index]
other_drugs = list_of_drugs[(index + 1) :]
for other_drug in other_drugs:
if (drug in G.nodes) & (other_drug in G.nodes):
edge = (drug, other_drug)
# If edge already exists, append the properties to their
# respective list
if G.has_edge(*edge):
G.edges[edge]["count"] += 1
G.edges[edge]["number_of_drugs_in_post"].append(len(list_of_drugs))
G.edges[edge]["polarity"].append(polarity)
G.edges[edge]["subjectivity"].append(subjectivity)
if include_link_contents:
G.edges[edge]["contents"].append(text)
# If the edge does not exist, initialize all the attributes
else:
G.add_edge(
*edge,
count=1,
number_of_drugs_in_post=[len(list_of_drugs)],
polarity=[polarity],
subjectivity=[subjectivity],
contents=[text] if include_link_contents else None
)
def weigh_attribute(attribute_to_weigh, all_edge_attributes):
value_attribute = np.array(all_edge_attributes[attribute_to_weigh])
number_of_drugs_in_post = np.array(all_edge_attributes["number_of_drugs_in_post"])
weights = 1 / (number_of_drugs_in_post - 1)
number_of_posts_containing_link = all_edge_attributes["count"]
value_weighted = np.sum(weights * value_attribute) / np.sum(weights)
return value_weighted
<file_sep>from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
def remove_stopwords(words: list,
language='english',
stem=False,
exclude=tuple()):
# Load stopwords.
if language == 'english':
stop_words = stopwords.words('english')
else:
raise Exception('Invalid language: "' + '".')
# Remove the stopwords on the list of excluded stopwords.
stop_words = [stop_word for stop_word in stop_words
if stop_word not in exclude]
# Stem if chosen by the user.
if stem:
stemmer = PorterStemmer()
stop_words = [stemmer.stem(stop_word) for stop_word in stop_words]
words = [stemmer.stem(word) for word in words]
return [word for word in words
if word.lower() not in stop_words]
<file_sep>import json
try:
from library_functions.config import Config
except ModuleNotFoundError:
from project.library_functions.config import Config
def load_substance_names():
with open(Config.Path.substance_names) as file:
substance_names = json.load(file)
return substance_names
<file_sep>import networkx as nx
def erdos_renyi_like(G: nx.Graph):
number_of_nodes = G.number_of_nodes()
possible_connections = number_of_nodes * (number_of_nodes - 1)
if not G.is_directed():
possible_connections /= 2
probability_of_connection = G.number_of_edges() / possible_connections
G_erdos_renyi = nx.gnp_random_graph(number_of_nodes,
probability_of_connection,
directed=G.is_directed())
return(G_erdos_renyi)<file_sep>from os import name
from typing import Collection, Dict, List
import networkx as nx
import numpy as np
import wojciech as w
import plotly.figure_factory as ff
import pickle
try:
import library_functions as lf
except ModuleNotFoundError:
import project.library_functions as lf
try:
from library_functions.config import Config
except ModuleNotFoundError:
from project.library_functions.config import Config
def inverse_communities_from_partition(
partition: Dict[str, int]
) -> Dict[int, List[str]]:
"""Given a partition mapping from nodes to their community, return a mapping from communities to the nodes in that community.
Args:
partition (Dict[str, int]): [description]
Returns:
Dict[int, List[str]]: [description]
"""
communities = {i: [] for i in range(max(partition.values()) + 1)}
for node in partition:
communities[partition[node]].append(node)
return communities
def inverse_categories(categories: Dict):
inverse = {}
for cat in categories:
for c in categories[cat]:
inverse[c] = cat
return inverse
def overlap(
community_names: Collection[str], category_names: Collection[str]
) -> Dict[str, float]:
"""Given a collection of nodes belonging to a community and a collection of
nodes in a category, compute several metrics about the overlap of those two collections.
Args:
community_names (Collection[str]): Collection of nodes that belong to a given community (f.ex., from the louvain algorithm)
category_names (Collection[str]): Collection of nodes in a category (on wikipedia)
Returns:
Dict[str, float]: Dict containing 3 metrics: "proportion_in_community","proportion_in_category", "overlap_proportion".
"""
nodeset = set(community_names)
nameset = set(category_names)
all = nodeset.union(nameset)
intersection = nodeset.intersection(nameset)
# Proportion of the community that is part of this category
proportion_of_nodes_in_category = len(intersection) / len(nodeset)
# Proportion of the the category that is represented in the community
proportion_category_in_nodes = len(intersection) / len(nameset)
# Overall overlap metric: proportion of nodes that are in both sets
# divided by total amount of different names
overall_overlap = len(intersection) / len(all)
return {
"proportion_in_community": proportion_category_in_nodes,
"proportion_in_category": proportion_of_nodes_in_category,
"overlap_proportion": overall_overlap,
}
def overlap_matrix(
attribute_A: str, attribute_B: str, graph: nx.Graph, savename: str = None
):
"""Given two attributes that are used to hold the category of nodes within a graph,
return a matrix that contains the overlaps of each category represented by attribute_A
and each category represented by attribute_B
Args:
attribute_A (str): name of the node attribute containing the first category
attribute_B (str): name of the node attribute containing the second category
graph (nx.Graph): 2D numpy array containing the overlaps
Returns:
[type]: np.Array
"""
try:
all_A_attributes = list(
set([data for _, data in graph.nodes(data=attribute_A)])
)
all_B_attributes = list(
set([data for _, data in graph.nodes(data=attribute_B)])
)
except TypeError:
# The above fails if the attributes contain lists
temp = [data for _, data in graph.nodes(data=attribute_A)]
all_A_attributes = sorted(list(set(lf.flatten(temp))))
temp = [data for _, data in graph.nodes(data=attribute_B)]
all_B_attributes = sorted(list(set(lf.flatten(temp))))
result = np.zeros((len(all_A_attributes), len(all_B_attributes)))
for i, a in enumerate(all_A_attributes):
nodes_a = w.graph.get_nodes_by_conditions(
graph, lambda x: x[attribute_A] == a or a in x[attribute_A]
)
for j, b in enumerate(all_B_attributes):
nodes_b = w.graph.get_nodes_by_conditions(
graph, lambda x: x[attribute_B] == b or b in x[attribute_B]
)
groups_overlap = overlap(nodes_a, nodes_b)["overlap_proportion"]
result[i, j] = groups_overlap
if savename:
np.save(Config.Path.shared_data_folder / savename, result)
return result, all_A_attributes, all_B_attributes
def draw_overlaps_plotly(
attribute_A: str,
attribute_B: str,
graph: nx.Graph,
save: str = None,
saved: str = None,
):
"""Get a 2D-histogram showing how much the categories of two categorization systems of the nodes in a graph overlap each other.
Args:
attribute_A (str): name of the node attribute containing the first category
attribute_B (str): name of the node attribute containing the second category
graph (nx.Graph): networkx graph whose nodes have the two attributes above
saved (str, optional): Name file containing a pre-computed figure. Defaults to None.
save (str, optional): Name file to which to save the figure. Defaults to None.
Returns:
[type]: plotly figure containing the 2D histogram
"""
if saved:
with open(Config.Path.shared_data_folder / saved, "rb") as f:
return pickle.load(f)
overlaps, A, B = overlap_matrix(
attribute_A=attribute_A, attribute_B=attribute_B, graph=graph
)
heatmap_text = np.around(overlaps, decimals=2)
fig = ff.create_annotated_heatmap(
z=overlaps,
text=overlaps,
x=[b.title() for b in B],
y=[f"Com. {i+1}" for i in range(len(A))],
annotation_text=heatmap_text,
colorscale="Greys",
hoverinfo="z",
)
for i in range(len(fig.layout.annotations)):
fig.layout.annotations[i].font.size = 8
if save:
with open(Config.Path.shared_data_folder / save, "wb+") as f:
pickle.dump(fig, f)
return fig
<file_sep>from nltk import FreqDist
import numpy as np
def word_frequency_vs_rank(text,
as_probability=False):
frequency_distribution = FreqDist(text)
frequency = np.asarray(sorted(frequency_distribution.values(),
reverse=True))
if as_probability:
frequency / len(text)
rank = np.arange(1, len(frequency) + 1)
return rank, frequency
<file_sep>import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import wojciech as w
import plotly.graph_objects as go
def plot_distribution(
G: nx.Graph,
quantity,
as_probability_distribution=False,
axes: plt.Axes = None,
annotate=True,
as_partial=(1, 1),
attribute_name=None,
attribute_function=None,
attribute_function_name="",
attribute_parent="node",
axis_scaling="lin-lin",
bar_width_scaling=0.9,
bins=None,
label=None,
show_cumulative=False,
plot_options_dict: dict = None,
plot_type="scatter",
plotting_backend="matplotlib",
**kwargs,
):
# Check input for errors.
valid_quantities = (
"attribute",
"degree",
"in-degree",
"out-degree",
"shortest path length",
)
if quantity not in valid_quantities:
raise Exception('Invalid quantity: "' + quantity + '".')
# Load quantities.
if quantity == "attribute":
if attribute_function is None:
x_label = (
f"{attribute_parent.capitalize()} attribute: " f'"{attribute_name}"'
)
else:
x_label = (
f"{attribute_function_name}("
f"{attribute_parent} attribute: "
f'"{attribute_name}")'
)
if attribute_parent == "node":
if as_probability_distribution:
y_label = "Probability of attribute value"
else:
y_label = "Number of nodes"
else:
if as_probability_distribution:
y_label = "Probability of attribute value"
else:
y_label = "Number of edges"
title = f'Distribution of attribute: "{attribute_name}"'
if attribute_parent == "node":
attributes_dict = dict(nx.get_node_attributes(G, attribute_name))
attribute_values = list(attributes_dict.values())
elif attribute_parent == "edge":
attributes_dict = dict(nx.get_edge_attributes(G, attribute_name))
attribute_values = list(attributes_dict.values())
else:
raise ValueError(f'Invalid attribute object: "{attribute_parent}"')
if attribute_function is not None:
attribute_values = list(map(attribute_function, attribute_values))
# Make sure attribute values is a numpy array
attribute_values = np.array(attribute_values)
# Remove NaNs
nan_indices = np.isnan(attribute_values)
attribute_values = attribute_values[~nan_indices]
if bins is None:
distribution, bins = np.histogram(attribute_values)
else:
distribution, bins = np.histogram(attribute_values, bins=bins)
if as_probability_distribution:
distribution = distribution / len(attribute_values)
bin_centers = [np.mean([bins[i], bins[i + 1]]) for i in range(len(bins) - 1)]
elif quantity in ["degree", "in-degree", "out-degree"]:
x_label = "Node degree"
if as_probability_distribution:
y_label = "Probability of node degree"
else:
y_label = "Number of nodes"
if quantity == "degree":
direction = None
title = "Degree distribution"
elif quantity == "in-degree":
direction = "in"
title = "In-degree distribution"
elif quantity == "out-degree":
direction = "out"
title = "Out-degree distribution"
bin_centers, distribution = w.graph.degree_distribution(
G,
direction=direction,
as_probability_distribution=as_probability_distribution,
)
elif quantity == "shortest path length":
bin_centers, distribution = w.graph.shortest_path_length_distribution(
G, as_probability_distribution=as_probability_distribution
)
title = "Shortest path length distribution"
x_label = "Path length"
if as_probability_distribution:
y_label = "Probability of path length"
else:
y_label = "Number of paths"
# Plot
if plot_options_dict is None:
if plot_type == "scatter":
plot_options_dict = {
"marker": "o",
"markerfacecolor": "black",
"markersize": 3,
"linestyle": "None",
"linewidth": 0.5,
"color": "blue",
}
else:
plot_options_dict = dict()
if "color" in kwargs:
plot_options_dict["color"] = kwargs["color"]
if plot_type == "bar":
number_of_parts = as_partial[0]
part_number = as_partial[1]
width_bin = bin_centers[1] - bin_centers[0]
width_all_bars = bar_width_scaling * width_bin
width_bar = width_all_bars / number_of_parts
adjustment = (
np.linspace(0, width_all_bars, number_of_parts, endpoint=False)
- width_all_bars / 2
+ width_bar / 2
)[part_number - 1]
bin_centers = bin_centers + adjustment
if axis_scaling == "lin-lin":
if plot_type == "scatter":
x_start = min(bin_centers)
x_end = max(bin_centers)
elif plot_type == "bar":
x_start = min(bin_centers) + np.min(adjustment) - 1.5 * width_bar
x_end = max(bin_centers) + np.min(adjustment) + 1.5 * width_bar
elif axis_scaling == "log-log":
x_start = 1
x_end = 10 ** np.ceil(np.log10(max(bin_centers)))
if plotting_backend == "plotly":
# plotly needs the log10 of the range for logplots
x_start = np.log10(x_start)
x_end = np.log10(x_end)
else:
raise Exception('Unknown axis scaling: "' + axis_scaling + '"')
if plotting_backend == "matplotlib":
new_figure_created = False
if axes is None:
new_figure_created = True
figure = plt.figure()
figure.set_facecolor("white")
axes = figure.gca()
axes.set_facecolor("white")
if annotate:
axes.set_title(title)
axes.set_xlabel(x_label)
axes.set_ylabel(y_label)
if plot_type == "scatter":
axes.plot(bin_centers, distribution, label=label, **plot_options_dict)
axes.grid()
elif plot_type == "bar":
axes.bar(
bin_centers,
distribution,
width=width_bar,
label=label,
**plot_options_dict,
)
else:
raise Exception('Unknown plot type: "' + plot_type + '"')
axes.set_xlim(x_start, x_end)
if axis_scaling == "lin-lin":
pass
elif axis_scaling == "log-log":
axes.set_xscale("log")
axes.set_yscale("log")
else:
raise Exception('Unknown axis scaling: "' + axis_scaling + '"')
if show_cumulative:
cumulative_curve = axes.plot(
bin_centers, np.cumsum(distribution), color="#eb9b34"
)
axes.legend((cumulative_curve[0],), ("Cumulative",))
if as_partial[0] > 1:
axes.legend()
if new_figure_created:
w.format_figure(figure)
return axes
elif plotting_backend == "plotly":
if plot_type == "scatter":
traces = [
go.Scatter(
name="Distribution",
x=bin_centers,
y=distribution,
marker={"color": plot_options_dict["color"]},
mode="markers",
hovertemplate=f"{x_label}: %{{x}} <br> {y_label}: %{{y}}",
)
]
elif plot_type == "bar":
traces = [
go.Bar(
name="Distribution",
x=bin_centers,
y=distribution,
hovertemplate=f"{x_label}: %{{x}} <br> {y_label}: %{{y}}",
)
]
if show_cumulative:
traces += [
go.Scatter(
x=bin_centers,
y=np.cumsum(distribution),
name="Cumulative Distribution",
mode="lines",
hovertemplate=f"{x_label}: %{{x}} <br> Total {y_label}: %{{y}}",
)
]
figure = go.Figure(
data=traces,
layout=go.Layout(
title=title,
xaxis_title=x_label,
yaxis_title=y_label,
autosize=True,
width=800,
height=600,
showlegend=True,
margin={"l": 20, "r": 20, "t": 25, "b": 25},
xaxis={
"type": "log" if axis_scaling == "log-log" else "linear",
"range": [x_start, x_end],
},
yaxis={"type": "log" if axis_scaling == "log-log" else "linear"},
),
)
return figure
else:
raise AssertionError("plotting_backeng can only be 'matplotlib' or 'plotly'")<file_sep>import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from mpl_toolkits.axes_grid1 import make_axes_locatable
import networkx as nx
import numpy as np
import wojciech as w
def plot_properties(G: nx.Graph,
x_property = None,
y_property = None,
plot_type ='scatter', # scatter / heatmap
axes: plt.Axes = None,
colormap_norm = 'lin',
bins=10):
# Error check
#
valid_graph_types = ('scatter',
'heatmap')
if plot_type not in valid_graph_types:
raise Exception('Invalid graph type: "' + plot_type + '"')
#
valid_colormap_norms = ('lin',
'log')
if colormap_norm not in valid_colormap_norms:
raise Exception('Invalid colormap norm: "' + colormap_norm + '"')
#
valid_properties = ('betweenness',
'eigenvector centrality',
'degree',
'in-degree',
'out-degree')
for property in [x_property, y_property]:
if property not in valid_properties:
raise Exception('Invalid property: "' + property + '"')
# Load properites
def load_property(property_name):
if property_name == 'betweenness':
data = w.graph.betweenness(G)
elif property_name == 'eigenvector centrality':
data = w.graph.eigenvector_centrality(G)
elif property_name == 'degree':
data = w.graph.degrees(G)
elif property_name == 'in-degree':
data = w.graph.degrees(G, direction='in')
elif property_name == 'out-degree':
data = w.graph.degrees(G, direction='out')
return data
x_data = load_property(x_property)
y_data = load_property(y_property)
max_of_data = np.max((x_data, y_data))
# Plot
new_figure_created = False
if axes is None:
new_figure_created = True
figure = plt.figure(figsize=(12, 8))
figure.set_facecolor('white')
axes = figure.gca()
axes.set_facecolor('white')
if plot_type == 'scatter':
plot_options = {'marker': 'o',
's': 5}
axes.scatter(x_data,
y_data,
**plot_options)
axes.set_xlabel(x_property)
axes.set_ylabel(y_property)
axes.set_xlim(np.floor(min(x_data)))
axes.set_ylim(np.floor(min(y_data)))
elif plot_type == 'heatmap':
# create an axes on the right side of ax. The width of cax will be 7%
# of ax and the padding between cax and ax will be fixed at 0.07 inch.
if colormap_norm == 'lin':
cnorm = None;
elif colormap_norm == 'log':
cnorm = LogNorm()
heatmap, xedges, yedges, image =\
axes.hist2d(x_data, y_data, bins=bins, cmap='Reds', norm=cnorm)
divider = make_axes_locatable(axes)
colorbar_axes = divider.append_axes("right", size=0.1, pad=0.07)
figure.colorbar(image, cax=colorbar_axes)
if new_figure_created:
w.format_figure(figure)
return axes<file_sep>import nltk
def unusual_words(text: nltk.Text,
language='english'):
text_vocab = set(w.lower() for w in text if w.isalpha())
if language == 'english':
usual_vocab = set(w.lower() for w in nltk.corpus.words.words())
else:
raise Exception('Invalid language: "' + language + '".')
unusual_vocab = text_vocab - usual_vocab
return sorted(unusual_vocab)
<file_sep>from . import plotly_draw
from .calculate_sentiment_reddit import calculate_sentiment_reddit
from .create_graph_reddit import create_graph_reddit
from .create_graph_wiki import create_graph_wiki
from .display_graph_size import display_graph_size
from .load_data_reddit import load_data_reddit
from .load_data_wiki import load_data_wiki
from .load_substance_names import load_substance_names
from .most_frequent_edges import most_frequent_edges
from .save_wiki_data import (
save_synonym_mapping,
save_contents,
save_substance_names,
save_urls,
save_wiki_data_files,
)
from .layouting import get_fa2_layout, get_circle_layout
from .communities import (
assign_louvain_communities,
get_infomap_communities,
assign_root_categories,
)
from .overlaps import inverse_communities_from_partition, overlap, \
draw_overlaps_plotly
from .flatten_list import flatten
from .text_analysis import (
assign_lemmas,
assign_tfs,
assign_idfs,
assign_tf_idfs,
wordcloud_from_node,
rank_dict,
wordcloud_from_nodes,
wordcloud_from_link,
)
from .plot_basic_data import get_wiki_plots_figure, get_reddit_plots_figure
from .get_from_wiki import (
get_page_from_name,
get_random_page,
get_page_lengths,
get_wiki_page_names,
get_wiki_synonyms_mapping,
get_number_of_links,
get_number_of_categories,
get_number_of_synonyms,
get_name_by,
get_top,
get_wiki_data,
get_root_category_mapping,
)
from .get_from_reddit import get_post_lengths, get_n_of_matches_per_post, \
get_top_posts
from .plotly_draw import draw_graph_plotly
<file_sep>import matplotlib.pyplot as plt
import networkx as nx
import wojciech as w
from typing import Any, Callable, Dict, Iterable, Tuple, Union
def plot_comparison_of_attribute_distributions(
graphs: Dict[str, nx.Graph],
attribute_name: str,
attribute_parent: str,
attribute_function: Callable[['str'], Any] = None,
attribute_function_name: str = '',
as_probability_distribution: bool = False,
bar_width_scaling: float = 1,
bins: Union[int, Iterable[Union[int, float]]] = 100,
x_limit: Tuple[Union[float, int], Union[float, int]] = None,
fig_width: Union[float, int] = 8,
show: bool = True
):
# Create subplots.
figure_size = (fig_width, fig_width / 3 * len(graphs) + 1)
figure, axess = plt.subplots(len(graphs), 1,
figsize=figure_size,
sharex='all',
sharey='all')
# Plot distributions.
for index, ((graph_name, graph), axes) \
in enumerate(zip(graphs.items(), axess)):
# Create the figure title.
figure.suptitle(f'Distribution of the {attribute_parent} attribute: '
f'"{attribute_name}"',
y=min(0.98 + 0.003 * (len(graphs) - 1), 0.995),
size=20)
# Plot the degree distribution in the chosen axes.
w.graph.plot_distribution(
graph,
quantity='attribute',
attribute_name=attribute_name,
attribute_parent=attribute_parent,
attribute_function=attribute_function,
attribute_function_name=attribute_function_name,
as_probability_distribution=as_probability_distribution,
plot_type='bar',
bar_width_scaling=bar_width_scaling,
bins=bins,
axes=axes,
annotate=False
)
# Annotate the graphs.
axes.set_title(graph_name)
if as_probability_distribution:
axes.set_ylabel('Probability of value')
else:
axes.set_ylabel('Count')
if index == len(graphs) - 1:
if attribute_function is not None:
axes.set_xlabel(f'{attribute_function_name}({attribute_name})')
else:
axes.set_xlabel(f'{attribute_name}')
if x_limit is not None:
axes.set_xlim(x_limit)
# Format the axes.
axes.spines['top'].set_color('white')
axes.spines['right'].set_color('white')
axes.set_facecolor('white')
axes.xaxis.label.set_fontsize(12)
axes.yaxis.label.set_fontsize(12)
axes.title.set_fontsize(14)
# Adjust the layout
figure.tight_layout()
# Display the graph.
if show:
plt.show()
return axess
<file_sep>import nltk
def content_fraction(text: nltk.Text,
language='english'):
if language == 'english':
stopwords = nltk.corpus.stopwords.words('english')
else:
raise Exception('Invalid language: "' + language + '".')
content = [word for word in text if word.lower() not in stopwords]
return len(content) / len(text)<file_sep>import json
try:
from library_functions.config import Config
except ModuleNotFoundError:
from project.library_functions.config import Config
from textblob import TextBlob
from tqdm import tqdm
def calculate_sentiment_reddit(alternative_path=None, alternative_path_out=None):
filepath_in = (
alternative_path if alternative_path else Config.Path.reddit_data_with_NER
)
filepath_out = (
alternative_path_out
if alternative_path_out
else Config.Path.reddit_data_with_NER_and_sentiment
)
with open(filepath_in) as file:
drug_database_reddit = json.load(file)
for post_id, post in tqdm(drug_database_reddit.items()):
try:
analysis = TextBlob(post["content"] + post["title"])
except KeyError:
analysis = TextBlob(post["body"] + post["title"]) # for comments
post["polarity"] = analysis.polarity
post["subjectivity"] = analysis.subjectivity
with open(filepath_out, "w+") as file:
json.dump(drug_database_reddit, file)
<file_sep>import networkx as nx
import numpy as np
def shuffle_attribute(G: nx.Graph, attribute_name):
G_attribute_shuffled = G.copy()
# Extract the old attribute values
nodes, attribute_values = \
zip(*nx.get_node_attributes(G, attribute_name).items())
# Create the new attribute values by shuffling the old ones
new_attribute_values = np.random.permutation(attribute_values)
# Set the values of the attributes to the shuffled values
new_attribute_values_dict = {node: {attribute_name: new_attribute_value}
for node, new_attribute_value
in zip(nodes, new_attribute_values)}
nx.set_node_attributes(G_attribute_shuffled, new_attribute_values_dict)
return G_attribute_shuffled
<file_sep>import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
def plot_wordcloud(text,
title=None,
axes: plt.Axes = None):
if isinstance(text, list):
text = ' '.join(text)
wc = WordCloud(max_words=100,
collocations=False,
stopwords=set(STOPWORDS),
margin=10,
random_state=1).generate(text)
new_figure_created = False
if axes is None:
new_figure_created = True
figure = plt.figure(figsize=(12, 8))
axes = figure.gca()
default_colors = wc.to_array()
axes.imshow(default_colors, interpolation="bilinear")
axes.set_axis_off()
if title is not None:
axes.set_title(title, fontsize=20)
return axes
<file_sep>import json
from typing import Dict, List, Literal, Set, Tuple
import random
try:
import library_functions as lf
except ModuleNotFoundError:
import project.library_functions as lf
try:
from library_functions.config import Config
except ModuleNotFoundError:
from project.library_functions.config import Config
# pre-compute some stuff for efficiency
reddit_data = lf.load_data_reddit()
post_lengths = [len(data["title"] + data["content"]) for data in reddit_data.values()]
n_of_matches_per_post = [len(data["matches"]) for data in reddit_data.values()]
def get_post_lengths() -> List[int]:
"""Get a list of the lengths of individual posts
Returns:
List[int]: The length in characters of each of the reddit posts
"""
return post_lengths.copy()
def get_n_of_matches_per_post() -> List[int]:
return n_of_matches_per_post.copy()
def get_top_posts(
attribute: Literal["length", "mentions"], reverse: bool = False, amount: int = 10
) -> List[Tuple[str, int, str]]:
tuples = []
for index, (id, post) in enumerate(reddit_data.items()):
if attribute == "mentions":
attr = n_of_matches_per_post[index]
else:
attr = post_lengths[index]
tuples.append(
(post["title"], attr, f"https://www.reddit.com/r/Nootropics/comments/{id}")
)
sorted_tuples = sorted(tuples, key=lambda x: x[1], reverse=reverse)
return sorted_tuples[:amount]<file_sep>import numpy as np
import networkx as nx
import wojciech as w
def degree_distribution(G: nx.Graph,
direction: str = None,
as_probability_distribution=False,
cumulative=False):
node_degrees = w.graph.degrees(G, direction=direction)
bin_edges = np.arange(np.max(node_degrees) + 1)
degrees = bin_edges[:-1]
distribution, _ = np.histogram(node_degrees, bins=bin_edges)
if as_probability_distribution:
distribution = distribution / G.number_of_nodes()
if cumulative:
distribution = np.cumsum(distribution)
return degrees, distribution<file_sep>import nltk
def lexical_diversity(text: nltk.Text):
return len(set(text)) / len(text)
<file_sep>import networkx as nx
import numpy as np
def degrees(G: nx.Graph,
node_labels=None,
direction: str = None):
if direction is None:
node_degrees = G.degree(node_labels)
elif direction == 'in':
node_degrees = G.in_degree(node_labels)
elif direction == 'out':
node_degrees = G.out_degree(node_labels)
else:
raise Exception('Invalid direction: "' + direction + '"')
return np.fromiter(dict(node_degrees).values(), dtype=int)
<file_sep>from .betweenness import betweenness
from .communities_louvain import communities_louvain
from .degree_distribution import degree_distribution
from .degree_statistics import degree_statistics
from .degrees import degrees
from .eigenvector_centrality import eigenvector_centrality
from .erdos_renyi_like import erdos_renyi_like
from .get_edges_by_conditions import get_edges_by_conditions
from .get_nodes_by_conditions import get_nodes_by_conditions
from .largest_connected_component import largest_connected_component
from .most_central_nodes import most_central_nodes
from .plot_comparison_of_attribute_distributions import \
plot_comparison_of_attribute_distributions
from .plot_degree_distribution import plot_degree_distribution
from .plot_degree_distribution_summary import plot_degree_distribution_summary
from .plot_distribution import plot_distribution
from .plot_distribution_of_attribute_of_1_instance import \
plot_distribution_of_attribute_of_1_instance
from .plot_force_atlas_2 import plot_force_atlas_2
from .plot_in_vs_out_degree import plot_in_vs_out_degree
from .plot_properties import plot_properties
from .remove_isolates import remove_isolates
from .shuffle_attribute import shuffle_attribute
from .shortest_path_length_distribution import shortest_path_length_distribution
from .to_dataframe import to_dataframe
<file_sep>import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import wojciech as w
def plot_degree_distribution(G: nx.Graph,
direction: str = None,
as_probability_distribution=False,
axes: plt.Axes = None,
annotate=['all'],
label=None,
axis_scaling='lin-lin',
show_cumulative=False,
plot_options_dict: dict = None,
plot_type='scatter',
**kwargs):
if isinstance(annotate, str):
annotate = [annotate]
# Histogram
degrees, distribution = w.graph.degree_distribution(
G,
direction=direction,
as_probability_distribution=as_probability_distribution
)
# Plot
if plot_options_dict is None:
if plot_type == 'scatter':
plot_options_dict = \
{'marker': 'o', 's': 3, 'c': 'blue'}
elif plot_type == 'bar':
plot_options_dict = {'color': 'blue'}
else:
plot_options_dict = dict()
if 'color' in kwargs:
if plot_type == 'scatter':
plot_options_dict['c'] = kwargs['color']
else:
plot_options_dict['color'] = kwargs['color']
if 'marker_size' in kwargs:
if plot_type == 'scatter':
plot_options_dict['s'] = kwargs['marker_size']
new_figure_created = False
if axes is None:
new_figure_created = True
figure = plt.figure()
figure.set_facecolor('white')
axes = figure.gca()
axes.set_facecolor('white')
if direction is None:
title = 'Degree distribution'
elif direction == 'in':
title = 'In-degree distribution'
elif direction == 'out':
title = 'Out-degree distribution'
else:
raise Exception('Invalid direction: "' + direction + '"')
if as_probability_distribution:
y_label = 'Probability of node degree'
else:
y_label = 'Number of nodes'
if ('title' in annotate) or ('all' in annotate):
axes.set_title(title)
if ('x_label' in annotate) or ('all' in annotate):
axes.set_xlabel('Node degree')
if ('y_label' in annotate) or ('all' in annotate):
axes.set_ylabel(y_label)
if plot_type == 'scatter':
plot = axes.scatter(degrees, distribution,
label=label, **plot_options_dict)
axes.grid()
elif plot_type == 'bar':
plot = axes.bar(degrees, distribution,
label=label, **plot_options_dict)
else:
raise Exception('Unknown plot type: "' + plot_type + '"')
if axis_scaling == 'lin-lin':
if plot_type == 'scatter':
axes.set_xlim(0, max(degrees))
elif plot_type == 'bar':
axes.set_xlim(-1, max(degrees))
elif axis_scaling == 'log-log':
axes.set_xscale('log')
axes.set_yscale('log')
axes.set_xlim(0.8, 10 ** np.ceil(np.log10(max(degrees))))
else:
raise Exception('Unknown axis scaling: "' + axis_scaling + '"')
if show_cumulative:
cumulative_curve = axes.plot(degrees, np.cumsum(distribution),
color='#eb9b34')
axes.legend((cumulative_curve[0],), ('Cumulative',))
if new_figure_created:
w.format_figure(figure)
return axes, (degrees, distribution)
<file_sep>import numpy as np
def find_nearest(array, value, output='value and index'):
array = np.asarray(array)
index = (np.abs(array - value)).argmin()
if output == 'value':
return array[index]
elif output == 'index':
return index
else:
return array[index], index<file_sep>import networkx as nx
import numpy as np
def get_nodes_by_conditions(G: nx.Graph, conditional_functions):
'''
:param G: networkx Graph
:param conditional_functions: conditional function or a list derof
:return: list of node labels (tuples containing labels of nodes that
edge connects) satisfying the conditions
:Example:
>>> conditional_functions = [lambda x: x['polarity'] > 0,
>>> lambda x: x['subjectivity'] > 0.5]
>>> nodes = get_nodes_by_conditions(G, conditional_functions)
'''
if not isinstance(conditional_functions, list):
conditional_functions = [conditional_functions]
return [node_label for node_label
in list(G.nodes)
if check_node(G.nodes[node_label], conditional_functions)]
def check_node(node, conditional_functions):
for conditional_function in conditional_functions:
if not conditional_function(node):
return False
return True
<file_sep>from collections import Iterable
# Convenience method to flatten a list, since doing that in python is a PITA. Credit @grym from #python on freenode.
def should_flatten(x):
return isinstance(x, Iterable) and not isinstance(x, (str, bytes))
def flatten(x, should_flatten=should_flatten):
for y in x:
if should_flatten(y):
yield from flatten(y, should_flatten=should_flatten)
else:
yield y
<file_sep>import matplotlib.pyplot as plt
def empty_figure():
figure = plt.figure(figsize=(12, 8))
axes = figure.gca()
return figure, axes
<file_sep>import networkx as nx
import numpy as np
import pandas as pd
import wojciech as w
def to_dataframe(G: nx.Graph,
properties = tuple()):
# Error check
valid_properties = ('betweenness',
'eigenvector centrality',
'degree',
'in-degree',
'out-degree')
for property in properties:
if property not in valid_properties:
raise Exception('Invalid property: "' + property + '"')
# ---
data_frame = pd.DataFrame.from_dict(dict(G.nodes(data=True)),
orient='index')
for property in properties:
if property == 'betweenness':
data_frame[property] = \
w.graph.betweenness(G)
if property == 'degree':
data_frame[property] = \
w.graph.degrees(G)
if property == 'eigenvector centrality':
data_frame[property] = \
w.graph.eigenvector_centrality(G)
elif property == 'in-degree':
data_frame[property] = \
w.graph.degrees(G, direction='in')
elif property == 'out-degree':
data_frame[property] = \
w.graph.degrees(G, direction='out')
return data_frame
<file_sep>import networkx as nx
import numpy as np
def get_edges_by_conditions(G: nx.Graph, conditional_functions):
'''
:param G: networkx Graph
:param conditional_functions: conditional function or a list derof
:return: list of edge labels (tuples containing labels of nodes that
edge connects) satisfying the conditions
:Example:
>>> conditional_functions = [lambda x: x['polarity'] > 0,
>>> lambda x: x['subjectivity'] > 0.5]
>>> nodes = get_edges_by_conditions(G, conditional_functions)
'''
if not isinstance(conditional_functions, list):
conditional_functions = [conditional_functions]
return [edge_label for edge_label
in list(G.edges)
if check_edge(G.edges[edge_label], conditional_functions)]
def check_edge(edge, conditional_functions):
for conditional_function in conditional_functions:
if not conditional_function(edge):
return False
return True
<file_sep>import networkx as nx
import numpy as np
import pandas as pd
from operator import itemgetter
from typing import Union, List, Tuple
def most_central_nodes(G: nx.Graph,
measures: Union[str, List, Tuple] = None,
n: int = np.inf,
printout: bool = False,
as_pandas: bool = False
) -> Union[dict, pd.DataFrame]:
# Set default measures.
if measures is None:
if G.is_directed():
measures = ["degree",
"in-degree",
"out-degree",
"betweenness",
"eigenvector"]
else:
measures = ["degree",
"betweenness",
"eigenvector"]
if isinstance(measures, str):
measures = [measures]
most_linked_dict = dict()
for measure in measures:
if measure == 'degree':
most_linked = sorted(G.degree, key=itemgetter(1), reverse=True)
elif measure == 'in-degree':
most_linked = sorted(G.in_degree, key=itemgetter(1), reverse=True)
elif measure == 'out-degree':
most_linked = sorted(G.out_degree, key=itemgetter(1), reverse=True)
elif measure == 'betweenness':
most_linked = sorted(nx.betweenness_centrality(G).items(),
key=itemgetter(1), reverse=True)
elif measure == 'eigenvector':
most_linked = sorted(nx.eigenvector_centrality(G).items(),
key=itemgetter(1), reverse=True)
else:
raise ValueError(f'Unknown centrality measure: "{measure}"')
most_linked_dict[measure] = most_linked[:min(n, len(most_linked))]
if as_pandas:
max_length = 0
for most_linked in most_linked_dict.values():
if len(most_linked) > max_length:
max_length = len(most_linked)
columns = list()
data = np.empty((max_length, len(most_linked_dict) * 2), dtype=object)
for measure_idx, (measure, most_linked) \
in enumerate(most_linked_dict.items()):
columns.append((measure.capitalize(), 'Drug'))
columns.append((measure.capitalize(), 'Score'))
data[:len(most_linked), measure_idx * 2] = \
list(map(itemgetter(0), most_linked))
data[:len(most_linked), measure_idx * 2 + 1] =\
list(map(itemgetter(1), most_linked))
most_linked_pandas = \
pd.DataFrame(data,
columns=pd.MultiIndex.from_tuples(columns),
index=np.arange(data.shape[0]) + 1)
if printout:
if as_pandas:
display(most_linked_pandas)
else:
for measure, most_linked in most_linked_dict.items():
print(f'\nNodes with highest {measure} centrality:')
for node, centrality_score in most_linked:
print(f'\t{node}: {centrality_score:.3f}')
if as_pandas:
return most_linked_pandas
else:
return most_linked_dict<file_sep>import networkx as nx
import numpy as np
import wojciech as w
def eigenvector_centrality(G: nx.Graph):
eigenvector_centrality = nx.eigenvector_centrality(G)
return np.fromiter(dict(eigenvector_centrality).values(), dtype=float)
<file_sep>import networkx as nx
import numpy as np
import pandas as pd
from IPython.core.display import display
from operator import itemgetter
def most_frequent_edges(graphs: nx.Graph,
n=None,
as_pandas=False,
printout=False):
if not isinstance(graphs, dict):
graphs = {'Graph 1': graphs}
edges_sorted = dict()
for graph_name, graph in graphs.items():
edges_count = nx.get_edge_attributes(graph, "count")
edges_count_sorted = sorted(edges_count.items(),
key=itemgetter(1),
reverse=True)
if n is not None:
edges_count_sorted = \
edges_count_sorted[:min(len(edges_count_sorted), n)]
edges_sorted[graph_name] = edges_count_sorted
if as_pandas:
column_names = list(edges_sorted.keys())
max_length = max([len(value) for value in edges_sorted.values()])
index = np.arange(max_length) + 1
edges_sorted_for_pandas = dict()
for graph_name, edges_count_sorted in edges_sorted.items():
edge_label = np.empty(max_length, dtype=object)
edge_count = np.empty(max_length, dtype=object)
edge_label[:len(edges_count_sorted)] =\
list(map(itemgetter(0), edges_count_sorted))
edge_count[:len(edges_count_sorted)] = \
list(map(itemgetter(1), edges_count_sorted))
edges_sorted_for_pandas[(graph_name, 'Edge')] = edge_label
edges_sorted_for_pandas[(graph_name, 'Count')] = edge_count
edges_sorted_pandas = pd.DataFrame.from_dict(edges_sorted_for_pandas)
edges_sorted_pandas.set_index(pd.Index(index), inplace=True)
if printout:
if as_pandas:
display(edges_sorted_pandas)
else:
print('\nMost frequent edges:')
for graph_name, edges_count_sorted in edges_sorted.items():
print(f'\n{graph_name}:')
for index, (edge, count) in enumerate(edges_count_sorted):
print(f'\t{index + 1}. {edge}, {count} occurrences')
if as_pandas:
return edges_sorted_pandas
else:
return edges_sorted
<file_sep>import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import wojciech as w
from fa2 import ForceAtlas2
def plot_force_atlas_2(G: nx.Graph,
alpha=None,
edge_color=(0, 0, 0, 0.1),
node_color=np.array([(0, 0, 1, 0.6)]),
node_size=30,
edge_width=0.15,
iterations=100,
outboundAttractionDistribution=False,
edgeWeightInfluence=0.5,
jitterTolerance=0.05,
barnesHutOptimize=True,
barnesHutTheta=0.6,
scalingRatio=5,
strongGravityMode=False,
gravity=1,
verbose=True):
if G.is_directed():
G = G.to_undirected()
# Calculate the positions of the nodes
forceatlas2 = ForceAtlas2(
# Behavior alternatives
outboundAttractionDistribution=outboundAttractionDistribution,
# Dissuade hubs
linLogMode=False, # NOT IMPLEMENTED
adjustSizes=False, # Prevent overlap (NOT IMPLEMENTED)
edgeWeightInfluence=edgeWeightInfluence,
# Performance
jitterTolerance=jitterTolerance, # Tolerance
barnesHutOptimize=barnesHutOptimize,
barnesHutTheta=barnesHutTheta,
multiThreaded=False, # NOT IMPLEMENTED
# Tuning
scalingRatio=scalingRatio,
strongGravityMode=strongGravityMode,
gravity=gravity,
# Log
verbose=verbose)
positions = forceatlas2.forceatlas2_networkx_layout(G,
pos=None,
iterations=iterations)
# If required by user, compute node sizes.
def compute_node_sizes(quantity_array):
size_biggest_node = 300
return (quantity_array / np.max(quantity_array) * size_biggest_node)
if node_size == 'by degree':
node_size = compute_node_sizes(w.graph.degrees(G))
# Create the plot
figure = plt.figure(figsize=(12, 8))
axes = figure.gca()
nx.draw(G,
positions,
edge_color=edge_color,
node_size=node_size,
node_color=node_color,
width=edge_width,
# alpha=alpha,
ax=axes)<file_sep>import community
import networkx as nx
from collections import Counter
def communities_louvain(G: nx.Graph,
return_communities_of_1=False):
# compute the best partition
partition = community.best_partition(G)
community_numbers = set(partition.values())
communities = dict()
if not return_communities_of_1:
# Find the detected communities with more than 1 member
number_of_nodes_in_community = Counter(partition.values())
communities_with_more_than_1 = \
[community_number for community_number
in community_numbers
if number_of_nodes_in_community[community_number] > 1]
for node, community_number in partition.items():
if return_communities_of_1:
if community_number not in communities.keys():
communities[community_number] = list()
communities[community_number].append(node)
else:
if community_number in communities_with_more_than_1:
if community_number not in communities.keys():
communities[community_number] = list()
communities[community_number].append(node)
return communities
<file_sep>import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import svd
import seaborn as sns
import pandas as pd
class MachineLearningData:
attributeNames = None
classNames = None
X = None
y = None
def __init__(self, X=None, attributeNames=None, y=None, classNames=None):
self.X = X
self.attributeNames = attributeNames
self.y = y
self.classNames = classNames
def attribute_correlation_matrix(self):
return np.corrcoef(self.X.T)
def attribute_mean(self, names_of_attributes='all'):
if names_of_attributes == 'all':
return np.mean(self.X, axis=0)
else:
return_as_array = True
if isinstance(names_of_attributes, str):
names_of_attributes = [names_of_attributes]
return_as_array = False
index_attributes = [self.attributeNames.index(name_of_attribute)
for name_of_attribute in names_of_attributes]
mean = np.mean(self.X[:, index_attributes], axis=0)
if return_as_array:
return mean
else:
return mean[0]
def attribute_std(self,
names_of_attributes='all',
empirical=False):
if names_of_attributes == 'all':
return np.std(self.X, axis=0)
else:
return_as_array = True
if isinstance(names_of_attributes, str):
names_of_attributes = [names_of_attributes]
return_as_array = False
index_attributes = [self.attributeNames.index(name_of_attribute)
for name_of_attribute in names_of_attributes]
if empirical:
ddof = 1 # std denominator = N - 1
else:
ddof = 0 # std denominator = N - 0 = N
std = np.std(self.X[:, index_attributes], axis=0, ddof=ddof)
if return_as_array:
return std
else:
return std[0]
def C(self):
return len(self.classNames)
def get_attribute(self, name_of_attribute):
return self.X[:, self.attributeNames.index(name_of_attribute)]
def delete_attributes(self, attribute_names):
if isinstance(attribute_names, str):
attribute_names = [attribute_names]
for attribute_name in attribute_names:
index_column_to_delete = self.attributeNames.index(attribute_name)
self.attributeNames.pop(index_column_to_delete)
self.X = np.delete(self.X, index_column_to_delete, axis=1)
def delete_data_rows(self, row_indices):
self.X = np.delete(self.X, row_indices, axis=0)
self.y = np.delete(self.y, row_indices, axis=0)
def M(self):
return self.X.shape[1]
def N(self):
return self.X.shape[0]
def plot_attribute_correlation_matrix(self):
# figure = plt.figure()
# axes = plt.axes()
# plt.imshow(self.attribute_correlation_matrix(),
# vmin=-1, vmax=1)
# plt.xticks(range(self.M()), self.attributeNames, rotation=90)
# plt.yticks(range(self.M()), self.attributeNames, rotation=0)
# plt.colorbar()
# plt.tight_layout()
# plt.show()
sns.set_style("white")
# Generate a large random dataset
rs = np.random.RandomState(33)
d = pd.DataFrame(data=self.X,
columns=self.attributeNames)
# Compute the correlation matrix
corr = d.corr()
# Generate a mask for the upper triangle
mask = np.triu(np.ones_like(corr, dtype=bool))
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(230, 20, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=1, vmin=-1, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5})
plt.show()
def plot_attributes(self,
name_attribute_x,
name_attribute_y=None,
outlier_threshold_std_from_median=2,
axes: plt.Axes = None,
annotate=True,
marker_size=2):
x = self.get_attribute(name_attribute_x)
show_plot_at_end = False
if axes is None:
figure = plt.figure()
axes = plt.axes()
figure.set_facecolor('white')
axes.set_facecolor('white')
show_plot_at_end = True
plot_options = \
{'marker': 'o', 'markersize': marker_size,
'linestyle': 'None', 'linewidth': 0.5}
if name_attribute_y is None:
# Statistics
N = len(x)
mean = np.mean(x)
median = np.median(x)
std = np.std(x)
# Find outliers
outliers_threshold_low = \
median - (2 * outlier_threshold_std_from_median * std)
outliers_threshold_high = \
median + (2 + outlier_threshold_std_from_median * std)
number_of_outliers = np.sum(np.logical_or(
x > outliers_threshold_high,
x < outliers_threshold_low
))
# Plot
if annotate:
axes.set_title(f"{name_attribute_x}\n"
f"N: {N}, "
f"$ \mu $: {mean:.1e}, "
f"median: {median:.1e}, "
f"$ \sigma $: {std:.1e}\n"
f"outliers (> {outlier_threshold_std_from_median:.1f} "
f"$ \sigma $ from median): {number_of_outliers}")
axes.set_xlabel('Element index')
axes.set_ylabel('Attribute value')
legend_entries = list()
for class_index in range(len(self.classNames)):
legend_entries.append(self.classNames[class_index])
logical_index_in_class = self.y == class_index
index_in_class = np.arange(len(self.y))[logical_index_in_class]
x_in_class = x[index_in_class]
axes.plot(index_in_class, x_in_class, **plot_options)
# Median line
if annotate:
axes.plot([1, len(x)], [median, median], # median
'k-', linewidth=1)
axes.set_xlim(0)
legend_entries.append('Median')
else:
y = self.get_attribute(name_attribute_y)
if annotate:
axes.set_xlabel(name_attribute_x)
axes.set_ylabel(name_attribute_y)
legend_entries = list()
for class_index in range(len(self.classNames)):
legend_entries.append(self.classNames[class_index])
logical_index_in_class = self.y == class_index
x_in_class = x[logical_index_in_class]
y_in_class = y[logical_index_in_class]
axes.plot(x_in_class, y_in_class, **plot_options)
if annotate:
axes.legend(legend_entries)
if show_plot_at_end:
plt.show()
def plot_attributes_boxplot(self, mode: str = 'raw',
y_scale: str = 'lin'):
if mode == 'raw':
X = self.X
mode_string = ', raw data'
elif mode == 'centered and normalized':
X = self.X_centered()
mode_string = ', data centered ($\mu = 0$) and normalized ' \
'with $\sigma$'
elif mode == 'centered':
X = self.X_centered(normalize_data_by_std=False)
mode_string = ', data centered with mean = 0'
else:
raise Exception('Unknown mode: "' + str(mode) + '"')
figure = plt.figure()
axes = plt.axes()
plt.title('Attribute overview' + mode_string)
plt.boxplot(X, labels=self.attributeNames)
plt.ylabel('Attribute values')
plt.xticks(rotation=90)
if y_scale == 'log':
axes.set_yscale('log')
plt.show()
def plot_attribute_reconstruction_from_svd(self, attribute_name,
number_of_principal_components='all',
axes: plt.Axes = None,
marker_size=3):
original_data = self.get_attribute(attribute_name)
reconstruction = self.reconstruction_from_principal_components(
number_of_principal_components=number_of_principal_components,
attribute_names=[attribute_name])
if axes is None:
figure = plt.figure()
axes = plt.axes()
figure.set_facecolor('white')
axes.set_facecolor('white')
axes.set_title(attribute_name
+ f", {number_of_principal_components} principal "
f"components")
axes.set_xlabel('Original data')
axes.set_ylabel('Reconstructed data')
axes.scatter(original_data, reconstruction, s=marker_size)
# plt.show()
def plot_principal_components_vs_original_attributes(self,
principal_component_numbers='all',
normalize_data_by_std=True,
new_figure=True):
principal_components = self.principal_components(
normalize_data_by_std=normalize_data_by_std)
if principal_component_numbers == 'all':
principal_component_indices = range(self.M())
else:
principal_component_indices = \
np.array(principal_component_numbers) - 1
if new_figure:
figure = plt.figure()
axes = plt.axes()
else:
figure = plt.gcf()
axes = plt.gca()
figure.set_facecolor('white')
axes.set_facecolor('white')
bar_width = 0.75 / len(principal_component_indices)
original_attribute_numbers = np.arange(1, self.M() + 1)
# Plot the significance of each of the original
for principal_component_index in principal_component_indices:
plt.bar(original_attribute_numbers
+ principal_component_index * bar_width,
principal_components[:, principal_component_index],
width=bar_width)
plt.xticks(original_attribute_numbers
+ (len(principal_component_indices) - 1) / 2 * bar_width,
self.attributeNames,
rotation=90)
plt.title('Contribution of original attributes to principal '
'components\n'
'Data normalized with their standard deviation')
plt.xlabel('Original attribute', size=12)
plt.ylabel('PCA coefficients', size=12)
plt.grid(linewidth=0.3)
legend_strings = ['PC ' + str(principal_component_index + 1)
for principal_component_index in
principal_component_indices]
plt.legend(legend_strings,
bbox_to_anchor=(1.005, 1.03),
loc='upper left')
plt.show()
def plot_variance_explained(self,
normalize_data_by_std=True,
threshold=0.9,
new_figure=True):
# compute the diagonal of the PCA's sigma matrix
s = self.svd(compute_uv=False,
normalize_data_by_std=normalize_data_by_std)
# Compute variance explained by principal components
rho = (s * s) / (s * s).sum()
if new_figure:
figure = plt.figure()
axes = plt.axes()
else:
figure = plt.gcf()
axes = plt.gca()
figure.set_facecolor('white')
axes.set_facecolor('white')
# Plot variance explained
plt.figure()
plt.plot(range(1, len(rho) + 1), rho * 100, 'x-')
plt.plot(range(1, len(rho) + 1), np.cumsum(rho) * 100, 'o-')
plt.plot([1, len(rho)], np.array([threshold, threshold]) * 100, 'k--')
plt.title('Variance explained by principal components', size=18)
plt.xlabel('Principal component', size=14)
plt.ylabel('Variance explained [%]', size=14)
plt.ylim(0, 105)
plt.legend(['Individual', 'Cumulative', 'Threshold'])
plt.grid()
plt.show()
def principal_components(self, normalize_data_by_std=True):
_, _, Vh = svd(self.X_centered(normalize_data_by_std),
full_matrices=False)
return Vh.T
def projection_onto_principal_components(self,
normalize_data_by_std=True):
return (self.X_centered() @ self.principal_components(
normalize_data_by_std=normalize_data_by_std))
def reconstruction_from_principal_components(self,
attribute_names='all',
number_of_principal_components='all',
normalize_data_by_std=True):
if number_of_principal_components == 'all':
number_of_principal_components = self.M()
projection = self.projection_onto_principal_components(
normalize_data_by_std=normalize_data_by_std)
projection = projection[:, :number_of_principal_components]
principal_components = \
self.principal_components()[:, :number_of_principal_components]
reconstruction_raw = projection @ principal_components.T
if normalize_data_by_std:
reconstruction = reconstruction_raw * self.attribute_std()
reconstruction = reconstruction + self.attribute_mean()
if attribute_names != 'all':
attribute_indices = [self.attributeNames.index(attribute_name)
for attribute_name in attribute_names]
reconstruction = reconstruction[:, attribute_indices]
return reconstruction
def svd(self, normalize_data_by_std=True, compute_uv=True):
return svd(self.X_centered(normalize_data_by_std),
full_matrices=False,
compute_uv=compute_uv)
def X_centered(self, normalize_data_by_std=True):
# Subtract the attribute mean the attribute values
X_centered = self.X - (np.ones((self.N(), 1)) * self.attribute_mean())
if normalize_data_by_std:
X_centered = X_centered / self.attribute_std()
return X_centered
<file_sep>import networkx as nx
def largest_connected_component(G: nx.Graph,
connection='weak'):
if G.is_directed():
if connection == 'weak':
largest_connected_component_nodes =\
max(nx.weakly_connected_components(G), key=len)
elif connection == 'strong':
largest_connected_component_nodes = \
max(nx.strongly_connected_components(G), key=len)
else:
raise Exception('Invalid connection: "' + connection + '".')
else:
largest_connected_component_nodes = \
max(nx.connected_components(G), key=len)
return G.subgraph(largest_connected_component_nodes).copy()
<file_sep>from wojciech import graph
from wojciech import nlp
from wojciech.empty_figure import empty_figure
from wojciech.find_nearest import find_nearest
from wojciech.format_figure import format_figure
from wojciech.MachineLearningData import MachineLearningData
<file_sep>pandas==1.1.1
networkx==2.5
matplotlib==3.3.2
numpy==1.19.2
seaborn==0.10.1
nltk==3.5
spacy==2.3.2
textblob==0.15.3
tqdm==4.50.0
powerlaw==1.4.6
wordcloud==1.8.0
plotly==4.12.0
scipy==1.5.2
infomap==1.2.1
python_louvain==0.14
community==1.0.0b1
ipython==7.19.0
project==20
en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.3.1/en_core_web_sm-2.3.1.tar.gz
-e git://github.com/bhargavchippada/forceatlas2.git#egg=fa2<file_sep>import json
try:
from library_functions.config import Config
except ModuleNotFoundError:
from project.library_functions.config import Config
def load_data_reddit(alternative_path=None):
if alternative_path:
filepath = alternative_path
else:
filepath = Config.Path.reddit_data_with_NER_and_sentiment
with open(filepath) as file:
drug_database_reddit = json.load(file)
return drug_database_reddit
<file_sep>import networkx as nx
try:
import library_functions as lf
except ModuleNotFoundError:
import project.library_functions as lf
def create_graph_wiki():
# Load data and substance names
wiki_data = lf.load_data_wiki()
substance_names = lf.load_substance_names()
# Get the wiki
g_wiki = nx.DiGraph()
g_wiki.add_nodes_from(substance_names, categories=[])
for index_drug, drug in enumerate(wiki_data["name"]):
if drug in g_wiki.nodes:
g_wiki.nodes[drug]["categories"] = wiki_data["categories"][index_drug]
g_wiki.nodes[drug]["content"] = wiki_data["content"][index_drug]
g_wiki.nodes[drug]["url"] = wiki_data["url"][index_drug]
# Add node properties.
for index_drug, drug in enumerate(wiki_data["name"]):
if drug in g_wiki.nodes:
g_wiki.nodes[drug]["categories"] = wiki_data["categories"][index_drug]
g_wiki.nodes[drug]["content"] = wiki_data["content"][index_drug]
g_wiki.nodes[drug]["url"] = wiki_data["url"][index_drug]
# Add edges.
for index_drug, drug in enumerate(wiki_data["name"]):
if drug not in g_wiki.nodes:
continue
for drug_to_link_to, n_links in wiki_data["links"][index_drug].items():
if drug_to_link_to in g_wiki.nodes:
g_wiki.add_edge(drug, drug_to_link_to, count=n_links)
return g_wiki
<file_sep>from nltk import FreqDist
def term_ratio(tf1: FreqDist,
tf2: FreqDist,
c=None,
normalize=False):
if normalize:
if c is None:
c = 1e-4
return {word: (tf1[word] / tf1.N()) / (tf2[word] / tf2.N() + c)
for word in tf1.keys()}
else:
if c is None:
c = 1
return {word: tf1[word] / (tf2[word] + c)
for word in tf1.keys()}
<file_sep>import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from mpl_toolkits.axes_grid1 import make_axes_locatable
import networkx as nx
import numpy as np
import wojciech as w
def plot_in_vs_out_degree(G: nx.Graph,
plot_type='heatmap', # scatter / heatmap
axes: plt.Axes = None,
colormap_norm='lin'):
# Error check
valid_plot_types = ('scatter',
'heatmap')
if plot_type not in valid_plot_types:
raise Exception('Invalid plot type: "' + plot_type + '"')
valid_colormap_norms = ('lin',
'log')
if colormap_norm not in valid_colormap_norms:
raise Exception('Invalid colormap norm: "' + colormap_norm + '"')
##
in_degrees = w.graph.degrees(G, direction='in')
out_degrees = w.graph.degrees(G, direction='out')
max_degree = np.max((in_degrees, out_degrees))
if plot_type == 'heatmap':
bins = np.arange(max_degree + 1)
heatmap, xedges, yedges = \
np.histogram2d(in_degrees, out_degrees, bins=bins)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
new_figure_created = False
if axes is None:
new_figure_created = True
figure = plt.figure(figsize=(12, 8))
figure.set_facecolor('white')
axes = figure.gca()
axes.set_facecolor('white')
if plot_type == 'scatter':
plot_options = {'marker': 'o',
's': 5}
axes.scatter(in_degrees,
out_degrees,
**plot_options)
axes.set_xlabel('In-degree')
axes.set_ylabel('Out-degree')
axes.set_xlim(0)
axes.set_ylim(0)
elif plot_type == 'heatmap':
if colormap_norm == 'lin':
cnorm = None
elif colormap_norm == 'log':
cnorm = LogNorm(vmin=1, vmax=np.max(heatmap))
plot = axes.imshow(heatmap.T,
extent=extent,
origin='lower',
cmap='Reds',
norm=cnorm)
axes.set_xlim((0, np.ceil(max(in_degrees))))
axes.set_ylim((0, np.ceil(max(out_degrees))))
# create an axes on the right side of ax. The width of cax will be 7%
# of ax and the padding between cax and ax will be fixed at 0.07 inch.
divider = make_axes_locatable(axes)
colorbar_axes = divider.append_axes("right", size="7%", pad=0.07)
figure.colorbar(plot, cax=colorbar_axes)
if new_figure_created:
w.format_figure(figure)
return axes
<file_sep>import json
from typing import Dict, List, Literal, Set, Tuple
import random
try:
import library_functions as lf
except ModuleNotFoundError:
import project.library_functions as lf
try:
from library_functions.config import Config
except ModuleNotFoundError:
from project.library_functions.config import Config
# pre-fetch/compute some stuff to make computations faster
wiki_data = lf.load_data_wiki()
with open(Config.Path.wiki_mechanism_categories, "r") as f:
mechanism_categories_mapping = json.load(f)
with open(Config.Path.wiki_effect_categories, "r") as f:
effects_categories_mapping = json.load(f)
def get_page_from_name(name: str) -> Dict:
"""Given a substance name (eventually one of its synonyms),
return the corresponding wikipedia entry
Args:
name (str): name or synonym for the substance
Returns:
Dict: Dict containing name, redirects, links, contents, categories, and url
"""
name = synonyms_to_names[name]
wiki_data_index = wiki_data["name"].index(name)
return {
"name": wiki_data["name"][wiki_data_index],
"url": wiki_data["url"][wiki_data_index],
"categories": wiki_data["categories"][wiki_data_index],
"content": wiki_data["content"][wiki_data_index],
"links": wiki_data["links"][wiki_data_index],
"synonyms": wiki_data["synonyms"][wiki_data_index],
}
def get_random_page() -> Dict:
"""Return a random Wikipedia page
Returns:
Dict: Dict containing name, redirects, links, contents, categories, and url
"""
name = random.choice(wiki_data["names"])
return get_page_from_name(name)
def get_wiki_page_names(with_synonyms: bool = False) -> Set[str]:
"""Get a list with the names of all the substance pages on wikipedia
Args:
with_synonyms (bool): include synonyms in the list
Returns:
List[str]: List containing all substance names on wikipedia , eventually with synonyms
"""
names = set(wiki_data["name"])
if with_synonyms:
names = names.union(synonyms_to_names.keys())
return names
def get_wiki_synonyms_mapping() -> Dict[str, str]:
"""Return a dict mapping synonyms to the name of the wiki pages
Returns:
Dict[str, str]: Dict mapping synonyms (and names) to names
"""
with open(Config.Path.synonym_mapping, "r") as f:
return json.load(f)
synonyms_to_names = get_wiki_synonyms_mapping()
all_names_and_synonyms = get_wiki_page_names(with_synonyms=True)
def get_page_lengths() -> List[int]:
"""Get a list of all the page lengths, in characters
Returns:
List[int]: List of the number of characters in each wiki page
"""
wiki_data["length"] = [len(p) for p in wiki_data["content"]]
return wiki_data["length"]
def get_number_of_links() -> List[int]:
"""Get a list of the number of links of each page (only counting links to other substances)
Returns:
List[int]: List of the number of links that each page has towards other pages
"""
valid_links_numbers = []
wiki_data["valid_links"] = []
for links in wiki_data["links"]:
valid_links = [link for link in links if link.lower() in all_names_and_synonyms]
valid_links_numbers.append(len(valid_links))
wiki_data["valid_links"].append(valid_links)
return valid_links_numbers
def get_number_of_categories() -> List[int]:
"""Get a list of the number of categories that each page is part of
Returns:
List[int]: List of the number of categories that each page belongs to
"""
return [len(cats) for cats in wiki_data["categories"]]
def get_number_of_synonyms() -> List[int]:
"""Get a list of the number of synonyms (redirects) of each page
Returns:
List[int]: List of the number of redirects that each page has
"""
return [len(syns) for syns in wiki_data["synonyms"]]
def get_name_by(indices: List[int]) -> List[str]:
"""Return the names corresponding to the indices passed as argument
Args:
indices (List[int]): List of indices of the pages for which to get names
Returns:
List[str]: List of names corresponding to the given indices
"""
return [wiki_data["name"][i] for i in indices]
def get_top(property: str, amount: int = 10, reverse=False) -> List[Tuple[str, int]]:
tuples = zip(
wiki_data["name"],
[p if type(p) == int else len(p) for p in wiki_data[property]],
)
sorted_tuples = sorted(
tuples, key=lambda x: x[1] if type(x[1]) == int else len(x[1]), reverse=reverse
)
return sorted_tuples[:amount]
def get_wiki_data() -> Dict:
"""Get a copy of the wiki_data dict
Returns:
Dict: shallow copy of the wiki_data dict
"""
return wiki_data.copy()
def get_root_category_mapping(which: Literal["effects", "mechanisms"]) -> Dict:
if which == "effects":
return effects_categories_mapping.copy()
elif which == "mechanisms":
return mechanism_categories_mapping.copy()
else:
raise RuntimeError("Can only be one of 'effects','mechanisms'")<file_sep>import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import wojciech as w
from typing import Dict, Iterable, Union
def plot_distribution_of_attribute_of_1_instance(
graphs: Union[nx.Graph, Dict],
instance,
instance_label,
attribute_name,
axess: Union[plt.Axes, Iterable[plt.Axes]] = None,
title=None,
annotate='all',
x_label_size=14,
y_label_size=14,
title_size=14,
bins=100,
fig_width: Union[float, int] = 8
):
# Sanitize inp ut
if not isinstance(graphs, dict):
graphs = {'': graphs}
if not isinstance(annotate, list):
annotate = [annotate]
# Get the figure and axes handles
new_figure_created = False
if axess is None:
new_figure_created = True
figure_size = (fig_width, fig_width / 3 * len(graphs) + 1)
figure, axess = plt.subplots(len(graphs), 1,
figsize=(figure_size),
sharey='all',
sharex='all')
if not isinstance(axess, (list, np.ndarray)):
axess = [axess]
figure = axess[0].get_figure()
# Set the title of the figure
if ('title' in annotate) or ('all' in annotate):
if title is None:
title = f'Distribution of attribute: "{attribute_name}" ' \
f'for {instance}: "{instance_label}"'
figure.suptitle(title,
y=min(0.98 + 0.003 * (len(graphs) - 1), 0.995),
verticalalignment='top',
fontsize=20)
for index, ((graph_name, graph), axes) in \
enumerate(zip(graphs.items(), axess)):
if instance == 'node':
if graph.has_node(instance_label):
attribute_values = graph.nodes[instance_label][attribute_name]
else:
attribute_values = []
elif instance == 'edge':
if graph.has_edge(*instance_label):
attribute_values = graph.edges[instance_label][attribute_name]
else:
attribute_values = []
else:
raise ValueError(f'Invalid instance "{instance}"')
axes.hist(attribute_values, bins=bins)
axes.set_title(graph_name)
if ('x_label' in annotate) or ('all' in annotate):
if index == len(graphs) - 1:
axes.set_xlabel(attribute_name.capitalize())
if ('y_label' in annotate) or ('all' in annotate):
axes.set_ylabel('Count')
axes.xaxis.label.set_fontsize(x_label_size)
axes.yaxis.label.set_fontsize(y_label_size)
axes.title.set_fontsize(title_size)
axes.spines['top'].set_color('white')
axes.spines['right'].set_color('white')
axes.set_facecolor("white")
if new_figure_created:
figure.tight_layout()
plt.show()
return axess
<file_sep>#%%
from typing import Dict, List, Optional, Tuple, Union
import community
import matplotlib
import networkx as nx
import numpy as np
import plotly.graph_objects as go
import spacy
import wojciech as w
from infomap import Infomap
from tqdm.auto import tqdm
from wordcloud import STOPWORDS, WordCloud
nlp = spacy.load("en_core_web_sm")
def get_lemmas(text, get_doc=False):
# utility function to get a list of lemmas from a text.
doc = nlp.make_doc(text)
# only keep lemmas that are not punctuation
lemmas = [i.lemma_.lower() for i in doc if not i.is_punct]
if not get_doc:
return lemmas
else:
return (lemmas, doc)
def assign_lemmas(graph: nx.Graph, save_spacy_docs=False):
# check that the graph was loaded with
assert (
"contents" in list(graph.nodes(data=True))[0][1]
or "content" in list(graph.nodes(data=True))[0][1]
), "The graph does not contain node contents."
# iterate over all nodes:
for node, data in tqdm(graph.nodes(data=True)):
# The data is kept in slightly different ways in the two networks,
# so we need the try/except statement:
try:
text = " ".join(data["contents"])
except:
text = data["content"]
# Get the lemmas and assign them to the node as a new attribute
lemmas, doc = get_lemmas(text, get_doc=True)
graph.nodes[node]["lemmas"] = lemmas
if save_spacy_docs:
graph.nodes[node]["doc"] = doc
# %%
def assign_tfs(graph: nx.Graph, type: str = "frequency"):
for node, data in tqdm(graph.nodes(data=True)):
graph.nodes[node]["tfs"] = w.nlp.term_frequency(
terms=None, document=data["lemmas"], type="frequency"
)
def assign_idfs(graph: nx.Graph, type: str = "regular"):
all_lemmas = [data["lemmas"] for node_, data in graph.nodes(data=True)]
for node, data in tqdm(graph.nodes(data=True)):
# other_lemmas_list = []
# for lemmas_list in other_lemmas:
# other_lemmas_list += lemmas_list
graph.nodes[node]["idfs"] = w.nlp.inverse_document_frequency(
terms=None, documents=all_lemmas, term_document=data["lemmas"], type=type
)
def assign_tf_idfs(graph: nx.Graph):
assert (
"tfs" in list(graph.nodes(data=True))[0][1]
and "idfs" in list(graph.nodes(data=True))[0][1]
), "The graph does not contain tfs and idfs, please call those functions first."
for node, data in tqdm(graph.nodes(data=True)):
tfidfs = {}
for lemma in data["lemmas"]:
tfidfs[lemma] = data["tfs"][lemma] * data["idfs"][lemma]
graph.nodes[node]["tf-idfs"] = tfidfs
def assign_text_analysis(graph: nx.Graph):
"""Apply (and assign as attribute) all the steps necessary to get tf-idfs
Args:
graph (nx.Graph): networkx graph with nodes containing a "content" or "contents" attribute
"""
assign_lemmas(graph)
assign_tfs(graph)
assign_idfs(graph)
assign_tf_idfs(graph)
def wordcloud_from_node(graph: nx.Graph, node: str, color_func=None):
if color_func:
wc = WordCloud(
background_color="white",
width=900,
height=900,
collocations=False,
color_func=color_func,
).generate_from_frequencies(graph.nodes[node]["tf-idfs"])
else:
wc = WordCloud(
background_color="white",
width=900,
height=900,
collocations=False,
).generate_from_frequencies(graph.nodes[node]["tf-idfs"])
return wc
def wordcloud_from_link(graph: nx.Graph, n1, n2, color_func):
edgetext = " ".join(graph.edges[(n1, n2)]["contents"])
lemmas = get_lemmas(edgetext)
tfs = w.nlp.term_frequency(terms=None, document=lemmas, type="frequency")
all_lemmas = [data["lemmas"] for node_, data in graph.nodes(data=True)]
idfs = w.nlp.inverse_document_frequency(
terms=None, documents=all_lemmas, term_document=lemmas, type="regular"
)
tfidfs = {}
for lemma in lemmas:
tfidfs[lemma] = tfs[lemma] * idfs[lemma]
wc = WordCloud(
background_color="white",
width=900,
height=900,
collocations=False,
color_func=color_func,
).generate_from_frequencies(tfidfs)
return wc
def wordcloud_from_nodes(graph: nx.Graph, nodes: List[str]):
"""Generate a wordcloud from a community (set of nodes).
Because the amount of possible combinations is enormous, this is generated on the fly and thus much slower than for single nodes.
Args:
graph (nx.Graph): Graph containing the nodes and the lemmas associated with each node.
nodes (List[str]): List of node labels for which to compute the wordcloud
Returns:
[type]: matplotlib image with the resulting wordcloud
"""
nodes_lemmas = []
for node in tqdm(nodes):
nodes_lemmas += graph.nodes[node]["lemmas"]
other_nodes_lemmas = []
for node, data in tqdm(graph.nodes(data=True)):
if node not in nodes:
other_nodes_lemmas += data["lemmas"]
tfs = w.nlp.term_frequency(terms=None, document=nodes_lemmas, type="frequency")
idfs = w.nlp.inverse_document_frequency(
terms=None,
documents=other_nodes_lemmas,
term_document=nodes_lemmas,
type="regular",
)
tf_idfs = {lemma: tfs[lemma] * idfs[lemma] for lemma in tqdm(nodes_lemmas)}
wc = WordCloud(
background_color="white", width=1800, height=1000, collocations=False
).generate_from_frequencies(tf_idfs)
return wc
def compute_dosage_mentions(reddit_data):
pass
def rank_dict(dict_: Dict[str, float], verbose=False, reverse=False):
res = sorted(dict_.items(), key=lambda x: x[1], reverse=reverse)
if verbose:
print("Top 5 elements:")
for name, val in res[:5]:
print(f"{val:.3f} \t- {name}")
return res
<file_sep>from nltk import FreqDist
import numpy as np
from typing import Any
# from tqdm import tqdm
def inverse_document_frequency(terms: Any,
documents: list,
type: str = 'regular',
term_document: list = None):
return_dict = True
# Terms will be regarded as a list.
# If terms is set to none, set terms to all the terms in the term document
if terms is None:
terms = set(term_document)
# If the terms is a string, the output of the function will also be
# a string.
elif isinstance(terms, str):
return_dict = False
terms = [terms]
n_documents = len(documents)
documents = [set(document) for document in documents]
n_documents_containing =\
{term: np.sum([term in document for document in documents])
for term in terms}
if type.lower() == 'regular':
result = {
term: np.log10(n_documents / n_documents_containing[term])
for term in terms}
elif type.lower() == 'smooth':
result = {
term: 1 + np.log10(n_documents / (1 + n_documents_containing[term]))
for term in terms}
elif type.lower() == 'max':
n_documents_containing = dict()
for word in term_document:
for document in documents:
if word in document:
n_documents_containing[word] += 1
max_n = max(n_documents_containing.values())
result = {term: np.log10(max_n / (1 + n_documents_containing[term]))
for term in terms}
elif type.lower() == 'probabilistic':
result = \
{term: np.log10((n_documents - n_documents_containing[term])
/ n_documents_containing[term])
for term in terms}
else:
raise Exception('Unknown type: "' + type + '".')
if not return_dict:
result = result[terms[0]]
return result
<file_sep># %% Functions to place nodes on a 2d space
import json
import networkx as nx
from fa2 import ForceAtlas2
try:
import library_functions as lf
except ModuleNotFoundError:
import project.library_functions as lf
try:
from library_functions.config import Config
except ModuleNotFoundError:
from project.library_functions.config import Config
# %%
forceatlas2 = ForceAtlas2(
# Behavior alternatives
outboundAttractionDistribution=True, # Dissuade hubs
linLogMode=False, # NOT IMPLEMENTED
adjustSizes=False, # Prevent overlap (NOT IMPLEMENTED)
edgeWeightInfluence=1.0,
# Performance
jitterTolerance=0.5, # Tolerance
barnesHutOptimize=True,
barnesHutTheta=1.2,
multiThreaded=False, # NOT IMPLEMENTED
# Tuning
scalingRatio=5,
strongGravityMode=False,
gravity=1,
# Log
verbose=True,
)
def get_fa2_layout(
graph: nx.Graph,
edge_weight_attribute: str = None,
saved: str = None,
save: str = None,
):
"""Generate a layout using the fa2 algorithm, or load one from disk.
Args:
graph (nx.Graph): graph for which to compute the layout
edge_weight_attribute (str, optional): Which edge attribute to use for computing the layout. WARNING: only works with latest fa2 version.
saved (str, optional): If not none, load the layout from the given path instead of computing it. Defaults to None.
save (str, optional): if not none, save the layout to the given path. Defaults to None.
Returns:
Dict: networkx layout giving the position of nodes
"""
if saved:
with open(Config.Path.shared_data_folder / saved, "r") as f:
layout = json.load(f)
assert (
len(layout) == graph.number_of_nodes()
), "Loaded layout does not have the same amount of nodes as the given graph"
for node in graph.nodes:
assert (
node in layout
), "The graph contains a node that was not found in the layout"
return layout
try:
if edge_weight_attribute:
layout = forceatlas2.forceatlas2_networkx_layout(
graph, pos=None, weight_attr=edge_weight_attribute, iterations=1000
)
else:
layout = forceatlas2.forceatlas2_networkx_layout(
graph, pos=None, iterations=1000
)
except TypeError:
print(
"You need to install force atlas from source because the pip version doesn't support weighted edges. "
)
print("See https://github.com/bhargavchippada/forceatlas2 ")
raise
if save:
with open(Config.Path.shared_data_folder / save, "w") as f:
json.dump(layout, f)
return layout
def get_circle_layout(graph: nx.Graph):
return nx.drawing.layout.circular_layout(graph)
<file_sep>from pathlib import Path
class Config:
class Path:
# Project root
project_root = Path(__file__).parent.parent
# Private data (not added to git to save space and bandwidth)
private_data_folder = project_root / "private_data"
# Shared data:
shared_data_folder = project_root / "data"
dietary_supplements_category_tree_clean = (
shared_data_folder / "dietary_supplements_category_tree_clean.json"
)
dietary_supplements_category_tree_raw = (
shared_data_folder / "dietary_supplements_category_tree_raw.json"
)
full_category_tree_clean = shared_data_folder / "full_category_tree_clean.json"
full_wiki_data = shared_data_folder / "full_wiki_data.json"
psychoactive_category_tree_clean = (
shared_data_folder / "psychoactive_category_tree_clean.json"
)
psychoactive_category_tree_raw = (
shared_data_folder / "psychoactive_category_tree_raw.json"
)
reddit_data_with_NER = shared_data_folder / "reddit_data_with_NER.json"
reddit_data_with_NER_and_sentiment = (
shared_data_folder / "reddit_data_with_NER_and_sentiment.json"
)
substance_names = shared_data_folder / "substance_names.json"
synonym_mapping = shared_data_folder / "synonym_mapping.json"
contents_per_substance = shared_data_folder / "contents_per_substance.json"
urls_per_substance = shared_data_folder / "urls_per_substance.json"
posts_per_substance = shared_data_folder / "posts_per_substance.json"
posts_per_link = shared_data_folder / "posts_per_link.json"
# Wiki data:
wiki_data_folder = shared_data_folder / "wikipedia_data"
all_categories_to_names_mapping = (
shared_data_folder / "all_categories_to_names_mapping.json"
)
wiki_mechanism_categories = (
shared_data_folder / "wiki_mechanism_categories.json"
)
wiki_effect_categories = shared_data_folder / "wiki_effect_categories.json"
# Graphs
wiki_digraph = shared_data_folder / "wiki_digraph.gpickle"
reddit_graph = shared_data_folder / "reddit_graph.gpickle"
wiki_gcc = shared_data_folder / "wiki_gcc.gpickle"
reddit_gcc = shared_data_folder / "reddit_gcc.gpickle"
reddit_with_text = shared_data_folder / "reddit_with_textdata.gpickle"
class Color:
red = (1, 0, 0, 0.3)
blue = (0, 0, 1, 0.3)
black = (0, 0, 0, 0.6)
<file_sep>import pandas as pd
import wojciech as w
import matplotlib.pyplot as plt
def plot_conditional_frequency_distribution(cfd,
axes: plt.Axes = None):
df_cfd = pd.DataFrame.from_dict(cfd, orient='index')
new_figure_created = False
if axes is None:
new_figure_created = True
figure = plt.figure(figsize=(12, 8))
axes = figure.gca()
df_cfd.plot.bar(ax=axes)
if new_figure_created:
w.format_figure(figure)
return axes
<file_sep>import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import powerlaw
import wojciech as w
from typing import Dict, List, Tuple, Union
def plot_degree_distribution_summary(graphs: Union[nx.Graph, Dict],
directions: Union[str, List, Tuple] = None,
graph_colors=None,
title=None,
title_y_position: float = 0.97,
x_lim_lin=None,
x_lim_log=None
):
'''
:param graphs: networkx Graph or dict keyed by graph names whose values
are graph objects
:param directions: degree direction or a list of directions whose length
corresponds to number of graphs.
:param graph_colors: graph color or a list of colors whose length
corresponds to number of graphs.
:param title: title of the figure.
:param title_y_position: the y position of the title of the figure.
:param x_lim_lin: the x-axis limits for the lin-lin axes
:param x_log_log: the x-axis limits for the log-log axes
:return: a numpy array containing the grid of axes in the plot
:Example:
>>> plot_degree_distribution_summary(G)
:Example:
>>> graphs = {'Graph 1': G_1,
>>> 'Graph 2': G_2}
>>> graph_colors = ['red', 'blue']
>>> directions = [None, 'in', 'out']
>>> title = ['Comparison of Graph 1 and Graph 2']
>>> title_y_position = 0.97
>>> x_lim_lin = (0, 100)
>>> x_lim_log = (1, 1000)
>>> plot_degree_distribution_summary(graphs,
>>> graph_colors=graph_colors,
>>> title=title,
>>> title_y_position=title_y_position,
>>> x_lim_lin=x_lim_lin,
>>> x_lim_log=x_lim_log
>>> )
'''
# If graph is not a dict (i.e. is single graph object), transform it into
# a dict.
if not isinstance(graphs, dict):
graphs = {'Graph 1': graphs}
# Assign default graph colors.
if graph_colors is None:
graph_colors = \
plt.rcParams['axes.prop_cycle'].by_key()['color'][:len(graphs)]
# Assign default directions
if directions is None:
if any([graph.is_directed() for graph in graphs.values()]):
directions = [None, 'in', 'out']
else:
directions = [None]
# Create a figure and axes for the plot
figure, axes_all = plt.subplots(len(directions), 2,
sharex='col', sharey='col',
figsize=(12, 4 * len(directions) + 1),
facecolor='white')
# Make sure that the axes_all 2 - dimensional, as we will use the
# left column for lin-lin and right column for log-log plots.
if len(axes_all.shape) < 2:
axes_all = np.expand_dims(axes_all, axis=0)
# Set the figure title
if title is not None:
figure.suptitle(title,
y=title_y_position,
verticalalignment='top',
fontsize=16)
# Initialize min and max finders
max_y_data = 0
max_y_data_without_0_degree = 0
min_y_data_without_0_degree = 1
max_x_data = 0
if len(graphs) == 1:
lin_lin_graph_type = 'bar'
else:
lin_lin_graph_type = 'scatter'
for (graph_name, graph), graph_color in zip(graphs.items(), graph_colors):
common_plot_options = {'as_probability_distribution': True,
'color': graph_color}
for index, (direction, axes_lin_lin, axes_log_log) \
in enumerate(zip(directions, axes_all[:, 0], axes_all[:, 1])):
# Ignore graphs
if (direction is not None) & (not graph.is_directed()):
continue
# Lin - lin axes
if index == len(directions) - 1:
annotate = ['title', 'x_label', 'y_label']
else:
annotate = ['title', 'y_label']
# Define the plot options for the lin-lin graph
lin_lin_plot_options = common_plot_options.copy()
lin_lin_plot_options.update({'annotate': annotate,
'axes': axes_lin_lin,
'axis_scaling': 'lin-lin',
'direction': direction,
'label': graph_name,
'plot_type': lin_lin_graph_type,
})
if lin_lin_graph_type == 'scatter':
lin_lin_plot_options.update({'marker_size': 40})
# Plot the degree distribution
_, (degrees, distribution) = \
w.graph.plot_degree_distribution(graph, **lin_lin_plot_options)
# Apply axes formatting
format_axes(axes_lin_lin)
# Update min and max counters
max_y_data = np.max((np.max(distribution), max_y_data))
max_y_data_without_0_degree = np.max((np.max(distribution[1:]),
max_y_data_without_0_degree))
min_y_data_nonzero =\
np.min((np.min(distribution[distribution != 0]),
min_y_data_without_0_degree))
max_x_data = np.max((np.max(degrees), max_x_data))
# Log - log axes
if index == len(directions) - 1:
annotate = ['title', 'x_label']
else:
annotate = ['title']
# Calculate power-law slope
alpha =\
powerlaw.Fit(w.graph.degrees(graph, direction=direction),
verbose=False).alpha
# Define the plot options for the lin-lin graph
log_log_plot_options = common_plot_options.copy()
log_log_plot_options.update({'annotate': annotate,
'axes': axes_log_log,
'axis_scaling': 'log-log',
'direction': direction,
'label': rf'$\alpha$ = {alpha:.2f}',
'marker_size': 40,
'plot_type': 'scatter',
})
w.graph.plot_degree_distribution(graph, **log_log_plot_options)
# Apply axes formatting
format_axes(axes_log_log)
# Adjust axes limits
axes_all[0, 0].set_ylim((0, max_y_data + 0.05))
axes_all[0, 1].set_ylim((
np.power(10, np.floor(np.log10(min_y_data_nonzero))),
np.power(10, np.ceil(np.log10(max_y_data_without_0_degree)))
))
if x_lim_lin is not None:
axes_all[0, 0].set_xlim(x_lim_lin)
else:
axes_all[0, 0].set_xlim((-3, max_x_data))
if x_lim_log is not None:
axes_all[0, 1].set_xlim(x_lim_log)
else:
axes_all[0, 1].set_xlim(
(0.9, np.power(10, np.ceil(np.log10(max_x_data)))))
# Show legends
for index, (axes_lin_lin, axes_log_log) \
in enumerate(zip(axes_all[:, 0], axes_all[:, 1])):
legend_lin_lin = axes_lin_lin.legend(prop={'size': 14})
legend_log_log = axes_log_log.legend(prop={'size': 14})
if (len(graphs) == 1) or (index != 0):
legend_lin_lin.remove()
# Show plots
plt.show()
return axes_all
def format_axes(axes):
axes.spines['top'].set_color('white')
axes.spines['right'].set_color('white')
axes.xaxis.grid(which="both", linewidth=0.5)
axes.yaxis.grid(which="both", linewidth=0.5)
axes.xaxis.label.set_fontsize(12)
axes.yaxis.label.set_fontsize(12)
axes.title.set_fontsize(14)
<file_sep>import json
from typing import Dict
try:
from library_functions.config import Config
except ModuleNotFoundError:
from project.library_functions.config import Config
def save_synonym_mapping(wiki_data: Dict):
"""Save a mapping from synonyms to substance names
Args:
wiki_data (Dict): Flat dict of substance names
"""
# Small snippet to save an inverse mapping from synonyms to names
synonym_mapping = {}
for index, name in enumerate(wiki_data["name"]):
for synonym in wiki_data["synonyms"][index]:
synonym_mapping[synonym] = name
# Also map from the substance to itself
synonym_mapping[name] = name
with open(Config.Path.synonym_mapping, "w+") as f:
json.dump(synonym_mapping, f, indent=2)
def save_substance_names(wiki_data: Dict):
"""Save the list of all substance names to a json file.
Args:
wiki_data (Dict): Dict containing the wikipedia data (flat)
"""
with open(Config.Path.substance_names, "w+") as f:
json.dump(wiki_data["name"], f, indent=2)
def save_contents(wiki_data: Dict):
"""Save mapping from substance name to wikipedia contents
Args:
wiki_data (Dict): Flat dict containing wikipedia data
"""
with open(Config.Path.contents_per_substance, "w+") as f:
json.dump(dict(zip(wiki_data["name"], wiki_data["content"])), f)
def save_urls(wiki_data: Dict):
"""Save mapping from substance name to wikipedia urls
Args:
wiki_data (Dict): Flat dict containing wikipedia data
"""
with open(Config.Path.urls_per_substance, "w+") as f:
json.dump(dict(zip(wiki_data["name"], wiki_data["url"])), f)
def save_wiki_data_files(wiki_data: Dict):
"""Save all secondary files to facilitate access to wiki data: names, synonym mapping, urls and content mapping.
Args:
wiki_data (Dict): flat dict with all wikipedia data
"""
save_synonym_mapping(wiki_data=wiki_data)
save_substance_names(wiki_data=wiki_data)
save_contents(wiki_data=wiki_data)
save_urls(wiki_data=wiki_data)
<file_sep>def lowercase(text):
if isinstance(text, str):
return text.lower()
if isinstance(text, list):
return [string.lower() for string in text]
else:
raise TypeError('"text" should be a string or a list of strings')<file_sep>import networkx as nx
import numpy as np
import pandas as pd
import wojciech as w
from typing import List
from scipy import stats
def degree_statistics(G: nx.Graph,
node_labels = None,
as_pandas: bool = False,
printout = False):
all_degrees = w.graph.degrees(G,
node_labels=node_labels)
if G.is_directed():
in_degrees = w.graph.degrees(G,
node_labels=node_labels,
direction='in')
out_degrees = w.graph.degrees(G,
node_labels=node_labels,
direction='out')
statistics = dict()
statistics['average degree'] = np.mean(all_degrees)
if G.is_directed():
statistics['average in-degree'] = np.mean(in_degrees)
statistics['average out-degree'] = np.mean(out_degrees)
statistics['median degree'] = np.median(all_degrees)
if G.is_directed():
statistics['median in-degree'] = np.median(in_degrees)
statistics['median out-degree'] = np.median(out_degrees)
mode_all_degrees, count_mode_in_degrees = np.asarray(stats.mode(all_degrees))
if G.is_directed():
mode_in_degrees, count_mode_in_degrees = np.asarray(stats.mode(in_degrees))
mode_out_degrees, count_mode_out_degrees =\
np.asarray(stats.mode(out_degrees))
statistics['mode degree'] = mode_all_degrees[0]
if G.is_directed():
statistics['mode in-degree'] = mode_in_degrees[0]
statistics['mode out-degree'] = mode_out_degrees[0]
statistics['minimum degree'] = np.min(all_degrees)
if G.is_directed():
statistics['minimum in-degree'] = np.min(in_degrees)
statistics['minimum out-degree'] = np.min(out_degrees)
statistics['maximum degree'] = np.max(all_degrees)
if G.is_directed():
statistics['maximum in-degree'] = np.max(in_degrees)
statistics['maximum out-degree'] = np.max(out_degrees)
if as_pandas:
index = ['Total degree']
degrees = ['degree']
if G.is_directed():
index = index + ['In-degree', 'Out-degree']
degrees = degrees + ['in-degree', 'out-degree']
column_names = ['Min', 'Max', 'Mean', 'Median', 'Mode']
data = {column_name: list() for column_name in column_names}
for degree in degrees:
data['Min'].append(statistics['minimum ' + degree])
data['Max'].append(statistics['maximum ' + degree])
data['Mean'].append(statistics['average ' + degree])
data['Median'].append(statistics['median ' + degree])
data['Mode'].append(statistics['mode ' + degree])
statistics_pandas = pd.DataFrame.from_dict(data)
statistics_pandas.set_index(pd.Index(index), inplace=True)
if printout:
if as_pandas:
display(statistics_pandas)
else:
print('Overall degree:')
print('\tMinimum: ', statistics['minimum degree'])
print('\tMaximum: ', statistics['maximum degree'])
print(f"\tAverage: {statistics['average degree']:.2f}")
print('\tMedian: ', statistics['median degree'])
print('\tMode: ', statistics['mode degree'])
if G.is_directed():
print()
print('In-degrees:')
print('\tMinimum: ', statistics['minimum in-degree'])
print('\tMaximum: ', statistics['maximum in-degree'])
print(f"\tAverage: {statistics['average in-degree']:.2f}")
print('\tMedian: ', statistics['median in-degree'])
print('\tMode: ', statistics['mode in-degree'])
print()
print('Out-degrees:')
print('\tMinimum: ', statistics['minimum out-degree'])
print('\tMaximum: ', statistics['maximum out-degree'])
print(f"\tAverage: {statistics['average out-degree']:.2f}")
print('\tMedian: ', statistics['median out-degree'])
print('\tMode: ', statistics['mode out-degree'])
if as_pandas:
return statistics_pandas
else:
return statistics
<file_sep>import networkx as nx
import numpy as np
import pandas as pd
from IPython.core.display import display
from typing import Dict
def display_graph_size(graphs: Dict[str, nx.Graph]):
pandas_dict = {
'Nodes': [graph.number_of_nodes()
for graph in graphs.values()],
'Edges': [graph.number_of_edges()
for graph in graphs.values()]
}
df_graph_size = (pd.DataFrame
.from_dict(pandas_dict)
.set_index(pd.Index(list(graphs.keys()))))
display(df_graph_size)<file_sep>from nltk.corpus import PlaintextCorpusReader
from nltk.tokenize import RegexpTokenizer
from pathlib import Path
def nvc():
corpus_root = str(Path(__file__).parent / 'Nonviolent_Communication')
return PlaintextCorpusReader(corpus_root, '.*', RegexpTokenizer(r"[\w']+"))
<file_sep>import matplotlib.pyplot as plt
def format_figure(fig: plt.Figure,
title: str = None,
x_label: str = None,
y_label: str = None,
title_y_position: float = 0.93):
fig.set_figwidth(12)
fig.set_figheight(8)
fig.set_facecolor("white")
if title is not None:
fig.suptitle(title,
y=title_y_position,
verticalalignment='top',
fontsize=24)
axes = fig.axes
for ax in axes:
ax.spines['top'].set_color('white')
ax.spines['right'].set_color('white')
ax.set_facecolor("white")
ax.xaxis.grid(which="both", linewidth=0.5)
ax.yaxis.grid(which="both", linewidth=0.5)
ax.xaxis.label.set_fontsize(18)
ax.yaxis.label.set_fontsize(18)
ax.title.set_fontsize(20)
if x_label is not None:
fig.text(0.5, 0.04, x_label,
ha='center',
fontdict={'size': 18})
if y_label is not None:
fig.text(0.04, 0.5, y_label,
va='center',
rotation='vertical',
fontdict={'size': 18})
<file_sep>import json
from typing import Dict
try:
import library_functions as lf
except ModuleNotFoundError:
import project.library_functions as lf
try:
from library_functions.config import Config
except ModuleNotFoundError:
from project.library_functions.config import Config
from wojciech.lowercase import lowercase
def load_data_wiki():
with open(Config.Path.full_wiki_data) as file:
drug_database = json.load(file)
wiki_properties = [
"name",
"categories",
"content",
"links",
"synonyms",
"url",
]
wiki_data = {prop: list() for prop in wiki_properties}
for drug, drug_data in drug_database.items():
data = drug_data["data"]
wiki_data["name"].append(drug.lower())
wiki_data["categories"].append(lowercase(data["categories"]))
wiki_data["content"].append(data["content"].lower())
wiki_data["links"].append(
{key.lower(): value for key, value in data["links"].items()}
)
wiki_data["synonyms"].append(lowercase(data["redirects"]))
wiki_data["url"].append(data["url"])
lf.save_synonym_mapping(wiki_data)
return wiki_data
<file_sep>#%%
import json
from typing import Dict, List, Tuple, Union
import networkx as nx
import numpy as np
import plotly.graph_objects as go
try:
from library_functions.config import Config
except:
from project.library_functions.config import Config
# %%
with open(Config.Path.contents_per_substance, "r+") as f:
contents_per_substance = json.load(f)
with open(Config.Path.urls_per_substance, "r+") as f:
url_per_substance = json.load(f)
def get_edge_traces(
graph: nx.Graph,
positions: Dict[Union[str, int], Tuple[int, int]] = None,
edge_weight_attribute: str = None,
edge_hover_attributes: List[str] = None,
):
edges_x = []
edges_y = []
widths = []
colors = []
names = []
counts = []
max_width = 20
for e1, e2, data in graph.edges(data=True):
x0, y0 = positions[e1]
x1, y1 = positions[e2]
# edges_x.append([x0, x1, x1 + 1, x0 + 1, x0])
edges_x.append([x0, x1])
# edges_y.append([y0, y1, y1, y0, y0])
edges_y.append([y0, y1])
names.append((e1, e2))
if edge_weight_attribute:
values = [data[edge_weight_attribute] for _, _, data in graph.edges(data=True)]
logs = np.log(values)
maxlog = np.max(logs)
maxval = np.max(values)
alphas = (logs / maxlog) ** 2
colors = [f"rgba(40,40,40,{a:.4f})" for a in alphas]
widths = (logs / maxlog) * max_width
else:
widths = np.repeat(1, len(edges_x))
colors = np.repeat("rgba(40,40,40,0.1)", len(edges_x))
edge_traces = []
for i in range(len(edges_x)):
if widths[i] > 0:
trace = go.Scatter(
x=edges_x[i],
y=edges_y[i],
line={"width": widths[i], "color": colors[i]},
hoverinfo="text" if edge_hover_attributes else "none",
mode="lines",
fill="toself",
)
if edge_hover_attributes:
text = f"Link between {names[i][0]} and +{names[i][1]}. <br>"
if "count" in edge_hover_attributes:
text += f"This link came up {counts[i]} times."
trace.text = text
edge_traces.append(trace)
return edge_traces
def split_text_at(text: str, length: int) -> str:
words = text.split()
results = []
line_length = 0
for word in words:
if line_length < length:
results.append(word)
line_length += len(word)
else:
results.append("<br>")
results.append(word)
line_length = len(word)
return " ".join(results)
def get_nodes_hover(graph: nx.Graph) -> List[str]:
node_hovers = []
for name, data in graph.nodes(data=True):
hover = f"Nootropic: {name}, Degree: {graph.degree(name)}. <br>"
if "categories" in data:
hover += f"\n Part of {len(data['categories'])} categories. <br><br>"
hover += f'"{split_text_at(contents_per_substance[name][:120], 40)}..."<br> <br> <br> '
hover += f"Read more: {url_per_substance[name]}"
node_hovers.append(hover)
return node_hovers
def get_nodes_trace(
graph: nx.Graph,
node_weight_attribute: str = None,
node_color_attribute: str = None,
node_size_attribute: str = None,
positions: Dict[Union[str, int], Tuple[int, int]] = None,
):
nodes_x = []
nodes_y = []
colors = [] if node_color_attribute else "rgba(0,0,0,0.5)"
sizes = [] if node_size_attribute else 12
for node, data in graph.nodes(data=True):
nodes_x.append(positions[node][0])
nodes_y.append(positions[node][1])
if node_color_attribute:
if node_color_attribute != "degree":
assert (
node_color_attribute in data
), f"Color attribute {node_color_attribute} not found in node data"
if data[node_color_attribute]:
colors.append(data[node_color_attribute][0])
else:
colors.append("None")
else:
colors.append(graph.degree(node))
if node_size_attribute:
if node_size_attribute != "degree":
assert (
node_size_attribute in data
), f"Size attribute {node_size_attribute} not found in node data"
sizes.append(data[node_size_attribute])
else:
sizes.append(graph.degree(node))
hovers = get_nodes_hover(graph)
node_names = list(graph.nodes)
node_trace = go.Scatter(
x=nodes_x,
y=nodes_y,
text=hovers,
marker_color=colors,
marker={"size": sizes, "sizemin": 5, "sizeref": 5},
mode="markers",
hoverinfo="text",
)
return node_trace
def draw_graph_plotly(
graph: nx.Graph,
positions: Dict[Union[str, int], Tuple[int, int]] = None,
edge_weight_attribute: str = None,
edges_only: bool = False,
node_color_attribute: str = None,
node_size_attribute: str = None,
edge_hover_attributes: List[str] = None,
size_dict: Dict[str, int] = None,
):
# If no positions are passed, compute spring layout positioning
if not positions:
positions = nx.layout.spring_layout(graph, weight=edge_weight_attribute)
edge_traces = get_edge_traces(
graph=graph,
positions=positions,
edge_weight_attribute=edge_weight_attribute,
edge_hover_attributes=edge_hover_attributes,
)
node_trace = get_nodes_trace(
graph=graph,
positions=positions,
node_color_attribute=node_color_attribute,
node_size_attribute=node_size_attribute,
)
data = edge_traces if edges_only else edge_traces + [node_trace]
annotations = compute_annotations(graph=graph)
figure = go.Figure(
data=data,
layout=go.Layout(
# autosize=False,
# width=1200,
# height=1200,
showlegend=False,
margin={"l": 20, "r": 20, "t": 25, "b": 25},
xaxis={"showgrid": False, "zeroline": False, "showticklabels": False},
yaxis={"showgrid": False, "zeroline": False, "showticklabels": False},
),
)
if size_dict:
figure.update_layout(
autosize=False, width=size_dict["width"], height=size_dict["height"]
)
figure.add_annotation(annotations)
return figure
def compute_annotations(graph: nx.Graph):
annotations = go.layout.Annotation(
text="Test",
align="left",
showarrow=False,
xref="paper",
yref="paper",
x=1.1,
y=0.8,
bordercolor="black",
borderwidth=1,
)
return annotations
# %%
<file_sep>from .content_fraction import content_fraction
from .inverse_document_frequency import inverse_document_frequency
from .lexical_diversity import lexical_diversity
from .nvc import nvc
from .plot_conditional_frequency_distribution import \
plot_conditional_frequency_distribution
from .plot_wordcloud import plot_wordcloud
from .plot_word_frequency_vs_rank import plot_word_frequency_vs_rank
from .remove_stopwords import remove_stopwords
from .stress import stress
from .term_frequency import term_frequency
from .term_ratio import term_ratio
from .unusual_words import unusual_words
from .word_frequency_vs_rank import word_frequency_vs_rank
<file_sep>#%%
from typing import Dict, List, Optional, Tuple, Union
import community
import networkx as nx
from infomap import Infomap
import numpy as np
import plotly.graph_objects as go
from collections import Counter
# %%
def assign_louvain_communities(
reddit_graph: nx.Graph,
wiki_graph: nx.Graph = None,
reddit_edge_weight: str = "count",
others_threshold: int = 2,
louvain_resolution_reddit: float = 1,
) -> Union[nx.Graph, Tuple[nx.Graph, nx.Graph]]:
""" "Calculate communities using the louvain algorithm and assign them as property to the graphs node.
if two graphs are given, also assign one graph's communities to the other's.
Args:
reddit_graph (nx.Graph): Reddit Graph
wiki_graph (nx.Graph, optional): Wikipedia graph. Defaults to None.
reddit_edge_weight (str, optional): edge attribute to use for weighting. Defaults to "count".
others_threshold (int, optional): minimum size of the communities. Communities smaller than this are mapped to "other". Defaults to 2.
louvain_resolution_reddit (float, optional): granularity for the louvain algorithm on the reddit graph. Defaults to 1
Returns:
Union[nx.Graph, Tuple[nx.Graph, nx.Graph]]: [description]
"""
reddit_dendrogram = community.generate_dendrogram(
reddit_graph, weight=reddit_edge_weight, resolution=louvain_resolution_reddit
)
if wiki_graph:
wiki_dendrogram = community.generate_dendrogram(
wiki_graph,
)
# Iterate over reddit nodes to assign communities
for node in reddit_graph:
# Iterate over all levels of the dendrogram
for level in range(len(reddit_dendrogram) - 1):
actual_level = len(reddit_dendrogram) - 2 - level
partition = community.partition_at_level(reddit_dendrogram, level)
node_community = partition[node]
counts = Counter(partition.values())
if counts[node_community] < others_threshold:
node_community = -1
reddit_graph.nodes[node][
f"louvain_community_reddit_R{louvain_resolution_reddit:.2f}_L{actual_level}"
] = f"L{actual_level}-{node_community:03}"
if wiki_graph:
# Also add the community from the other graph to allow comparing
# Again, iterate over all levels in the dendrogram
for level in range(len(wiki_dendrogram) - 1):
actual_level = len(wiki_dendrogram) - 2 - level
partition = community.partition_at_level(wiki_dendrogram, level)
try:
node_community = partition[node]
counts = Counter(partition.values())
if counts[node_community] < others_threshold:
node_community = -1
reddit_graph.nodes[node][
f"louvain_community_wiki_L{actual_level}"
] = f"L{actual_level}-{node_community:03}"
except:
reddit_graph.nodes[node][
f"louvain_community_wiki_L{level}"
] = f"L{level}-NONE"
if wiki_graph:
for node in wiki_graph:
for level in range(
len(wiki_dendrogram) - 1,
):
actual_level = len(wiki_dendrogram) - 2 - level
partition = community.partition_at_level(wiki_dendrogram, level)
node_community = partition[node]
counts = Counter(partition.values())
if counts[node_community] < others_threshold:
node_community = -1
wiki_graph.nodes[node][
f"louvain_community_wiki_L{actual_level}"
] = f"L{actual_level}-{node_community:03}"
# Also add the community from the other graph to allow comparing
for level in range(len(reddit_dendrogram) - 1):
actual_level = len(reddit_dendrogram) - 2 - level
partition = community.partition_at_level(reddit_dendrogram, level)
try:
node_community = partition[node]
counts = Counter(partition.values())
if counts[node_community] < others_threshold:
node_community = -1
wiki_graph.nodes[node][
f"louvain_community_reddit_R{louvain_resolution_reddit:.2f}_L{actual_level}"
] = f"L{actual_level}-{node_community:03}"
except:
wiki_graph.nodes[node][
f"louvain_community_reddit_R{louvain_resolution_reddit:.2f}_L{level}"
] = f"L{level}-NONE"
return (
(reddit_graph, reddit_dendrogram, wiki_graph, wiki_dendrogram)
if wiki_graph
else (reddit_graph, reddit_dendrogram)
)
def get_infomap_communities(graph: nx.Graph, reddit_edge_weight=None):
im = Infomap("--flow-model undirected -N 10 --prefer-modular-solution")
## im only works with numerical ids, so we need to save a mapping
ids_to_names = {}
names_to_ids = {}
for index, node in enumerate(graph.nodes):
ids_to_names[index] = node
names_to_ids[node] = index
im.add_node(index, name=node)
# iterate over edges and add them to the im tree, optionally adding the weight
for e1, e2, data in graph.edges(data=True):
e1_id = names_to_ids[e1]
e2_id = names_to_ids[e2]
weight = data[reddit_edge_weight] if reddit_edge_weight else None
link = (e1_id, e2_id, weight) if weight else (e1_id, e2_id)
im.add_link(*link)
im.run()
for node in im.tree:
if node.is_leaf:
graph.nodes[ids_to_names[node.node_id]][
"infomap_community"
] = node.module_id
return graph
def assign_root_categories(
graph: nx.Graph,
wiki_data: Dict[str, List],
mapping: Dict[str, List[str]],
name: str,
):
"""Given a graph and wikipedia data, assign a new attribute to the nodes that represent the root category of that node on wikipedia.
Args:
graph (nx.Graph): nootropics graph
wiki_data (Dict[str, List]): wikipedia data as obtained by lf.load_wiki_data
mapping (Dict[str, List[str]]): Dict of the form {"root_category":["list","of","sub","categories"]}
name (str): name of the new node attribute to which to assign the mapping.
"""
inverse_mapping = {}
for category, subcategories in mapping.items():
for subcategory in subcategories:
inverse_mapping[subcategory.lower()] = category.lower()
names_to_categories = dict(zip(wiki_data["name"], wiki_data["categories"]))
for node in graph.nodes:
graph.nodes[node][name] = []
for category in names_to_categories[node]:
if category in inverse_mapping:
graph.nodes[node][name].append(inverse_mapping[category])
# def partition_from_nodes(graph: nx.)
# # %%
# def plot_partition_sizes(partition: Dict[str, int]):
# partitions_amount = len(set(partition.values()))
# partition_values = list(partition.values())
# unique, frequency = np.unique(partition_values, return_counts=True)
<file_sep># %%
try:
from library_functions.config import Config
except ModuleNotFoundError:
from project.library_functions.config import Config
try:
import library_functions as lf
except ModuleNotFoundError:
import project.library_functions as lf
lf.calculate_sentiment_reddit()
# %%
<file_sep>import networkx as nx
def remove_isolates(G: nx.Graph):
G.remove_nodes_from(list(nx.isolates(G)))
return G<file_sep># Imports
import library_functions as lf
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import warnings
import wojciech as w
from fa2 import ForceAtlas2
from IPython.core.interactiveshell import InteractiveShell
from IPython.display import Markdown, display
from library_functions.config import Config
# Define a function that will print a markdown text.
def printmd(string):
display(Markdown(string))
# Disable warnings
warnings.filterwarnings('ignore')
# Define maximum of rows to show for the pandas tables
pd.options.display.max_rows = 100
# Show all code outputs in the cell outputs
InteractiveShell.ast_node_interactivity = "all"
<file_sep>import matplotlib.pyplot as plt
from wojciech.nlp.word_frequency_vs_rank import word_frequency_vs_rank
from wojciech.format_figure import format_figure
def plot_word_frequency_vs_rank(text,
axes: plt.Axes = None,
label=None,
title=None,
annotate=True,
as_probability=False):
vs_rank = word_frequency_vs_rank
rank, frequency = vs_rank(text,
as_probability=as_probability)
new_figure_created = False
if axes is None:
new_figure_created = True
figure = plt.figure(figsize=(12, 8))
axes = figure.gca()
axes.scatter(rank, frequency, label=label)
axes.set_yscale('log')
axes.set_xscale('log')
axes.grid()
if annotate:
axes.set_xlabel('Word rank')
if as_probability:
y_label = 'Probability of occurrence'
else:
y_label = 'Frequency of occurrence'
axes.set_ylabel(y_label)
if title is not None:
axes.set_title(title)
if new_figure_created:
format_figure(figure)
return axes
|
6e93b2c487d783c59cff5d89a4161d5f8bee394d
|
[
"Python",
"Text"
] | 67 |
Python
|
wrubino/Social_Graphs_and_Interactions_Final_Project
|
2f3852a4fb41beac8dda2c7992795f53d4174825
|
928ead55d25de66527b80a2dad93c62cef4d5b9b
|
refs/heads/master
|
<repo_name>TestJavaProgramer/AngielskiGuava<file_sep>/src/main/java/Angielski/DBClasses/QueryThread.java
package Angielski.DBClasses;
/**
* W tej klasie następuje faktyczne utworzenie zapytania
*/
import Angielski.Controller.Login;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
public class QueryThread extends Thread {
private static final String STEROWNIK = "com.mysql.jdbc.Driver";
private static String JDBC_URL = Login.getJdbcUrl();
//"jdbc:mysql://localhost:3306/angielski";
private static String JDBC_URL_DATABASE;
private static String JDBC_USER = "JohnTest";
private static String PASSWORD = "<PASSWORD>";
private String sql;
private String nazwaTabeli;
private Connection connection;
private PreparedStatement preparedStatement;
private Statement statement;
private ResultSet resultSet;
private ArrayList<String> Pol; // służą do otrzymania zmiennych i do ich wysłania do bazy danych
private ArrayList<String> Ang;
private ArrayList<String> poPolsku; // służą do przetrzymywania wartości pobranych z bazy danych
private ArrayList<String> poAngielsku;
private List<Map<String, String>> lista;
private String name;
private String pass;
private String email;
private boolean selectISdefined;
private boolean isInsert;
private boolean isUsers;
private boolean isCreate;
private boolean isUSER;
private ReentrantLock lock;
@Override
public void run() {
System.out.println("Thread is running " + Thread.currentThread().getName());
try {
connect();
if (selectISdefined)
{
executeSELECT();
if (isUsers)
processUser();
else
process();
}
else {
if (isInsert) {
if (isUSER) {
insertProcessUser();
} else
insertSecond();
}
else if (isCreate)
executeSQL();
else
processCreateDatabase();
}
//executeSELECT();
close();
} catch (ClassNotFoundException e){
e.printStackTrace();
} catch (SQLException ee) {
ee.printStackTrace();
}
System.out.println("Thread is stop");
}
void select(String nazwaTabeli)
{
this.nazwaTabeli = nazwaTabeli;
JDBC_URL = Login.getJdbcUrl();
sql = "SELECT * FROM " + nazwaTabeli;
selectISdefined = true;
isInsert = false;
isUsers = false;
isCreate = false;
isUSER = false;
runThread();
}
void insert(ArrayList<String> pol, ArrayList<String> ang, String nazwa)
{
JDBC_URL = Login.getJdbcUrl();
isInsert = true;
isUsers = false;
isCreate = false;
isUSER = false;
this.nazwaTabeli = nazwa;
Pol.clear();
Ang.clear();
Pol.addAll(pol);
Ang.addAll(ang);
runThread();
}
private void insertSecond() throws SQLException
{
JDBC_URL = Login.getJdbcUrl();
selectISdefined = false;
isUsers = false;
isCreate = false;
sql = "";
int i=0;
while (i != Pol.size())
{
preparedStatement = connection.prepareStatement("INSERT INTO " + nazwaTabeli +
"(Polski, Angielski) VALUES ('" + Pol.get(i) + "', '" + Ang.get(i) + "')");
preparedStatement.executeUpdate();
i++;
}
}
void create(String nazwaTabeli) throws SQLException
{
JDBC_URL = Login.getJdbcUrl();
this.nazwaTabeli = nazwaTabeli;
selectISdefined = false;
isInsert = false;
isUsers = false;
isCreate = false;
isUSER = false;
sql = ("CREATE TABLE IF NOT EXISTS " + nazwaTabeli +
"(id int NOT NULL AUTO_INCREMENT, " +
"Polski TEXT, Angielski TEXT, " +
"PRIMARY KEY(id))");
runThread();
}
void delete(String nazwaTabeli) throws SQLException
{
JDBC_URL = Login.getJdbcUrl();
selectISdefined = false;
isInsert = false;
isUsers = false;
isCreate = false;
isUSER = false;
//preparedStatement = connection.prepareStatement("DROP TABLE " + nazwaTabeli);
sql = "DROP TABLE " + nazwaTabeli;
runThread();
}
void deleteRecords(String nazwaTabeli) throws SQLException
{
JDBC_URL = Login.getJdbcUrl();
this.nazwaTabeli = nazwaTabeli;
sql = "TRUNCATE TABLE " + nazwaTabeli;
selectISdefined = false;
isInsert = false;
isUsers = false;
isCreate = false;
isUSER = false;
runThread();
}
void selectUserDetails()
{
JDBC_URL = "jdbc:mysql://localhost:3306/uzytkownicy";
sql = "SELECT * FROM test "; // users
selectISdefined = true;
isInsert = false;
isUsers = true;
isCreate = false;
isUSER = false;
runThread();
JDBC_URL = Login.getJdbcUrl();
}
void createDATABASE(String nameDATA)
{
//JDBC_URL = "jdbc:mysql://localhost:3306/uzytkownicy";
//sql = "SELECT * FROM users ";
sql = "CREATE DATABASE " + nameDATA + " DEFAULT CHARACTER SET utf8 COLLATE utf8_polish_ci";
selectISdefined = false;
isInsert = false;
isUsers = true;
isCreate = true;
isUSER = false;
runThread();
JDBC_URL = Login.getJdbcUrl();
}
void insertUSER(String name, String pass, String email) throws SQLException
{
JDBC_URL = Login.getJdbcUrl() + "uzytkownicy";
this.name = name;
this.pass = pass;
this.email = email;
isInsert = true;
isUsers = false;
isCreate = false;
selectISdefined = false;
isUSER = true;
sql = "";
runThread();
JDBC_URL = Login.getJdbcUrl();
}
private void insertProcessUser() throws SQLException
{
preparedStatement = connection.prepareStatement("INSERT INTO test " + // users
"(name, password, email) VALUES ('" + name + "', '" + pass + "', '" + email + "')");
preparedStatement.executeUpdate();
}
private void connect() throws ClassNotFoundException , SQLException {
Class.forName(STEROWNIK);
connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, PASSWORD);
}
private void executeSELECT() throws SQLException {
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
}
private void executeSQL() throws SQLException {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();
}
private void process() throws SQLException {
poPolsku.clear();
poAngielsku.clear();
while (resultSet.next()){
poPolsku.add(resultSet.getString(2));
poAngielsku.add(resultSet.getString(3));
}
}
private void processUser() throws SQLException {
while (resultSet.next()){
Map<String, String> raz = new HashMap<String, String>();
raz.put("name", resultSet.getString("name"));
raz.put("password", resultSet.getString("password"));
raz.put("email", resultSet.getString("email"));
lista.add(raz);
}
}
private void processCreateDatabase() throws SQLException {
statement = connection.createStatement();
statement.execute(sql);
}
private void close() throws SQLException {
if ( connection != null)
connection.close();
if ( preparedStatement != null)
preparedStatement.close();
if ( statement != null)
statement.close();
if ( resultSet != null)
resultSet.close();
}
public QueryThread() {
Pol = new ArrayList<String>();
Ang = new ArrayList<String>();
poPolsku = new ArrayList<String>();
poAngielsku= new ArrayList<String>();
lista = new ArrayList<Map<String, String>>();
sql = "";
selectISdefined = false;
isInsert = false;
isUsers = false;
isCreate = false;
isUSER = false;
name = "";
pass = "";
email = "";
lock = new ReentrantLock();
}
private void runThread() {
lock.lock();
this.start();
try {
join();
System.out.println("Zabija Threada: " + Thread.currentThread().getName());
} catch (InterruptedException ee) {
ee.printStackTrace();
}
lock.unlock();
}
ArrayList<String> addPolskiResultTo(ArrayList<String> masz) {
masz.addAll(poPolsku);
return masz;
}
ArrayList<String> addAngielskiResultTo(ArrayList<String> masz) {
masz.addAll(poAngielsku);
return masz;
}
List<Map<String,String>> getLista() {return lista;}
public static void setJDBC_URL(String jdbc_url) {JDBC_URL = jdbc_url;}
public static String getJDBC_URL_DATABASE() {return JDBC_URL_DATABASE;}
public static void refresh(String data) {
JDBC_URL_DATABASE = data;
}
}
<file_sep>/src/main/java/Angielski/ButtonsEvent/DialogEvents/ButtonWczytaj.java
package Angielski.ButtonsEvent.DialogEvents;
import Angielski.Controller.Login;
import Angielski.DBClasses.ExQueryThread;
import Angielski.DBClasses.QueryThread;
import Angielski.Model.DataManagement;
import Angielski.View.DialogWczytaj;
import Angielski.View.MainWindow;
import com.google.common.eventbus.Subscribe;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
/**
* Created by Dan on 2017-06-14.
*/
public class ButtonWczytaj implements ActionListener {
// wymagane
private DialogWczytaj dialogWczytaj;
// nie wymagane
private MainWindow mainWindow;
private DataManagement data;
private ExQueryThread exQueryThread;
@Subscribe
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == dialogWczytaj.getButton())
{
dialogWczytaj.setOkData(true);
String nazwa = dialogWczytaj.getNazwaBazy();
try {
// sprawdz czy podana baza danych istniej
// https://stackoverflow.com/questions/2780284/how-to-get-all-table-names-from-a-database
Class.forName("com.mysql.jdbc.Driver");
String jdbc = Login.getJdbcUrl();
Connection conn = DriverManager.getConnection(jdbc, "JohnTest", "przykladowehaslo");
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
ArrayList<String> dataname = new ArrayList<String>();
while (rs.next()) {
dataname.add(rs.getString(3));
}
boolean nieMaBazy = true;
for (String str : dataname)
{
if ( str.equals(nazwa))
{
exQueryThread.selectAll(str);
int ile = dialogWczytaj.getile();
if ( ile > exQueryThread.size()) {
ile = exQueryThread.size();
}
// teraz wstaw wszystkie dane do DataManagement oraz wyswietl to
mainWindow.foomiwczytaj();
data.setDataManagement(exQueryThread.getPoPolsku(), exQueryThread.getPoAngielsku()); // model ustawia sobie słownik
data.losuj(ile);
mainWindow.setText1(data.getWylosowane());
mainWindow.foomiwczytaj();
nieMaBazy = false;
}
}
if (nieMaBazy)
{
// nie ma takiej bazy danych
JOptionPane.showMessageDialog(null, "Nie masz takiej bazy zdefiniowanej.\n"+
"Sprawdź czy nie popełniłeś błędu w pisowni");
}
}catch (Exception ee){
ee.printStackTrace();
}
mainWindow.focusText2();
}
else
{
dialogWczytaj.setOkData(false);
JOptionPane.showMessageDialog(null, "Nie udało Ci się wczytać bazy danych");
}
dialogWczytaj.setVisible(false);
}
public static class Builder {
private DialogWczytaj dialogWczytaj;
private MainWindow mainWindow;
private DataManagement data;
public Builder(DialogWczytaj dialogWczytaj) {
this.dialogWczytaj = dialogWczytaj;
}
public Builder mainWindow(MainWindow mainWindow) {this.mainWindow = mainWindow; return this;}
public Builder data(DataManagement data) {this.data = data; return this;}
public ButtonWczytaj build() {return new ButtonWczytaj(this);}
}
private ButtonWczytaj(Builder builder){
dialogWczytaj = builder.dialogWczytaj;
mainWindow = builder.mainWindow;
data = builder.data;
dialogWczytaj.addbutton(this);
exQueryThread = new ExQueryThread(new QueryThread());
System.out.println("Konstruktor ButtonWczytaj przez Builder");
}
}
|
59ace75916cab2861ff044486c6292c41c9082ad
|
[
"Java"
] | 2 |
Java
|
TestJavaProgramer/AngielskiGuava
|
536c46d2377f2d9a00730d8a3aa81c7608782308
|
847e2b940a715d306e57264241e41f27d9944f44
|
refs/heads/master
|
<repo_name>dsmith-projects/AgendaContactos<file_sep>/include/Contacto.h
/*
* Contacto.h
*
* Created on: Sep 5, 2017
* Author: dsmith
*/
#ifndef INCLUDE_CONTACTO_H_
#define INCLUDE_CONTACTO_H_
#include <string>
#include <sstream>
using namespace std;
class Contacto
{
public:
string nombre;
string apellido;
string tipo;
string email;
Contacto(string, string, string, string);
void buscarContacto(string);
void agregarTelefono(string, string);
protected:
private:
};
#endif /* INCLUDE_CONTACTO_H_ */
<file_sep>/README.md
# AgendaContactos
Es una agenda que maneja los contactos en forma de lista con punteros y también con árbol binario. Está en C++
<file_sep>/src/Telefono.cpp
/*
* Telefono.cpp
*
* Created on: Sep 6, 2017
* Author: dsmith
*/
#include "../include/Telefono.h"
#include <new>
#include <string>
#include <sstream>
Telefono::Telefono() {
numeroTelefono = "";
tipoTelefono = "";
usado = false;
ptr_Next = NULL;
}
Telefono::Telefono(string numero, string tipo) {
numeroTelefono = numero;
tipoTelefono = tipo;
usado = true;
ptr_Next = NULL;
}
Telefono::~Telefono() {
delete this;
}
void Telefono::setValores(string numero, string tipo) {
numeroTelefono = numero;
tipoTelefono = tipo;
}
string Telefono::getValores() {
ostringstream flujo;
flujo << numeroTelefono << " (" << tipoTelefono << ")" << endl;
return flujo.str();
}
bool Telefono::enUso() {
return usado;
}
void Telefono::actualizarNumeroTelefono(string numeroActualizado) {
numeroTelefono = numeroActualizado;
}
void Telefono::actualizarTipoTelefono(string nuevoTipo) {
tipoTelefono = nuevoTipo;
}
Telefono *Telefono::getNext() {
return ptr_Next;
}
<file_sep>/src/Agenda.cpp
/*
* Agenda.cpp
*
* Created on: Sep 5, 2017
* Author: dsmith
*/
#include "../include/Agenda.h"
void crearContacto(string pnombre, string papellido, string ptipo, string pemail) {
Contacto contacto = new Contacto(pnombre, papellido, ptipo, pemail);
agregarContactoALista(contacto);
contacto = consultarContacto();
}
void Agenda::agregarContacto(Contacto contacto) {
// acá se agrega el contacto a la lista de contactos
}
Contacto consultarContacto(string){
// devuelve el contacto solo para despelgar sus datos
}
void Agenda::actualizarContacto(){
}
string Agenda::obtenerContactos() {
ostringstream flujo;
Telefono *iterador = ptr_First;
while(iterador != NULL) {
flujo << iterador->getValores() << endl;
iterador = iterador->getNext();
}
return flujo.str();
}
<file_sep>/include/Telefono.h
/*
* Telefono.h
*
* Created on: Sep 6, 2017
* Author: dsmith
*/
#ifndef INCLUDE_TELEFONO_H_
#define INCLUDE_TELEFONO_H_
#include <string>
#include <sstream>
using namespace std;
class Telefono
{
public:
string numeroTelefono;
string tipoTelefono;
bool usado;
Telefono *ptr_Next;
Telefono(); // podemos prescindir de este constructor?
Telefono(string numero, string tipo);
virtual ~Telefono();
void setValores(string numero, string tipo);
string getValores();
bool enUso();
void actualizarNumeroTelefono(string);
void actualizarTipoTelefono(string);
Telefono *getNext();
protected:
private:
};
#endif /* INCLUDE_TELEFONO_H_ */
<file_sep>/src/Contacto.cpp
/*
* Contacto.cpp
*
* Created on: Sep 5, 2017
* Author: dsmith
*/
#include "../include/Contacto.h"
Contacto::Contacto(string pnombre, string papellido, string ptipo, string pemail){
nombre = pnombre;
apellido = papellido;
tipo = ptipo;
email = pemail;
}
void Contacto::agregarTelefono(string telefono, string tipoTelefono) {
new Telefono(telefono, tipoTelefono);
}
void Contacto::buscarContacto(string palabra) {
}
<file_sep>/include/Agenda.h
/*
* Agenda.h
*
* Created on: Sep 5, 2017
* Author: dsmith
*/
#ifndef INCLUDE_AGENDA_H_
#define INCLUDE_AGENDA_H_
#include <string>
#include <sstream>
#include "../include/Contacto.h"
using namespace std;
class Agenda
{
public:
Contacto *ptr_FirstContacto;
Contacto *ptr_LastContacto;
Agenda();
Agenda(Contacto *contacto);
virtual ~Agenda();
void agregarContacto(Contacto *contacto);
void consultarContacto(string);
void actualizarContacto(); //debería recibir al Contacto como parámetro?
// void migrarContactosAArbol();
// void buscarContactoEnArbol();
protected:
private:
};
#endif /* INCLUDE_AGENDA_H_ */
<file_sep>/src/main.cpp
/*
* main.cpp
*
* Created on: Sep 5, 2017
* Author: dsmith
*/
#include <iostream>
#include <string>
#include "../include/Contacto.h"
#include "../include/Agenda.h"
#include "../include/Telefono.h"
#include "../include/ListaTelefonos.h"
using namespace std;
void desplegarMenu(){
cout << "\t*** AGENDA DE CONTACTOS ***\n" << endl;
cout << "1. Agregar un contacto" << endl;
cout << "2. Consultar un contacto" << endl;
cout << "3. Modificar un contacto" << endl;
cout << "4. Eliminar un contacto" << endl;
cout << "5. Mostrar contactos como lista ordenada" << endl;
cout << "6. Migrar contactos a un arbol balanceado" << endl;
cout << "7. Buscar contacto en arbol balanceado" << endl;
cout << "8. Salir" << endl;
cout << "\n" << endl;
}
int main() {
/* Variables para la ejecucion del menu */
bool salir = false; // Bandera que indica el momento de parada
int opcion = 0; // Entero ingresado por el usuario para la seleccion una escoger una opcion del menu
/* Variables para almacenar los datos de un contacto */
string nombre;
string apellido;
string tipoContacto;
string email;
string tel;
string tipoTelefono;
string busqueda; // variable temporal para buscar un contacto
/* Instancias de las clases necesarias para manejar los contactos */
Agenda agenda;
Telefono telefono;
ListaTelefonos listaTelefonos; // el telefono debe ser una lista no ordenada nueva para cada uno de los contactos
while(!salir){
desplegarMenu();
cout << "Ingrese una opcion del menu: ";
cin >> opcion;
cout << "\n" << endl;
switch(opcion) {
case 1:
Contacto *ptr_contacto; // Debería igualarse a NULL ???
ListaTelefonos *ptr_ListaTelef = new ListaTelefonos(); // Creacion de un puntero de tipo ListaTelefonos
// Solicito datos del contacto excepto numeros telefonicos
cout << "Nombre y apellido: ";
cin >> nombre >> apellido;
cout << "Tipo [familiar, amigo, comercial, profesional]: ";
cin >> tipoContacto;
cout << "Correo electronico: ";
cin >> email;
// variables que maneja el ciclo que solicita un nuevo numero telefonico hasta que el usuario lo desee
bool agregarNumero = true;
char seguir;
//ciclo que se mantiene solicitando numeros telefonicos del nuevo contacto hasta que el usuario lo desee
do {
cout << "Numero de telefono: ";
cin >> tel;
cout << "Tipo de telefono [celular, hogar, trabajo]: ";
cin >> tipoTelefono;
Telefono *ptr_Telef = new Telefono(tel, tipoTelefono); // Creacion de un puntero de tipo Telefono
ptr_ListaTelef->agregarTelefono(ptr_Telef);
cout << "¿Agregar otro numero de telefono? [s/n]: ";
cin >> seguir;
if(seguir == 'n'){
agregarNumero = false;
}
}while(agregarNumero);
ptr_contacto = new Contacto();
contacto = agenda.crearContacto(nombre, apellido, tipo, email); // la agenda crea el contacto y lo devuelve para que se le agreguen los numeros de telefono
break;
case 2:
cout << "Buscar contacto: " << endl;
cout << "Ingrese el nombre o apellido del contacto: ";
cin >> busqueda;
buscarContacto(busqueda);
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
cout << nombre << " " << apellido << endl;
cout << telefono << " (" << tipo << ")" << endl;
cout << email << endl;
break;
case 8:
salir = true;
cout << "Usted ha salido del programa\n" << endl;
break;
default:
cout << "Opcion invalida. Intentelo nuevamente.\n" << endl;
break;
}
}
return 0;
}
<file_sep>/include/ListaTelefonos.h
/*
* ListaTelefonos.h
*
* Created on: Sep 6, 2017
* Author: dsmith
*/
#ifndef INCLUDE_LISTATELEFONOS_H_
#define INCLUDE_LISTATELEFONOS_H_
#include "Telefono.h"
using namespace std;
class ListaTelefonos
{
public:
Telefono *ptr_First;
Telefono *ptr_Last;
ListaTelefonos();
ListaTelefonos(Telefono *tel);
virtual ~ListaTelefonos();
void agregarTelefono(Telefono *tel);
string obtenerTelefonos();
protected:
private:
};
#endif /* INCLUDE_LISTATELEFONOS_H_ */
<file_sep>/src/ListaTelefonos.cpp
/*
* ListaTelefonos.cpp
*
* Created on: Sep 6, 2017
* Author: dsmith
*/
#include "../include/ListaTelefonos.h"
#include <string>
#include <sstream>
using namespace std;
ListaTelefonos::ListaTelefonos() {
ptr_First = NULL;
ptr_Last = NULL;
}
ListaTelefonos::ListaTelefonos(Telefono *tel) {
ptr_First = tel;
ptr_Last = tel;
}
ListaTelefonos::~ListaTelefonos() {
Telefono *iterador = ptr_First;
Telefono *borrador;
while(iterador != NULL) {
borrador = iterador;
iterador = iterador->getNext();
delete borrador;
}
}
void ListaTelefonos::agregarTelefono(Telefono *tel) {
if(!ptr_First->enUso()) {
ptr_First = tel;
ptr_Last = tel;
} else {
ptr_Last->ptr_Next = tel;
ptr_Last = tel;
}
}
string ListaTelefonos::obtenerTelefonos() {
ostringstream flujo;
Telefono *iterador = ptr_First;
while(iterador != NULL) {
flujo << iterador->getValores() << endl;
iterador = iterador->getNext();
}
return flujo.str();
}
|
888beeaf7f559cc07019f13880deacc2c7cf4e0f
|
[
"Markdown",
"C++"
] | 10 |
C++
|
dsmith-projects/AgendaContactos
|
d583165b2e9724dd00308033cd2644230be6c2d0
|
1178234891af119e30362a0bc9d664ded7a3b5f3
|
refs/heads/master
|
<file_sep># Youtube
Code related to my youtube channel GET SET PYTHON are available here
Watch here : https://www.youtube.com/getsetpython
<file_sep>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
driver=webdriver.Chrome()
driver.get('https://web.whatsapp.com/')
wait = WebDriverWait(driver, 600)
name=input('Enter the name of contact or group you want to text: ')
text=input('Enter the text you want to send: ')
n=int(input('Enter the number of times you want the text to be sent: '))
input('Make sure you have scanned the QR code of whatsapp web. After that, press any key')
user = driver.find_element_by_xpath('//span[@title = "{}"]'.format(name))
user.click()
text_box = driver.find_element_by_class_name('_3u328')
for i in range(n):
text_box.send_keys(text)
butn = '_3M-N-'
button=wait.until(EC.presence_of_element_located((By.CLASS_NAME,butn)))
button.click()
|
17069c80882fd0b3d6e144f1e54d5c77349ae316
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
vaibhavrajsingh2001/automation-scripts
|
a85b475fb0cd28e9392435c24364594d6d0f1a41
|
4d12fa1b9dbea004d9d6f4fe510b7fda14666d9d
|
refs/heads/master
|
<file_sep>import * as dotenv from 'dotenv'
import validateEnv from './utils/validateEnv'
import PostController from './controllers/post.controller'
import AuthenticationController from './controllers/authentication.controller'
const multer = require("multer")
const path = require("path")
import * as express from 'express';
import App from './app'
// get env variables
dotenv.config({
path:'./src/config/.env'
});
// validate env variables
validateEnv();
// instantiate app class
const app = new App(
[
new AuthenticationController(),
new PostController()
],
);
const storage = multer.diskStorage({
destination: "./public/",
filename: (req: express.Request, file, cb : any) => {
cb(null + path.extname(file.originalname) + "_" + Date.now() );
}
});
const upload = multer({
storage: storage,
limits:{fileSize: 1000000},
}).single("uploads");
app.listen();
<file_sep>import * as mongoose from 'mongoose'
import UserInterface from '../interfaces/user.interface';
const UserSchema = new mongoose.Schema({
email: {
type: String,
match: [
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
'Please add a valid email'
],
required:true,
unique:true,
trim:true,
minlength:3
},
username: { type: String, required: true, unique:true },
firstName: { type: String, required: true },
lastName: { type: String, required: true },
password: { type: String, required: true },
role: {
type: String,
required: false
}
},
{timestamps:true}
)
const UserModel = mongoose.model<UserInterface & mongoose.Document>('User',UserSchema)
export default UserModel<file_sep>const jwt = require('jsonwebtoken')
import express from 'express'
import Controller from '../interfaces/controller.interface'
import PostInterface from '../interfaces/post.interface'
import PostModel from '../models/post.model'
import HttpException from '../exceptions/http/HttpException'
import PostNotFoundException from '../exceptions/post/PostNotFoundException'
import CreatePostDto from '../post/post.dto'
import validationMiddleware from '../middleware/validation.middleware'
import authMiddleware from '../middleware/auth.middleware';
class PostController implements Controller {
public path = '/posts';
public router = express.Router();
private post = PostModel;
constructor() {
this.initializeRoutes()
}
private initializeRoutes() {
this.router.get(this.path, this.postList);
this.router.get(`${this.path}/:id`, this.findPostById);
this.router.post(`${this.path}/add`, authMiddleware, validationMiddleware(CreatePostDto), this.addPost);
this.router.patch(`${this.path}/update/:id`, authMiddleware, this.updatePostById);
this.router.delete(`${this.path}/delete`, authMiddleware, this.deletePostById);
}
// list all posts
private postList = async (req:express.Request, res:express.Response) => {
await this.post.find()
.then(posts => res.json(posts))
.catch(err => res.status(400).json('Error: ' + err))
}
// add post
private addPost = async (req:express.Request, res:express.Response) => {
const addPostData : CreatePostDto = req.body
const newPost = new this.post(addPostData)
const saveNewPost = await newPost.save()
.then(() => res.json({"Response":`Post ${addPostData.postTitle} added`}))
.catch(err => res.status(400).json('Error: ' + err));
}
// Get post Info by Id
private findPostById = async (req:express.Request, res:express.Response, next:express.NextFunction) => {
this.post.findById(req.params.id)
.then(post => {
if (post)
res.json(post)
else {
next(new HttpException(404, 'Post not found'));
}
})
}
// Update Exercide
private updatePostById = async (req:express.Request, res:express.Response, next:express.NextFunction) => {
const id = req.params.id
const updatePostData: PostInterface = req.body
this.post.findByIdAndUpdate(id, updatePostData, {new: true})
.then(post => {
if (post)
res.json({"Response":`Post with id ${id} updated`})
else{
next(new PostNotFoundException(id))
}
}
)}
// Delete by id
private deletePostById = async (req:express.Request, res:express.Response, next:express.NextFunction) => {
const id = req.body.id
this.post.findByIdAndDelete(id)
.then(successResponse => {
if (successResponse) {
res.json({"Response":`Post with id ${id} deleted successfully`});
} else {
next(new PostNotFoundException(id));
}
})
}
// class end
}
export default PostController<file_sep>import * as bcrypt from 'bcrypt';
import * as express from 'express';
// const bcrypt = require('bcrypt')
import UserWithThatEmailAlreadyExistsException from '../exceptions/auth/UserWithThatEmailAlreadyExistsException';
import InvalidCredentialsException from '../exceptions/auth/InvalidCredentialsException'
import PasswordMismatchException from '../exceptions/auth/PasswordMismatchException'
import InvalidPasswordLengthException from '../exceptions/auth/InvalidPasswordLengthException'
import UserNotFoundException from '../exceptions/auth/UserNotFoundException'
import UserWithThatUsernameAlreadyExistsException from '../exceptions/auth/UserWithThatUsernameAlreadyExistsException'
import Controller from '../interfaces/controller.interface';
import validationMiddleware from '../middleware/validation.middleware';
import CreateUserDto from '../user/user.dto';
import UserModel from '../models/user.model';
import LogInDto from '../login/login.dto'
import TokenData from '../interfaces/tokenData.interface'
import UserInterface from '../interfaces/user.interface'
import DataStoredInToken from '../interfaces/dataStoredInToken.interface'
const jwt = require('jsonwebtoken')
class AuthenticationController implements Controller {
public path = '/auth';
public router = express.Router();
private user = UserModel;
constructor() {
this.initializeRoutes();
}
private initializeRoutes() {
this.router.get(`${this.path}/users`, this.userList);
this.router.get(`${this.path}/:id`, this.findUserById);
this.router.post(`${this.path}/register`, validationMiddleware(CreateUserDto), this.registration);
this.router.post(`${this.path}/login`, validationMiddleware(LogInDto), this.loggingIn);
}
// get all users
private userList = async (req, res) => {
await this.user.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error: ' + err))
}
// Get Exercise Info by Id
private findUserById = async (req:express.Request, res:express.Response, next:express.NextFunction) => {
this.user.findById(req.params.id)
.then(user => {
if (user)
res.json(user)
else {
next(new UserNotFoundException(404));
}
})
}
// registration middleware
private registration = async (req: express.Request, res: express.Response, next: express.NextFunction) => {
const userData: CreateUserDto = req.body;
const passwordsMatch = await bcrypt.compare(req.body.password, req.body.password2)
if (passwordsMatch) {
if(userData.password.length < 6){
next(new InvalidPasswordLengthException())
}
if(req.body.password != req.body.password2){
next(new PasswordMismatchException())
}
if ( await this.user.findOne({ email: userData.email }) ) {
next(new UserWithThatEmailAlreadyExistsException(userData.email));
}
if ( await this.user.findOne({ username: userData.username }) ) {
next(new UserWithThatUsernameAlreadyExistsException(userData.username));
}
// create user
const hashedPassword = await bcrypt.hash(userData.password, 10);
const user = await this.user.create({
...userData,
password: <PASSWORD>,
});
user.password = '';
const tokenData = this.createToken(user);
res.setHeader('Set-Cookie', [this.createCookie(tokenData)])
res.json({"Response":`User with username ${user.username} created successfully`})
}
else {
next(new PasswordMismatchException())
}
}
// login middleware
private loggingIn = async (req: express.Request, res: express.Response, next: express.NextFunction) => {
const logInData: LogInDto = req.body;
const user = await this.user.findOne({ username: logInData.username });
if (user) {
const isPasswordMatching = await bcrypt.compare(logInData.password, user.password)
if (isPasswordMatching) {
user.password = '';
res.json({"Response":"User authenticated successfully"});
} else {
next(new InvalidCredentialsException())
}
} else {
next(new InvalidCredentialsException());
}
}
private createCookie(tokenData: TokenData) {
return `Authorization=${tokenData.token}; HttpOnly; Max-Age=${tokenData.expiresIn}`;
}
get getCookie(){
return this.createCookie
}
// create token
private createToken(user): TokenData {
const expiresIn = 15 * 60
const secret = process.env.JWT_SECRET;
const dataStoredInToken: DataStoredInToken = {
_id: user._id
};
return {
expiresIn,
token: jwt.sign(dataStoredInToken, secret, { expiresIn }),
};
}
}
export default AuthenticationController<file_sep>## A blogging app (with user auth) using MERN stack
### The `api` directory contains the Nodejs (Express) API
### The `web` directory contains the React app<file_sep>interface PostInterface {
post_image: Object,
post_title: string,
post_body: number,
}
export default PostInterface<file_sep>import * as mongoose from 'mongoose'
import PostInterface from '../interfaces/post.interface'
const PostSchema = new mongoose.Schema({
postImagePath:{type: String, required: true},
postTitle:{type: String, required: true},
postBody: {type: String, required: true},
username: {type: String, required:true},
},
{timestamps:true}
)
const PostModel = mongoose.model<PostInterface & mongoose.Document>('Post', PostSchema);
export default PostModel<file_sep>import { IsString } from 'class-validator';
class CreatePostDto {
public constructor(){}
@IsString()
public postImagePath: string;
@IsString()
public postTitle: string
@IsString()
public postBody: string;
@IsString()
public username: string;
}
export default CreatePostDto;
|
a57f1bc5fb256f7babb118f609c4d64ed5000083
|
[
"Markdown",
"TypeScript"
] | 8 |
TypeScript
|
mhope-2/mern_blog
|
d2985213f72de61027e2e5a439c66efcc6ecd53a
|
2afcad62eec5080abda8281ab7196f8216524603
|
refs/heads/main
|
<repo_name>1amageek/FirestoreRepository<file_sep>/Sources/FirestoreRepository/Query+Combine.swift
//
// Query+Combine.swift
//
//
// Created by nori on 2021/03/11.
//
import Foundation
import Combine
import FirestoreProtocol
import FirebaseFirestore
import FirebaseFirestoreSwift
extension Query {
struct Publisher: Combine.Publisher {
typealias Output = QuerySnapshot
typealias Failure = Error
private let query: Query
private let includeMetadataChanges: Bool
init(_ query: Query, includeMetadataChanges: Bool) {
self.query = query
self.includeMetadataChanges = includeMetadataChanges
}
func receive<S>(subscriber: S) where S : Subscriber, Publisher.Failure == S.Failure, Publisher.Output == S.Input {
let subscription = QuerySnapshot.Subscription(subscriber: subscriber, query: query, includeMetadataChanges: includeMetadataChanges)
subscriber.receive(subscription: subscription)
}
}
}
extension Query: CollectionPublishable {
public func getDocument(source: FirestoreSource = .default) -> AnyPublisher<QuerySnapshot?, Error> {
Future<QuerySnapshot?, Error> { [weak self] promise in
self?.getDocuments(source: source, completion: { (querySnapshot, error) in
if let error = error {
promise(.failure(error))
} else {
promise(.success(querySnapshot))
}
})
}.eraseToAnyPublisher()
}
public func get<Document>(as type: Document.Type) -> AnyPublisher<[Document]?, Error> where Document : Decodable {
getDocument()
.tryMap { try $0?.documents.compactMap({ try $0.data(as: type) }) }
.eraseToAnyPublisher()
}
public func get<Document>(source: Source, as type: Document.Type) -> AnyPublisher<[Document]?, Error> where Document : Decodable {
getDocument(source: source.rawValue)
.tryMap { try $0?.documents.compactMap({ try $0.data(as: type) }) }
.eraseToAnyPublisher()
}
public func publisher<Document>(as type: Document.Type) -> AnyPublisher<[Document]?, Error> where Document : Decodable {
publisher(includeMetadataChanges: true, as: type)
}
public func publisher<Document>(includeMetadataChanges: Bool = true, as type: Document.Type) -> AnyPublisher<[Document]?, Error> where Document : Decodable {
publisher(includeMetadataChanges: includeMetadataChanges)
.tryMap { try $0.documents.compactMap({ try $0.data(as: type) }) }
.eraseToAnyPublisher()
}
public func publisher(includeMetadataChanges: Bool = true) -> AnyPublisher<QuerySnapshot, Error> {
Query.Publisher(self, includeMetadataChanges: includeMetadataChanges).eraseToAnyPublisher()
}
}
<file_sep>/Package.swift
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "FirebaseInterface",
platforms: [.iOS(.v14)],
products: [
.library(
name: "FirestoreProtocol",
targets: ["FirestoreProtocol"]),
.library(
name: "FirestoreRepository",
targets: ["FirestoreRepository"]),
],
dependencies: [
.package(name: "Firebase", url: "https://github.com/firebase/firebase-ios-sdk.git", .upToNextMajor(from: "8.3.0"))
],
targets: [
.target(
name: "FirestoreProtocol",
dependencies: [],
path: "Sources/FirestoreProtocol"),
.target(
name: "FirestoreRepository",
dependencies: [
"FirestoreProtocol",
.product(name: "FirebaseFirestore", package: "Firebase"),
.product(name: "FirebaseFirestoreSwift-Beta", package: "Firebase")
],
path: "Sources/FirestoreRepository"),
.testTarget(
name: "FirestoreRepositoryTests",
dependencies: [
"FirestoreRepository",
.product(name: "FirebaseFirestore", package: "Firebase"),
.product(name: "FirebaseFirestoreSwift-Beta", package: "Firebase")
]),
]
)
<file_sep>/Sources/FirestoreRepository/Source.swift
//
// FirestoreRepository.swift
//
//
// Created by nori on 2021/02/18.
//
import Foundation
import Combine
import FirestoreProtocol
import FirebaseFirestore
import FirebaseFirestoreSwift
extension Source: RawRepresentable {
public init?(rawValue: FirestoreSource) {
switch rawValue {
case .default: self = .default
case .server: self = .server
case .cache: self = .cache
@unknown default: fatalError()
}
}
public var rawValue: FirestoreSource {
switch self {
case .default: return .default
case .server: return .server
case .cache: return .cache
}
}
}
<file_sep>/Demo/Demo/ContentView.swift
//
// ContentView.swift
// Demo
//
// Created by nori on 2021/02/18.
//
import SwiftUI
import Combine
import FirebaseFirestore
import FirestoreRepository
class Repository {
var userID: String
init(userID: String) {
self.userID = userID
}
func usersPublisher() -> AnyPublisher<[User]?, Never> {
return Firestore.firestore()
.collection("users")
.publisher(as: User.self)
.assertNoFailure()
.eraseToAnyPublisher()
}
func itemPublisher() -> AnyPublisher<Item?, Never> {
return Firestore.firestore()
.collection("users")
.document("kk")
.publisher(as: Item.self)
.assertNoFailure()
.eraseToAnyPublisher()
}
func a() {
usersPublisher()
.compactMap({ $0 })
.flatMap { users in
users.map { user in
Future<Item?, Never> { promise in
itemPublisher().sink { item in
promise(.success(item))
}
}
}
}
// .flatMap({ users in
// Publishers.MergeMany(users.map({ _ in BPublisher() }))
// })
// .flatMap({ _ in BPublisher() })
// Firestore.firestore()
// .collection("users")
// .publisher(as: User.self)
// .assertNoFailure()
// .eraseToAnyPublisher()
}
}
class Interactor: ObservableObject {
var cancelables: [AnyCancellable] = []
var repository: Repository
init(repository: Repository) {
self.repository = repository
}
// @DocumentRepository<User> var reference: Reference
//
// init(reference: Reference) {
// self._reference = DocumentRepository(reference)
// }
}
struct User: Codable {
var item: Item?
}
struct Item: Codable { }
struct ContentView: View {
@EnvironmentObject var interactor: Interactor
@State var data: [User] = []
@State var user: User?
var body: some View {
Button(action: {
// self.interactor.repository.doc
}, label: {
Text("Hello, world!")
.padding()
})
.onAppear {
interactor.repository.publisher.sink { user in
print(user)
}.store(in: &interactor.cancelables)
// interactor.$repository.sink { _ in
//
// } receiveValue: { user in
// self.user = user
// }
// interactor.repository.publisher.sink { _ in
//
// } receiveValue: { user in
// self.user = user
// }.store(in: &self.interactor.cancelables)
// interactor.documentRef.get(source: .default)
// interactor.collectionRef.get(source: .cache).sink { collection in
// self.data = collection
// }
// interactor.repository.usersPublisher.sink { error in
//
// } receiveValue: { users in
// self.data = users ?? []
// }.store(in: &interactor.cancelables)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(Interactor(repository: Repository(userID: "aa")))
// .environmentObject(
// Interactor(
// repository: DocumentRepository(Firestore.firestore().document("")) { $0.get() }
// ))
}
}
<file_sep>/README.md
# FirestoreRepository
A description of this package.
<file_sep>/Sources/FirestoreProtocol/FirestoreProtocol.swift
//
// FirestoreProtocol.swift
//
//
// Created by nori on 2021/02/18.
//
import Foundation
import Combine
public enum Source {
case `default`
case server
case cache
}
public enum FirestoreError: Error {
case nilResultError
}
public protocol DocumentPublishable {
func get<Document: Decodable>(as type: Document.Type) -> AnyPublisher<Document?, Error>
func get<Document: Decodable>(source: Source, as type: Document.Type) -> AnyPublisher<Document?, Error>
func publisher<Document: Decodable>(as type: Document.Type) -> AnyPublisher<Document?, Error>
func publisher<Document: Decodable>(includeMetadataChanges: Bool, as type: Document.Type) -> AnyPublisher<Document?, Error>
}
public protocol CollectionPublishable {
func get<Document: Decodable>(as type: Document.Type) -> AnyPublisher<[Document]?, Error>
func get<Document: Decodable>(source: Source, as type: Document.Type) -> AnyPublisher<[Document]?, Error>
func publisher<Document: Decodable>(as type: Document.Type) -> AnyPublisher<[Document]?, Error>
func publisher<Document: Decodable>(includeMetadataChanges: Bool, as type: Document.Type) -> AnyPublisher<[Document]?, Error>
}
public protocol DocumentWritable {
func setData(_ documentData: [String: Any])
func setData(_ documentData: [String: Any], completion: ((Error?) -> Void)?)
func setData(_ documentData: [String: Any], merge: Bool)
func setData(_ documentData: [String: Any], merge: Bool, completion: ((Error?) -> Void)?)
func setData(_ documentData: [String: Any], mergeFields: [Any])
func setData(_ documentData: [String: Any], mergeFields: [Any], completion: ((Error?) -> Void)?)
func setData<T: Encodable>(from value: T) throws
func setData<T: Encodable>(from value: T, merge: Bool) throws
func setData<T: Encodable>(from value: T, merge: Bool, completion: ((Error?) -> Void)?) throws
func updateData(fields: [AnyHashable: Any])
func updateData(fields: [AnyHashable: Any], completion: ((Error?) -> Void)?)
func delete()
func delete(completion: ((Error?) -> Void)?)
}
public protocol CollectionWritable {
func document() -> DocumentPublishable & DocumentWritable
func document(_ documentPath: String) -> DocumentPublishable & DocumentWritable
}
<file_sep>/Sources/FirestoreRepository/DocumentReference+Combine.swift
//
// File.swift
//
//
// Created by nori on 2021/03/11.
//
import Foundation
import Combine
import FirestoreProtocol
import FirebaseFirestore
import FirebaseFirestoreSwift
extension DocumentReference {
struct Publisher: Combine.Publisher {
typealias Output = DocumentSnapshot
typealias Failure = Error
private let documentReference: DocumentReference
private let includeMetadataChanges: Bool
init(_ documentReference: DocumentReference, includeMetadataChanges: Bool) {
self.documentReference = documentReference
self.includeMetadataChanges = includeMetadataChanges
}
func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input {
let subscription = DocumentSnapshot.Subscription(subscriber: subscriber, documentReference: documentReference, includeMetadataChanges: includeMetadataChanges)
subscriber.receive(subscription: subscription)
}
}
}
extension DocumentReference: DocumentPublishable {
public func getDocument(source: FirestoreSource = .default) -> AnyPublisher<DocumentSnapshot, Error> {
Future<DocumentSnapshot, Error> { [weak self] promise in
self?.getDocument(source: source) { (documentSnapshot, error) in
if let error = error {
promise(.failure(error))
} else if let documentSnapshot = documentSnapshot {
promise(.success(documentSnapshot))
} else {
promise(.failure(FirestoreError.nilResultError))
}
}
}.eraseToAnyPublisher()
}
public func get<Document>(as type: Document.Type) -> AnyPublisher<Document?, Error> where Document : Decodable {
getDocument()
.tryMap({ try $0.data(as: type) })
.eraseToAnyPublisher()
}
public func get<Document>(source: Source = .default, as type: Document.Type) -> AnyPublisher<Document?, Error> where Document : Decodable {
getDocument(source: source.rawValue)
.tryMap({ try $0.data(as: type) })
.eraseToAnyPublisher()
}
public func publisher<Document>(as type: Document.Type) -> AnyPublisher<Document?, Error> where Document : Decodable {
publisher(includeMetadataChanges: true, as: type)
}
public func publisher<Document>(includeMetadataChanges: Bool = true, as type: Document.Type) -> AnyPublisher<Document?, Error> where Document : Decodable {
publisher(includeMetadataChanges: includeMetadataChanges)
.tryMap({ try $0.data(as: type) })
.eraseToAnyPublisher()
}
public func publisher(includeMetadataChanges: Bool = true) -> AnyPublisher<DocumentSnapshot, Error> {
DocumentReference.Publisher(self, includeMetadataChanges: includeMetadataChanges).eraseToAnyPublisher()
}
}
<file_sep>/Sources/FirestoreRepository/QuerySnapshot+Combine.swift
//
// QuerySnapshot+Combine.swift
//
//
// Created by nori on 2021/03/11.
//
import Foundation
import Combine
import FirestoreProtocol
import FirebaseFirestore
extension QuerySnapshot {
final class Subscription<SubscriberType: Subscriber>: Combine.Subscription where SubscriberType.Input == QuerySnapshot, SubscriberType.Failure == Error {
private var registration: ListenerRegistration?
init(subscriber: SubscriberType, query: Query, includeMetadataChanges: Bool) {
registration = query.addSnapshotListener (includeMetadataChanges: includeMetadataChanges) { (querySnapshot, error) in
if let error = error {
subscriber.receive(completion: .failure(error))
} else if let querySnapshot = querySnapshot {
_ = subscriber.receive(querySnapshot)
} else {
subscriber.receive(completion: .failure(FirestoreError.nilResultError))
}
}
}
func request(_ demand: Subscribers.Demand) {
// We do nothing here as we only want to send events when they occur.
// See, for more info: https://developer.apple.com/documentation/combine/subscribers/demand
}
func cancel() {
registration?.remove()
registration = nil
}
}
}
|
98398b807edd2958d3d079829449a25102432620
|
[
"Swift",
"Markdown"
] | 8 |
Swift
|
1amageek/FirestoreRepository
|
b92093118b969919f018830ea2f964627e53cf0b
|
ef02d3ad32919a441b0e1e5412b7b0c8e9c5e0d6
|
refs/heads/master
|
<repo_name>Philippus23/List<file_sep>/List.java
/**
* <p>
* Materialien zu den zentralen NRW-Abiturpruefungen im Fach Informatik ab 2018
* </p>
* <p>
* Generische Klasse List<ContentType>
* </p>
* <p>
* Objekte der generischen Klasse List (Warteschlange) verwalten beliebige
* Objekte vom Typ ContentType nach dem First-In-First-Out-Prinzip, d.h., das
* zuerst abgelegte Objekt wird als erstes wieder entnommen. Alle Methoden haben
* eine konstante Laufzeit, unabhaengig von der Anzahl der verwalteten Objekte.
* </p>
*
* @author Qualitaets- und UnterstuetzungsAgentur - Landesinstitut fuer Schule
* @version Generisch_02 2014-02-21
*/
public class List<ContentType> {
/* --------- Anfang der privaten inneren Klasse -------------- */
private class ListNode {
private ContentType content = null;
private ListNode nextNode = null;
/**
* Ein neues Objekt vom Typ ListNode<ContentType> wird erschaffen.
* Der Inhalt wird per Parameter gesetzt. Der Verweis ist leer.
*
* @param pContent das Inhaltselement des Knotens vom Typ ContentType
*/
public ListNode(ContentType pContent) {
content = pContent;
nextNode = null;
}
/**
* Der Verweis wird auf das Objekt, das als Parameter uebergeben wird,
* gesetzt.
*
* @param pNext der Nachfolger des Knotens
*/
public void setNext(ListNode pNext) {
nextNode = pNext;
}
/**
* Liefert das naechste Element des aktuellen Knotens.
*
* @return das Objekt vom Typ ListNode, auf das der aktuelle Verweis zeigt
*/
public ListNode getNext() {
return nextNode;
}
/**
* Liefert das Inhaltsobjekt des Knotens vom Typ ContentType.
*
* @return das Inhaltsobjekt des Knotens
*/
public ContentType getContent() {
return content;
}
}
/* ----------- Ende der privaten inneren Klasse -------------- */
public ListNode head;
public ListNode tail;
public ListNode current;
/**
* Eine leere Schlange wird erzeugt.
* Objekte, die in dieser Schlange verwaltet werden, muessen vom Typ
* ContentType sein.
*/
public List() {
head = null;
tail = null;
current = null;
}
/**
* Die Anfrage liefert den Wert true, wenn die Schlange keine Objekte enthaelt,
* sonst liefert sie den Wert false.
*
* @return true, falls die Schlange leer ist, sonst false
*/
public boolean isEmpty() {
return head == null;
}
/**
* Die Anfrage liefert den Wert true, wenn die Schlange keine Objekte enthaelt,
* sonst liefert sie den Wert false.
*
* @return true, falls die Schlange leer ist, sonst false
*/
public boolean hasAccess() {
return current != null;
}
/**
* Das erste Objekt wird aus der Schlange entfernt.
* Falls die Schlange leer ist, wird sie nicht veraendert.
*/
public void next() {
if (this.hasAccess()) {
current = current.getNext();
}
}
public void toFirst(){
if(!this.isEmpty()){
current = head;
}
}
public void toLast(){
if(!this.isEmpty()){
current = tail;
}
}
public ContentType getContent() {
return (this.hasAccess()) ? current.getContent() : null;
}
public void setContent(ContentType pContent) {
if (pContent != null && this.hasAccess()) {
current.setContent(pContent);
}
}
public void insert(ContentType pContent) {
if (pContent != null) {
ListNode neu = new ListNode(pContent);
if (this.hasAccess()) {
if (current == head) {
neu.setNext(head);
head = neu;
} else {
ListNode previous = this.getPrevious(current);
neu.setNext(previous.getNext());
previous.setNext(neu);
}
} else if (this.isEmpty()) {
head = neu;
tail = neu;
}
}
}
/**
* Das Objekt pContentType wird an die Schlange angehaengt.
* Falls pContentType gleich null ist, bleibt die Schlange unveraendert.
*
* @param pContent
* das anzuhaengende Objekt vom Typ ContentType
*/
public void append(ContentType pContent) {
if (pContent != null) {
ListNode neu = new ListNode(pContent);
if (!this.isEmpty()) {
tail.setNext(neu);
tail = neu;
} else {
head = neu;
tail = neu;
}
}
}
public void concat(List<ContentType> pList) {
if (pList != null && pList != this && !pList.isEmpty()) {
if (!this.isEmpty()) {
tail.setNext(pList.head);
tail = pList.tail;
} else {
head = pList.head;
tail = pList.tail;
}
pList.current = null;
pList.head = null;
pList.tail = null;
}
}
/**
* Das erste Objekt wird aus der Schlange entfernt.
* Falls die Schlange leer ist, wird sie nicht veraendert.
*/
public void remove() {
if (this.hasAccess() && !this.isEmpty()) {
if (current != head) {
ListNode previous = this.getPrevious(current);
if (current == last) {
tail = previous;
}
previous.setNext(current.getNext());
} else {
head = head.getNext();
}
ListNode nxt = current.getNext();
current.setContent(null);
current.setNext(null);
current = nxt;
if (this.isEmpty()) {
tail = null;
}
}
}
private ListNode getPrevious(ListNode pNode) {
ListNode ret = null;
if (pNode != first && pNode != null && !this.isEmpty()) {
ListNode tmp = first;
while (tmp != null && tmp.getNextNode() != pNode) {
tmp = tmp.getNextNode();
}
ret = tmp;
}
return ret;
}
}
|
49da4567e3aa34c814c3d390c8fd2fbad4ca6a24
|
[
"Java"
] | 1 |
Java
|
Philippus23/List
|
b819e017b39c926680e7e388cde919639d8f78ee
|
85d41d7ec9c3a7260356343301c77cdf5d7495d2
|
refs/heads/main
|
<file_sep>import React, { useState } from "react";
import {
Container,
TextField,
Box,
Typography,
Button,
CircularProgress,
makeStyles,
} from "@material-ui/core";
import { authAxios } from "../config/axiosConfig";
import { useHistory } from "react-router";
import { useMutation } from "react-query";
import { Alert } from "@material-ui/lab";
const Register = () => {
const history = useHistory();
const [email, setEmail] = useState("");
const [username, setUsername] = useState("");
const [companyName, setCompanyName] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const { mutate, isLoading, isSuccess, isError, data } = useMutation(
async (data) => {
const resp = await authAxios.post("/company/register", { user: data });
return resp?.data;
},
{
onSuccess: (data) => {
localStorage.setItem("company-token", JSON.stringify(data));
},
}
);
const handleRegister = (e) => {
e.preventDefault();
mutate({
company_name: companyName,
username: username,
email: email,
password: <PASSWORD>,
password_confirmation: <PASSWORD>,
});
};
const classes = useStyles();
if (isSuccess) {
return (
<Container>
<Alert severity="success">
You have registered successfully.
<p>
Please{" "}
<Button variant="text" onClick={() => history.push("/login")}>
login
</Button>{" "}
with your credentials
</p>
</Alert>
</Container>
);
}
return (
<div>
<Container>
<Box className={classes.wrapper}>
<Typography variant="h6" className={classes.txt}>
Register Your Company
</Typography>
{isError && (
<Alert severity="error">
Something went wrong! Please provide correct information
</Alert>
)}
<form onSubmit={handleRegister}>
<Box
display="flex"
flexDirection="column"
className={classes.formWrapper}
>
<TextField
id="outlined-basic"
label="Company Name"
variant="outlined"
required
onChange={(e) => setCompanyName(e.target.value)}
className={classes.input}
/>
<TextField
id="outlined-basic"
label="<NAME>"
variant="outlined"
required
onChange={(e) => setUsername(e.target.value)}
className={classes.input}
/>
<TextField
id="outlined-basic"
type="email"
label="Email"
variant="outlined"
required
onChange={(e) => setEmail(e.target.value)}
className={classes.input}
/>
<TextField
type="password"
id="outlined-basic"
label="Password"
variant="outlined"
required
onChange={(e) => setPassword(e.target.value)}
className={classes.input}
/>
<TextField
type="password"
id="outlined-basic"
label="Confirm Password"
variant="outlined"
required
onChange={(e) => setConfirmPassword(e.target.value)}
className={classes.input}
/>
{isLoading ? (
<CircularProgress className={classes.spinner} />
) : (
<Button
variant="contained"
color="primary"
type="submit"
size="large"
className={classes.btn}
>
Register
</Button>
)}
</Box>
</form>
<Box mt={2} display="flex" alignItems="center">
<Typography>have an account ?</Typography>
<Button
variant="text"
color="primary"
onClick={() => history.push("/login")}
>
Login
</Button>
</Box>
</Box>
</Container>
</div>
);
};
export default Register;
const useStyles = makeStyles((theme) => ({
wrapper: {
width: "min(500px,95%)",
margin: "60px auto 0px",
background: "#fff",
padding: "30px",
borderRadius: 15,
boxShadow: "10px 1px 25px 10px rgb(226 221 221 / 75%)",
},
input: {
margin: "10px 0px",
},
formWrapper: {},
btn: {
marginTop: 20,
},
txt: {
fontSize: 22,
textAlign: "center",
marginBottom: 10,
},
spinner: {
display: "block",
margin: "20px auto",
},
}));
<file_sep>import React, { useState } from "react";
import {
Container,
TextField,
Box,
Typography,
Button,
CircularProgress,
makeStyles,
} from "@material-ui/core";
import { authAxios } from "../config/axiosConfig";
import { useMutation } from "react-query";
import { Alert } from "@material-ui/lab";
import { useHistory } from "react-router";
const Login = ({ setLoggedIn }) => {
const history = useHistory();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const { mutate, isLoading, isSuccess, isError, data } = useMutation(
async (data) => {
const resp = await authAxios.post("/login", data);
return resp?.data;
},
{
onSuccess: (data) => {
localStorage.setItem("company-token", JSON.stringify(data));
setLoggedIn(true);
history.push("/");
},
}
);
const handleLogin = (e) => {
e.preventDefault();
mutate({ email, password });
};
const classes = useStyles();
return (
<div>
<Container>
<Box className={classes.wrapper}>
<Typography variant="h6" className={classes.txt}>
{" "}
Login
</Typography>
{isError && <Alert severity="error">Credentials did not match</Alert>}
<form onSubmit={handleLogin}>
<Box display="flex" flexDirection="column">
<TextField
type="email"
id="outlined-basic"
label="Email"
variant="outlined"
required
onChange={(e) => setEmail(e.target.value)}
className={classes.input}
/>
<TextField
type="password"
id="outlined-basic"
label="Password"
variant="outlined"
required
onChange={(e) => setPassword(e.target.value)}
className={classes.input}
/>
{isLoading ? (
<CircularProgress className={classes.spinner} />
) : (
<Button
variant="contained"
color="primary"
type="submit"
size="large"
className={classes.btn}
>
Login
</Button>
)}
</Box>
</form>
<Box mt={2} display="flex" alignItems="center">
<Typography>Don't have an account ?</Typography>
<Button
variant="text"
color="primary"
onClick={() => history.push("/register")}
>
Register
</Button>
</Box>
</Box>
</Container>
</div>
);
};
export default Login;
const useStyles = makeStyles((theme) => ({
wrapper: {
width: "min(500px,95%)",
margin: "60px auto 0px",
background: "#fff",
padding: "30px",
borderRadius: 15,
boxShadow: "10px 1px 25px 10px rgb(226 221 221 / 75%)",
},
input: {
margin: "10px 0px",
},
formWrapper: {},
btn: {
marginTop: 20,
},
txt: {
fontSize: 22,
textAlign: "center",
marginBottom: 10,
},
spinner: {
display: "block",
margin: "20px auto",
},
}));
<file_sep>import React, { useEffect, useState } from "react";
import Login from "./components/Login";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Register from "./components/Register";
import Appbar from "./components/Appbar";
import PublicRoute from "./components/PublicRoute";
import PrivateRoute from "./components/PrivateRoute";
import AddProduct from "./components/AddProduct";
import { updateAxiosToken } from "./config/axiosConfig";
function App() {
const [loggedIn, setLoggedIn] = useState(false);
useEffect(() => {
if (localStorage.getItem("company-token")) {
updateAxiosToken();
setLoggedIn(true);
}
});
return (
<div>
<Router>
<Appbar loggedIn={loggedIn} />
<Switch>
<PrivateRoute exact path="/">
<AddProduct />
</PrivateRoute>
<PublicRoute path="/login">
<Login setLoggedIn={setLoggedIn} />
</PublicRoute>
<PublicRoute path="/register">
<Register />
</PublicRoute>
</Switch>
</Router>
</div>
);
}
export default App;
<file_sep>import React, { useState } from "react";
import {
Box,
Button,
CircularProgress,
Container,
makeStyles,
TextField,
Typography,
} from "@material-ui/core";
import {
KeyboardDatePicker,
MuiPickersUtilsProvider,
} from "@material-ui/pickers";
import DateFnsUtils from "@date-io/date-fns";
import { useMutation } from "react-query";
import { userAxios } from "../config/axiosConfig";
import { Alert } from "@material-ui/lab";
import dayjs from "dayjs";
import DayjsUtil from "@date-io/dayjs";
const AddProduct = () => {
const [name, setName] = useState("");
const [origin, setOrigin] = useState("");
const [vendor, setVendor] = useState("");
const [upc, setUpc] = useState("");
const [selectedDate, setSelectedDate] = useState(new Date());
const { mutate, isLoading, isSuccess, isError } = useMutation(
async (data) => {
const resp = await userAxios.post("/products/new", { product: data });
}
);
const handleProductSubmit = (e) => {
e.preventDefault();
mutate({
name: name,
origin: origin,
vendor: vendor,
expiry_date: dayjs(selectedDate).format("DD/MM/YYYY"),
upc: upc,
});
};
const classes = useStyles();
return (
<div>
<Container>
<Box className={classes.wrapper}>
<Typography variant="h6" className={classes.txt}>
Insert New Product
</Typography>
{isError && (
<Alert severity="error" style={{ margin: "10px 0px" }}>
Something went wrong! please try again
</Alert>
)}
{isSuccess && (
<Alert tyle={{ margin: "10px 0px" }}>
Product has been added succesfully
</Alert>
)}
<form onSubmit={handleProductSubmit}>
<Box
display="flex"
flexDirection="column"
className={classes.formWrapper}
>
<TextField
type="text"
variant="outlined"
label="Product name"
required
className={classes.input}
onChange={(e) => setName(e.target.value)}
/>
<TextField
type="text"
variant="outlined"
label="Product Origin"
required
className={classes.input}
onChange={(e) => setOrigin(e.target.value)}
/>
<TextField
type="text"
variant="outlined"
label="Product Vendor"
required
className={classes.input}
onChange={(e) => setVendor(e.target.value)}
/>
<MuiPickersUtilsProvider utils={DayjsUtil}>
<KeyboardDatePicker
margin="normal"
id="date-picker-dialog"
label="Product Expiry Date"
format="DD/MM/YYYY"
value={selectedDate}
onChange={(v) => {
setSelectedDate(v);
}}
KeyboardButtonProps={{
"aria-label": "change date",
}}
/>
</MuiPickersUtilsProvider>
<TextField
type="number"
required
variant="outlined"
label="Product UPC"
className={classes.input}
onChange={(e) => setUpc(e.target.value)}
/>
{isLoading ? (
<CircularProgress className={classes.spinner} />
) : (
<Button
variant="contained"
color="primary"
type="submit"
size="large"
className={classes.btn}
>
Submit
</Button>
)}
</Box>
</form>
</Box>
</Container>
</div>
);
};
export default AddProduct;
const useStyles = makeStyles((theme) => ({
wrapper: {
width: "min(500px,95%)",
margin: "60px auto 0px",
background: "#fff",
padding: "30px",
borderRadius: 15,
boxShadow: "10px 1px 25px 10px rgb(226 221 221 / 75%)",
},
input: {
margin: "10px 0px",
},
formWrapper: {},
btn: {
marginTop: 20,
},
txt: {
fontSize: 22,
textAlign: "center",
marginBottom: 10,
},
spinner: {
display: "block",
margin: "20px auto",
},
}));
|
3b7fdef15273ab15566f151070e6b97a76108318
|
[
"JavaScript"
] | 4 |
JavaScript
|
aakash1122/product_sergeant_company
|
abc064449f9109350654d4acac81ba0d8417c279
|
8d971e71646c08fd7fe5dbf13f3d4066b289ee7b
|
refs/heads/master
|
<repo_name>nectoc/rec_demo_api<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Demo-CXF</groupId>
<artifactId>Demo-CXF</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<cxf.version>3.0.3</cxf.version>
<httpclient.version>3.1</httpclient.version>
<jax.ws.rs>2.0.1</jax.ws.rs>
<springmvc>4.1.4.RELEASE</springmvc>
<jackson.version>1.1.1</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springmvc}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springmvc}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springmvc}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-security-cors</artifactId>
<version>3.1.4</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${jax.ws.rs}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
<version>2.0.0.wso2v1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20151123</version>
</dependency>
</dependencies>
</project><file_sep>/src/server/obj/Movie.java
package server.obj;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Movie")
public class Movie {
private int userID;
private int movieID;
private int rating;
private String timeStamp;
/**
* @return the userID
*/
public int getUserID() {
return userID;
}
/**
* @param userID the userID to set
*/
public void setUserID(int userID) {
this.userID = userID;
}
/**
* @return the movieID
*/
public int getMovieID() {
return movieID;
}
/**
* @param movieID the movieID to set
*/
public void setMovieID(int movieID) {
this.movieID = movieID;
}
/**
* @return the rating
*/
public int getRating() {
return rating;
}
/**
* @param rating the rating to set
*/
public void setRating(int rating) {
this.rating = rating;
}
/**
* @return the timeStamp
*/
public String getTimeStamp() {
return timeStamp;
}
/**
* @param timeStamp the timeStamp to set
*/
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
}
|
5079bca1dc78a024e3a276b53bc849e494c6a6ba
|
[
"Java",
"Maven POM"
] | 2 |
Maven POM
|
nectoc/rec_demo_api
|
e1bb77ff4e49fa0771439ead51a72a1a2004d117
|
29971a5f642b8b01112a71f3aae445bee0d03ef5
|
refs/heads/master
|
<repo_name>Siipis/bookTracker<file_sep>/README.md
# Book Tracker
*This is a course project for the University of Helsinki.*
Book Tracker on sovellus, jolla käyttäjä voi hallinnoida omistamiaan kirjoja. Sovellukseen voi luoda oman kirjaston ja lisätä siihen käyttäjiä. Käyttäjät voivat lisätä kirjoja kirjastoon ja muuttaa niiden sijaintia. Näin esimerkiksi kirjan sijainti voi olla "Lainassa", "Kotona", "Laukussa" jne.
### Sovellus Herokussa
https://siipis-booktracker.herokuapp.com/
##### Testitunnukset
Käyttäjätunnus: `hello`
<br />
Salasana: `world`
## Käyttäjätarinat
[Katso käyttäjätarinat dokumentaatiosta](documentation/UserStories.md)
### Tietokantakaavio
<file_sep>/application/__init__.py
from flask import Flask
app = Flask(__name__)
from flask_sqlalchemy import SQLAlchemy
import os
if os.environ.get("HEROKU"):
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL")
else:
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///bookTracker.db"
app.config["SQLALCHEMY_ECHO"] = True
db = SQLAlchemy(app)
from application import views
from application.auth import models
from application.auth import views
from application.libraries import models
from application.libraries import views
from application.books import models
from application.books import views
#kirjautuminen
from application.auth.models import User
from os import urandom
app.config["SECRET_KEY"] = urandom(32)
from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "auth_login"
login_manager.login_message = "Ole hyvä ja kirjaudu käyttääksesi tätä sivua."
@login_manager.user_loader
def user_loader(user_id):
return User.query.get(user_id)
# luodaan taulut tietokantaan tarvittaessa
try:
db.create_all()
except:
pass
<file_sep>/application/books/models.py
from application import db
from application.models import Base
class Book(Base):
isbn = db.Column(db.String(144))
title = db.Column(db.String(144), nullable=False)
authors = db.Column(db.String(144), nullable=False)
publisher = db.Column(db.String(144))
year = db.Column(db.Integer)
added_by = db.Column(db.Integer, db.ForeignKey("account.id"), nullable=False)
def __init__(self, title, authors):
self.title = title
self.authors = authors
<file_sep>/application/books/views.py
from application import app, db
from flask import render_template, request, redirect, url_for
from flask_login import login_required, current_user
from application.books.models import Book
from application.books.forms import BookForm
@app.route("/books/", methods=["GET"])
def books_list():
return render_template("books/list.html", books=Book.query.all())
@app.route("/book/<book_id>/", methods=["GET"])
def book_view(book_id):
return render_template("books/view.html", book=Book.query.get(book_id))
@app.route("/book/<book_id>/edit", methods=["GET"])
@login_required
def book_edit(book_id):
return render_template("books/edit.html", book=Book.query.get(book_id), form=BookForm())
@app.route("/book/<book_id>/edit", methods=["POST"])
@login_required
def book_update(book_id):
form = BookForm(request.form)
if not form.validate():
return render_template("books/new.html", form=form)
b = Book.query.get(book_id)
b.title = form.title.data
b.authors = form.authors.data
b.publisher = form.publisher.data
b.year = form.year.data
b.isbn = form.isbn.data
db.session.commit()
return redirect(url_for("books_list"))
@app.route("/book/<book_id>/delete", methods=["GET"])
@login_required
def book_delete(book_id):
Book.query.filter_by(id=book_id).delete()
db.session.commit()
return redirect(url_for("books_list"))
@app.route("/books/new", methods=["GET"])
@login_required
def book_form():
return render_template("books/new.html", form=BookForm())
@app.route("/books/new", methods=["POST"])
@login_required
def books_create():
form = BookForm(request.form)
if not form.validate():
return render_template("books/new.html", form=form)
b = Book(form.title.data, form.authors.data)
b.publisher = form.publisher.data
b.year = form.year.data
b.isbn = form.isbn.data
b.added_by = current_user.id
db.session.add(b)
db.session.commit()
return redirect(url_for("books_list"))
<file_sep>/application/books/forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, validators
class BookForm(FlaskForm):
title = StringField("<NAME>", [
validators.Length(min=2)
])
authors = StringField("Kirjailija(t)", [
validators.Length(min=2)
])
publisher = StringField("Kustantaja", [
validators.Length(min=2)
])
year = IntegerField("Julkaisuvuosi", [
validators.NumberRange(min=0)
])
isbn = StringField("ISBN")
class Meta:
csrf = False<file_sep>/application/libraries/views.py
from application import app, db
from flask import render_template, request, redirect, url_for
from flask_login import login_required, current_user
from application.auth.models import User
from application.books.models import Book
from application.libraries.models import Library
from application.libraries.forms import LibraryForm
@app.route("/libraries")
@login_required
def libraries_list():
return render_template("libraries/list.html",
libraries=User.find_libraries(current_user))
@app.route("/libraries/new", methods=["GET"])
@login_required
def library_form():
return render_template("libraries/new.html", form=LibraryForm())
@app.route("/libraries/new", methods=["POST"])
@login_required
def library_create():
form = LibraryForm(request.form)
if not form.validate():
return render_template("libraries/new.html", form=form)
existing = Library.query.filter_by(slug=form.slug.data).first()
if existing:
return render_template("libraries/new.html",
form=form, error="Kirjaston url on jo käytössä")
lib = Library(form.name.data, form.slug.data)
lib.users.append(current_user)
db.session.add(lib)
db.session.commit()
return redirect(url_for("libraries_list"))
@app.route("/library/<library_slug>")
@login_required
def library_view(library_slug):
# TODO: Varmista, että käyttäjällä on oikeus nähdä tämä kirjasto.
library = Library.query.filter_by(slug=library_slug).first()
return render_template("libraries/view.html",
library=library,
users=User.query.all(),
own_users=Library.find_users(library),
books=Book.query.all(),
own_books=Library.find_books(library))
@app.route("/library/<library_slug>/edit", methods=["GET"])
@login_required
def library_edit(library_slug):
# TODO: Varmista, että käyttäjällä on oikeus nähdä tämä kirjasto.
return render_template("libraries/edit.html",
library=Library.query.filter_by(slug=library_slug).first(),
form=LibraryForm())
@app.route("/library/<library_slug>/edit", methods=["POST"])
@login_required
def library_update(library_slug):
# TODO: Varmista, että käyttäjällä on oikeus nähdä tämä kirjasto.
form = LibraryForm(request.form)
if not form.validate():
return render_template("libraries/edit.html", form=form)
lib = Library.query.filter_by(slug=library_slug).first()
lib.name = form.name.data
lib.slug = form.slug.data
db.session.commit()
return redirect(url_for("library_view", library_slug=lib.slug))
@app.route("/library/<library_slug>/delete", methods=["GET"])
@login_required
def library_delete(library_slug):
# TODO: Varmista, että käyttäjällä on oikeus nähdä tämä kirjasto.
Library.query.filter_by(slug=library_slug).delete()
db.session.commit()
return redirect(url_for("libraries_list"))
@app.route("/library/<library_slug>/add", methods=["POST"])
@login_required
def library_add_book(library_slug):
# TODO: Varmista, että käyttäjällä on oikeus nähdä tämä kirjasto.
if request.form.get("book") == "":
return redirect(url_for("library_view", library_slug=library_slug))
lib = Library.query.filter_by(slug=library_slug).first()
book = Book.query.get(request.form.get("book"))
lib.books.append(book)
db.session.commit()
return redirect(url_for("library_view", library_slug=library_slug))
@app.route("/library/<library_slug>/remove/<book_id>", methods=["GET"])
@login_required
def library_remove_book(library_slug, book_id):
# TODO: Varmista, että käyttäjällä on oikeus nähdä tämä kirjasto.
lib = Library.query.filter_by(slug=library_slug).first()
book = Book.query.get(book_id)
lib.books.remove(book)
db.session.commit()
return redirect(url_for("library_view", library_slug=library_slug))
@app.route("/library/<library_slug>/user", methods=["POST"])
@login_required
def library_add_user(library_slug):
# TODO: Varmista, että käyttäjällä on oikeus nähdä tämä kirjasto.
if request.form.get("user") == "":
return redirect(url_for("library_view", library_slug=library_slug))
lib = Library.query.filter_by(slug=library_slug).first()
user = User.query.get(request.form.get("user"))
lib.users.append(user)
db.session.commit()
return redirect(url_for("library_view", library_slug=library_slug))
@app.route("/library/<library_slug>/user/<user_id>", methods=["GET"])
@login_required
def library_remove_user(library_slug, user_id):
# TODO: Varmista, että käyttäjällä on oikeus nähdä tämä kirjasto.
lib = Library.query.filter_by(slug=library_slug).first()
user = User.query.get(user_id)
lib.users.remove(user)
db.session.commit()
return redirect(url_for("library_view", library_slug=library_slug))
<file_sep>/documentation/UserStories.md
# Käyttäjätarinat (User Stories)
Käyttäjänä haluan voida rekisteröityä.
Käyttäjänä haluan voida kirjautua sisään.
Käyttäjänä haluan voida luoda oman kirjaston.
Kirjaston omistajana haluan voida lisätä muita käyttäjiä kirjaston omistajiksi.
Kirjaston omistajana haluan voida lisätä kirjoja kirjastoon.
Kirjaston omistajana haluan voida päivittää kirjan tiedot.
Kirjaston omistajana haluan voida poistaa kirjan.
Kirjaston omistajana haluan voida lisätä sijainteja kirjastoon.
Kirjaston omistajana haluan voida uudelleennimetä sijainteja kirjastossa.
Kirjaston omistajana haluan voida poistaa sijainteja kirjastosta.
Kirjaston omistajana haluan voida asettaa kirjalle sijainnin.
Kirjaston omistajana haluan voida etsiä kirjaa kirjastosta nimen tai kirjailijan perusteella.<file_sep>/application/views.py
from flask import render_template, redirect, url_for
from application import app
from flask_login import current_user
@app.route("/")
def index():
if current_user.is_authenticated:
return redirect(url_for("libraries_list"))
return render_template("index.html")
<file_sep>/application/auth/models.py
from application import db
from application.models import Base
from sqlalchemy.sql import text
library_pivot = db.Table("library_user", Base.metadata,
db.Column("library_id", db.Integer, db.ForeignKey("library.id"), nullable=False),
db.Column("user_id", db.Integer, db.ForeignKey("account.id"), nullable=False)
)
class User(Base):
__tablename__ = "account"
name = db.Column(db.String(144), nullable=False)
username = db.Column(db.String(144), nullable=False)
password = db.Column(db.String(144), nullable=False)
books = db.relationship("Book", backref="account", lazy=True)
libraries = db.relationship("User", secondary=library_pivot, backref="users", cascade="all,delete")
def __init__(self, name, username, password):
self.name = name
self.username = username
self.password = <PASSWORD>
def get_id(self):
return self.id
def is_active(self):
return True
def is_anonymous(self):
return False
def is_authenticated(self):
return True
@staticmethod
def find_libraries(current_user):
stmt = text("SELECT l.id, l.name, l.slug FROM library l"
+ " LEFT JOIN library_user lu on l.id = lu.library_id"
+ " LEFT JOIN account a on lu.user_id = a.id"
+ " WHERE a.id = :user_id"
+ " ORDER BY l.name").params(user_id=current_user.id)
return db.engine.execute(stmt)
<file_sep>/application/libraries/models.py
from application import db
from application.models import Base
from application.auth.models import library_pivot, User
from application.books.models import Book
from sqlalchemy import text
book_pivot = db.Table("library_book", Base.metadata,
db.Column("library_id", db.Integer, db.ForeignKey("library.id"), nullable=False),
db.Column("book_id", db.Integer, db.ForeignKey("book.id"), nullable=False)
)
class Library(Base):
name = db.Column(db.String(144), nullable=False)
slug = db.Column(db.String(144), nullable=False, unique=True)
users = db.relationship(User, secondary=library_pivot)
books = db.relationship(Book, secondary=book_pivot, backref="library", cascade="all,delete")
def __init__(self, name, slug):
self.name = name
self.slug = slug
@staticmethod
def find_books(library):
stmt = text("SELECT b.* FROM book b"
+ " LEFT JOIN library_book lb on b.id = lb.book_id"
+ " WHERE lb.library_id = :library_id"
+ " ORDER BY b.title").params(library_id=library.id)
return db.engine.execute(stmt)
@staticmethod
def find_users(library):
stmt = text("SELECT a.* FROM account a"
+ " LEFT JOIN library_user lu on a.id = lu.user_id"
+ " WHERE lu.library_id = :library_id"
+ " ORDER BY a.name").params(library_id=library.id)
return db.engine.execute(stmt)
<file_sep>/application/libraries/forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, validators
class LibraryForm(FlaskForm):
name = StringField("Kirjaston nimi", [
validators.Length(min=2)
])
slug = StringField("Kirjaston url", [
validators.Length(min=2),
validators.Regexp("^[a-z]+$")
])
class Meta:
csrf = False
|
f7bdede3eb6cc5958148d4608b65ef53987004a0
|
[
"Markdown",
"Python"
] | 11 |
Markdown
|
Siipis/bookTracker
|
1e0bae798cdcdcbd533f135e688d713544998790
|
61f48d3a77950091816962a5b297f4706c3280fe
|
refs/heads/master
|
<file_sep><?php
$gen->chemdocConfig()->customInsets['FunctionIndex'] = function ($formatter, $token) {
if (!($formatter instanceof Chemdoc\Formatters\HTML)) {
throw new Exception("$token->name: unsupported formatter ".get_class($formatter));
}
$lines = explode("\n", $token->textContent(''));
$header = [];
$functions = []; // index in $header => hash
$aliases = [];
foreach ($lines as $i => $line) {
$line = trim($line);
$parts = array_map('trim', explode('|', $line));
if ($line === '') {
continue;
} elseif (!$i) {
$header = [];
foreach ($parts as $i => $part) {
$header[] = $i
? ['url' => strtok($part, ' '), 'title' => strtok(null)]
: ['url' => '', 'title' => $part];
}
} else {
$columns = $defined = [];
foreach ($parts as $col => $part) {
if ($part === '') {
$columns[] = null;
} elseif (!preg_match('/^((\d+\s+)*)(\S+)(\s*->\s*(.+))?$()/u', $part, $match)) {
throw new Exception("$token->name: cannot parse line: $line");
} else {
list(, $footnotes, , $name, , $aliasedTo) = $match;
$footnotes = $footnotes ? preg_split('/\s+/u', trim($footnotes)) : [];
$defined[] = $columns[] = compact('footnotes', 'name', 'aliasedTo');
$ref = &$aliases[$col][$aliasedTo] or $ref = [];
$ref[] = $name;
}
}
foreach ($columns as $i => &$ref) {
$ref and $ref['diffName'] = $ref['name'] !== $defined[0]['name'];
}
$functions[] = $columns;
}
}
usort($functions, function ($a, $b) {
while (!$a[0]) { array_shift($a); }
while (!$b[0]) { array_shift($b); }
return strcasecmp($a[0]['name'], $b[0]['name']);
});
$entities = new Chem\EntityList;
$entities->unserialize(json_decode(file_get_contents('docs/entities.json')));
$output = new Chem\HtmlOutput;
$urlOf = new ReflectionMethod($output, 'urlOf');
$urlOf->setAccessible(true);
$esc = 'htmlspecialchars';
ob_start();
?>
<style>
.func-idx { table-layout: fixed; width: 100%; border-collapse: collapse; }
.func-idx thead { background: #e1e1e1; }
.func-idx tr > * { border: 1px solid #c0c0c0; }
.func-idx_ok { background: #efe; }
.func-idx_miss { background: #fee; color: #faa; }
</style>
<p>Green cells mark functions supported by NoDash and by one of the other libraries.</p>
<table class="func-idx">
<thead>
<tr>
<?php foreach ($header as $i => $column) {?>
<th>
<?php if ($column['url']) {?>
<a href="<?=$esc($column['url'])?>" target="_blank">
<?php }?>
<?=$esc($column['title']), $column['url'] ? '</a>' : ''?>
(<a href="#" onclick="funcIdx.toggleSupportedIn(<?=$i?>); return false" title="Hide functions supported only by <?=$esc($column['title'])?>">T</a>)
</th>
<?php }?>
</tr>
</thead>
<tbody>
<?php foreach ($functions as $cols) {?>
<tr>
<?php foreach ($cols as $i => $col) {?>
<?php if ($col) {?>
<td class="<?=($cols[0] and count(array_filter($cols)) > 1) ? 'func-idx_ok' : ''?>">
<?php if (strrchr($header[$i]['url'], '#')) {?>
<a href="<?=$esc($header[$i]['url'].$col['name'])?>" target="_blank">
<?php } else if (!$header[$i]['url']) {?>
<a href="<?=$esc($urlOf->invoke($output, $entities->find(['name' => $col['name']])[0]))?>">
<?php }?>
<?=$esc($col['name'])?></a>
<?php if ($col['aliasedTo']) {?>
(alias of <?=$esc($col['aliasedTo'])?>)
<?php }?>
<?php if (isset($aliases[$i][$col['name']])) {?>
(<abbr title="<?=$esc(join(', ', $aliases[$i][$col['name']]))?>">aliases</abbr>)
<?php }?>
<?php if ($col['diffName']) {?>
<b>diff. name</b>
<?php }?>
<?php foreach ($col['footnotes'] as $note) {?>
[<a href="#-footnote<?=$note?>" id="footnoteuse<?=$note?>"><?=$note?></a>]
<?php }?>
<?php } else {?>
<td class="func-idx_miss">
missing
<?php }?>
</td>
<?php }?>
</tr>
<?php }?>
</tbody>
</table>
<script>
var funcIdx = {
_data: <?=json_encode($functions, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)?>,
_columnStates: <?=json_encode(array_fill(0, count($header), []), JSON_FORCE_OBJECT)?>,
el: document.querySelector('.func-idx'),
toggleSupportedIn: function (col) {
var nodes = this.el.querySelectorAll('tbody tr')
this._columnStates[col].hiddenUnsupported = !this._columnStates[col].hiddenUnsupported
nodes.forEach(function (node, index) {
var vis = this._data[index].some(function (func, i) {
return !this._columnStates[i].hiddenUnsupported && !!func
}, this)
node.style.display = vis ? '' : 'none'
}, this)
},
}
</script>
<?php
return ob_get_clean();
};<file_sep>NoDash.js - a terse utility library based on ES5+ features
==========================================================
NoDash is yet another variant of Underscore.js and LoDash.js but with focus on:
* Native ES5+ features - say "No" to reinventing the wheel
* Minimum code - isolated, easy to understand functions (6 lines on average)
* Completeness - with ajax()*, trim() and others for day-to-day development
* Universality - work on arrays, objects (map()) and strings (first()) alike
With NoDash, you might not need another utility library and yet your bundle's
size will keep fit as NoDash is smaller than Underscore and LoDash.
Size: 14K minified, 4K gzipped. Functions: 85 + 3*.
(*) Large functions: ajax(), template() and format() are part of nodash-extra.js
(8K minified). Included in nodash.min.js. Usable with Underscore/LoDash too.
Dependencies
============
None.
Documentation
=============
Functions reference:
https://squizzle.me/js/nodash/
Compatibility table for migrating from Underscore and LoDash:
https://squizzle.me/js/nodash/map.html#COMPATIBILITY
Ways to Install
===============
$ npm install squizzle-nodash
License
=======
Public domain.
http://unlicense.org
Quick list of goodness
======================
Originally Array functions
--------------------------
every function ( value, func, cx )
fill function ( value [, filler [, begin [, end]]] )
filter function ( value, func, cx )
find function ( value, func, cx )
findIndex function ( value, func, cx )
flat function ( value [, depth] )
forEach function ( value, func, cx )
includes function ( value, member [, fromIndex] )
indexOf function ( value, member [, fromIndex] )
join function ( value, glue )
lastIndexOf function ( value, member [, fromIndex] )
map function ( value, func, cx )
reduce function ( value, func [, initial )
reduceRight function ( value, func [, initial )
reverse function ( value )
slice function ( value [, begin [, end]] )
some function ( value, func, cx )
sort function ( value, func )
Originally Object functions
---------------------------
assign function ( ...objects )
entries function ( value )
fromEntries function ( value )
has function ( value, property )
keys function ( value )
values function ( value )
Originally String functions
---------------------------
endsWith function ( value, sub [, endIndex] )
escape function ( value )
escapeRegExp function ( str )
padEnd function ( value, length [, pad] )
padStart function ( value, length [, pad] )
repeat function ( value, count )
startsWith function ( value, sub [, startIndex] )
trim function ( value [, blank] )
trimEnd function ( value [, blank] )
trimStart function ( value [, blank] )
Utilities not part of any ES standard
-------------------------------------
allKeys function ( value )
at function ( value, path, default )
bind function ( func, cx, ...args )
chunk function ( value [, length] )
compact function ( value )
countBy function ( value, func, cx )
debounce function ( func, ms [, immediate] )
defer function ( func, ...args )
delay function ( func, ms, ...args )
difference function ( value, ...values )
first function ( value [, length] )
flip function ( value )
groupBy function ( value, func, cx )
indexBy function ( value, func, cx )
initial function ( value [, length] )
intersection function ( value, ...values )
invoke function ( value, method, ...args )
isArguments function ( value )
isArrayLike function ( value )
isElement function ( value )
isEmpty function ( value )
last function ( value [, length] )
max function ( value [, func [, cx]] )
min function ( value [, func [, cx]] )
negate function ( func [, numeric] )
object function ( keys [, values] )
omit function ( value, func [, cx] | value, keys | value, ...keys )
once function ( func )
partition function ( value, func, cx )
pick function ( value, func [, cx] | value, keys | value, ...keys )
pluck function ( value, property )
property function ( path, default )
random function ( [[min,] max] )
range function ( [begin,] end [, step] )
redraw function ( node [, class] )
reject function ( value, func, cx )
rest function ( value [, length] )
sample function ( value [, n] )
shuffle function ( value [, length] )
size function ( value )
sortBy function ( value, func, cx )
sum function ( value )
throttle function ( func, ms, options )
times function ( times, func, cx )
toArray function ( value )
union function ( ...values )
unique function ( value [, func [, cx]] )
unzip function ( value )
without function ( value, ...members )
zip function ( ...values )
Aliases
-------
all → every
any → some
contains → includes
drop → rest
dropRight → initial
each → forEach
extend → assign
findKey → findIndex
flatten → flat
flattenDeep function ( value )
flattenDepth → flat
forOwn → forEach
fromPairs → fromEntries
head → first
invert → flip
isArray function ( value )
isEqual function ( a, b )
keyBy → indexBy
mapValues → map
maxBy → max
minBy → min
nth → at
pairs → entries
partial function ( func, ...args )
remove → reject
sampleSize → shuffle
sign function ( value )
tail → rest
take → first
takeRight → last
toPairs → entries
transform → reduce
trimLeft → trimStart
trimRight → trimEnd
uniq → unique
zipObject → object
extra.js
--------
ajax function ( options )
format function ( [options,] str [, arg [, ...]] )
template function ( str [, options] )
---
Squizzle ♥ it
https://squizzle.me
<file_sep>/*!
NoDash.js - extra, longer, useful functions (pick any three)
https://squizzle.me/js/nodash | Public domain/Unlicense
*/
;(function (factory) {
var deps = 'nodash?main:_'
var me = '_'
// --- Universal Module (squizzle.me) - CommonJS - AMD - window --- IE9+ ---
if (typeof exports != 'undefined' && !exports.nodeType) {
// CommonJS/Node.js.
deps = (deps.replace(/\?[^:]*/g, '').match(/\S+(?=:)/g) || []).map(require)
if (typeof module != 'undefined' && module.exports) {
module.exports = factory.apply(this, deps)
} else {
exports = factory.apply(this, deps)
}
} else if (typeof define == 'function' && define.amd) {
// AMD/Require.js.
define(deps.replace(/\?/g, '/').match(/\S+(?=:)/g) || [], factory)
} else {
// In-browser. self = window or web worker scope.
var root = typeof self == 'object' ? self
: typeof global == 'object' ? global
: (this || {})
var by = function (obj, path) {
path = path.split('.')
while (obj && path.length) { obj = obj[path.shift()] }
return obj
}
// No lookbehind in IE.
deps = (deps.match(/:\S+/g) || []).map(function (dep) {
var res = by(root, dep = dep.substr(1))
if (!res) { throw me + ': missing dependency: ' + dep }
return res
})
me = me.split(/\.([^.]+)$/)
if (me.length > 1) { root = by(root, me.shift()) }
Object.assign(root[me[0]], factory.apply(this, deps))
}
}).call(this, function (NoDash) {
"use strict";
//! +cl=Extra
// These functions are provided by `[nodash/extra`]. In browser context they
// are part of the main `'_/`'NoDash object.
//
// This module depends on NoDash by default but it can also work with
// Underscore or LoDash. See `@sq@start#deps`@ on how to override this
// dependency (except the NPM's `'override method won't work because `'extra
// uses a dependency on self). An example for Require.js:
//[
// requirejs.config({
// map: {
// 'nodash/extra': {
// 'nodash/main': 'lodash'
// }
// }
// })
//]
return {
// Performs a remote request using `'XMLHttpRequest, offering a subset of
// jQuery's `'ajax() API.
//= XMLHttpRequest `- the `'xhr
//> options object
// Possible `'options keys:
//> url str
//> type str `- `'GET by default
//> data str`, object `- request data for `'POST, etc.; useful object types
// are `@mdn:API/FormData`@, `@mdn:API/Blob`@ and
// `@mdn:API/URLSearchParams`@ (not in IE)
//> dataType str `- type of `[xhr.response`], from standard
// `@mdn:API/XMLHttpRequestResponseType`@; `'text by default; other useful
// types are `'document (for HTML and XML), `'json, `'arraybuffer and
// `'blob
//> context object `- calling context for below callbacks
//> beforeSend function `- called before `[xhr.open()`]; receives `'xhr and
// `'options (mutable, affects internal copy, not given `'options); if
// returns `[=== false`] then the request is not performed and `'error is
// called without giving `'e (imitates `'abort())
//> success function `- called when response has arrived; receives `'xhr and
// `'e
//
// Warning: if `'dataType is `'json, responses being empty or the string
// "null" trigger `'success with `'response set to `'null.
//> error function `- called on a request or response error, and also on
// `'beforeSend and `[xhr.abort()`]; receives `'xhr (always) and `'e (only
// if not on `'beforeSend)
//> complete function `- called after completion, successful or not;
// receives `'xhr and `'e
//> progress function `- called during response transmission; receives `'xhr
// and `'e where useful `'e properties are:
// `> lengthComputable bool
// `> loaded int bytes
// `> total int bytes `- or 0
//> timeout int milliseconds `- if exceeded, request `'error-s with the
// `'status of 0
//> headers object `- members can be strings or arrays; if missing, assumed
// `[X-Requested-With: XMLHttpRequest`] (for compatibility with jQuery's
// `'ajax())
//
// `[Content-Type: application/x-www-form-urlencoded`] is added if `'type
// is not `'GET and `'data is not an object (browsers set the correct
// `[Content-Type`] automatically if it's an object).
//
// For CORS, custom headers like `[X-Requested-With`] (but not
// `[Content-Type`]) mandate the preflight request. Give `'headers of `'{}
// to avoid it. Details:
// `@https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests`@.
//> username str `- for HTTP Basic Authentication
//> password str `- for HTTP Basic Authentication
// It is guaranteed that, per given `#ajax() call:
//* exactly one of `[success or error`] and one `[complete`] is called
//* `[success`] is called on a 200-299 `'status and `'responseType matching
// `'dataType (the latter is browser-dependent and not very reliable)
//* `[complete`] is called after `[success or error`], even if the latter
// has thrown an exception (it's re-thrown after `'complete provided it
// didn't throw another one)
//* `[progress`] is never called after calling `[success or error`]
// ECMAScript equivalents: `@mdn:API/XMLHttpRequest`@, `@mdn:API/Fetch_API`@.
//?`[
// _.ajax({
// url: 'form.php',
// type: 'POST',
// data: new FormData(document.querySelector('form')),
// })
//
// _.ajax({
// url: 'some.json',
// dataType: 'json',
// timeout: 5000, // 5 seconds
// headers: {}, // remove X-Requested-With
// beforeSend: () => $('#loading').show()
// complete: () => $('#loading').hide()
// success: xhr => alert(xhr.response),
// error: (xhr, e) => alert(xhr.statusText),
// progress: (xhr, e) => $('progress').attr({
// max: e.total,
// value: e.lengthComputable && e.total
// }),
// })
// `]
ajax: function (options) {
var o = NoDash.assign({}, {
url: location.href,
type: 'GET',
data: undefined,
dataType: 'text',
context: undefined,
beforeSend: new Function,
success: new Function,
error: new Function,
complete: new Function,
progress: new Function,
timeout: 0,
headers: {'X-Requested-With': 'XMLHttpRequest'},
username: undefined,
password: <PASSWORD>,
}, options)
if (!o.headers['Content-Type'] && o.type != 'GET' && typeof o.data != 'object') {
o.headers['Content-Type'] = 'application/x-www-form-urlencoded'
}
var xhr = new XMLHttpRequest
var queue = []
function finish() {
// Delayed processing to let all other events (errors) pass through.
queue.length || NoDash.defer(function () {
// No pop() - queue.length must be non-0 to prevent late XHR events
// from re-triggering this.
var args = [xhr].concat(Array.prototype.slice.call(queue[queue.length - 1]))
var ok = xhr.status >= 200 && xhr.status < 300 &&
// This check isn't very reliable as at least Firefox leaves
// 'json' as is even if response is 'text/html'.
xhr.responseType == o.dataType
try {
NoDash.bind(ok ? o.success : o.error).apply(o.context, args)
} catch (e) {
var ex = e
}
NoDash.bind(o.complete).apply(o.context, args)
if (ex) { throw ex }
})
queue.push(arguments)
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
finish.apply(undefined, arguments)
}
}
// ontimeout is fired after onreadystatechange.
xhr.ontimeout = finish
xhr.upload.onprogress = function () {
if (!queue.length) {
var args = [xhr].concat(Array.prototype.slice.call(arguments))
NoDash.bind(o.progress).apply(o.context, args)
}
}
if (NoDash.bind(o.beforeSend).call(o.context, xhr, o) === false) {
NoDash.bind(o.error).call(o.context, xhr)
} else {
xhr.open(o.type, o.url, true, o.username, o.password)
xhr.timeout = o.timeout
xhr.responseType = o.dataType
NoDash.forEach(o.headers, function (value, name) {
NoDash.toArray(value).forEach(function (item) {
xhr.setRequestHeader(name, item)
})
})
xhr.send(o.data)
}
return xhr
},
//! `, +fna=function ( str [, options] )
// Converts a template `'str to a function that accepts variables and
// returns a formatted string.
//= function accepting `'vars`, string if `[options.source`]
//> str string`,
// function take the contents of the first `[/**/`] comment (make sure it's not minified away)`,
// Node take `'textContent `- the template
//> options object`, omitted `- compilation options
// ` `#template() can be used outside of web browser environment.
//
// See also `#format().
//
// Possible `'options keys:
//> prepare omitted`, object defaults for formatting variables and/or
// options (under `'o)`, function `- function receives caller-given `'vars
// (`'{} if not given) and options under `'o (may be `'undefined) and
// returns an object with complete variables and options (may be mutated)
//> source bool`, omitted `- if set, returns a JavaScript string - code of
// the function to be compiled
//> with bool`, omitted = `'true `- if set, members of `'vars can be
// referenced directly, not through `'v; such templates are slower due to
// using JavaScript's `[with { }`]
//> laxRef bool`, omitted = `'true `- if set, non-code `'ref are resolved
// with `#at(), meaning they return the non-object value immediately, even
// if there are more path components (that triggers an error without
// `'laxRef, but is faster)
//> code bool`, omitted = `'true `- if unset, fails to compile if there are
// constructs allowing arbitrary code execution; in such case it should be
// safe to pass `'str from untrusted input since it can only read values
// given to the compiled function and from global `'window (unless there
// are custom `'blocks)
//> backslash bool`, omitted = `'false `- if set, preprocesses `'str by
// removing backslashes placed before a line break together with all the
// following whitespace and line breaks; useful for splitting long lines
// that can't normally be split, wrapping `'{{ `'}} or getting rid of
// unwanted spaces inside `[<u>`]
//> blocks object`, omitted = default `'if/`'for/etc. `- new `'custom or
// overridden standard `'if/`'for/etc.; key is the block's name
// (alphanumeric), value is a function receiving `[param, value, c`]:
// `> param null if no `':... given`, str `- part after `': (may be blank)
// `> value null no space given`, str `- part after space; on conflict
// with non-code `'echo the latter wins so add a colon for unambiguity:
// `[{{echo}}`] but `[{{block:}}`]
// `> c object `- current compiler's state; keys:
// `> options object `- an internal copy of `'options given to
// `#template(), with filled defaults
// `> ref function `- resolves a reference (see `'ref below); receives
// a raw string, returns a JavaScript code snippet evaluating to
// string
// `> stack `- current chain of blocks, first being last opened
// `> extra object `- for passing non-serializable data to the compiled
// function; available under `'_x variable
// `> * `- other keys can be used for storing custom state data
// Attention: be mindful of operator precedence: returning code like
// `[a || b`] will prevent the template from running; instead, return
// `[(a || b)`]. Brackets are not added automatically because `'( may
// appear in `'start and a matching `') appears in `'end.
// Function must return an object with keys:
// `> start omitted`, str `- JavaScript code evaluating to string
// `> end omitted`, str `- JavaScript code evaluating to string at the
// time block's end is met (`[{{/}}`]); if `'null then the block isn't
// opened and needs not be closed (alike to `[<input>`] in HTML)
// `> type omitted`, str `- used together with `'end; sets matching
// `'block_end's type; defaults for the block's key
// `> head omitted`, str `- JavaScript code added to the beginning of
// the compiled function; useful for declaring `[var`]iables
// Code snippets can use context variables like `'v (see below).
// Use `[JSON.stringify()`] to properly escape a string.
// Template syntax loosely resembles that of Mustache.js/Handlebars.js - all
// substitutions are performed within `[{{...}}`]:
//[
// escaped = \[\\...]{{
// echo = {{ [=] ref }}
// conditional = {{ [else]if[:not] ref }}
// | {{ else[:] }}
// loop = {{ for[:[*][pf]] ref }}
// | {{ elseif[:pf|-[:not]] ref }}
// | {{ else[:pf|-] }}
// block_end = {{ / [if|for] }}
// custom = {{ key[:[param]][ value] }}
// | {{ / [key] }}
//
// ref = var[.prop...] | code
//]
//* `'escaped: a pair of `'{ prefixed with odd number of `'\ becomes raw
// `'{{ prefixed with half that number of `[\`]; even number of `'\ doesn't
// escape `'{{ but is still emitted "halved": `[
// \{{ = {{ \\\{{ = \{ \\\\\{{ = \\{{
// \\{{...}} = \ + result \\\\{{...}} = \\ + result
// `]
//* `'echo: emits value of a variable/property (not of global like `'window)
// or result of executing arbitrary code (if `'ref is not alphanumeric with
// periods). Without `'= the result is post-processed by `[v.o.escaper`]
// (e.g. HTML-escaped). If `'ref is `'null or `'undefined, emits nothing.
//* `'conditional: emits the enclosed block only if `'ref is truthy (or
// falsy with `':not).
//* `'loop: emits the enclosed block once for every iteration. `'ref is
// given to `#forEach(), with `#forceObject if asterisk (`[*`]) is present.
// Optional `'pf specifies prefix for variables inside the block that are
// by default `'m ("m"ember's value), `'k ("k"ey), `'i ("i"ndex, same as
// `'k if `'ref `#isArrayLike), `'a ("a"ll, the `'ref). In object mode,
// iterations are seamlessly ordered by comparing keys as strings
// (`[for:array`] iterates in different order than `[for:*array`]:
// `[2 < 10`] but `['2' > '10'`]).
//
// Only `'i exists outside of the block and is `'undefined prior to the
// first `'loop with that `'pf; after a `'loop it holds index of the last
// iterated member, or `'-1 if `'ref was empty (or
// `'undefined/`'null/`'false) - this is what `'loop's enclosed
// `'elseif/`'else test (they also change `'for's `'block_end from `'/for
// to `'/if). Without `': or with `[:-`], last `'for (its `'pf) is checked:
// `[{{elseif}} {{elseif:-}} {{elseif:-:not}}`] - but here last `'for with
// empty `'pf is checked: `[{{elseif:}} {{elseif::not}}`].
//* `'block_end: give the expected block's type (not simply `[{{/}}`]) for
// extra syntax safety: `[
// {{if ...}} {{for ...}} {{/}} {{/}} - works
// {{if ...}} {{for ...}} {{/for}} {{/if}} - works
// {{if ...}} {{for ...}} {{/if}} {{/for}} - fails to compile
// `]
//* Nested and multi-line `'{{ `'}} are not supported but you can use string
// `'backslash or escapes: `[{{'}}\n'}}`] fails but `[{{'\\x7d\\n}'}}`]
// works.
//
// The returned compiled template function accepts these arguments:
//> v object`, falsy = `'{} `- variables for access by `'ref; the `'o key
// contains formatting options; standard `'o subkeys:
// `> escaper function`, omitted return as is `- `'echo without `'= runs
// the value through this; in HTML context you'd set it to `#escape()
//
// These variables exist within the returned function:
//> _ `- reference to NoDash regardless of the global `'_
//> v `- variables given by the caller (`[v.o`] = options, or `[{}`])
//> _x `- the `[c.extra`] object (see the `'blocks option)
//> * `- members of `'v, if `[options.with`] is set
//
//?`[
// _.template('{{a.b.c}}')({}) //=> ''
// _.template('{{a.b.c}}', {laxRef: false})() // Error
// _.template('{{a}}', {laxRef: false})() // Error
// _.template('{{v["a"]}}', {laxRef: false})()
// //=> '' (v is always present)
// _.template('{{a["b"]}}')()
// // Error (laxRef only affects non-code ref)
// _.template('{{Math.random()}}')() //=> 0.2446989
//
// _.template('{{if Math.random() > 0.5}}win!{{/}}')()
// //=> 'win!' or ''
// _.template('{{if Math.random > 1}}win!{{/}}')({
// Math: {random: 9000},
// })
// //=> 'win!'
//
// _.template('{{if Math.random}}win!{{/}}', {laxRef: false, with: false})({})
// //=> 'win!'
// _.template('{{if:not Math.random}}win!{{/}}')()
// //=> ''
// _.template('{{if Math.random}}win!{{/}}')({Math: {random: 0}}) //=> ''
// _.template('{{Math.random}}')({Math: {random: -451}}) //=> '-451'
//
// _.template('{{document.title}}')()
// //=> 'bar' (window.document.title)
// _.template('{{document.title}}')({
// document: {title: 'foo'},
// })
// //=> 'foo'
// _.template('{{v.document.title}}')({
// document: {title: 'foo'},
// })
// //=> 'foo'
// _.template('{{document.title}}', {with: false})()
// //=> 'bar'
// _.template('{{document.title}}', {with: false})({
// document: {title: 'foo'},
// })
// //=> 'bar'
// _.template('{{v.document.title}}', {with: false})({
// document: {title: 'foo'},
// })
// //=> 'foo'
//
// _.template('{{document["title"]}}')()
// //=> 'bar'
// _.template('{{document["title"]}}')({
// document: {title: 'foo'},
// })
// //=> 'foo'
// _.template('{{document["title"]}}', {with: false})({
// document: {title: 'foo'},
// })
// //=> 'bar'
// _.template('{{v.document["title"]}}', {with: false})({
// document: {title: 'foo'},
// })
// //=> 'foo'
// `]
//
//?`[
// var tpl = function () { /*
// {{if homepage}}<a href="{{homepage}}">Homepage</a>{{/}}
// */ }
// _.template(tpl)({homepage: 'https://squizzle.me'})
// //=> <a href="https://squizzle.me">Homepage</a>
//
// var tpl = function () { /*
// https://very.long/\
// string?with=lotta&\
// query=params#!and-stuff
// */ }
// _.template(tpl, {backslash: true})()
// //=> https://very.long/string?with=lotta&query=params#!and-stuff
// `]
// Other examples where `'backslash is useful:
// `[
// {{if foo... && \ becomes {{if foo... && bar... }}
// bar... \ without spaces before \ would be:
// }} {{if foo...&& bar...}}
//
// <u ...>\ becomes <u ...>text</u> rather than
// text\ <u ...> text </u>, removing underline of the
// </u> whitespace after "text" when viewed in browser
// `]
//
//? Given this node somewhere in DOM (`[<template>`] is unsupported in IE):
// `[
// <script type="text/template" id="menuTemplate">
// <ul>
// {{for menu}}
// <li>
// {{i+1}}. <a href="{{m.url}}">{{m.caption}}</a>
// </li>
// {{/for}}
// </ul>
// </script>
// `]
// This call:
// `[
// var func = _.template(document.getElementById('menuTemplate'))
// func({
// menu: [
// {url: '//squizzle.me', caption: "Squizzle's home"},
// {url: '//squizzle.me/js/sqimitive', caption: "Sqimitive.js"},
// ],
// }, {escaper: _.escape})
// `]
// ...will produce:
// `[
// <ul>
// <li>
// 1. <a href="//squizzle.me">Squizzle&39;s home</a>
// </li>
// <li>
// 2. <a href="//squizzle.me/js/sqimitive">Sqimitive.js</a>
// </li>
// </ul>
// `]
//? Using `'prepare:
// `[
// var f = _.template('{{a}}', {prepare: {a: '&', o: {escaper: _.escape}}})
// f() //=> '&'
// f({a: '<'}) //=> '<'
// f({}, {escaper: null}) //=> '&'
// f({a: '<'}, {escaper: null}) //=> '<'
// `]
// To force certain variables and/or options wrap the returned function:
// `[
// var f = _.template('{{a}}')
// var w = function (v) {
// var o = _.assign({}, v.o, {escaper: _.escape})
// return f(_.assign({}, v, {a: '&', o: o}))
// }
// w({a: '<'}, {escaper: null}) //=> '&'
// `]
// Function form of `'prepare is useful if the template is compiled early
// but the defaults it should use change over time:
// `[
// var f = _.template('{{r}}', {prepare: {r: Math.random()}})
// f() //=> 0.2446989
// f() //=> 0.2446989
// f({r: -1}) //=> -1
//
// var f = _.template('{{r}}', {prepare: function (v) {
// return {r: Math.random(), o: v.o}
// // ignores all caller-given variables, keeps its options
// return _.assign({}, v, {r: Math.random(), o: v.o})
// // overrides r's value, keeps other variables and all options
// }})
// f() //=> 0.0682551
// f() //=> 0.4187164
// f({r: -1}) //=> 0.1058262
// `]
//? `[
// var f = _.template(``
// {{for a}}
// a
// {{elseif b}}
// b
// {{else}}
// c
// {{/if}}
// ``)
// // Equivalent to:
// var f = _.template(``
// {{for a}}
// a
// {{/for}}
// {{if i == -1 && b}}
// b
// {{elseif i == -1}}
// c
// {{/if}}
// ``)
//
// f() //=> 'c'
// f({b: true}) //=> 'b'
// f({a: [1, 2, 3]}) //=> 'a a a'
// `]
//
//? With enabled `[options.with`], `'loop's variables shadow global ones
// with the same name but globals are still accessible through `[v.`]. Use
// `':pf to avoid shadowing. Assuming enabled `'with:
// `[
// {{a}} {{v.a}} // .a of the global variables object
// {{v.v.a}} // .a property of a global variable .v
// {{for y}} {{a}} {{v.a}} {{m.a}} {{v.m.a}} {{/for}}
// // loop's .a (!), global .a variable, member's .a,
// // .a property of a global variable .m
// {{for:f y}} {{a}} {{fa}} {{m.a}} {{fm.a}} {{/for}}
// // global .a variable, loop's .a, global .m's .a, member's .a
// `]
//
//? Custom blocks:
// `[
// var sample = function (param, value, c) {
// return {start: '_.sample(' + c.ref(value) + ')'}
// }
// _.template('{{sample items}}', {blocks: {sample}})
// ({items: ['a', 'b', 'c']})
// //=> 'a' or 'b' or 'c'
// `]
// Removing whitespace outside of HTML tags (`[< >`]):
// `[
// var ws = function () {
// return {start: '(""', end: '"").replace(/\\s(?=<|$)/g, "")'}
// }
// _.template('{{ws}} <abbr title="Oh"> {{/ws}} </abbr>', {blocks: {ws}})()
// //=> '<abbr title="Oh"> </abbr>'
//
// _.template(..., {..., source: true})
// // Compiled to code (cleaned):
// return (" <abbr title=\"Oh\"> ").replace(/\s(?=<|$)/g, "") + " </abbr>"
// `]
template: function (str, options) {
options = NoDash.assign({with: true, laxRef: true, code: true}, options)
options.blocks = NoDash.assign({
if: function (param, value, c, ref) {
if (param && param != 'not') {
throw new Error('template: bad "if:' + param + '".')
}
return {start: '(' + (param ? '!' : '') + (ref || c.ref)(value) + '?""',
end: '"":"")'}
},
elseif: function (param, value, c, ref) {
var prev = c.stack[0] && !c.stack[0]._else && c.stack[0].type
if (prev == 'for') {
param = (param == null ? '-' : param).match(/^(\w*|-)(:(.*))?$/)
if (param[1] == '-') { param[1] = c._lastFor }
var res = options.blocks.if(param[3], value, c, function (s) {
return '(' + param[1] + 'i==-1&&' + (ref || c.ref)(s) + ')'
})
return NoDash.assign(res, {start: c.stack.shift().end + '+' + res.start,
type: 'if', _for: param[1]})
} else if (prev != 'if') {
throw new Error('template: elseif: no preceding if or for.')
} else {
if (c.stack[0]._for != null) {
arguments[3] = function (s) {
return '(' + c.stack[0]._for + 'i==-1&&' + (ref || c.ref)(s) + ')'
}
arguments.length++
}
var res = options.blocks.if.apply(this, arguments)
c.stack[0].end += ')'
return {start: '"":' + res.start}
}
},
else: function (param, value, c) {
if ((param && ((c.stack[0] || {}).type != 'for')) || value) {
throw new Error('template: else takes no arguments.')
} else {
var res = options.blocks.elseif(param, '', c, function () { return 1 })
c.stack[0]._else = true // may have been shift()'ed
return res
}
},
for: function (pf, value, c) {
var match = (pf || '').match(/^(\*)?(\w*)()$/)
if (!match) {
throw new Error('template: bad "for:' + pf + '".')
}
pf = c._lastFor = match[2]
return {
head: 'var ' + pf + 'i;',
start: '(' + pf + 'i=-1,' +
'_x.for(' + c.ref(value) + ',' + !!match[1] + ',' +
'function(' + pf + 'm,' + pf + 'k,' + pf + 'a){' +
pf + 'i++;return""',
end: '""}))',
}
},
}, options.blocks)
var c = {
options: options,
stack: [],
_lastFor: null,
extra: {
for: function (value, forceObject, func) {
if (value == null || value === false) {
return ''
} else if (forceObject || !NoDash.isArrayLike(value)) {
return NoDash.entries(value)
.sort(function (a, b) {
// Keys may be numbers if forceObject && isArrayLike.
return (a[0] += '') > (b[0] += '') ? +1 : -1
})
.map(function (entry) { return func(entry[1], entry[0], value) })
.join('')
} else {
return NoDash.map(value, func).join('')
}
},
},
ref: function (s) {
if (!(s = s.trim())) { throw new Error('template: blank ref.') }
var m
if (m = s.match(/^(\w+)((\.\w+)*)$/)) {
s = '["' + m[2].substr(1).replace(/\./g,
(options.laxRef ? '","' : '"]["')) + '"]'
if (options.laxRef) {
s = '(typeof ' + m[1] + '=="undefined"?undefined:' +
(m[2] ? '_.at(' + m[1] + ',' + s + ')' : m[1]) + ')'
} else {
s = m[1] + (m[2] ? s : '')
}
} else if (!options.code) {
throw new Error('template: code refs prohibited.')
} else {
s = '(' + s + ')'
}
return s
},
}
var head = ''
var blocks = NoDash.keys(options.blocks).join('|')
var blockStart = new RegExp('^(' + blocks + ')(:\\S*)?(\\s+(.*))?$')
var blockEnd = new RegExp('^\\/\\s*(' + blocks + ')?\\s*$')
if (str instanceof Function) {
// RegExp /s flag (dotAll) is not supported in IE and older FF.
str = str.toString().match(/\/\*([\s\S]*)\*\//)[1].trim()
} else if (NoDash.isElement(str)) {
str = str.textContent
}
if (options.backslash) {
str = str.replace(/\\[\r\n]\s*/g, '')
}
str = str.replace(/(\\(\\\\)*)\{\{|((?:\\\\)*)\{\{\s*(.*?)\}\}|(["\\\0-\x1F])/g, function () {
var m = arguments
if (m[1]) {
var res = m[0].substr(1)
} else if (m[5]) { // \ or " or non-printable
var code = m[0].charCodeAt(0)
var res = '\\x' + (code < 16 ? '0' : '') + code.toString(16)
} else {
var res = m[3] + '"+'
var inside = m[4]
if (m = inside.match(blockStart)) {
var block = options.blocks[m[1]](m[2] ? m[2].substr(1) : null,
m[3] ? m[4] : null, c)
head += block.head || ''
res += block.start || ''
block.type = block.type || m[1]
block.end && c.stack.unshift(block)
} else if (m = inside.match(blockEnd)) {
if (!c.stack.length || (m[1] && c.stack[0].type != m[1])) {
throw new Error('template: /' + c.stack[0].type + ' expected, {{' + m[0] + '}} found.')
}
res += c.stack.shift().end
} else {
res += '((T=' + c.ref(inside.substr(inside[0] == '=')) + ')==null?"":' +
(inside[0] == '=' ? 'T' : 'E(T)') + ')'
}
res += '+"'
}
return res
})
if (c.stack.length) {
str = NoDash.pluck(c.stack, 'type').join('}} <- {{')
throw new Error('template: unclosed {{' + str + '}}.')
}
str = head + 'return"' + str + '"'
// str (head) may contain "var".
if (options.with) { str = 'with(v){' + str + '}' }
if (!options.source) {
var def = options.prepare
if (def && (typeof def != 'function')) {
options.prepare = function (v) {
return NoDash.assign({}, def, v, {o: NoDash.assign({}, def.o, v.o)})
}
}
// It appears that strict mode isn't applied to such functions even
// though it applies to eval, neither when they're created nor called.
// But unlike eval they have access to the global scope only.
str = 'v=v||{};v=_p?_p(v):v;v.o=v.o||{};' +
'var T,E=v.o.escaper||function(s){return s};' + str
str = (new Function('_p,_,_x,v', str))
.bind(undefined, options.prepare, NoDash, c.extra)
}
return str
},
//! `, +fna=function ( [options,] str [, arg [, ...]] )
// Interpolates `'arg'uments into `'str'ing according to format
// specifiers inspired by `'printf() of C, or returns a function doing so.
//= string formatted `'str`, string function's source code`,
// function accepting `'arg'uments `- result depends on `[options.return`]
//> options object`, omitted
// See also `#template().
//
// Specifiers in `'str start with `[%`]. Special `'%% is output as is while
// others have this format (unsupported specifier triggers an error):
//[
// % [[+|-][n]$] [+[ ]] [[-|=][0|``c]d] [.[-][p]] (s|c|d|f|x|X|b|o|H|I|S|Y|M|D|K|T)
// n - takes 1-based n'th arg; causes next $-less % to take n+1, etc.
// +-n - ...relative: %+1$ = %+$ skip over next, %-2$ go back by two
// + - prefix positive number with '+' or ' '
// d - number of symbols to pad to, using spaces on the left unless...
// - - ...pads on the right
// = - ...pads on both sides (centers)
// 0 - ...pads with zeros
// c - ...pads with that symbol
// p - %f: rounds to this number of decimal places (without .p = 6),
// padding with zeros on the right if no '-'; %s %c: cuts if
// longer, from the right if no '-'; '.' alone = defaultPrecision
// %s - treats arg as a string
// %c - treats arg as one or many (if array) String.fromCharCode()-s
// %d - treats arg as an integer, discarding fractional part
// %f - treats arg as a fractional number; mantissa is exempted from d
// %x - treats arg as an integer, output in hexadecimal lower case
// %X - as %x but in upper case
// %b - as %x but in binary
// %o - as %x but in octal
// %H - treats arg as a Date instance, outputs local hours (1-24)
// %I - as %H but outputs minutes (0-59)
// %S - as %H but outputs seconds (0-59)
// %Y - as %H but outputs full year (like 2022)
// %M - as %H but outputs month number (1-12)
// %D - as %H but outputs day number (1-31)
// %K - as %H but outputs week day number (1-7, 1 for Monday)
//]
// Possible `'options keys:
//> return int`, omitted = `'2 `- if `'2, `#format() returns the formatted
// string; if `'1, returns a function that can be used to format the same
// `'str using different set of `'arg'uments; if `'0, returns its source
// code
//> silent bool`, omitted `- if set, doesn't throw on insufficient number of
// `'arg-s and other warnings
//> ellipsis str`, null/omitted = `''...' `- terminator used when
// `'.p'recision outputs a longer `'%s/`'%c string; use `''' to cut without
// one
//> defaultPrecision object`, omitted `- `'p value when no number follows
// the dot; unset `'%s/`'%c default to 100
//> specifiers object`, omitted `- non-standard or overridden specifiers
// (`[%...`]); key is a single `'\w character, value is a function
// receiving `[params, c`]:
// `> params array `- specifier string parameters; useful keys (all but
// first and last can be empty):
// `> 0 `- full specifier string without leading `'%
// `> 2 `- if `'$ used: `'arg index wrapped in `'"
// `> 3 `- sign: `'+ or `'+ + space
// `> 5 `- padding side: `'- or `'=
// `> 6 `- padding symbol: `'0 or `[```] + character
// `> 7 `- padding length (numeric)
// `> 9 `- precision padding: `'-
// `> 10 `- precision (numeric), empty if only `'. used
// `> 11 `- the specifier character
// Note: sign and padding are handled by `#format(), not this function.
// `> c object `- current state; keys:
// `> args array `- only when formatting; `'arg'uments for interpolation
// `> arg int `- only when formatting; index of current `'arg'ument
// `> head str `- only when compiling; JavaScript code added to the
// beginning of the compiled function; useful for declaring
// `[var`]iables
// `> options object `- `'options given to `#format()
// `> e function `- throws an `'Error unless `[options.silent`];
// receives `'msg, returns `'true
// `> next function `- only call when formatting; returns current `'arg
// and advances the index; receives `'null or a 1-based number:
// `['c.next(' + params[2] + ')'`]
// `> * `- other keys can be used for storing custom state data
// Function must return a JavaScript code string (will be wrapped in
// `[( )`]) which can use context variables like `'a (see below).
// Use `[JSON.stringify()`] to properly escape a string.
//
// These variables exist within the returned function:
//> _ `- reference to NoDash regardless of the global `'_
//> c `- current formatter's state (see above), shallow-copied for every new
// call of the returned function (still sharing `'options and others)
//> a `- temporary variable for use by the specifier formatter while it
// transforms the current `'arg
//
// For pretty formatting visible to user consider using standard `'Intl
// classes, such as:
//* `@mdn:JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat`@
//* `@mdn:JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat`@
//* `@mdn:JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat`@
// (this one is not in IE)
//?`[
// _.format('from char codes: %c', [97, 98, 99])
// //=> 'from char codes: abc'
// _.format('from char codes: %s', [97, 98, 99])
// //=> 'from char codes: 97,98,99'
// _.format('|%=``+10s|', 'head')
// //=> '|+++head+++|'
// _.format('%.5s %1$.-5s %02.5f %2$02.-5f', 'abcdef', 3.14)
// //=> 'ab... ...ef 03.14000 03.14'
// _.format('%Y-%1$02M-%1$02D', new Date)
// //=> '2022-11-01'
// _.format('%f(ms) %1$d(s) %1$.f(rounded)', new Date / 1000)
// //=> '1667314562.619000(ms) 1667314562(s) 1667314563(rounded)'
//
// // Ensure %s is exactly 5 chars, padding and cutting as necessary:
// var fmt = _.format({return: 1}, '%5.5s')
// //=> function (arg, arg, ...)
// fmt('abc') //=> ' abc'
// fmt('abcdef') //=> 'ab...'
// `]
//? Custom specifiers:
// `[
// var escaper = function (params) {
// return '_.escape(c.next(' + params[2] + '))'
// }
// var s = '<pre>%20h</pre>'
// var fmt = _.format({return: 1, specifiers: {h: escaper}}, s)
// //=> function (arg, ...) {
// // return _.padStart(_.escape(c.next(undefined)), 20, ' ')
// // }
// fmt('</SCRiPT>&')
// //=> <pre> </SCRiPT>&</pre>
// `]
format: function (options, str) {
function noPrecision(c, params) {
if (params[8]) {
c.e('%' + params[11] + ' is incompatible with precision (' + params[8] + ')')
}
}
if (!(options instanceof Object)) {
str = options
options = {}
}
var args = NoDash.rest(arguments, 1 + (options == arguments[0]))
options.defaultPrecision = NoDash.assign({
s: 100,
c: 100,
}, options.defaultPrecision)
options.specifiers = NoDash.assign({
s: function (params, c, res) {
res = res || 'c.next(' + params[2] + ')'
if (params[8]) {
res = 'c.ellipsize(' + res + ',' + (params[10] || params[7] || options.defaultPrecision[params[11]] || 0) + ',' + !!params[9] + ')'
}
return res
},
c: function (params, c) {
var res = 'a=c.next(' + params[2] + '),String.fromCharCode.apply(undefined,_.isArrayLike(a)?a:[a])'
return options.specifiers.s(params, c, res)
},
d: function (params, c) {
noPrecision(c, params)
return 'Math.trunc(c.next(' + params[2] + '))'
},
f: function (params) {
var p = params[8] ? +params[10] || options.defaultPrecision[params[11]] || 0 : 6
var m = NoDash.repeat('0', p)
var variableWidth = params[9] /*'-' p*/ || !p /*no '.' p or '.0'*/
// If number is below 0, its string form will be shorter than p:
// %.2f: 0.012 * 100 = '1', not '01' and we won't know the length of
// mantissa.
var res = 'Math.round((c.next(' + params[2] + ')' + (variableWidth ? '' : '+1') + ')' + (m && '*1' + m) + ')'
if (variableWidth) {
return 'a=' + res + (m && '/1' + m) + '+"",al-=a.length-Math.max(0,a.indexOf(".")),a'
} else {
return 'al-=' + (p + 1 /*dot*/) + ',a=' + res + '+"",a.substr(0,a.length-' + p + ')-1+"."+a.substr(-' + p + ')'
}
},
x: function (params, c, base) {
noPrecision(c, params)
return '(+c.next(' + params[2] + ')).toString(' + (base || 16) + ')'
},
X: function (params, c) {
return options.specifiers.x(params, c) + '.toUpperCase()'
},
b: function (params, c) {
return options.specifiers.x(params, c, 2)
},
o: function (params, c) {
return options.specifiers.x(params, c, 8)
},
H: function (params, c, func) {
noPrecision(c, params)
return 'c.next(' + params[2] + ').' + (func || 'getHours') + '()'
},
I: function (params, c) {
return options.specifiers.H(params, c, 'getMinutes')
},
S: function (params, c) {
return options.specifiers.H(params, c, 'getSeconds')
},
Y: function (params, c) {
return options.specifiers.H(params, c, 'getFullYear')
},
M: function (params, c) {
return options.specifiers.H(params, c, 'getMonth') + '+1'
},
D: function (params, c) {
return options.specifiers.H(params, c, 'getDate')
},
K: function (params, c) {
return options.specifiers.H(params, c, 'getDay')
},
}, options.specifiers)
var c = {
//! +ig
//args: null, // format-time
//arg: 0, // format-time
head: 'var a,al,c=_.assign({arg:0,args:_.rest(arguments,2)},_c);',
options: options,
e: function (msg) {
if (!this.options.silent) {
throw new Error('format: ' + msg + '.')
}
return true
},
//! +ig
next: function (param) { // [+-][n]
if (param) {
isNaN(param[0]) ? this.arg += +param : this.arg = param - 1
}
if (++this.arg > this.args.length) {
this.e('too few arguments')
return ''
} else {
return this.args[this.arg - 1]
}
},
ellipsize: function (s, max, left) {
s += ''
if (s.length > max) {
var ell = options.ellipsis == null ? '...' : options.ellipsis
s = max <= ell.length
? left ? s.substr(-max) : s.substr(0, max)
: left
? ell + s.substr(-(max - ell.length))
: s.substr(0, max - ell.length) + ell
}
return s
},
}
// Since specifier format looks the same when stringify()'ed, can call the
// latter once on the entire string rather than on every parts.shift().
var parts = JSON.stringify(str)
// Note: update doc comment above and splice() below if changing ( )s.
.split(/%(%|(([+-]\d*|\d+)\$)?(\+ ?)?(([-=])?(0|`.)?(\d+))?(\.(-)?(\d*))?(\w))/)
// 0 12 3 45 6 7 8 9 10 11
var code = ''
while (true) {
code += parts.shift() // A%sB%dC = [A] [%s] [B] [%d] [C]
if (!parts.length) { break } // ^shift ^shift ^shift
// 0 part after initial '%': '%' or full specifier
// 1 n + '$'
// 2 [+|-] [n]
// 3 '+' or '+ '
// 4 [[-|=][0|`c]d]
// 5 '-' or '='
// 6 '0' or '`' + c
// 7 d
// 8 [.[-][p]]
// 9 '-'
// 10 p
// 11 specifier symbol
var params = parts.splice(0, 12) // 12 = number of ( )s above
if (params[0] == '%') {
code += '%'
continue
}
var func = options.specifiers[params[11]]
if (!func) {
c.e('unsupported specifier %' + params[11] + ': %' + params[0])
continue
}
if (params[2] == '+' || params[2] == '-') { params[2] += '1' }
params[2] = params[2] ? '"' + params[2] + '"' : ''
code += '"+(al=0,a=(' + func(params, c) + '),'
if (params[3]) {
code += '(a>0?"' + params[3].substr(-1) + '":"")+'
}
if (!params[4]) {
code += 'a'
} else {
var n = params[7]
var p = JSON.stringify(NoDash.repeat((params[6] || ' ').substr(-1), +n))
if (params[5] == '=') {
code += '(a+="",a=' + p + '.substr(0,(' + n + '-a.length+al)/2)+a)+' + p + '.substr(a.length)'
} else {
p += '.substr(a.length+al)'
code += '(a+="",' + (params[5] ? 'a+' + p : p + '+a') + ')'
}
}
code += ')+"'
}
code = c.head + 'a=' + code + ';c.arg==c.args.length||c.e("too many arguments");return a'
if (options.return != 0) {
code = (new Function('_c,_', code)).bind(undefined, c, NoDash)
if (options.return != 1) {
return code.apply(undefined, args)
}
}
if (args.length) {
c.e("have both format arg-s and options.return < 2")
}
return code
},
}
});
|
9fa44f11e43e23342e6b5f832852fa09f2715490
|
[
"JavaScript",
"Text",
"PHP"
] | 3 |
PHP
|
ProgerXP/NoDash
|
37622ba3491776b00734dea7f765ee2caa75ba62
|
1b0de6c93ccac6f374cccedb7e60193dda4d66d9
|
refs/heads/master
|
<file_sep>//: Playground - noun: a place where people can play
// my key ZW44-PTQ7-9ULT-DWE9
import UIKit
import SWXMLHash
import Foundation
//http://api.bart.gov/api/etd.aspx?cmd=etd&orig=ALL&key=<KEY>
let path = NSBundle.mainBundle().URLForResource("etd-allStations", withExtension: "xml")
let xmlText = try String(contentsOfURL: path!)
//NSBundle.mainBundle().pathForResource("etd-allStations", ofType: "xml")
let xml = SWXMLHash.config {
config in
config.shouldProcessLazily = true
}.parse(xmlText)
let count = xml["root"].all.count
func enumerate(indexer: XMLIndexer){
for child in indexer.children {
NSLog(child.element!.name)
enumerate(child)
}
}
//print(xml["root"]["station"].all)
//enumerate(xml)
var station = [String]()
// get all the stations and put them in an array
for elem in xml["root"]["station"].all{
var stations = elem["name"].element!.text!
station.append(stations)
}
print(station)
class Station {
var name : String // <NAME>
var destinations:[(dest:String, times:[Int])] // [[Daly City : [3, 10, 17]], [Dublin : [7, 22, 37]]]
init(withName name: String, destinations:[(dest:String, times:[Int])]){
self.name = name
self.destinations = destinations
}
}
// create an empty array of Station class
var stationsTest = [Station]()
// create an empty array of destination
var destination = [String]()
// retrieve the name of the depart stations and add them to and array of Station add the.name
for elem in xml["root"]["station"].all{
for elem2 in elem["etd"].all{
var stations = elem["name"].element!.text!
var destinationStation = elem2["destination"].element!.text!
var stationPlaceHolder = Station(withName: stations, destinations: [(dest:destinationStation,times:[1])])
stationsTest.append(stationPlaceHolder)
}
}
print(stationsTest[0].name)
print(stationsTest[0].destinations)
for elem in stationsTest {
print("\(elem.name)...\(elem.destinations)")
}
//var destination = [String]()
//
// get all the stations and put them in an array
for elem in xml["root"]["station"][12]["etd"].all{
var destinations = elem["destination"].element!.text!
destination.append(destinations)
}
print(destination) // ["Pittsburg/Bay Point", "SF Airport"]
//var times = [String]()
////
//// get all the stations and put them in an array
//for elem in xml["root"]["station"][12]["etd"]["estimate"].all{
// var time = elem["minutes"].element!.text!
// times.append(time)
//
//}
//
//print(times)
//// this line gets the minutes of a specific destination
//print(".......\(xml["root"]["station"][0]["etd"][0]["estimate"][0]["minutes"].all)")
////[<minutes>3</minutes>]\
//var exampleDest:[(dest:String, times:[Int])] = [(dest:"", times:[1])]
//exampleDest.append((dest: "aziz", times: [1,2,3]))
|
2f42cc2e3228738bba603ed703895f64054c524c
|
[
"Swift"
] | 1 |
Swift
|
aziz-boudi4/BartApp--parsed-with-SWXMLHash
|
66e76814b3636c8cb8d83e37c91eea26c7b934df
|
5cd2246fc7b541130097a53b31757d3468d77810
|
refs/heads/main
|
<file_sep># PRO-C28
This game is about plucking mangos you need to drag the stone and hit the mangos of the trees.
<file_sep>class Launcher {
constructor(bodyAInput, pointBInput) {
var options = {
bodyA: bodyAInput,
pointB: pointBInput,
stiffness: 0.004,
length: 10
}
this.pointB = pointBInput
this.launcher = Constraint.create(options);
World.add( userWorld, this.launcher);
}
attach(body) {
this.launcher.bodyA = body;
}
fly() {
this.launcher.bodyA = null;
}
display() {
if (this.launcher.bodyA) {
var pointA = this.launcher.bodyA.position;
var pointB = this.pointB;
push();
stroke(48, 22, 8);
if (pointA.x < 220) {
strokeWeight(7);
line(pointA.x - 20, pointA.y, pointB.x - 10, pointB.y);
line(pointA.x - 20, pointA.y, pointB.x + 30, pointB.y - 3);
}
else {
strokeWeight(3);
line(pointA.x + 25, pointA.y, pointB.x - 10, pointB.y);
line(pointA.x + 25, pointA.y, pointB.x + 30, pointB.y - 3);
}
pop();
}
}
}
|
d624c1910fed5313a5a327d201ca9a1aeddc02f1
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
harsidhkamat/PRO-C28
|
e937263b6ec55cd86d55c8e9497ed1f34ec3d584
|
24479d0034c0dc4f0673bf98e4b59da51815e1cf
|
refs/heads/master
|
<file_sep>var Utils = function() {};
Utils.prototype.getAspectRatio = function(containerWidth,containerHeight,imageWidth,imageHeight){
var hRatio = containerWidth / imageWidth ;
var vRatio = containerHeight / imageHeight ;
var ratio = Math.min ( hRatio, vRatio );
return ratio;
};
Utils.prototype.getAdParameters = function(specs) {
var params = {};
if (ad_dynamic_parameters && ad_dynamic_parameters.split("&").forEach(function(item) {
params[item.split("=")[0]] = decodeURIComponent(item.split("=")[1])
}), specs) {
for (var param in params)
if ("undefined" != typeof specs[param]) switch (specs[param].type.toLowerCase()) {
case "int":
case "integer":
params[param] = parseInt(params[param]);
break;
case "int[]":
case "integer[]":
for (var intArray = params[param].split(","), i = 0; i < intArray.length; i++) intArray[i] = +intArray[i];
params[param] = intArray;
break;
case "float":
params[param] = parseFloat(params[param]);
break;
case "bool":
case "boolean":
"true" == params[param].toLowerCase() ? params[param] = !0 : params[param] = !1
}
for (var param in specs) "undefined" == typeof params[param] && (params[param] = specs[param]["default"])
}
return params
}, Utils.prototype.applyAdParameters = function(pTarget) {
var params = {};
if (!ad_dynamic_parameters) return void console.log("[UTILS]: ad_dynamic_parameters was not found.");
ad_dynamic_parameters.split("&").forEach(function(pItem) {
params[pItem.split("=")[0]] = decodeURIComponent(pItem.split("=")[1])
});
for (var k in params) {
var val = params[k],
o = pTarget;
if (o = k == k.toUpperCase() ? window : pTarget, o.hasOwnProperty(k)) {
var tp = o[k];
tp.constructor === Array ? (o[k] = [], val.split(",").forEach(function(pItem) {
o[k].push(utils.convertType(0, pItem))
})) : o[k] = utils.convertType(tp, val)
} else console.log("[UTILS]: unable to find property:", k)
}
}, Utils.prototype.convertType = function(pTargetProperty, pVal) {
return "boolean" == typeof pTargetProperty ? "true" == pVal ? !0 : "1" == pVal ? !0 : !1 : "number" == typeof pTargetProperty ? parseFloat(pVal) : pVal
}, Utils.prototype.checkOverlap = function(spriteA, spriteB) {
var boundsA = spriteA.getBounds(),
boundsB = spriteB.getBounds();
return Phaser.Rectangle.intersects(boundsA, boundsB)
}, Utils.prototype.checkPointInside = function(point, sprite) {
var pointRect = new PIXI.Rectangle(point.x, point.y, 1, 1),
spriteBounds = sprite.getBounds();
return Phaser.Rectangle.intersects(pointRect, spriteBounds)
}, Utils.prototype.lineLength = function(x, y, x0, y0) {
var xd = Math.abs(x0 - x),
yd = Math.abs(y0 - y);
return Math.sqrt(xd * xd + yd * yd)
}, Utils.prototype.highlightRegion = function(game, x, y, radius, alpha) {
alpha = alpha || .4;
var mask_small = null;
imageLoader.hasFrameName("mask.png") ? mask_small = !1 : imageLoader.hasFrameName("mask_small.png") && (mask_small = !0);
var highlight = imageLoader.sprite(x, y, mask_small ? "mask_small.png" : "mask.png");
highlight.alpha = alpha, highlight.anchor.set(.5, .5);
var scale = radius / 20;
return mask_small && (scale *= 2), highlight.scale.setTo(scale, scale), highlight
}, Utils.prototype.random = function(min, max) {
return null == max && (max = min, min = 0), min + Math.floor(Math.random() * (max - min + 1))
}, Utils.prototype.shuffle = function(obj) {
for (var rand, value, index = 0, shuffled = [], i = obj.length - 1; i >= 0; i--) value = obj[i], rand = this.random(index++), shuffled[index - 1] = shuffled[rand], shuffled[rand] = value;
return shuffled
}, Utils.prototype.arrayDistinct = function(needles, haystack) {
var res_array = [];
return haystack.forEach(function(entry) {
-1 == needles.indexOf(entry) && res_array.push(entry)
}), res_array
}, Utils.prototype.forceOrientation = function(game, orientation) {
if (!game.device.desktop) {
console.log("forcing orientation: " + orientation), game.scale.forceOrientation("landscape" == orientation ? !0 : !1, "landscape" == orientation ? !1 : !0);
var ths = this;
game.scale.enterIncorrectOrientation.add(function() {
ths.handleIncorrectOrientation(game)
}), game.scale.leaveIncorrectOrientation.add(function() {
ths.handleCorrectOrientation(game)
})
}
}, Utils.prototype.handleIncorrectOrientation = function(game) {
console.log("entered incorrect orientation"), document.getElementById("orientation").style.display = "block"
}, Utils.prototype.handleCorrectOrientation = function() {
console.log("resumed correct orientation"), document.getElementById("orientation").style.display = "none"
}, Utils.prototype.parseXML = function(xmlStr) {
if ("undefined" != typeof window.DOMParser) return (new window.DOMParser).parseFromString(xmlStr, "text/xml");
if ("undefined" != typeof window.ActiveXObject && new window.ActiveXObject("Microsoft.XMLDOM")) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
return xmlDoc.async = "false", xmlDoc.loadXML(xmlStr), xmlDoc
}
return null
}, Utils.prototype.applyAdParameters = function(target) {
var params = utils.getAdParameters();
for (var k in params) {
var val = params[k],
o = target;
o = k == k.toUpperCase() ? window : target, o.hasOwnProperty(k) ? "boolean" == typeof o[k] ? o[k] = "true" == val ? !0 : "1" == val ? !0 : !1 : o[k] = val : console.log("Ad params: unable to find property:", k)
}
}, Object.prototype.hasOwnProperty = function(property) {
return "undefined" != typeof this[property]
}, String.prototype.lpad = function(padString, length) {
for (var str = this; str.length < length;) str = padString + str;
return str
}, String.prototype.isUpperCase = function(val) {
return val == val.toUpperCase()
}, Utils.prototype.lerp = function(a, b, t) {
return a + t * (b - a)
}, Utils.prototype.hermite = function(start, end, value) {
return this.lerp(start, end, value * value * (3 - 2 * value))
}, Utils.prototype.sinerp = function(start, end, value) {
return this.lerp(start, end, Math.sin(value * Math.PI * .5))
}, Number.prototype.mod = function(n) {
return (this % n + n) % n
}, Utils.prototype.fitIntoRect = function(sprite, bounds, fillRect, align) {
var wD = sprite.width / sprite.scale.x,
hD = sprite.height / sprite.scale.y,
wR = bounds.width,
hR = bounds.height,
sX = wR / wD,
sY = hR / hD,
rD = wD / hD,
rR = wR / hR,
sH = fillRect ? sY : sX,
sV = fillRect ? sX : sY,
s = rD >= rR ? sH : sV,
w = wD * s,
h = hD * s,
tX = 0,
tY = 0;
switch (align) {
case "left":
case "topLeft":
case "bottomLeft":
tX = 0;
break;
case "right":
case "topRight":
case "bottomRight":
tX = w - wR;
break;
default:
tX = .5 * (w - wR)
}
switch (align) {
case "top":
case "topLeft":
case "topRight":
tY = 0;
break;
case "bottom":
case "bottomLeft":
case "bottomRight":
tY = h - hR;
break;
default:
tY = .5 * (h - hR)
}
sprite.x = bounds.x - tX, sprite.y = bounds.y - tY, sprite.scale.set(s)
};
var utils = new Utils;<file_sep>var Localization = function() {};
Localization.prototype.init = function() {
this._strings = [], this._language = null, navigator && navigator.userAgent && (this._language = navigator.userAgent.match(/android.*\W(\w\w)-(\w\w)\W/i)) && (this._language = this._language[1]), !this._language && navigator && (navigator.languages ? this._language = navigator.languages[0] : navigator.language ? this._language = navigator.language : navigator.browserLanguage ? this._language = navigator.browserLanguage : navigator.systemLanguage ? this._language = navigator.systemLanguage : navigator.userLanguage && (this._language = navigator.userLanguage), this._language && (console.log("Truncating language: " + this._language), this._language = this._language.substr(0, 2))), this._language || (this._language = "en"), console.log("Language: " + this._language)
}, Localization.prototype.registerString = function(string, translations) {
console.log("localization: registering string:", string), this._strings[string] = translations
}, Localization.prototype.registerStrings = function(translations) {
for (var string in translations) this.registerString(string, translations[string])
}, Localization.prototype.getLanguage = function() {
return this._language
}, Localization.prototype.get = function(string, macros) {
var s = string;
if (this._strings[string] && this._strings[string][this._language] && (s = this._strings[string][this._language]), macros)
for (var macro in macros) s = s.replace(macro, macros[macro]);
return s
}, Localization.prototype.fitText = function(field, width, height) {
if (field.defaultFontSize || (field.defaultFontSize = field.fontSize.replace(/\D/g, "")), field.fontSize = field.defaultFontSize + "pt", field.wordWrap && (width = field.wordWrapWidth), width > 0 && height > 0)
for (var size = field.defaultFontSize;
(field.width > width || field.height > height) && size > 4;) size -= 1, field.fontSize = size + "pt"
};
var localization = new Localization;
localization.init();<file_sep>ImageLoader = function() {};
ImageLoader.prototype.registerGame = function(game) {
this._game = game, this._game.load.crossOrigin = "Anonymous", console.log("load.crossOrigin: ", this._game.load.crossOrigin)
}, ImageLoader.prototype.registerBackgroundImage = function(imageUrl, imageWidth, imageHeight) {
var background = {
url: imageUrl,
width: imageWidth,
height: imageHeight,
landscape: imageWidth > imageHeight ? !0 : !1
};
this._backgrounds.push(background)
}, ImageLoader.prototype.preloadBackground = function() {
var landscape = !1;
this._game.width > this._game.height && (landscape = !0), this._backgrounds = Phaser.ArrayUtils.shuffle(this._backgrounds);
for (var i = 0; i < this._backgrounds.length; i++)
if (landscape == this._backgrounds[i].landscape) return console.log("Preloading background: " + this._backgrounds[i].url + " landscape? " + this._backgrounds[i].landscape), void this.loadImage("background", this._backgrounds[i].url);
console.log("No matching background found for preloading")
}, ImageLoader.prototype.displayBackground = function() {
return this._game.add.sprite(0, 0, "background")
}, ImageLoader.prototype.loadImage = function(name, imgpath) {
return this._game.load.image(name, imgpath)
}, ImageLoader.prototype.sprite = function(x, y, name) {
for (var i = 0; i < this._atlases.length; i++) {
var img = this._game.cache.getFrameByName(this._atlases[i], name);
if (void 0 !== img && null != img) return this._game.add.sprite(x, y, this._atlases[i], name)
}
return console.log("image_loader: warning: sprite not found in atlases; assuming it was loaded individually: " + name), this._game.add.sprite(x, y, name)
}, ImageLoader.prototype.spriteMake = function(x, y, name) {
for (var i = 0; i < this._atlases.length; i++) {
var img = this._game.cache.getFrameByName(this._atlases[i], name);
if (void 0 !== img && null != img) return this._game.make.sprite(x, y, this._atlases[i], name)
}
return this._game.make.sprite(x, y, name)
}, ImageLoader.prototype.button = function(x, y, name, cbk, ths) {
console.log("CBBB"), console.log(cbk);
for (var i = 0; i < this._atlases.length; i++) {
var img = this._game.cache.getFrameByName(this._atlases[i], name);
if (void 0 !== img && null != img) return console.log("key"), console.log(this._atlases[i]), this._game.add.button(x, y, this._atlases[i], name, cbk, ths)
}
return console.log("image_loader: warning: button not found in atlases; assuming it was loaded individually: " + name), this._game.add.button(x, y, "", name, cbk, ths)
}, ImageLoader.prototype.hasFrameName = function(name) {
for (var i = 0; i < this._atlases.length; i++) {
var img = this._game.cache.getFrameByName(this._atlases[i], name);
if (void 0 !== img && null != img) return !0
}
return !1
}, ImageLoader.prototype.loadSpritesheet = function(name, imgpath, frameheight, framewidth, spacing) {
return this._game.load.spritesheet(name, imgpath, frameheight, framewidth, spacing)
}, ImageLoader.prototype.loadAtlasHash = function(key, textureURL, atlasURL, atlasData) {
var loader = this._game.load.atlasJSONHash(key, textureURL, atlasURL, atlasData);
return this._atlases.push(key), console.log("Loaded atlas: " + key), loader
}, ImageLoader.prototype.loadAtlasArray = function(key, textureURL, atlasURL, atlasData) {
var loader = this._game.load.atlasJSONArray(key, textureURL, atlasURL, atlasData);
return this._atlases.push(key), console.log("Loaded atlas: " + key), loader
};
var imageLoader = new ImageLoader;<file_sep>function ad_begin() {
ad_state = "ready"
}
function setupMraid(stage) {
mraid.useCustomClose(!0), time_mraid_ready = (new Date).getTime(), genlog_time_since(time_wrapper_start, "time_mraid_ready"), console.log("setupMraid - start"), genlog("funnel", "setupMraid." + stage), registerMraidHandlers(mraid), showAd(), console.log("setupMraid - end")
}
function registerMraidHandlers(mraid) {
console.log("registerMraidHandlers - start"), mraid.addEventListener("viewableChange", function(state) {
console.log("viewable changed to: " + state + " (" + typeof state + ")"), genlog("mraidviewable", state), mraid.isViewable() && (console.log("showAd (viewable listener): calling"), showAd())
}), mraid.addEventListener("error", function(message, action) {
console.log("mraid error. message: " + message + " action: " + action), log_remote("mraid_error", "message: " + message + " action: " + action)
}), mraid.addEventListener("stateChange", function(state) {
switch (console.log("stateChange: " + state), genlog("mraidstate", state), state) {
case "hidden":
break;
case "default":
}
}), console.log("registerMraidHandlers - end")
}
function wrapper_click_go(depth) {
genlog("funnel", "click_go");
var url = ad_click_dest;
url += "adex" == ad_exchange ? "%26sub12%3Dcta" : "&sub12=cta", depth && (url += "." + depth.toString()), localization && (url += "&lang=" + localization.getLanguage()), console.log("clicked; going to click destination: " + url), mraid.open(url)
}
function showCloseButtonCountdown() {
if (!close_button_showing) {
var seconds_remaining = close_button_time_remaining / 1e3,
closeTimer = document.getElementById("close_timer");
closeTimer.innerHTML = seconds_remaining;
var styleAttr = document.createAttribute("style");
styleAttr.value = "display:block", closeTimer.setAttributeNode(styleAttr), close_button_time_remaining -= 1e3, close_button_time_remaining > 0 && setTimeout(function() {
showCloseButtonCountdown()
}, 1e3)
}
}
function showCloseButton() {
genlog("render", "showCloseButton"), console.log("showCloseButton - start");
var closeTimer = document.getElementById("close_timer"),
timerStyleAttr = document.createAttribute("style");
timerStyleAttr.value = "display:none", closeTimer.setAttributeNode(timerStyleAttr);
var closeZone = document.getElementById("close_zone"),
styleAttr = document.createAttribute("style");
styleAttr.value = "display:block", closeZone.setAttributeNode(styleAttr), closeZone.onclick = function() {
return console.log("clicked close button"), genlog("funnel", "close"), mraid.close(), !1
}, close_button_showing = !0, console.log("showCloseButton - end")
}
function showAd() {
if (console.log("showAd"), query_params.dev_nomraid || mraid.isViewable()) {
time_mraid_viewable = (new Date).getTime(), genlog_time_since(time_mraid_ready, "time_mraid_viewable"), console.log("showAd - viewable"), genlog("funnel", "viewable");
var addiv = document.getElementById("ad");
if (addiv) {
console.log("has ad div; setting style display:block");
var styleAttr = document.createAttribute("style");
styleAttr.value = "display:block", addiv.setAttributeNode(styleAttr)
}
wrapper_splash_shadows_start(), "mopub" == ad_exchange && (close_button_timeout_id = setTimeout(function() {
showCloseButton()
}, ad_close_duration)), console.log("ad_begin: calling"), ad_begin(), genlog("lang", localization.getLanguage())
}
}
function wrapper_preload_complete() {
time_app_preload_complete = (new Date).getTime(), genlog_time_since(time_wrapper_start, "time_app_preload")
}
function wrapper_load_progress(percent) {
var splash = document.getElementById("splash_loading_bar_full");
if (splash) {
var styleAttr = document.createAttribute("style");
styleAttr.value = "width:" + Math.floor(135 * percent / 100) + "px", splash.setAttributeNode(styleAttr)
}
}
function wrapper_hide_splash() {
wrapper_load_progress(100), time_app_start = (new Date).getTime(), genlog_time_since(time_mraid_viewable, "time_app_start"), genlog("funnel", "hide_splash");
var splash = document.getElementById("splash");
if (splash) {
var styleAttr = document.createAttribute("style");
styleAttr.value = "display:none", splash.setAttributeNode(styleAttr)
}
var header_logo = document.getElementById("ad_header_logo");
if (header_logo) {
var styleAttr = document.createAttribute("style");
styleAttr.value = "display:block", header_logo.setAttributeNode(styleAttr)
}
console.log("close duration:", ad_close_duration), close_button_timeout_id && (clearTimeout(close_button_timeout_id), close_button_timeout_id = null), setTimeout(function() {
showCloseButton()
}, ad_close_duration), "mopub" == ad_exchange && ad_close_duration > 2e3 && (close_button_time_remaining = ad_close_duration, showCloseButtonCountdown())
}
function wrapper_mark_interaction() {
return hadFirstInteraction ? hadSecondInteraction ? hadThirdInteraction ? void 0 : (genlog("funnel", "third_interaction"), void(hadThirdInteraction = !0)) : (genlog("funnel", "second_interaction"), void(hadSecondInteraction = !0)) : (genlog("funnel", "first_interaction"), void(hadFirstInteraction = !0))
}
function wrapper_mark_cta(depth) {
var subbin = "cta";
depth && (subbin += "." + depth.toString()), genlog("funnel", subbin)
}
function log_remote(bin, text) {
console.log("%c[log_remote] %s ==> %s", "background:tan;color:white", bin, text);
var url = ad_logroot + "/log_string?bin=" + encodeURIComponent(ad_name + "." + bin) + "&s=" + encodeURIComponent(text),
req = new XMLHttpRequest;
req.open("GET", url), req.send()
}
function genlog(bin, subbin) {
console.log("%c[genlog] %s ==> %s", "background:grey;color:white", bin, subbin);
var url = ad_logroot + "/log?bin=" + encodeURIComponent(ad_name + "." + bin) + "&subbin=" + encodeURIComponent(subbin),
req = new XMLHttpRequest;
req.open("GET", url), req.send()
}
function genlog_time_since(start, bin) {
if (start) {
var subbin = bucket_time_since(start);
genlog(bin, subbin)
}
}
function bucket_time_since(start) {
var end = (new Date).getTime(),
time = end - start,
bucket = get_bucket(time, 0, 1e4, 40),
bucket_str = "[";
return bucket_str += bucket.start == Number.NEGATIVE_INFINITY ? "-inf" : bucket.start, bucket.start != bucket.end && (bucket_str += " to ", bucket_str += bucket.end == Number.POSITIVE_INFINITY ? "+inf" : bucket.end), bucket_str += "]"
}
function bucketObj() {
this.offset = null, this.start = null, this.end = null, this.width = null
}
function get_bucket(item, min, max, numBuckets) {
var bucket = new bucketObj;
if (bucket.width = (max - min) / numBuckets, min >= item || max == min) bucket.offset = 0, bucket.start = Number.NEGATIVE_INFINITY, bucket.end = min + bucket.width;
else if (item >= max) bucket.offset = numBuckets - 1, bucket.start = max - bucket.width, bucket.end = Number.POSITIVE_INFINITY;
else {
var position = numBuckets * (item - min) / (max - min),
floored = Math.floor(position);
bucket.offset = Math.round(floored), bucket.start = min + bucket.offset * bucket.width, bucket.end = bucket.start + bucket.width
}
return 0 == bucket.offset && (bucket.start = Number.NEGATIVE_INFINITY), bucket.offset == numBuckets - 1 && (bucket.end = Number.POSITIVE_INFINITY), bucket
}
function wrapper_splash_shadows_start() {
var splash = document.getElementById("splash");
if (splash) {
for (var i = 0; bgNumShadows > i; i++) {
var div = document.createElement("div");
div.id = "bgShadow" + i;
var width = 50 + i * Math.floor(150 / bgNumShadows);
div.style.width = width + "px", div.style.height = Math.floor(width / 5) + "px";
var colorAdd = 3 * Math.floor((200 - width) / 20) + 1;
10 == colorAdd && (colorAdd = "A"), 11 == colorAdd && (colorAdd = "B"), 12 == colorAdd && (colorAdd = "C"), 13 == colorAdd && (colorAdd = "D"), 14 == colorAdd && (colorAdd = "E"), 15 == colorAdd && (colorAdd = "F"), colorAdd > 15 && (colorAdd = "E"), div.style.background = "#2" + colorAdd + "2" + colorAdd + "2" + colorAdd, div.style.borderRadius = Math.floor(width / 2) + "px", div.style.position = "absolute", div.style.zIndex = 1, div.style.left = -100 + Math.floor(Math.random() * (gameWidth + 1)) + "px", div.style.top = 50 + Math.floor(Math.random() * (gameHeight + 1)) + "px", splash.insertBefore(div, splash.firstChild)
}
setTimeout(wrapper_splash_shadows_move, 20)
}
}
function wrapper_splash_shadows_move() {
for (var i = 0; bgNumShadows > i; i++) {
var div = document.getElementById("bgShadow" + i),
left = parseInt(div.style.left),
width = parseInt(div.style.width);
left += Math.floor((200 - width) / 15) + 1, left > gameWidth + 200 && (left = -200), div.style.left = left + "px"
}
setTimeout(wrapper_splash_shadows_move, 20)
}
function fitTitle(elem) {
var title = document.getElementById("ad_title");
console.log(title);
for (var curSize = 1.25; title.scrollHeight > 28 && curSize > .5;) {
curSize -= .1;
var styleAttr = document.createAttribute("style");
styleAttr.value = "font-size: " + curSize + "em;line-height: " + curSize + "em", title.setAttributeNode(styleAttr)
}
}
|
533bdeb49f78f0a03677fc389524c3d3c57c7a7d
|
[
"JavaScript"
] | 4 |
JavaScript
|
kaustubhkushte/kaustubhkushte.github.io
|
2db1f21554b9b3342d9df3206df9fc6420f2e733
|
7ae2a8b6836d3232b45409c5ebb01324489d068f
|
refs/heads/master
|
<file_sep>const dropDown =document.querySelector('#dropdown'),
btnRemove =document.getElementById('btn-remove');
function btnHandler(){
dropDown.options[dropDown.selectedIndex].remove()
}
btnRemove.addEventListener('click', btnHandler);<file_sep>let value = prompt('Type a number', 0);
if (value > 0) {
alert( 1 );
} else if (value < 0) {
alert( -1 );
} else {
alert( 0 );
}<file_sep>function factorial(n) {
let num = 1
while (n > 1) {
num *= n
n -= 1
}
return num
}
console.log(factorial(4));<file_sep>//Check the range outside
let age = prompt('Write Your Age please?')
if (age >= 14 && age <= 90){
alert ('Age is between 14 & 90')
}
else if (!(age >= 14 && age <=90)){
alert ('Age in not between 14 & 90')
}
<file_sep>function getArea(length, width) {
let area = length * width;
return area;
}
getArea(3 , 4.5);
function getPerimeter(length, width) {
let perimeter=2*(length+width) ;
return perimeter;
}
|
7b428141f9e04619e8d41ea6862c6244a4c7c050
|
[
"JavaScript"
] | 5 |
JavaScript
|
RandaMoustafa/js
|
bdd9ad0ed66a9fdda4c61f5962fa29595f4fe0fc
|
f709e26d1ced1bf7bfe8f7661fb27a9c4e24a349
|
refs/heads/master
|
<file_sep>plot2 <- function() {
plot(data$time,data$Global_active_power,xlab="", type="l", ylab="Global Active Power (kilowatts)")
dev.copy(png, file="plot2.png", width=480, height=480)
dev.off()
}<file_sep>plot1 <- function() {
hist(data$Global_active_power, col="2", main = "Global Active Power", xlab="Global Active Power (kilowatts)")
dev.copy(png, file="plot1.png", width=480, height=480)
dev.off()
}
<file_sep>plot4 <- function () {
par(mfrow=c(2,2))
plot(data$time,data$Global_active_power, type="l", ylab="Global Active Power", xlab="")
plot(data$time,data$Voltage, type="l",ylab="Voltage", xlab="datetime")
plot(data$time,data$Sub_metering_1, type="l",ylab="Energy sub metering", xlab="")
lines(data$time,data$Sub_metering_2,col="red")
lines(data$time,data$Sub_metering_3,col="blue")
legend("topright", col=c("black","red","blue"), c("Sub_metering_1 ","Sub_metering_2 ", "Sub_metering_3 "),lty=c(1,1),cex = 0.75)
plot(data$time,data$Global_reactive_power, type="l", xlab="datetime", ylab="Global_reactive_power")
dev.copy(png, file="plot4.png", width=480, height=480)
dev.off()
}
|
3379742640d91076affc122681c0d5b0494144bf
|
[
"R"
] | 3 |
R
|
HGCobos/ExData_Plotting1
|
d985bf5a21e33ce42bac20e9f5f34efc845d3865
|
c751499d8ce813374c31ecd59f0ab5880f99b596
|
refs/heads/master
|
<repo_name>lil-nordy/IntroductionToPython<file_sep>/src/m3_turtles.py
"""
I think I fixed the network error associated with the Git directory in my Rose-Hulman. I want to see if it will make me log into GitHub.
"""
"""
Demonstrates using OBJECTS via Turtle Graphics.
Concepts include:
-- CONSTRUCT an INSTANCE of a CLASS (we call such instances OBJECTS).
-- Make an object ** DO ** something by using a METHOD.
-- Reference an object's ** DATA ** by using an INSTANCE VARIABLE.
Also:
-- ASSIGNING a VALUE to a NAME (VARIABLE).
Authors: <NAME>, <NAME>, <NAME>, <NAME>,
their colleagues and <NAME>.
"""
########################################################################
# DONE: 11. Why was to do 1 done?
# There could be some problems with you having taken this class before. Are you forking, then pulling, then editing,
# then commiting the proper code that you have never touched before? Why is my name, <NAME>, under toodo 1?
#
# DONE: 1.
# (Yes, that means for YOU to DO things per these instructions:)
#
# On Line 13 above, replace Neil Nordquist with your OWN name.
#
# BTW, the top block of text above forms what is called a DOC-STRING.
# It documents what this module does, in a way that exterior programs
# can make sense of. It has no other effect on this program.
#
########################################################################
import rosegraphics as rg
########################################################################
#
# DONE: 2.
# Allow this file to use the rosegraphics.py file by marking the src
# directory as a "Sources Root". Do that by right clicking on the src folder,
# then selector Mark Directory As --> Sources Root
# Watch the red underlines on the line of code above disappear as you do that step.
# You will do that once for every project that uses rosegraphics so get used to it. :)
#
# Run this module by Right clicking in this window and select Run 'filename'
# A window will pop up and Turtles will move around. After the
# Turtles stop moving, *click anywhere in the window to close it*.
#
# Then look at the code below. Raise your hand as you have questions
# about what the code is doing.
#
########################################################################
# ----------------------------------------------------------------------
# Set up a TurtleWindow object for animation. The definition of a
# TurtleWindow is in the rg (shorthand for rosegraphics) module.
# ----------------------------------------------------------------------
window = rg.TurtleWindow()
window.delay(20) # Bigger numbers mean slower animation.
# ----------------------------------------------------------------------
# Makes (constructs) a SimpleTurtle object.
# ----------------------------------------------------------------------
dave = rg.SimpleTurtle()
# ----------------------------------------------------------------------
# Ask the SimpleTurtle objects to do things:
# ----------------------------------------------------------------------
dave.forward(100)
dave.left(90)
dave.forward(200)
# ----------------------------------------------------------------------
# Construct a new turtle and ask it to do things.
# ----------------------------------------------------------------------
matt = rg.SimpleTurtle('turtle')
matt.pen = rg.Pen('red', 30)
matt.speed = 10 # Faster
matt.backward(50)
matt.left(90)
matt.forward(50)
matt.left(45)
matt.forward(50)
########################################################################
#
# DONE: 3.
# Add a few more line of your own code above to make one of the
# existing Turtles move some more and/or have different
# characteristics.
#
# ** Nothing fancy is required. **
# ** A SUBSEQUENT exercise will let you show your creativity. **
#
# As always, test by running the module.
#
########################################################################
########################################################################
#
# done: 4.
# The code above CONSTRUCTS two SimpleTurtle objects and gives those objects NAMES:
# dave matt
#
# Below this TO DO comment construct another SimpleTurtle object,
# naming it whatever you want.
# Names cannot have spaces or special characters, but they can have
# digits and underscores like this_1_has (get it?).
#
# After you construct a SimpleTurtle, add a few more lines that
# make YOUR SimpleTurtle move around a bit.
#
# ** Nothing fancy is required. **
# ** A SUBSEQUENT exercise will let you show your creativity. **
#
# As always, test by running the module.
#
########################################################################
nate = rg.SimpleTurtle('turtle')
neil = rg.SimpleTurtle('classic')
nordy = rg.SimpleTurtle('arrow')
nate.right(90)
nate.forward(50)
neil.backward(50)
nordy.left(90)
nordy.forward(50)
########################################################################
#
# DONE: 5.
# Run one more time to be sure that all is still OK.
# Ensure that no blue bars on the scrollbar-thing to the right remain.
#
# Then COMMIT and Push your work using the VCS menu option.
#
# Reminder of those steps...
# COMMIT your work by selecting VCS from the menu bar, then select Commit Changes
# Make sure only the files you want to commit are checked and optionally
# add a quick Commit message to describe your work. Then hover over the
# Commit button and select Commit and Push. Commit saves the work to
# your computer. "and Push" saves a copy of your work up into your Github
# repository (saving to the cloud is a better way to permanently safe work).
#
# You can COMMIT as often as you like. DO FREQUENT COMMITS.
#
########################################################################
# ----------------------------------------------------------------------
# This line keeps the window open until the user clicks in the window:
# Throughout this exercise, close_on_mouse_click should be the last line in the file.
# ----------------------------------------------------------------------
window.close_on_mouse_click()
<file_sep>/src/m5_your_turtles.py
"""
Your chance to explore Loops and Turtles!
Authors: <NAME>, <NAME>, <NAME>, <NAME>,
their colleagues and <NAME>.
"""
########################################################################
# DONE: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
########################################################################
## >> Final Questions: How to line break in the editor? Google didn't seem to help. Why does the speed not seem to matter
## when I have the speed set to accummulate by an interval of 10 on each iteration of the loop, but doesn't increase at
## all when I set the speed to accumulate by an interval of 9 on each iteration? strange.
########################################################################
# DONE: 2.
#
# You should have RUN the PREVIOUS module and READ its code.
# (Do so now if you have not already done so.)
#
# Below this comment, add ANY CODE THAT YOUR WANT, as long as:
# 1. You construct at least 2 rg.SimpleTurtle objects.
# 2. Each rg.SimpleTurtle object draws something
# (by moving, using its rg.Pen). ANYTHING is fine!
# 3. Each rg.SimpleTurtle moves inside a LOOP.
#
# Be creative! Strive for way-cool pictures! Abstract pictures rule!
#
# If you make syntax (notational) errors, no worries -- get help
# fixing them at either this session OR at the NEXT session.
#
# Don't forget to COMMIT your work by using VCS ~ Commit and Push.
########################################################################
import rosegraphics as rg
window = rg.TurtleWindow()
erik2 = rg.SimpleTurtle('turtle')
erik2.paint_bucket = rg.PaintBucket('red')
speed = 10
angle = 0
radius = 50
for k in range(25):
erik2.pen_down()
erik2.begin_fill()
erik2.speed = speed + 10
erik2.draw_circle(radius)
radius = radius + 5
angle = angle + 5
erik2.left(angle)
erik2.end_fill()
nate = rg.SimpleTurtle('turtle')
nate.paint_bucket = rg.PaintBucket('green')
nate.left(270)
nate.forward(25)
nate.left(270)
speed = 10
angle = 0
radius = 50
for k in range(25):
nate.pen_down()
nate.begin_fill()
nate.speed = speed + 10
nate.draw_circle(radius)
radius = radius + 3
angle = angle + 5
nate.left(angle)
nate.end_fill()
window.close_on_mouse_click()
<file_sep>/src/m2_hello_world.py
print('Hello, World')
########################################################################
# This line is a COMMENT -- a note to human readers of this file.
# When a program runs, it ignores everything from a # (hash) mark
# to the end of the line with the # mark.
#
# We call files that have Python code in them MODULES. Line 1 of this
# module (look at it now) prints onto the Console the STRING
# Hello, World
# Anything surrounded by quote marks (single or double) is a STRING.
########################################################################
########################################################################
#
# DONE: 1.
# (Yes, that means for YOU to DO things per these instructions:)
#
# Run this module by right clicking anywhere in this window and select
# Run 'name of file'
# After running, find the Console tab (below) and confirm that
# Hello, World
# did indeed get printed (displayed) on the Console.
#
########################################################################
########################################################################
#
# DONE: 2.
# Notice the small horizontal BLUE bars on the scrollbar-like thing
# on the right. Each blue bar indicates a TO DO in this module.
#
# a. You can use the blue bars to go from one TO DO to the next
# by clicking on the blue bars. ** Try that now. **
#
# b. When you have completed a TO DO, you should change the word
# TO DO
# to
# DONE.
# Try it now on line 16 above, and note that its blue bar on
# the scrollbar-like thing to the right has gone away.
#
# If you change TODOs to DONEs like this, you can tell when you have
# finished all the exercises in a module -- there will be no blue bars
# left on the scrollbar-like thing to the right.
#
# You have now completed TO DO #2, so change its TO DO on line 29 to DONE
# (and proceed similarly for all forthcoming TODOs in this course).
#
########################################################################
########################################################################
#
# DONE: 3.
# Add another print statement below.
# It should print any string that you want (but keep it G-rated!)
# Test your code by re-running this module using either the right click
# method again or by using the play button in the upper right.
# Look at the Console to be sure that your string printed as expected.
#
########################################################################
print("<NAME>, FCC, G Rating.")
########################################################################
#
# DONE: 4.
# Add yet another print statement.
# This one should print the *product* of 3,607 and 34,227.
# Let the computer do the arithmetic for you (no calculators!).
# You do NOT have to use strings for this, so no quotation marks!
#
# TEST your code by re-running this module, then asking someone
# whom you trust: What number did your print display for TO DO 4?
# (HINT: It is an INTERESTING number.) Get help if your value is wrong.
#
########################################################################
print(3607 * 34227)
########################################################################
#
# DONE: 5.
# Look at the list of files in this project to the left.
# Note that this file (m2_hello_world.py) is now displayed in a blue
# font color (if the file is highlighted select a different file so yu can
# see the blue font color). That means that you have made changes to
# this file which have not yet been committed.
#
# COMMIT your work by selecting VCS from the menu bar, then select Commit Changes
# Make sure only the files you want to commit are checked and optionally
# add a quick Commit message to describe your work. Then hover over the
# Commit button and select Commit and Push. Commit saves the work to
# your computer. "and Push" saves a copy of your work up into your Github
# repository (saving to the cloud is a better way to permanently safe work).
#
# Oh, one more thing:
# Do you have any blue bars left on the on the scrollbar-like thing
# to the right? If so, click on each blue bar and change
# its TO DO to DONE. Then run the file (to make sure you didn't break
# anything) then Commit and Sync again.
#
# You can COMMIT as often as you like. DO FREQUENT COMMITS.
#
########################################################################
|
1191af2cd2ece27cc4bc43867db0204e8efc532c
|
[
"Python"
] | 3 |
Python
|
lil-nordy/IntroductionToPython
|
835cf4c0a51525447bfd0c3ec0c6f2a285a71396
|
22f8f541cfe4b72b7bf69d517f6d62561d41362a
|
refs/heads/master
|
<file_sep>def more_than_n(lst, item, n):
if lst.count(item) > n:
return lst.count(item) > n
print(more_than_n([2, 4, 6, 2, 3, 2, 1, 2], 2, 3))
def more_than_n(lst, item, n):
count = 0
for i in lst:
if i == item:
count = count + 1
return count > n
print(more_than_n([2, 4, 6, 2, 3, 2, 1, 2], 2, 3))
#If there are an odd number of elements in lst, the function should return the middle element.
#If there are an even number of elements, the function should return the average of the middle two elements.
import math
def middle_element(lst):
length = len(lst)
halfLength = math.floor(length / 2)
if length % 2 == 0:
item1 = lst[halfLength - 1]
item2 = lst[halfLength]
return (item1 + item2) / 2
else:
return lst[length / 2]
print(middle_element([5, 2, -10, -4, 4, 5]))
def middle_element(lst):
length = len(lst)
halfLength = length // 2
if length % 2 == 0:
item1 = lst[halfLength - 1]
item2 = lst[halfLength]
return (item1 + item2) / 2
else:
return lst[length / 2]
print(middle_element([5, 2, -10, -4, 4, 5]))
def append_sum(lst):
length = len(lst)
for i in range(3):
sum = lst[-2] + lst[-1]
lst.append(sum)
return lst
print(append_sum([1, 1, 2]))
def append_sum(lst):
i = 0
while i < 3:
lst.append(lst[-2] + lst[-1])
i += 1
return(lst)
print(append_sum([1, 1, 2]))
def every_three_nums(start):
return list(range(start, 101, 3))
print(every_three_nums(91))
#The function should return a list where all elements in lst with an index between start and end (inclusive) have been removed
def remove_middle(lst, start, end):
lst = lst[:start] + lst[end+1:]
return (lst)
print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))
<file_sep> toppings = ['pepperoni', 'pineapple', 'cheese', 'sausage', 'olives', 'anchovies', 'mushrooms']
prices = [2, 6, 1, 3, 2, 7, 2]
num_pizzas = len(toppings)
x = num_pizzas
print("We sell " + str(x) + " different kinds of pizza!")
pizzas = list(zip(toppings, prices))
print(pizzas)
pizzas.sort(key = lambda x: x[1])
cheapest_pizza = pizzas[0]
priciest_pizza = pizzas[-1]
three_cheapest = pizzas[0:3]
print(three_cheapest)
num_two_dollar_slices = prices.count(2)
print(num_two_dollar_slices)
#We sell 7 different kinds of pizza!
#[('pepperoni', 2), ('pineapple', 6), ('cheese', 1), ('sausage', 3), ('olives', 2), ('anchovies', 7), ('mushrooms', 2)]
#[('cheese', 1), ('pepperoni', 2), ('olives', 2)]
#3<file_sep>sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
scoops_sold = 0
for location in sales_data:
for amount in location:
scoops_sold += amount
print(scoops_sold)
celsius = [0, 10, 15, 32, -5, 27, 3]
fahrenheit = []
for temperature_in_celsius in celsius:
temperature_in_fahrenheit = temperature_in_celsius * 9/5 + 32
fahrenheit.append(temperature_in_fahrenheit)
print(fahrenheit)
<file_sep>#COMPREHENTION
single_digits = range(10)
cubes = [i**3 for i in single_digits]
#WHILE
students_age = [7, 8, 9, 11, 9, 8]
summation = 0
index = 0
while index < 4:
summation += students_age[index] #slice
index += 1
print(summation)
scores = {
'mary': [19, 17, 18],
'john': [15, 20, 16],
'mark': [14, 19, 19],
}
for name in scores.keys():
sum = 0
for score in scores[name]:
sum += score
print("{}'s average is {:0.2f}".format(
name, sum / 3
))
<file_sep>def divisible_by_ten(nums):
num_10 = []
for num in nums:
if num % 10 == 0:
num_10.append(num)
return len(num_10)
print(divisible_by_ten([20, 25, 30, 35, 40]))
def add_greetings(names):
greetings = []
for name in names:
greetings.append("Hello, " + name)
return greetings
print(add_greetings(["Owen", "Max", "Sophie"]))
def add_greetings(names):
return ["Hello, " + names[i] for i in range(len(names))]
print(add_greetings(["Owen", "Max", "Sophie"]))
def delete_starting_evens(lst):
i = 0
while i % 2 == 1:
lst = lst.append(lst.pop(i))
i += 1
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))<file_sep>all_students = ["Alex", "Briana", "Cheri", "Daniele", "Dora", "Minerva", "Alexa", "Obie", "Arius", "Loki"]
students_in_poetry = []
while len(students_in_poetry) < 6 and len(all_students) > 0:
students_in_poetry.append(all_students.pop())
print(students_in_poetry)<file_sep>class SortedList(list):
def __init__(self, lst):
super().__init__(lst)
self.sort()
def append(self, value):
super().append(value)
self.sort()
new_list = SortedList([4, 1, 5])
new_list.append(3)
print(new_list)
class DefaultDictionary(dict):
def __init__(self, my_dict, default):
super().__init__(my_dict)
self.default = default
def __getitem__(self, key):
if key in self:
return super().__getitem__(key)
return self.default
test = DefaultDictionary({"Sveta": 2, "Dima": 3}, 4)
print(test["Sveta"])
print(test["Ira"])
<file_sep>def double_index(lst, index):
if index >= 0 and index < len(lst):
lst[index] *= 2
return lst
print(double_index([3, 8, -10, 12], 2))<file_sep>import random
from Pokemon import Pokemon
class PokemonMaker:
PRESETS = [('Sunflora', 'Grass'),
('Rapidash', 'Fire'),
('Krabby', 'Water'),
('Charmander', 'Fire'),
('Grovyle', 'Grass'),
('Wartortle', 'Water')]
MIN_LEVEL = 1
MAX_LEVEL = 5
def make():
preset = random.choice(PokemonMaker.PRESETS)
level = random.randint(PokemonMaker.MIN_LEVEL, PokemonMaker.MAX_LEVEL)
return Pokemon(preset[0], preset[1], level)<file_sep>def reverse(lst):
i = 0
j = len(lst) - 1
while i < j:
t = lst[i]
lst[i] = lst[j]
lst[j] = t
i += 1
j -= 1
def reversed_list(lst1, lst2):
reverse(lst2)
for i in range(len(lst1)):
if lst1[i] != lst2[i]:
return False
return True
print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))<file_sep>alphabet_caps = 'A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z'
alphabet = ''.join([letter.strip() for letter in (alphabet_caps.lower()).split(',')])
length = len(alphabet)
n = 10
res_text = ''
text = 'xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je t setu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj!'
for symbol in text:
index = alphabet.find(symbol)
if index == -1:
res_text += symbol
else:
res_text += alphabet[(index + 10) % length]
#print(res_text)
text_my = 'glad to hear from you! how long have you been at home due to coronavirus?'
res_text_my = ''
for symbol in text_my:
index = alphabet.find(symbol)
if index == -1:
res_text_my += symbol
else:
res_text_my += alphabet[(index - 10) % length]
#print(res_text_my)
def coder(message, offset):
res_text = ''
for symbol in message:
index = alphabet.find(symbol)
if index == -1:
res_text += symbol
else:
res_text += alphabet[(index + offset) % length]
return res_text
#print(coder('bqdradyuzs ygxfubxq omqemd oubtqde fa oapq kagd yqeemsqe ue qhqz yadq eqogdq!', 14))
#def key_word_coder(message, key_word):
# for n in range(len(message)):
# if message[n] in alphabet:
#print(coder('vhfinmxkl atox kxgwxkxw tee hy maxlx hew vbiaxkl tl hulhexmx. px\'ee atox mh kxteer lmxi ni hnk ztfx by px ptgm mh dxxi hnk fxlltzxl ltyx.', n))
# print(alphabet.find(message[n]))
# else:
# print(message[n])
# for m in range(len(key_word)):
# if key_word[m] in alphabet:
# print(alphabet.find(key_word[m]))
# else:
# print(key_word[m])
#print(key_word_coder('<KEY>', 'dog'))
def translateMessage(message, key_word):
keyIndex = 0
translated = []
for symbol in message:
num = alphabet.find(symbol)
if num != -1:
num -= alphabet.find(key_word[keyIndex])
num %= len(alphabet)
translated.append(alphabet[num])
keyIndex += 1
if keyIndex == len(key_word):
keyIndex = 0
else:
translated.append(symbol)
return ''.join(translated)
print(translateMessage('dfc aruw fsti gr vjtwhr wznj? vmph otis! cbx swv jipreneo uhllj kpi rahjib eg fjdkwkedhmp!', 'friends'))
def codeMessage(message, key_word):
keyIndex = 0
translated = []
for symbol in message:
num = alphabet.find(symbol)
if num != -1:
num += alphabet.find(key_word[keyIndex])
num %= len(alphabet)
translated.append(alphabet[num])
keyIndex += 1
if keyIndex == len(key_word):
keyIndex = 0
else:
translated.append(symbol)
return ''.join(translated)
print(codeMessage('Hi dude, are you happy with my skill? So let us spot it!', 'friends'))
print(translateMessage('Hn uchr, djj pwy udhup emgk ed jsmyo? Sg qvb yf vhtk qx!', 'friends'))
<file_sep>import random
from PokemonMaker import PokemonMaker
class PokemonTrainer:
POKEMONS_AMOUNT = 6
HEALING_POTIONS_AMOUNT = 10
REVIVE_POTIONS_AMOUNT = 5
CRITICAL_HP_PERCENT = 0.2 #20%
HEALING_AMOUNT_PERCENT = 0.1
HEAL_DECISION_CHANCE = 0.5
REVIVE_DECISION_CHANCE = 0.5
POKEMON_SWITCH_DECISION_CHANCE = 0.2
def __init__(self, name):
self.name = name
self.healing_potions = PokemonTrainer.HEALING_POTIONS_AMOUNT
self.revive_potions = PokemonTrainer.REVIVE_POTIONS_AMOUNT
self.pokemons_list = []
for i in range(PokemonTrainer.POKEMONS_AMOUNT):
self.pokemons_list.append(PokemonMaker.make())
self.choose_random_pokemon()
def get_name(self): # it's "getter"
return self.name
def decide(self): #main logic
print(self.name + ' plans his actions...')
p = self.current_pokemon
if p.is_knocked_out():
if self.revive_potions > 0 and random.random() <= PokemonTrainer.REVIVE_DECISION_CHANCE:
print('50%-chance revive!')
p.revive()
self.revive_potions -= 1
self.current_pokemon = p #save chosen as current
else:
print('50%-chance to switch but revive')
self.choose_random_pokemon()
elif p.get_health() <= p.get_max_health() * PokemonTrainer.CRITICAL_HP_PERCENT:
if self.healing_potions > 0 and random.random() <= PokemonTrainer.HEAL_DECISION_CHANCE:
print('50%-chance heal!')
p.gain_health(p.get_max_health() * PokemonTrainer.HEALING_AMOUNT_PERCENT)
self.healing_potions -= 1
else:
print('50%-chance to switch but heal')
self.choose_random_pokemon()
elif random.random() <= PokemonTrainer.POKEMON_SWITCH_DECISION_CHANCE:
print('Chance to try a new one!')
self.choose_random_pokemon()
def choose_random_pokemon(self):
alive_pokemons = [] #local variable useful only for this method
for pokemon in self.pokemons_list:
if not pokemon.is_knocked_out():
alive_pokemons.append(pokemon)
if len(alive_pokemons) > 0:
p = random.choice(alive_pokemons)
if p.get_health() <= p.get_max_health() * PokemonTrainer.CRITICAL_HP_PERCENT and \
self.healing_potions > 0:
p.gain_health(p.get_max_health() * PokemonTrainer.HEALING_AMOUNT_PERCENT)
self.healing_potions -= 1
self.current_pokemon = p #save chosen as current
print(self.get_name() + ' chose new current pokemon from alive', len(alive_pokemons))
else:
if self.revive_potions > 0:
p = random.choice(self.pokemons_list)
p.revive()
self.revive_potions -= 1
self.current_pokemon = p #save chosen as current
else:
print('No alive pokemons!')
self.current_pokemon = None
def can_fight(self):
return self.current_pokemon != None
def get_current_pokemon(self):
return self.current_pokemon
<file_sep>#Advanced Python Code Challenges: Lists
def every_three_nums(start):
return list(range(start, 101, 3))
print(every_three_nums(91))
def remove_middle(lst, start, end):
lst = lst[:start] + lst[end+1:]
return (lst)
print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))
def more_frequent_item(lst, item1, item2):
if lst.count(item1) >= lst.count(item2):
return item1
else:
return item2
print(more_frequent_item([2, 3, 3, 2, 3, 2, 3, 2, 3], 2, 3))
def double_index(lst, index):
if index >= 0 and index < len(lst):
lst[index] *= 2
return lst
print(double_index([3, 8, -10, 12], 2))
import math
def middle_element(lst):
length = len(lst)
halfLength = math.floor(length / 2)
if length % 2 == 0:
item1 = lst[halfLength - 1]
item2 = lst[halfLength]
return (item1 + item2) / 2
else:
return lst[length // 2]
print(middle_element([5, 2, -10, -4, 4, 5]))<file_sep>class Pokemon:
BASE_HEALTH = 10
BASE_DAMAGE = 3
DAMAGE_STRING = '{this_pokemon_name} did {damage} damage to {attacked_pokemon_name}'
CURRENT_HP_STRING = '{pokemon_name} now has {HP} HP'
KNOCKED_OUT_STRING = '{pokemon_name} is knocked out'
REVIVE_STRING = '{pokemon_name} is revived'
GAIN_HEALTH_STRING = '{pokemon_name}\'s been healed, current health is {health}'
DAMAGE_TYPE_FACTORS = { 'FireGrass': 2.0, 'WaterFire': 2.0, 'GrassWater': 2.0,
'FireFire': 1.0, 'GrassGrass': 1.0, 'WaterWater': 1.0,
'FireWater': 0.5, 'WaterGrass': 0.5, 'GrassFire': 0.5 }
def __init__(self, name, pokemon_type, level):
self.name = name
self.level = level
self.pok_type = pokemon_type
self.health = self.max_health = Pokemon.BASE_HEALTH * level
self.knocked_out = False
def attack(self, other_pokemon):
if self.knocked_out: return
damage_multiplier = Pokemon.DAMAGE_TYPE_FACTORS[self.pok_type + other_pokemon.pok_type]
damage = Pokemon.BASE_DAMAGE * self.level * damage_multiplier
print(Pokemon.DAMAGE_STRING.format(this_pokemon_name = self.name, damage = damage, attacked_pokemon_name = other_pokemon.name))
other_pokemon.lose_health(damage)
#decreased Pokemon’s health
def lose_health(self, lost_health):
if self.knocked_out: return
self.health = max(0, self.health - lost_health)
print(Pokemon.CURRENT_HP_STRING.format(pokemon_name = self.name, HP = self.health))
if self.health == 0:
self.knock_out()
#regaining health
def gain_health(self, gained_health):
if self.knocked_out: return
self.health = min(self.health + gained_health, self.max_health)
print(Pokemon.GAIN_HEALTH_STRING.format(pokemon_name = self.name, health = self.health))
def knock_out(self):
self.knocked_out = True
print(Pokemon.KNOCKED_OUT_STRING.format(pokemon_name = self.name))
def is_knocked_out(self):
return self.knocked_out
# to revive a knocked out Pokémon
def revive(self):
self.knocked_out = False
self.health = self.max_health
print(Pokemon.REVIVE_STRING.format(pokemon_name = self.name))
def __repr__(self):
return 'Pokemon {0} ({1}) - level {2}'.format(self.name, self.pok_type, self.level)
def get_max_health(self):
return self.max_health
def get_health(self):
return self.health
def get_name(self):
return self.name
<file_sep># API PART
class PersonManager:
def login(email, password):
if email == '<EMAIL>' and password == '<PASSWORD>':
return 1
elif email == '<EMAIL>' and password == '<PASSWORD>':
return 2
elif email == '<EMAIL>' and password == '<PASSWORD>':
return 3
return 0
def getPersonFromDB(id):
if id == 1:
return Person('<NAME>')
elif id == 2:
return Doctor('<NAME>')
elif id == 3:
return Knight('<NAME>')
return None
class Person:
def __init__(self, name):
self.name = name
self.HP = 100
# polymorphic method
def getTitle(self):
return self.name
def getHP(self):
return self.HP
class Doctor(Person):
def __init__(self, name):
super().__init__(name)
self.healing = 10
def getTitle(self):
return 'Dr. ' + self.name
def heal(self, patient):
patient.HP += self.healing
class Knight(Person):
def __init__(self, name):
super().__init__(name)
self.damage = 10
def getTitle(self):
return 'Sir ' + self.name
def fight(self, enemy):
enemy.HP -= self.damage
# DEVELOPER PART
# imagine form data comes from client request
# form = { 'email': '<EMAIL>', 'password': '<PASSWORD>' }
form = { 'email': '<EMAIL>', 'password': '<PASSWORD>' }
# form = { 'email': '<EMAIL>', 'password': '<PASSWORD>' }
# getting person
id = PersonManager.login(form['email'], form['password'])
p = PersonManager.getPersonFromDB(id)
print('Welcome ' + p.getTitle() + '!')
<file_sep>gamers = []
def add_gamer(gamer, gamers_list):
if "name" and "availability" in gamer.keys():
gamers_list.append(gamer)
return gamers_list
kimberly = {"name": "<NAME>", "availability": ["Monday", "Tuesday", "Friday"]}
add_gamer(kimberly, gamers)
add_gamer({'name':'<NAME>','availability': ["Tuesday", "Thursday", "Saturday"]}, gamers)
add_gamer({'name':'<NAME>','availability': ["Monday", "Wednesday", "Friday", "Saturday"]}, gamers)
week_days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
def build_daily_frequency_table():
ft = {}
for day in week_days:
ft[day] = 0
return ft
count_availability = build_daily_frequency_table()
print(count_availability)
#The function should iterate through each gamer in gamers_list and iterate through each day
#in the gamer's availability. For each day in the gamer's availability, add one
#to that date on the frequency table.
def calculate_availability(gamers_list, available_frequency):
for gamer in gamers_list:
for day in gamer["availability"]:
available_frequency[day] += 1
calculate_availability(gamers, count_availability)
print(count_availability)
def find_best_night(availability_table):
max = 0
maxDay = ''
for day in availability_table:
availability = availability_table[day]
if availability > max:
max = availability
maxDay = day
return maxDay
game_night = find_best_night(count_availability)
print(game_night)
def available_on_night(gamers_list, day):
people_list = []
for gamer in gamers_list:
if day in gamer["availability"]:
people_list.append(gamer["name"])
return people_list
attending_game_night = available_on_night(gamers, game_night)
print(attending_game_night)
form_email = "Dear {name}, come on {day_of_week} to play \"{game}\""
def send_email(gamers_who_can_attend, day, game):
for person in gamers_who_can_attend:
print(form_email.format(name = person, day_of_week = day, game = game))
send_email(attending_game_night, game_night, "Abruptly Goblins!")
unable_to_attend_best_night = []
for user in gamers:
if user["name"] not in attending_game_night:
unable_to_attend_best_night.append(user)
second_night_availability = build_daily_frequency_table()
calculate_availability(unable_to_attend_best_night, second_night_availability)
second_night = find_best_night(second_night_availability)
print(second_night_availability)
available_second_game_night = available_on_night(gamers, second_night)
send_email(available_second_game_night, second_night, "Abruptly Goblins!")
<file_sep>#1
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def unique_english_letters(word):
unique_count = 0
for letter in letters:
if letter in word:
unique_count += 1
return unique_count
def unique_letters1(word):
encountered_letters = ''
unique_count = 0
for letter in word:
if letter not in encountered_letters:
unique_count += 1
encountered_letters += letter
return unique_count
def unique_letters2(word):
encountered_letters = [False] * 256
unique_count = 0
for letter in word:
letter_index = ord(letter)
if not encountered_letters[letter_index]:
unique_count += 1
encountered_letters[letter_index] = True
return unique_count
def unique_letters3(word):
encountered_letters = {}
for letter in word:
if letter not in encountered_letters:
encountered_letters[letter] = True
print(encountered_letters)
return len(encountered_letters)
print(unique_letters3("mississippi"))
#2
def count_char_x(word, x):
print(word.count(x))
count_char_x("mississippi", "s")
count_char_x("mississippi", "m")
#3
def count_multi_char_x(word, x):
new_word = word.split(x)
return(len(new_word) - 1)
print(count_multi_char_x("mississippi", "iss"))
print(count_multi_char_x("apple", "pp"))
#4
#This function should return the substring between the first
#occurrence of start and end in word. If start or end are
#not in word, the function should return word.
def substring_between_letters(word, start, end):
substring = ()
if start and end in word:
i = word.find(start)
j = word.find(end)
substring = word[(i+1):j]
return substring
else:
return word
print(substring_between_letters("apple", "p", "e"))
print(substring_between_letters("apple", "p", "c"))
<file_sep>def delete_starting_evens(lst):
while lst[0] % 2 == 0:
lst = lst[1:]
return lst
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
def delete_starting_evens(lst):
while len(lst) > 0 and lst[0] % 2 == 0:
lst.pop(0)
return lst
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
def delete_starting_evens(lst):
i = 0
while lst[0] % 2 == 0:
lst = lst[1:]
i += 1
return lst
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
#The function should create a new empty list and add every element from lst
#that has an odd index.
#The function should then return this new list.
def odd_indices(lst):
new_lst = []
for i in range(len(lst)):
if i % 2 == 1:
new_lst.append(lst[i])
return new_lst
print(odd_indices([4, 3, 7, 10, 11, -2]))
#comprehention
def odd_indices(lst):
result = [lst[i] for i in range(len(lst)) if i % 2 == 1]
return(result)
print(odd_indices([4, 3, 7, 10, 11, -2]))
def exponents(bases, powers):
new_lst = []
for m in bases:
for n in powers:
new_lst.append(m**n)
return new_lst
print(exponents([2, 3, 4], [1, 2, 3]))
# function should return the list whose elements sum to the greater number.
#If the sum of the elements of each list are equal, return lst1.
def larger_sum(lst1, lst2):
if sum(lst1) >= sum(lst2):
return lst1
else:
return lst2
print(larger_sum([1, 9, 5], [2, 3, 7]))
#sum the elements of the list until the sum is greater than 9000.
#When this happens, the function should return the sum.
#If the sum of all of the elements is never greater than 9000,
#the function should return total sum of all the elements.
#If the list is empty, the function should return 0.
def func(lst):
sum = 0
for x in lst:
sum += x
if sum > 9000:
break
return sum
print(func([8000, 900, 120, 5000]))
#The function should return the largest number in nums
def max_num(nums):
max = nums[0]
for num in nums:
if num > max:
max = num
return max
print(max_num([50, -10, 0, 75, 20]))
def same_values(lst1, lst2):
lst3 = []
for i in range(len(lst1)):
if lst1[i] == lst2[i]:
lst3.append(i)
return lst3
print(same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5]))
def reversed_list(lst1, lst2):
l = len(lst1)
i = 0
j = l - 1
while i < l:
if lst1[i] != lst2[j]:
return False
i += 1
j -= 1
return True
print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))<file_sep>import random
money = 100
def generator(num, bet):
global money
num = random.randint(1, 10)
return num
if num >= bet:
money = money * 2
print ("Win!")
else:
money = money - (money/2)
print ("Lose!")
generator(num, 8)
import random
money = 100
#Write your game of chance functions here
def flip_coin(bet, x):
num = random.randint(1, 2)
if (num == x):
print("Win!" + " " + str(bet))
else:
print("Lose!" + " " + str (-bet))
flip_coin(20, 1)
def cho_han(bet, s):
num = random.randint(2, 12)
if num%2 == 0 and s%2 == 0:
print("Win!", "Even", str(bet))
elif num%2 == 1 and s%2 == 1:
print("Win!", "Odd", str(bet))
elif num%2 == 0 and s%2 == 1:
print("Lose!", "Even", str(-bet))
elif num%2 == 1 and s%2 == 0:
print("Lose!", "Odd", str(-bet))
cho_han(10, 8)
def deck_cards(bet):
num1 = random.randint(1, 9)
num2 = random.randint(1, 9)
if num1 > num2:
print(num1, num2, str(bet))
elif num1 == num2:
return 0
else:
print(num2, num1, str(-bet))
deck_cards(30)
<file_sep>def sum_even_keys(my_dictionary):
summa = 0
for key, value in my_dictionary.items():
if int(key) % 2 == 0:
summa += value
return summa
#print(sum_even_keys({1:5, 2:2, 3:3}))
#print(sum_even_keys({10:1, 100:2, 1000:3}))
def add_ten(my_dictionary):
for key, value in my_dictionary.items():
value +=10
my_dictionary.update({key: value})
return my_dictionary
#print(add_ten({1:5, 2:2, 3:3}))
#print(add_ten({10:1, 100:2, 1000:3}))
def values_that_are_keys(my_dictionary):
values_list = []
for value in my_dictionary.values():
if value in list(my_dictionary):
values_list.append(value)
return values_list
#print(values_that_are_keys({1:100, 2:1, 3:4, 4:10}))
#print(values_that_are_keys({"a":"apple", "b":"a", "c":100}))
def max_key(my_dictionary):
max_value = max(my_dictionary.values())
for key, value in my_dictionary.items():
if value == max_value:
return key
#print(max_key({1:100, 2:1, 3:4, 4:10}))
#print(max_key({"a":100, "b":10, "c":1000}))
#return a dictionary of key/value pairs where every key is
#a word in words and every value is the length of that word.
def word_length_dictionary(words):
new_dic = {}
for word in words:
new_dic.update({word: len(word)})
return new_dic
#print(word_length_dictionary(["apple", "dog", "cat"]))
#print(word_length_dictionary(["a", ""]))
def frequency_dictionary(words):
return {word: words.count(word) for word in words}
#print(frequency_dictionary(["apple", "apple", "cat", 1]))
#dictionary where each key is the first letter of a last name, and the value is
#the number of people whose last name begins with that letter.
#names = {"Stark": ["Ned", "Robb", "Sansa"], "Snow" : ["Jon"], "Lannister": ["Jaime", "Cersei", "Tywin"]}
def count_first_letter(names):
letters = {}
for last in list(names):
if last[0] not in letters:
letters.update({last[0]: len(names[last])})
else:
letters[last[0]]+= len(names[last])
return letters
print(count_first_letter({"Stark": ["Ned", "Robb", "Sansa"], "Snow" : ["Jon"], "Lannister": ["Jaime", "Cersei", "Tywin"]}))
<file_sep>letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]
letter_to_points = {letters: points for letters, points in zip(letters, points)}
letter_to_points.update({" ": 0})
def score_word(player, word):
score = 0
for letter in word:
for key, value in letter_to_points.items():
if letter == key:
score += value
return score
#print(score_word("BROWNIE"))
player_to_words = {"player1": ["BLUE", "TENNIS", "EXIT"], "wordNerd": ["EARTH", "EYES", "MACHINE"], "Lexi Con": ["ERASER", "BELLY", "HUSKY"], "Prof Reader": ["ZAP", "COMA", "PERIOD"]}
player_to_points = {}
for player, words in player_to_words.items():
player_points = 0
for word in words:
b = score_word(word)
player_points += b
player_to_points.update({player: player_points})
#After the inner loop ends, set the current player value to be a key of
#player_to_points, with a value of player_points
print(player_to_points)
#play_word() — a function that would take in a player and a word,
#and add that word to the list of words they’ve played update_point_totals()
#— turn your nested loops into a function that you can
#call any time a word is played make your letter_to_points dictionary able
#to handle lowercase inputs as well
<file_sep>from PokemonTrainer import PokemonTrainer
trainer_1 = PokemonTrainer('Sveta')
trainer_2 = PokemonTrainer('Dima')
i = 1
while True:
print('=====\nRound #' + str(i) + '\n=====')
i += 1
trainer_1.decide()
if not trainer_1.can_fight():
print(trainer_2.get_name() + ' is the winner!')
break
print(trainer_1.get_name() + ' attacks:')
trainer_1.get_current_pokemon().attack(trainer_2.get_current_pokemon())
trainer_2.decide()
if not trainer_2.can_fight():
print(trainer_1.get_name() + ' is the winner!')
break
print(trainer_2.get_name() + ' attacks:')
trainer_2.get_current_pokemon().attack(trainer_1.get_current_pokemon())
<file_sep>class Student:
def __init__(self, name, year):
self.name = name
self.year = year
self.grades = []
self.attendance = {}
def set_attendance(self, date, value):
self.attendance[date] = value
def get_attendance(self, date):
if date not in self.attendance:
return None
return self.attendance[date]
def add_grade(self, grade):
if type(grade) == Grade:
(self.grades).append(grade)
def get_average(self):
sum = 0
for grade in self.grades:
sum += grade.score
return sum/len(self.grades)
roger = Student('<NAME>', 10)
sandro = Student('<NAME>', 12)
pieter = Student('<NAME>', 8)
class Grade:
minimum_passing = 65
def __init__(self, score):
self.score = score
def is_passing(self):
return Grade.score > minimum_passing
pieter.add_grade(Grade(100))
pieter.add_grade(Grade(100))
pieter.add_grade(Grade(40))
print(pieter.get_average())
pieter.set_attendance('2020-04-13', True)
print(pieter.get_attendance('2020-04-13'))
print(pieter.get_attendance('2020-04-12'))
#Write a Grade method .is_passing() that returns whether a Grade has a passing .score.
#Write a Student method get_average() that returns the student’s average score.
#Add an instance variable to Student that is a dictionary called .attendance,
#with dates as keys and booleans as values that indicate whether the student attended
#school that day.
|
ac4fc04cbcdd6dcea5bc09090cb2fe60cfe94c26
|
[
"Python"
] | 23 |
Python
|
suglanova/CodecademyChallenges
|
b82917564618c7e5e07dfd19fd947b9a1d5cb19f
|
d7086d1767bd2afd9d6d902543bdd80884e8bf03
|
refs/heads/master
|
<file_sep>package classcode.p01IntroJava;
/**
* float operation
*/
public class C08Float {
/**
* @param args
*/
public static void main(String[] args) {
// one float variable
float n = 0.3f;
// show its value
System.out.println("n = " + n);
// subtract 0.1
n = n - 0.1f;
// show new value
System.out.println("n = " + n);
// check if they are equals by ==
boolean theyAreEquals = (n == 0.2f);
System.out.println("n == 0.2 -> " + theyAreEquals);
theyAreEquals = Math.abs(n - 0.2f) < 0.000001f;
System.out.println("n == 0.2 -> " + theyAreEquals);
}
}
<file_sep>package classcode.p10ExceptionHandling;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Apanhar também as excepções de input e diferenciar o seu tratamento por
* vários blocos de catch. Experimentar vários inputs com erro e sem erro.
*
*/
public class C06SeveralCatchs {
/**
* main
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Realizacao da operacao de divisao...");
try {
System.out.print("Introduza o dividendo -> ");
// depois comentar a linha seguinte
keyboard.close();
int dividendo = keyboard.nextInt();
System.out.print("Introduza o divisor -> ");
int divisor = keyboard.nextInt();
// realizar a processamento
int quociente = dividendo / divisor;
// mostrar resultado
System.out.println("Divisao de " + dividendo + " por " + divisor
+ " -> " + quociente);
// gerar uma excepção
"ola".charAt(10);
} catch (ArithmeticException e) {
System.err.println("Ocorreu a excepcao de divisão por zero: "
+ e.getMessage());
// gerar uma excepção
"ola".charAt(10);
} catch (InputMismatchException e) {
System.err.println("Ocorreu a excepcao de Input Mismatch");
} catch (Exception e) {
System.err.println("Ocorreu a excepcao: " + e.getMessage());
}
System.out.println("Fim de programa...");
keyboard.close();
}
// a excepção é avaliada e ficará entregue ao primeiro catch que seja do seu
// tipo.
// e mais excepções!!!
}
<file_sep>package classcode.p10ExceptionHandling;
public class DivideByZeroException extends Exception {
private static final long serialVersionUID = 1L;
static int n = 0;
public DivideByZeroException() {
super("Dividing by Zero!");
++n;
}
public DivideByZeroException(String message) {
super(message);
++n;
}
public static int getN() {
return n;
}
}
<file_sep>package tps.tp4;
import java.io.File;
import java.io.FileNotFoundException;
public class TabuleiroDim9 extends Tabuleiro {
private static final long serialVersionUID = 6784824663872156802L;
public TabuleiroDim9(File file) throws FileNotFoundException {
super(9, 9, file);
}
}<file_sep>package tps.tp4;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import classcode.p07Inheritance.layouts.ProportionalLayout;
public class Menu extends JPanel {
private static final long serialVersionUID = -3433891252895060316L;
private boolean createGame = false;
private Jogo jogo;
public Menu(Jogo jogo) {
this.jogo = jogo;
setBackground(Color.yellow);
JButton buttonTab4_nivel1 = new JButton("4x4 - Nivel 1");
buttonTab4_nivel1.setActionCommand("newgame");
add(buttonTab4_nivel1);
ActionListener tab4listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
apagaFrame();
File file = new File(
"C:\\Users\\Joao\\git\\MOP\\MOP\\src\\tps\\tp4\\levels\\44Easy\\44Easy_01.txt");
geraTab4(file);
resetFrame();
setSize();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
buttonTab4_nivel1.addActionListener(tab4listener);
JButton buttonTab5_nivel1 = new JButton("5x5 - Nivel 1");
buttonTab5_nivel1.setActionCommand("newgame");
add(buttonTab5_nivel1);
ActionListener tab5listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
apagaFrame();
File file = new File(
"C:\\Users\\Joao\\git\\MOP\\MOP\\src\\tps\\tp4\\levels\\55NotSoEasy\\55NotSoEasy_01.txt");
geraTab5(file);
resetFrame();
setSize();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
buttonTab5_nivel1.addActionListener(tab5listener);
JButton buttonTab6_nivel1 = new JButton("6x6 - Nivel 1");
buttonTab4_nivel1.setActionCommand("newgame");
add(buttonTab6_nivel1);
ActionListener tab6listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
apagaFrame();
File file = new File(
"C:\\Users\\Joao\\git\\MOP\\MOP\\src\\tps\\tp4\\levels\\66Medium\\66Medium_01.txt");
geraTab6(file);
resetFrame();
setSize();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
buttonTab6_nivel1.addActionListener(tab6listener);
JButton buttonTab7_nivel1 = new JButton("7x7 - Nivel 1");
buttonTab7_nivel1.setActionCommand("newgame");
add(buttonTab7_nivel1);
ActionListener tab7listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
apagaFrame();
File file = new File(
"C:\\Users\\Joao\\git\\MOP\\MOP\\src\\tps\\tp4\\levels\\77NotSoMedium\\77NotSoMedium_01.txt");
geraTab7(file);
resetFrame();
setSize();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
buttonTab7_nivel1.addActionListener(tab7listener);
JButton buttonTab8_nivel1 = new JButton("8x8 - Nivel 1");
buttonTab8_nivel1.setActionCommand("newgame");
add(buttonTab8_nivel1);
ActionListener tab8listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
apagaFrame();
File file = new File(
"C:\\Users\\Joao\\git\\MOP\\MOP\\src\\tps\\tp4\\levels\\88Hard\\88Hard_01.txt");
geraTab8(file);
resetFrame();
setSize();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
buttonTab8_nivel1.addActionListener(tab8listener);
JButton buttonTab9_nivel1 = new JButton("9x9 - Nivel 1");
buttonTab9_nivel1.setActionCommand("newgame");
add(buttonTab9_nivel1);
ActionListener tab9listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
apagaFrame();
File file = new File(
"C:\\Users\\Joao\\git\\MOP\\MOP\\src\\tps\\tp4\\levels\\99VeryHard\\99VeryHard_01.txt");
geraTab9(file);
resetFrame();
setSize();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
buttonTab9_nivel1.addActionListener(tab9listener);
}
public boolean getCreateGame() {
return createGame;
}
public void apagaFrame() {
jogo.getFrame().setVisible(false);
jogo.getFrame().dispose();
}
public void geraTab4(File file) throws FileNotFoundException {
JFrame frame = new JFrame();
ProportionalLayout cl = new ProportionalLayout(0.0f);
cl.setInsets(0.1f, 0.1f, 0.1f, 0.1f);
frame.setLayout(cl);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// frame.add(tabuleiro);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JLabel panelLeft = new JLabel("TESTEEEE");
panelLeft.setBackground(Color.BLUE);
Tabuleiro tabuleiro = new TabuleiroDim4(file);
panel.add(tabuleiro, BorderLayout.CENTER);
frame.add(panelLeft, BorderLayout.EAST);
frame.add(panel);
jogo.setFrame(frame);
}
public void geraTab5(File file) throws FileNotFoundException {
Tabuleiro tabuleiro = new TabuleiroDim5(file);
JFrame frame = new JFrame();
frame.add(tabuleiro);
jogo.setFrame(frame);
}
public void geraTab6(File file) throws FileNotFoundException {
Tabuleiro tabuleiro = new TabuleiroDim6(file);
JFrame frame = new JFrame();
frame.add(tabuleiro);
jogo.setFrame(frame);
}
public void geraTab7(File file) throws FileNotFoundException {
Tabuleiro tabuleiro = new TabuleiroDim7(file);
JFrame frame = new JFrame();
frame.add(tabuleiro);
jogo.setFrame(frame);
}
public void geraTab8(File file) throws FileNotFoundException {
Tabuleiro tabuleiro = new TabuleiroDim8(file);
JFrame frame = new JFrame();
frame.add(tabuleiro);
jogo.setFrame(frame);
}
public void geraTab9(File file) throws FileNotFoundException {
Tabuleiro tabuleiro = new TabuleiroDim9(file);
JFrame frame = new JFrame();
frame.add(tabuleiro);
jogo.setFrame(frame);
}
public void resetFrame() {
jogo.getFrame().setTitle("ConnectAll - by <NAME>");
jogo.getFrame().setSize(700, 700);
jogo.getFrame().setLocationRelativeTo(null);
jogo.getFrame().setDefaultCloseOperation(
WindowConstants.DISPOSE_ON_CLOSE);
System.out.println("Frame created...");
}
public void setSize() {
jogo.getFrame().setMinimumSize(new Dimension(400, 400));
// puts the frame visible (is not visible at start)
jogo.getFrame().setVisible(true);
}
}
<file_sep>package classcode.p10ExceptionHandling;
import java.util.Scanner;
/**
* Agora o método DIVISAO tem de declarar que pode lançar a excepção Exception e
* o método METODO1 tem de declarar que pode lançar a a excepção
* NegativeValueException. Deste modo quem usar estes métodos sabe com o que
* pode esperar.
*
*/
public class C11HandleExceptionsOutsideTheMethod2 {
/**
* Método base
*/
public static int divisao(int dividendo, int divisor) throws Exception {
if (divisor == 0)
throw new Exception("Divisao por zero");
int quociente = dividendo / divisor;
return quociente;
}
/**
* método que utiliza o método base
*/
public static int metodo1(int dividendo, int divisor)
throws NegativeValueException {
if (divisor < 0)
throw new NegativeValueException("Divisor negativo.");
try {
return divisao(dividendo, divisor);
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
/**
* main
*/
public static void main(String[] args) throws ClassNotFoundException {
Scanner keyboard = new Scanner(System.in);
do {
System.out.println("Realizacao da operacao de divisao...");
try {
System.out.print("Introduza o dividendo -> ");
int dividendo = keyboard.nextInt();
System.out.print("Introduza o divisor -> ");
int divisor = keyboard.nextInt();
// realizar a processamento
int quociente = metodo1(dividendo, divisor);
// subsituir a linha anterior pela seguinte, observar a
// informação do compilador
// int quociente = divisao(dividendo, divisor);
// mostrar resultado
System.out.println("Divisao de " + dividendo + " por "
+ divisor + " -> " + quociente);
} catch (NegativeValueException e) {
System.out.println("Ocorreu a excepcao: "
+ e.getClass().getSimpleName() + ": " + e.getMessage());
}
} while (NegativeValueException.getN() < 2);
keyboard.close();
}
// finally??
// isto quer dizer que chegámos ao fim????
}<file_sep>package classcode.p13EDD;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class C11CollectionsDemo {
static class CmpByLength implements Comparator<String> {
static Comparator<String> cmp = new CmpByLength();
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
}
public static Comparator<String> getComparator() {
return CmpByLength.cmp;
}
public static void main(String[] args) {
ArrayList<String> al1 = new ArrayList<String>(Arrays.asList("Marta",
"Ana", "Pedro", "Joćo"));
System.out.println("al1 -> " + al1);
// static <T> boolean addAll(Collection<? super T> c, T... elements)
Collections.addAll(al1, "Tiago", "Amilcar");
System.out.println("\nCollections.addAll(al1, \"Tiago\", \"Amilcar\")");
System.out.println("al1 -> " + al1);
// static <T> void fill(List<? super T> list, T obj)
// Replaces all of the elements of the specified list with the
// specified element.
ArrayList<String> al2 = new ArrayList<String>(al1);
Collections.fill(al2, "Francisco");
System.out.println("\nCollections.fill(al2, \"...\")");
System.out.println("al2 -> " + al2);
// static <T> void copy(List<? super T> dest, List<? extends T> src)
// Copies all of the elements from one list into another.
// the dest collection must have size >= src.size()
Collections.copy(al2, al1);
System.out.println("\nCollections.copy(al2, al1)");
System.out.println("al2 -> " + al2);
// static int frequency(Collection<?> c, Object o)
// Returns the number of elements in the specified collection equal to
// the specified object.
Collections.addAll(al1, "Ana", "Ana");
System.out.println("\nal1 -> " + al1);
int noccurs = Collections.frequency(al1, "Ana");
System.out.println("Collections.frequency(al1, \"Ana\") -> " + noccurs);
System.out.println("Collections.frequency(al1, \"Pedro\") -> "
+ Collections.frequency(al1, "Pedro"));
// static void reverse(List<?> list)
// Reverses the order of the elements in the specified list.
Collections.reverse(al1);
System.out.println("\nCollections.reverse(al1)");
System.out.println("al1 -> " + al1);
// static <T extends Comparable<? super T>> void sort(List<T> list)
// Sorts the specified list into ascending order, according to the
// natural ordering of its elements.
Collections.sort(al1);
System.out.println("\nCollections.sort(al1)");
System.out.println("al1 -> " + al1);
// static <T> void sort(List<T> list, Comparator<? super T> c)
// Sorts the specified list according to the order induced by the
// specified comparator.
Collections.sort(al1, getComparator());
System.out.println("\nCollections.sort(al1, getComparator())");
System.out.println("al1 -> " + al1);
// static <T> Comparator<T> reverseOrder()
// Returns a comparator that imposes the reverse of the natural
// ordering on a collection of objects that implement the Comparable
// interface.
Comparator<String> cmp = Collections.reverseOrder();
Collections.sort(al1, cmp);
System.out
.println("\nCollections.sort(al1, Collections.reverseOrder())");
System.out.println("al1 -> " + al1);
// static <T> Comparator<T> reverseOrder(Comparator<T> cmp)
// Returns a comparator that imposes the reverse ordering of the
// specified comparator.
cmp = Collections.reverseOrder(getComparator());
Collections.sort(al1, cmp);
System.out.println("\nCollections.sort(al1, "
+ "Collections.reverseOrder(getComparator()))");
System.out.println("al1 -> " + al1);
// static <T> int binarySearch(List<? extends Comparable<? super T>>
// list, T key)
// Searches the specified list for the specified object using the
// binary search algorithm.
Collections.sort(al1);
System.out.println("\nal1 -> " + al1);
int idx = Collections.binarySearch(al1, "Pedro");
System.out
.println("Collections.binarySearch(al1, \"Pedro\") -> " + idx);
// static <T> int binarySearch(List<? extends T> list, T key,
// Comparator<? super T> c)
// Searches the specified list for the specified object using the
// binary search algorithm.
cmp = getComparator();
Collections.sort(al1, cmp);
System.out.println("\nal1 -> " + al1);
idx = Collections.binarySearch(al1, "Marta", cmp);
System.out
.println("Collections.binarySearch(al1, \"Marta\", getComparator()) -> "
+ idx);
// static <T> List<T> nCopies(int n, T o)
// Returns an immutable list consisting of n copies of the specified
// object.
List<String> l = Collections.nCopies(4, "Joana");
System.out.println("\nl = Collections.nCopies(4, \"Joana\")");
System.out.println("l -> " + l);
// static boolean disjoint(Collection<?> c1, Collection<?> c2)
// Returns true if the two specified collections have no elements in
// common.
System.out.println("\nal1 -> " + al1);
System.out.println("l -> " + l);
boolean b = Collections.disjoint(al1, l);
System.out.println("Collections.disjoint(al1, l) -> " + b);
System.out.println("al2 -> " + al2);
b = Collections.disjoint(al1, al2);
System.out.println("Collections.disjoint(al1, al2) -> " + b);
// static int indexOfSubList(List<?> source, List<?> target)
// Returns the starting position of the first occurrence of the
// specified target list within the specified source list, or -1 if
// there is no such occurrence.
al2 = new ArrayList<String>(Arrays.asList("Ana", "Joćo"));
System.out.println("\nal1 -> " + al1);
System.out.println("al2 -> " + al2);
idx = Collections.indexOfSubList(al1, al2);
System.out.println("Collections.indexOfSubList(al1, al2) -> " + idx);
// static int lastIndexOfSubList(List<?> source, List<?> target)
// Returns the starting position of the last occurrence of the
// specified target list within the specified source list, or -1 if
// there is no such occurrence.
// static <T extends Object & Comparable<? super T>> T max(Collection<?
// extends T> coll)
// Returns the maximum element of the given collection, according to
// the natural ordering of its elements.
System.out.println("\nal1 -> " + al1);
String s = Collections.max(al1);
System.out.println("Collections.max(al1) -> " + s);
// static <T> T max(Collection<? extends T> coll, Comparator<? super T>
// comp)
// Returns the maximum element of the given collection, according to
// the order induced by the specified comparator.
System.out.println("\nal1 -> " + al1);
s = Collections.max(al1, getComparator());
System.out.println("Collections.max(al1, getComparator()) -> " + s);
// static <T extends Object & Comparable<? super T>> T min(Collection<?
// extends T> coll)
// Returns the minimum element of the given collection, according to
// the natural ordering of its elements.
// static <T> T min(Collection<? extends T> coll, Comparator<? super T>
// comp)
// Returns the minimum element of the given collection, according to
// the order induced by the specified comparator.
// static void rotate(List<?> list, int distance)
// Rotates the elements in the specified list by the specified
// distance.
System.out.println("\nal1 -> " + al1);
Collections.rotate(al1, 3);
System.out.println("Collections.rotate(al1, 3)");
System.out.println("al1 -> " + al1);
// static void shuffle(List<?> list)
// Randomly permutes the specified list using a default source of
// randomness.
System.out.println("\nal1 -> " + al1);
Collections.shuffle(al1);
System.out.println("Collections.shuffle(al1)");
System.out.println("al1 -> " + al1);
// static void shuffle(List<?> list, Random rnd)
// Randomly permute the specified list using the specified source of
// randomness.
// static void swap(List<?> list, int i, int j)
// Swaps the elements at the specified positions in the specified
// list.
Collections.sort(al1);
System.out.println("\nal1 -> " + al1);
Collections.swap(al1, 2, 6);
System.out.println("Collections.swap(al1, 2, 6)");
System.out.println("al1 -> " + al1);
// static <T> Collection<T> unmodifiableCollection(Collection<? extends
// T> c)
// Returns an unmodifiable view of the specified collection.
System.out.println("\nal1 -> " + al1);
Collection<String> c = Collections.unmodifiableCollection(al1);
System.out.println("Collections.unmodifiableCollection(al1)");
System.out.println("c -> " + c);
try {
System.out.println("c.add(\"Rodrigo\")");
c.add("Rodrigo");
} catch (UnsupportedOperationException e) {
System.out.println(e.getClass().getSimpleName());
}
// static <T> List<T> unmodifiableList(List<? extends T> list)
// Returns an unmodifiable view of the specified list.
System.out.println("\nal1 -> " + al1);
List<String> list = Collections.unmodifiableList(al1);
System.out.println("Collections.unmodifiableList(al1)");
System.out.println("lis -> " + list);
try {
System.out.println("list.add(\"Rodrigo\")");
list.add("Rodrigo");
} catch (UnsupportedOperationException e) {
System.out.println(e.getClass().getSimpleName());
}
}
}
<file_sep>package classcode.p07Inheritance.cenario2Figuras;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import classcode.p07Inheritance.layouts.ProportionalLayout;
/**
* Class FiguresViewer - classe que permite visualizar um array de Figuras num
* painel de uma frame.
*
* As classes anteriores são um exemplo de herenaç de classes. NEste ficheiro a
* classe JPanelFiguras contém o código exemplo de se ter um array de
* referências para o tipo base e nele conter elementos das suas classes
* fderivadas.
*
*/
public class C11FiguresViewer extends JFrame {
private static final long serialVersionUID = -4162886183937541L;
private JFrame frame;
private JPanel panelFiguras;
void init(C04Figura[] figuras) {
// criar a frame
frame = new JFrame("...: Figures viewer 0.1 :...");
// definir a dimensão da frame
frame.setSize(500, 300);
// definir que quando se premir o botão de close da janela e para fazer
// dispose à frame, ou seja, para a destruir
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// colocar a frame centrada no écran
frame.setLocationRelativeTo(null);
// criar um gestor proporcional de área com rebordo de 10%
ProportionalLayout pl = new ProportionalLayout(0.1f);
// colocar esse gestor na frame
frame.setLayout(pl);
// criar o painel que conterá as figuras
panelFiguras = new JPanelFiguras(figuras);
// adicionar o panel à frame, no seu centro
frame.add(panelFiguras, ProportionalLayout.CENTER);
// adicionar ao panel um rebordo a preto
panelFiguras.setBorder(BorderFactory.createLineBorder(Color.black));
// colocar a frame visivel, por omissão é invisível
frame.setVisible(true);
}
/**
* Métodod main
*/
public static void main(String[] args) {
// array com várias figuras
final C04Figura[] figuras = new C04Figura[] {
new C05Recta(new C02Ponto2D(10, 10), new C02Ponto2D(40, 40),
Color.blue),
new C06Rectangulo(new C02Ponto2D(100, 10), 90, 50, Color.red),
new C07Quadrado(new C02Ponto2D(200, 10), 100, Color.green),
new C08Triangulo(new C02Ponto2D(50, 100), new C02Ponto2D(150,
100), new C02Ponto2D(50, 150), 100, 50, Color.blue),
new C09TrianguloIsosceles(new C02Ponto2D(250, 150), 100, 50,
Color.magenta),
new C10Elipse(new C02Ponto2D(150, 120), 80, 50, Color.yellow),
new C10Elipse(new C02Ponto2D(165, 140), 20, 5, Color.red),
new C10Elipse(new C02Ponto2D(195, 140), 20, 5, Color.red),
new C11Circulo(new C02Ponto2D(85, 140), 25, Color.orange), };
// submeter um pedido de execução para a Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// criar um objecto FiguresViewer
C11FiguresViewer figFrame = new C11FiguresViewer();
// construir a frame e torná-la visível
figFrame.init(figuras);
}
});
}
}
/**
* Classe JPanelFiguras - classe auxiliar, não se justifica colocar esta classe
* num ficheiro próprio, pois não é extensa, nem é uma classe com relevância
* suficiente para isso e ela só tem interesse no contexto da classe
* FiguresViewer. Ela ficar num ficheiro próprio só iria aumentar o número de
* ficheiros e isso também não facilita a visualização ao nível do package
*/
class JPanelFiguras extends JPanel {
private static final long serialVersionUID = 1L;
// o array de figuras para serem desenhadas
C04Figura[] figuras;
/**
* constructor
*/
public JPanelFiguras(C04Figura[] figuras) {
// super();
this.figuras = figuras;
}
/**
* Método para desenhar as várias figuras
*
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
public void paintComponent(Graphics g) {
// deve-se mandar desenhar todo o background primeiro
super.paintComponent(g);
// depois desenhar os nossos objectos
for (int i = 0; i < figuras.length; i++) {
// figuras[i].translate();
// C06Rectangulo ref = ((C06Rectangulo) figuras[i]);
// ref.translate();
if (figuras[i] instanceof C06Rectangulo) {
C06Rectangulo ref = (C06Rectangulo) figuras[i];
ref.translate();
}
// if (figuras[i] instanceof C06Rectangulo
// && !(figuras[i] instanceof C07Quadrado))
figuras[i].paintComponent(g);
}
}
}
<file_sep>package oldClass.tp1;
import java.util.Scanner;
public class P01Multiplicador {
public static void main(String[] args) {
// init scanner
Scanner keyboard = new java.util.Scanner(System.in);
// boolean para possivel saida do ciclo
boolean go = true;
int nReps = 0;
int num = 0;
// ciclo while para repeticao do pedido caso nao se insiram os valores
// pretendidos
while (go) {
System.out
.println("choose a number to reply, between 1 and 20 -> ");
// valor guardado para repetir
num = keyboard.nextInt();
System.out
.println("choose the number of replys, between 1 and 10 -> ");
// valor guardado de repeticoes
nReps = keyboard.nextInt();
// condicao para a pergunta ser repetida
if ((num < 1 || num > 20) || (nReps < 1 || nReps > 10)) {
System.out.println("error, please respect the awnser");
// condicao caso ja existam 2 valores pretendidos
} else {
go = false;
}
}
int i = 0;
int result = 1;
while (nReps > i) {
// contador para saida do while
i++;
// actualizacao do resultado
// multiplicacao sucessiva do valor escolhido o numero pretendido
result = result * num;
}
System.out.println(result);
keyboard.close();
}
}
<file_sep>package classcode.p10ExceptionHandling;
class NegativeValueException extends Exception {
private static final long serialVersionUID = 1L;
static int n = 0;
public NegativeValueException() {
super("Negative value!");
++n;
}
public NegativeValueException(String message) {
super(message);
++n;
}
public static int getN() {
return n;
}
}<file_sep>package tps.tp4;
import java.io.File;
import java.io.FileNotFoundException;
public class TabuleiroDim8 extends Tabuleiro {
private static final long serialVersionUID = 6784824663872156802L;
public TabuleiroDim8(File file) throws FileNotFoundException {
super(8, 8, file);
}
}<file_sep>package classcode.p14EDDLinkedLists.p2GenericLinkedList;
import java.util.*;
/**
* Este exemplo apenas acrescenta o facto de a lista ser genérica. É uma lista
* simples sem sentinela
*/
public class C01GenericLinkedList<E> {
private ListNode head;
public C01GenericLinkedList() {
head = null;
}
public int length() {
int count = 0;
ListNode position = head;
while (position != null) {
count++;
position = position.link;
}
return count;
}
/**
* The added node will be the first node in the list.
*/
public void addANodeToStart(E addData) {
head = new ListNode(addData, head);
}
public E deleteHeadNode() {
E data = null;
if (head != null) {
data = head.data;
head = head.link;
} else {
System.out.println("Deleting from an empty list.");
System.exit(0);
}
return data;
}
public boolean contains(E target) {
return (find(target) != null);
}
/**
* Finds the first node containing the target data, and returns a reference
* to that node. If target is not in the list, null is returned.
*/
private ListNode find(E target) {
ListNode currElem = head;
while (currElem != null) {
E data = currElem.data;
if (data.equals(target))
return currElem;
currElem = currElem.link;
}
// target was not found.
return null;
}
public void showList() {
ListNode position = head;
while (position != null) {
System.out.println(position.data);
position = position.link;
}
}
// Obter um vector com a copia dos elementos
public ArrayList<E> ArrayListCopy() {
ArrayList<E> v = new ArrayList<E>(length());
ListNode position;
position = head;
while (position != null) {
v.add(position.data);
position = position.link;
}
return v;
}
// esta classe é uma inner class (nested class)
// a declaração do E está válida neste contexto
// mas se a classe fosse declarada fora da classe principal
// já teria que ter: class LisNode<E> {
private class ListNode {
private E data;
private ListNode link;
public ListNode(E newData, ListNode linkValue) {
data = newData;
link = linkValue;
}
}
}
<file_sep>package classcode.p15Swing.p04SimpleSwingApps;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
/**
* Calculator
*
*
* Novos componentes: JtextField - componente que permite o input de texto
*
* Novas funcionalidades: setEditable, setResizable
*
* @author <NAME>
*
*/
public class C1Calculator extends JFrame {
private static final long serialVersionUID = 1L;
private FlowLayout layout = null;
private JLabel label1 = null;
private JButton buttonAdd = null;
private JButton buttonSub = null;
private JLabel label2 = null;
private JTextField text1 = null;
private JTextField text2 = null;
private JTextField textResult = null;
private JLabel labelResult = null;
/**
* Este método cria toda a frame e coloca-a visível
*
*/
public void init() {
// set title
setTitle("...: My calculator v1 :...");
// on close button hide and dispose frame
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
layout = new FlowLayout();
getContentPane().setLayout(layout);
// label1 - oper1
label1 = new JLabel("Value1 :");
label1.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add(label1);
// text1 - oper1
text1 = new JTextField("1000", 10);
getContentPane().add(text1);
// button1
buttonAdd = new JButton("+");
buttonAdd.setActionCommand("add");
getContentPane().add(buttonAdd);
// button2
buttonSub = new JButton("-");
buttonSub.setActionCommand("sub");
getContentPane().add(buttonSub);
// label2 - oper2
label2 = new JLabel("Value2 :");
label2.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add(label2);
// text2 - JTextField oper2
text2 = new JTextField("200", 10);
add(text2);
// text2.setEditable(false); // teste 2 - retirar comentário
// labelResult
labelResult = new JLabel("Result :");
labelResult.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add(labelResult);
// textResult
textResult = new JTextField(10);
getContentPane().add(textResult);
textResult.setEditable(false);
// adjust size to minimum as needed
pack();
// set location
setLocationRelativeTo(null); // to center a frame
// disable resize ---------------
setResizable(false);
// set dynamic behavior
// Listener comum aos dois botões, a distinção é realizada pelo
// actionCommand
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Scanner sc1 = new Scanner(text1.getText());
Scanner sc2 = new Scanner(text2.getText());
if (sc1.hasNextInt() && sc2.hasNextInt()) {
int oper1 = sc1.nextInt();
int oper2 = sc2.nextInt();
int result = 0;
if (((JButton) e.getSource()).getActionCommand().equals(
"add")) {
result = oper1 + oper2;
} else { // sub
result = oper1 - oper2;
}
textResult.setText(Integer.toString(result));
} else {
textResult.setText("Invalid input values!");
}
sc1.close();
sc2.close();
}
};
buttonAdd.addActionListener(al);
buttonSub.addActionListener(al);
// puts the frame visible and working
setVisible(true);
}
/**
* Main
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
C1Calculator myFrame = new C1Calculator();
myFrame.init();
// life goes on
System.out.println("Frame created...");
}
});
System.out.println("End of main...");
}
}
<file_sep>package classcode.p14EDDLinkedLists.p3LinkedListWithIterator;
import java.util.*;
/**
*
* Lista com head, current, previous, que implementa a interface Iterator
*
* A lista tem a noção de iteração. A iteração NÃO PERMITE MODIFICAÇÕES
* CONCORRENTES. É um exemplo simples de como uma inserção fora do iterador
* invalida a iteração corrente
*
* @author <NAME>
*
*/
public class C04StringLinkedListWithIterator3<E> implements Iterator<E> {
private ListNode head;
private ListNode current; // elemento corrente a ser devolvido
private ListNode previous; // follows current
private boolean nextCalled; // true if next has called
private boolean insertDone; // true if insert has done
public C04StringLinkedListWithIterator3() {
head = null;
resetIteration();
}
/**
* Returns the next element (String) in the list. Throws a
* NoSuchElementException if there is no next element to return.
*/
public E next() {
if (insertDone) {
throw new IllegalStateException("List modified");
}
if (head == null) {
throw new NoSuchElementException();
}
if (current == null && previous == null) {
// primeira vez que o next é chamado
current = head;
} else if (current != null && current.link != null) {
previous = current;
current = current.link;
} else {
throw new NoSuchElementException();
}
nextCalled = true;
return (current.data);
}
/**
* Removes the last element that was returned by next. Throws an
* IllegalStateException if the next method has not yet been called or if
* the remove method has already been called after the last call to the next
* method.
*/
public void remove() {
if (insertDone) {
throw new IllegalStateException("List modified.");
}
if (!nextCalled) {
throw new IllegalStateException("Double remotion.");
}
if (previous != null) {
// remove on middle of list
previous.link = current.link;
current = previous;
} else {
// remove at head
head = current.link;
current = null;
}
nextCalled = false;
}
/**
* Returns true if there is at least one more element for next to return.
* Otherwise, returns false.
*/
public boolean hasNext() {
if (insertDone) {
throw new IllegalStateException("List modified");
}
return (current != null ? current.link != null : previous == null
&& head != null);
}
/* outros métodos */
public void resetIteration() {
current = null;
previous = null;
nextCalled = false;
insertDone = false;
}
public void addANodeToStart(E addData) {
head = new ListNode(addData, head);
if (current == head.link && current != null) {
// if current is at old start node
previous = head;
}
insertDone = true;
}
public void showList() {
ListNode position;
position = head;
while (position != null) {
System.out.println(position.data);
position = position.link;
}
}
private class ListNode {
private E data;
private ListNode link;
public ListNode(E newData, ListNode linkValue) {
data = newData;
link = linkValue;
}
}
}<file_sep>package classcode.p07Inheritance.cenario2Figuras;
import java.awt.Color;
/**
* Class Rectangulo - suporta um rectângulo
*
*/
class C06Rectangulo extends C04Figura {
double largura, altura;
int count = 0;
boolean grow = true;
public C06Rectangulo(C02Ponto2D p1, int largura, int altura, Color color) {
super(color);
C02Ponto2D[] ps = new C02Ponto2D[4];
this.largura = largura;
this.altura = altura;
ps[0] = p1.clone();
ps[1] = new C02Ponto2D(p1.getX() + largura, p1.getY());
ps[2] = new C02Ponto2D(p1.getX() + largura, p1.getY() + altura);
ps[3] = new C02Ponto2D(p1.getX(), p1.getY() + altura);
setPontos(ps);
}
public String getNome() {
return "rectangulo";
}
public double getArea() {
return largura * altura;
}
public void translate() {
if (grow) {
if (++count == 200) {
count = 0;
grow = false;
}
} else {
if (++count == 200) {
count = 0;
grow = true;
}
}
for (int i = 0; i < 4; i++) {
pontos[i].setX(pontos[i].getX() + (grow ? 1 : -1));
pontos[i].setY(pontos[i].getY() + (grow ? 1 : -1));
}
}
/**
*
*/
public static void main(String[] args) {
C06Rectangulo r1 = new C06Rectangulo(new C02Ponto2D(1, 1), 4, 2,
Color.green);
System.out.println("r1 -> " + r1);
}
}<file_sep>package classcode.p06ClassesAndObjects;
/**
*
*/
class Requisicao {
private String data;
private int nDias;
private Livro livro;
private String dataEntrega; // null, significa que o livro não está entregue
private Pessoa utente;
public Requisicao(String data, int nDias, Livro livro, Pessoa utente) {
this.data = data;
this.nDias = nDias;
this.livro = livro;
this.utente = utente;
}
public String getDataEntrega() {
return dataEntrega;
}
public void setDataEntrega(String dataEntrega) {
this.dataEntrega = dataEntrega;
}
public String getData() {
return data;
}
public int getnDias() {
return nDias;
}
public Livro getLivro() {
return livro;
}
public Pessoa getUtente() {
return utente;
}
}<file_sep>package classcode.p15Swing.p01layoutframes;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
/**
* Frame, JLabel
*
* Criar uma JFrame, dar-lhe tamanho, colocar-lhe um JLabel, alterar cores e
* font, posicioná-la no centro do ecran e destruí-la quando se clicar no icon
* de close. Excepto o acto de criar a frame, todos os outros podem ser
* comentados e observar-se os seus efeitos
*
* @author <NAME>
*
*/
public class C1MyFirstSwingObject {
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new MyRun());
System.out.println("End of main...");
}
static class MyRun implements Runnable {
public void run() {
createAndShowGUI();
}
}
public static void main2(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
System.out.println("End of main...");
// Runnable doRun = new Runnable() {
// public void run() {
// createAndShowGUI();
// }
// };
// javax.swing.SwingUtilities.invokeLater(doRun);
}
public static void createAndShowGUI() {
// create a JFrame
JFrame frame = new JFrame();
// set title
frame.setTitle("...: My first frame :...");
// set size
frame.setSize(700, 200);
// set location
frame.setLocationRelativeTo(null); // to center a frame
// set what appends when close button is pressed
// default: HIDE_ON_CLOSE
// verificar o comportamento com as opções seguintes. DISPOSE_ON_CLOSE é
// a opção que queremos
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
// frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
// frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// Criar a label com algum texto
JLabel label1 = new JLabel("Olá");
// colocar a label dentro da frame
frame.getContentPane().add(label1);
// também se poderia fazer:
// frame.add(label1);
// obter e afectar o texto da label
label1.setText(label1.getText() + " boas férias");
// indicar que o texto é para ficar centrado horizontalmente,
// verticalmente já o é por omissão
label1.setHorizontalAlignment(SwingConstants.CENTER);
// label1.setVerticalAlignment(SwingConstants.BOTTOM);
// mudar a font do texto
label1.setFont(new Font("Courier", Font.BOLD, 60));
// mudar a font do texto
String fontType = "Comic Sans MS";
int size = 40;
Font f1 = new Font(fontType, Font.BOLD, size);
label1.setFont(f1);
// colocar uma cor nas letras
label1.setForeground(Color.magenta);
label1.setForeground(new Color(200, 0, 0));
// colocar uma cor de fundo
label1.setOpaque(true);
label1.setBackground(Color.yellow);
// label1.setBackground(new Color(200, 150, 200));
// reduzir a frame às mínimas dimensões
frame.pack();
// set location at center
frame.setLocationRelativeTo(null);
// puts the frame visible (is not visible at start)
frame.setVisible(true);
// frame.setResizable(false);
// não se deve fazer sleep à thread do swing (Events Dispatch Thread)
// eset sleep irá paralizar toda a frame
// try {
// Thread.sleep(8000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// frame.setSize(400, 700);
// frame.setLocationRelativeTo(null); // to center a frame
// life goes on
System.out.println("Frame created...");
}
}
<file_sep>package classcode.p14EDDLinkedLists.p6Maps;
import java.util.Set;
import java.util.TreeSet;
public class C02SetTest {
public static void main(String[] args) {
// a set
Set<Pessoa> set = new TreeSet<Pessoa>();
// create some elements
Pessoa p1 = new Pessoa("José", 12345611);
Pessoa p2 = new Pessoa("Pedro", 564564566);
Pessoa p3 = new Pessoa("Marco", 745547457);
Pessoa p4 = new Pessoa("André", 46546);
// add the elements to the set
set.add(p1);
set.add(p2);
set.add(p3);
set.add(p4);
// show set contents
System.out.println("set -> " + set);
// try to add an element that already exists in the set
boolean result = set.add(p4);
// show the result
System.out.println("Set.add(" + p4 + ") -> " + result);
System.out.println("set -> " + set);
}
}
<file_sep>package classcode.p01IntroJava;
/**
* Class with some literals from the diferent types
*
*/
public class C04Literals {
/**
* Main method
*/
public static void main(String[] args) {
// byte literal
byte b1 = 100;
System.out.println("byte b1 = " + b1);
// short literal
short s1 = 10000;
System.out.println("short s1 = " + s1);
// int literal
int i1 = 1000000000;
System.out.println("int i1 = " + i1);
// int in format binary, starts with 0b
int iBinary = 0b110011111;
System.out.println("int iBinary = 0b110011111; -> " + iBinary);
// int in octal format, starts with zero
int iOctal = 0234;
System.out.println("int iOctal = 0234 -> " + iOctal);
// int in hexadecimal format, starts with 0x
int iHexadecimal = 0x234;
System.out.println("int iHexadecimal = 0x234; -> " + iHexadecimal);
// long literal, ends with l
long l = 1000000000000000000L, l2 = 3l;
System.out.println("long l = " + l + ", l2 = " + l2);
// float literals, ends with f
float f1 = 1.2f;
System.out.println("float f1 = 1.2f -> " + f1);
// double literals, decimal value that may ends with d
double d1 = 0.1, d2 = 0.2d;
System.out.println("double d1 = 0.1, d2 = 0.2d; d1 -> " + d1
+ " d2 -> " + d2);
// char literals - char literals always use ''
char c1 = 'a';
System.out.println("char c1 = \'a\'; -> " + c1);
char c2 = '\n';
System.out.println("char c2 = \'\\n\'; -> " + c2);
// java have the following escape sequences: '\' is a escape char,
// means that the char after the \ have special meaning: '\n'(new
// line), '\r' (carriage return),'\t' (tab), '\b' (backspace),
// '\f' (form feed), '\'' the ' character, '\"' (the " caracter),
// '\\' (the \ character);
char c3 = '\u0034'; // unicode escape char- value must be 4 hexadecimal
// digits
System.out.println("char c3 = \'\\u0034\'; -> " + c3);
// we can put a underscore in any place on a literal, but it has to be
// in the middle of two digits.
int j1 = 1_000_000;
System.out.println("int j1 = 1_000_000; -> " + j1);
// String literals - string literals always use " "
String str1 = "olá";
System.out.println("String str1 = \"olá\"; -> " + str1);
// explicitly creates a new object
String str2 = new String("Olá");
System.out.println("String str2 = new String(\"Olá\"); -> " + str2);
// null is a special literal that means emptiness, to be used in obejct
// references
String str3 = null;
System.out.println("String str3 = null; -> " + str3);
}
}
<file_sep>package classcode.p02FlowDecisionsCycles;
/**
* Switch com inteiros (bytes) - com múltiplas entradas para o mesmo código
*
*
* @author ateofilo
*
*/
public class C07Switch {
/**
* @param args
*/
public static void main(String[] args) {
// número do mês no ano
byte month = 1;
System.out.println("Mês -> " + month);
// nome da respectiva estação - estação em maioria nesse mês
String seasonName;
switch (month) {
case 1:
case 2:
case 3:
seasonName = "Inverno";
break;
case 4:
case 5:
case 6:
seasonName = "Primavera";
break;
case 7:
case 8:
case 9:
seasonName = "Verão";
break;
case 10:
case 11:
case 12:
seasonName = "Outono";
break;
default:
seasonName = "mês inválido";
}
System.out.println("Nome da estação -> " + seasonName);
}
}
<file_sep>package classcode.p07Inheritance.cenario4Produto;
/*
* Classe base do cenário.
* Exemplo formado pelas classes: ProdutoBase, ProdutoSimples e ProdutoComposto
*
* Ver a documentação de cada método, colocar o rato por cima do nome do método
*
*/
public class C1ProdutoBase {
/**
* Prefixo a ser utilizado aquando da identação de produtos dentro de um
* produtoComposto
*/
protected static String PREFIXBASE = " ";
/**
* Nome do produto
*/
private String name;
//
//
// ### Métodos ### -------------------------------------------------
/**
* Método constructor, deve guardar o nome recebido na variável name
*/
public C1ProdutoBase(String name) {
this.name = name;
}
/**
* Devolve o nome do produto
*
* @return o nome do produto
*/
public String getName() {
return name;
}
/**
* Devolve a descrição do produto
*
* @return a descrição do produto
*/
public String getDescricao() {
return null;
}
/**
* Devolve o preço do produto
*
* @return o preço do produto
*/
public int getPreco() {
return 0;
}
/**
* Devolve o stock deste do produto
*
* @return o stock deste produto
*/
public int getStock() {
return 0;
}
/**
* Devolve uma descrição textual do produto
*
* @return uma String com a descrição sumária deste produto
*/
public String toString() {
return getName() + ", " + getDescricao() + ", preço de " + getPreco()
+ ", stock de " + getStock();
}
/**
* Mostra na consola a descrição do produto, por omissão essa descrição é o
* toString aqui declarado. A descrição deve ser prefixada com o prefixo
* recebido.
*
* @param prefix
* O prefixo a colocar antes da descrição do objecto
*/
public void print(String prefix) {
// A colocação de this na string, vai implicar a chamada ao método
// toSTring do objecto.
// É equivalente a System.out.println(prefix + toString());
System.out.println(prefix + this);
}
}
<file_sep>package classcode.p07Inheritance.cenario4Produto;
public class C2ProdutoSimples extends C1ProdutoBase {
// preço do produto
private int preco;
// stock do produto
private int stock = 0;
//
//
// ### Métodos ### -------------------------------------------------
/**
* constructor
*/
public C2ProdutoSimples(String name, int preco, int initialStock) {
super(name);
this.preco = preco;
stock = initialStock;
}
/**
* Devolve a descrição do produto
*
* @return a descrição do produto
*/
public String getDescricao() {
return "produto simples";
}
/**
* Devolve o preço do produto
*
* @return o preço do produto
*/
public int getPreco() {
return preco;
}
/**
* Devolve o stock deste do produto
*
* @return o stock deste produto
*/
public int getStock() {
return stock;
}
/**
* main
*/
public static void main(String[] args) {
// um produto simples
C2ProdutoSimples p1 = new C2ProdutoSimples(
"Sapatilhas Mike Air Blue Mountain", 60, 100);
p1.print("p1 -> ");
System.out.println(p1);
}
}
<file_sep>package classcode.p12Generics;
/**
* Classe para testes avulsos
*/
public class C10Test<T> {
T u;
private C10Test(T u) {
this.u = u;
}
T m1(T x) {
T old = u;
u = x;
return old;
}
T get() {
return u;
}
public static void main(String[] args) {
C10Test<String> o1 = new C10Test<String>("olá");
System.out.println(o1.m1("bom"));
System.out.println(o1.m1("dia"));
// C10Test<Integer> o3 = o1;
C10Test<Integer> o4 = new C10Test<Integer>(10);
System.out.println("o4.get() -> " + o4.get());
C10Test<Cat> myCat = new C10Test<Cat>(new Cat());
System.out.println("myCat -> " + myCat);
// C10Test<Long> o5 = new C10Test<Integer>(10);
C10Test<C10Test<String>> o2 = new C10Test<C10Test<String>>(o1);
// C10Test<String> r = o2.m1(new C10Test<String>("xx"));
// System.out.println(r.get());
System.out.println(o2.get());
}
}
class Cat {
}
<file_sep>package classcode.p15Swing.p07MyModelViewController;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* Esta classe é um Viewer
*
*/
class VisualTemp extends JLabel implements ChangeListener {
private static final long serialVersionUID = 5424313808713066892L;
private static String[] weatherChanges = { "sunny", "mostly_sunny",
"chance_of_rain", "cloudy", "rain", "chance_of_storm",
"thunderstorm" };
// MODEL
Weather weather;
private ImageIcon[] images = null;
public VisualTemp(Weather weather) {
super();
this.weather = weather;
setHorizontalAlignment(SwingConstants.CENTER);
setVerticalTextPosition(SwingConstants.BOTTOM);
setHorizontalTextPosition(SwingConstants.CENTER);
images = new ImageIcon[weatherChanges.length];
loadImages();
setImage(weather.getValue());
// REGISTO NO MODEL
weather.addChangeListener(this);
}
private void loadImages() {
for (int i = 0; i < weatherChanges.length; i++) {
images[i] = loadImageIcon("images/" + weatherChanges[i] + ".gif");
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon loadImageIcon(String path) {
// getResource - verifica se o recurso existe
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
ImageIcon ic = new ImageIcon(imgURL);
System.out.println("Image: " + path + " loaded");
return ic;
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private void setImage(int value) {
int idx = 0;
if (value < 10) {
idx = images.length - 1;
} else if (value < 25) {
idx = (int) (((15 - (value - 10)) / 15.0f) * (images.length - 2)) + 1;
}
setIcon(images[idx]);
System.out.println("image index -> " + idx);
setText(weatherChanges[idx]);
}
public void stateChanged(ChangeEvent e) {
setImage(weather.getValue());
}
}
<file_sep>package classcode.p11StreamsAndFileIO;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TestRead {
public static void main(String[] args) {
try {
Scanner fileScan = new Scanner(new File("file1.txt"));
int numLines = 0;
while(fileScan.hasNextLine()){
String line = fileScan.nextLine();
System.out.println(line);
numLines++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
<file_sep>package classcode.p15Swing.p05listenersAndAdapters;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import classcode.p15Swing.p02buildedLayouts.CenterLayout;
import classcode.p15Swing.p02buildedLayouts.ProportionalLayout;
/**
* MouseMotionListener: mouse motion Events, MouseWheelListener
*
* @author <NAME>
*
*/
public class C4MyMouseMotionListenerFrame extends JFrame {
private static final long serialVersionUID = 1L;
GridLayout gl = null;
JLabel label1 = null;
JButton button1 = null;
private final Color leftColor = new Color(120, 240, 140);
private final Color rightColor = new Color(120, 140, 240);
private JPanel buttonsPanel;
/**
* Este método cria toda a frame e coloca-a visível
*
*/
public void init() {
// set title
setTitle("...: My Mouse Motion Listener frame :...");
// set size
setSize(400, 200);
// set location
setLocationRelativeTo(null); // to center a frame
// set what happens when close button is pressed
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
ProportionalLayout cl = new ProportionalLayout(0.1f, 0.2f, 0.2f, 0.2f);
setLayout(cl);
// use of BorderLayout
buttonsPanel = new JPanel();
buttonsPanel.setLayout(new CenterLayout());
add(buttonsPanel, ProportionalLayout.SOUTH);
// build JLabel
label1 = new JLabel("See events in console...");
label1.setHorizontalAlignment(SwingConstants.CENTER);
label1.setOpaque(true);
label1.setBackground(rightColor);
add(label1, ProportionalLayout.CENTER);
// button1
button1 = new JButton("Ckick here!!!");
MouseListener ml = new MouseListener() {
public void mouseClicked(MouseEvent e) {
System.out.print("Mouse clicked...");
int b = e.getButton();
// System.out.println(e);
switch (b) {
case MouseEvent.BUTTON1:
System.out.println(" left button...");
label1.setBackground(leftColor);
break;
case MouseEvent.BUTTON3:
System.out.println(" right button...");
label1.setBackground(rightColor);
break;
default:
System.out.println(" center button...");
// C1MyMouseListenerFrame.this.dispose(); // 118
}
}
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered...");
}
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited...");
}
public void mousePressed(MouseEvent e) {
System.out.println("Mouse pressed...");
}
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse released...");
}
};
button1.addMouseListener(ml);
buttonsPanel.add(button1);
// label1.addMouseListener(ml); // 141
MouseMotionListener mml = new MouseMotionListener() {
// event that fires when mouse moves over component
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse moved at -> " + e.getX() + ","
+ e.getY());
}
// event that fires when mouse moves over component (and outside)
// when mouse is pressed
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse dragged at -> " + e.getX() + ","
+ e.getY());
}
};
label1.addMouseMotionListener(mml);
label1.addMouseListener(ml);
MouseWheelListener mwl = new MouseWheelListener() {
// event that fires when user moves mouse wheel over component
public void mouseWheelMoved(MouseWheelEvent e) {
System.out.println("mouseWheelMoved event..."
+ (e.getPreciseWheelRotation() > 0 ? "up" : "down"));
}
};
label1.addMouseWheelListener(mwl);
// puts the frame visible (is not visible at start)
setVisible(true);
}
/**
* Main
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
C4MyMouseMotionListenerFrame myFrame = new C4MyMouseMotionListenerFrame();
myFrame.init();
// life goes on
System.out.println("Frame created...");
}
});
System.out.println("End of main...");
}
}
// teste1: retirar o comentário da linha 118 e observar o resultado
// teste2: retirar o comentário da linha 141 e observar o resultado
<file_sep>package classcode.p13EDD;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class C02IterableRemove {
/**
* Print
*/
public static void printIterable(Iterable<String> container) {
Iterator<String> it = container.iterator();
System.out.print("[");
while (it.hasNext()) {
System.out.print(it.next());
if (it.hasNext())
System.out.print(", ");
}
System.out.println("]");
}
/**
* remove strings with n chars
*/
public static void removeWordsWithNChars(Iterable<String> container,
int nChars) {
Iterator<String> it = container.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.length() == nChars)
it.remove();
}
}
/**
* remove all strings
*/
public static void removeAll(Iterable<String> container) {
Iterator<String> it = container.iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
}
public static void main(String[] args) {
// Um ArrayList é um contentor dinâmico baseado num array
Iterable<String> itStrings = new ArrayList<String>(Arrays.asList("um",
"dois", "três", "quatro"));
// mostrar conteúdo
printIterable(itStrings);
// remover as String com size == 4
removeWordsWithNChars(itStrings, 4);
// mostrar o contentor sem essas strings
printIterable(itStrings);
// remover os restantes elementos
removeAll(itStrings);
// mostrar
printIterable(itStrings);
}
}
<file_sep>package classcode.p15Swing.p05listenersAndAdapters;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import classcode.p15Swing.p02buildedLayouts.CenterLayout;
import classcode.p15Swing.p02buildedLayouts.ProportionalLayout;
/**
* KeyListener: key Events, registo de uma acção no ActionMap associado às
* teclas, e apanhar os eventos no dispatcher
*
* @author <NAME>
*
*/
public class C6MyKeyListenerFrame extends JFrame {
private static final long serialVersionUID = 1L;
GridLayout gl = null;
JLabel label1 = null;
JButton button1 = null;
private final Color leftColor = new Color(120, 240, 140);
private final Color rightColor = new Color(120, 140, 240);
private JPanel buttonsPanel;
/**
* Este método cria toda a frame e coloca-a visível
*
*/
public void init() {
// set title
setTitle("...: My Mouse Motion Listener frame :...");
// set size
setSize(400, 200);
// set location
setLocationRelativeTo(null); // to center a frame
// set what happens when close button is pressed
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
ProportionalLayout cl = new ProportionalLayout(0.1f, 0.2f, 0.2f, 0.2f);
setLayout(cl);
// buttons Panel
JPanel panelAux = new JPanel(new CenterLayout());
buttonsPanel = new JPanel();
panelAux.add(buttonsPanel);
add(panelAux, ProportionalLayout.SOUTH);
// build JLabel
label1 = new JLabel("See events in console...");
label1.setHorizontalAlignment(SwingConstants.CENTER);
label1.setOpaque(true);
label1.setBackground(rightColor);
add(label1, ProportionalLayout.CENTER);
// button1
button1 = new JButton("Ckick here!!!");
MouseListener ml = new MouseListener() {
public void mouseClicked(MouseEvent e) {
System.out.print("Mouse clicked...");
int b = e.getButton();
switch (b) {
case MouseEvent.BUTTON1:
System.out.println(" left button...");
label1.setBackground(leftColor);
break;
case MouseEvent.BUTTON3:
System.out.println(" right button...");
label1.setBackground(rightColor);
break;
default:
System.out.println(" center button...");
// C1MyMouseListenerFrame.this.dispose(); // 118
}
}
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered...");
}
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited...");
}
public void mousePressed(MouseEvent e) {
System.out.println("Mouse pressed...");
}
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse released...");
}
};
button1.addMouseListener(ml);
buttonsPanel.add(button1);
JButton button2 = new JButton("Button of keys");
buttonsPanel.add(button2);
label1.addMouseListener(ml);
MouseWheelListener mwl = new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
System.out.println("mouseWheelMoved event...");
}
};
label1.addMouseWheelListener(mwl);
/**
* Uma forma de apanhar keys, registar uma ActionKey num componente
*
* criar uma acção para ser executada quando button1 receber F2
*/
Action doActionF2 = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
System.out.println("doActionF2...");
label1.setVisible(!label1.isVisible());
}
};
// registar a acção para quando button1 tiver o focus e for
// premido F2
button1.getInputMap().put(KeyStroke.getKeyStroke("F2"), "doActionF2");
button1.getActionMap().put("doActionF2", doActionF2);
/**
*
* outra forma de apanhar uma key num componente, registar um
* KeyListener
*
** registar um KeyListener no Button2
**/
KeyListener kl = new KeyListener() {
public void keyTyped(KeyEvent e) {
print(e, "typed");
}
public void keyPressed(KeyEvent e) {
print(e, "pressed");
}
public void keyReleased(KeyEvent e) {
print(e, "released");
}
private void print(KeyEvent e, String keyAction) {
System.out.println("button2 has focus: received key "
+ keyAction + " -> " + e.getKeyChar() + " "
+ e.getKeyCode());
System.out.println(e + " " + keyAction);
}
};
button2.addKeyListener(kl);
/**
*
* uma forma de apanhar keys em termos globais a uma aplicação
*
* Registar um KeyDispatcher, no FocusManager - um keyDispatcher é um
* componente que deve gerir o que fazer com as keys entregues à
* aplicação
*/
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
System.out.println("KD " + e);
if (e.getID() == KeyEvent.KEY_TYPED)
System.out.println("key typed on dispatcher-> "
+ e.getKeyChar());
if (e.getID() == KeyEvent.KEY_RELEASED)
System.out.println();
return false;
}
});
// puts the frame visible (is not visible at start)
setVisible(true);
}
/**
* Main
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
C6MyKeyListenerFrame myFrame = new C6MyKeyListenerFrame();
myFrame.init();
// life goes on
System.out.println("Frame created...");
}
});
System.out.println("End of main...");
}
}
<file_sep>package classcode.p14EDDLinkedLists.p3LinkedListWithIterator;
import java.util.*;
/**
* Lista que implementa a interface de Iterator. Mas com iterador modelado como
* uma classe. Permite obter vários iteradores.
*
* O controle das alterações pelos vários iteradores segue o modelo utilizado na
* plataforma Java. Ver código da classe java.util.LinkedList
*
* @author <NAME>
*
*/
public class C06StringLinkedListWithSelfIterator4<E> implements Iterable<E> {
private ListNode head;
private transient int modCount = 0;
public C06StringLinkedListWithSelfIterator4() {
head = null;
}
public void addANodeToStart(E addData) {
head = new ListNode(addData, head);
++modCount;
}
public void showList() {
ListNode position;
position = head;
while (position != null) {
System.out.println(position.data);
position = position.link;
}
}
/**
* Class LisNode
*
*/
private class ListNode {
private E data;
private ListNode link;
public ListNode(E newData, ListNode linkValue) {
data = newData;
link = linkValue;
}
}
/**
* Method of Iterable interface
*/
public Iterator<E> iterator() {
StringListIterator it = new StringListIterator();
return it;
}
/**
* Class StringListIterator
*
*/
public class StringListIterator implements Iterator<E> {
private ListNode current = null; // elemento corrente a ser devolvido
private ListNode previous = null; // follows current
private boolean nextCalled = false; // true if next has called
/**
* expectedModCount inicializado com o valor corrente de modCount -
* usado para verificar se houve alterações fora do iterador
*/
private int expectedModCount = modCount;
/**
* Returns the next element (String) in the list. Throws a
* NoSuchElementException if there is no next element to return.
*/
public E next() {
checkForConcurrentModifications();
if (head == null) {
throw new NoSuchElementException();
}
if (current == null && previous == null) {
// primeira vez que o next é chamado
current = head;
} else if (current != null && current.link != null) {
previous = current;
current = current.link;
} else {
throw new NoSuchElementException();
}
nextCalled = true;
return (current.data);
}
/**
* Removes the last element that was returned by next. Throws an
* IllegalStateException if the next method has not yet been called or
* if the remove method has already been called after the last call to
* the next method.
*/
public void remove() {
checkForConcurrentModifications();
if (nextCalled) {
if (previous != null) {
// remove on middle of list
previous.link = current.link;
current = previous;
} else {
// remove at head
head = current.link;
current = null;
}
nextCalled = false;
} else {
throw new IllegalStateException();
}
++modCount; // register an alteration
++expectedModCount;
}
/**
* Returns true if there is at least one more element for next to
* return. Otherwise, returns false.
*/
public boolean hasNext() {
// na plataforma não se executa esta verificação
checkForConcurrentModifications();
return (current != null ? current.link != null : previous == null
&& head != null);
}
/**
* Método que verifica se ocorreu modificações fora deste iterador
*
*/
private void checkForConcurrentModifications() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
}
}<file_sep>package oldClass.tp1;
import java.util.Scanner;
public class P02Ifs {
public static void main(String[] args) {
Scanner keyboard = new java.util.Scanner(System.in);
System.out.println("Insert 3 different numbers -> ");
int maior = keyboard.nextInt();
int meio = keyboard.nextInt();
int menor = keyboard.nextInt();
int aux;
if (maior < meio) {
aux = maior;
maior = meio;
meio = aux;
}
if (maior < menor) {
aux = maior;
maior = menor;
menor = aux;
}
if (meio < menor) {
aux = meio;
meio = menor;
menor = aux;
}
if (maior == meio || maior == menor || meio == menor) {
System.out.println("please, the numbers must be different");
} else {
System.out.println("the smallest number is " + menor
+ " the middle number is " + meio
+ " and the biggest number is " + maior);
;
}
keyboard.close();
}
}
<file_sep>package classcode.p10ExceptionHandling;
/**
* Agora o método DIVISAO tem de declarar que pode lançar a excepção Exception e
* o método METODO1 tem de declarar que pode lançar a a excepção
* NegativeValueException. Deste modo quem usar estes métodos sabe com o que
* pode esperar.
*
*/
public class C21Catch {
/**
* Método base
*/
public static int divisao(int dividendo, int divisor) {
// try {
if (divisor == 0)
throw new RuntimeException("Divisao por zero");
System.out.println("jhgjhhjjh");
// } catch (Exception e) {
// divisor = 1;
// }
int quociente = dividendo / divisor;
return quociente;
}
/**
* método que utiliza o método base
*/
public static int metodo1(int dividendo, int divisor) {
return divisao(dividendo, divisor);
}
/**
* main
*/
public static void main(String[] args) throws ClassNotFoundException {
try {
metodo1(10, 0);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
}
}<file_sep>package tps.tp1.pack2Ciclos;
import java.util.Scanner;
public class P01Multiplicador {
public static void main(String[] args) {
int num;
int nReps;
int resultado = 0;
String multiplicacao = null;
// boolean para possivel saida do ciclo do-while
boolean invalido = false;
// init scanner
Scanner keyboard = new Scanner(System.in);
/*
* Ciclo do-while: Pede ao utilizador que insira um número inteiro entre
* 0 e 20, e outro número inteiro entre 1 e 10, se os números inseridos
* não respeitarem alguma destas condições a variável invalido irá ficar
* a true e o ciclo não irá terminar, continuando a pedir os valores. Se
* o utilizador respeitar as condiçõe a variável invalido continuará a
* false terminando assim este ciclo for.
*/
do {
invalido = false;
System.out.println("Introduza um inteiro entre 0 e 20 -> ");
num = keyboard.nextInt();
System.out
.println("Introduza o número de repetições entre 1 e 10 -> ");
nReps = keyboard.nextInt();
if ((num < 1 || num > 20) || (nReps < 1 || nReps > 10)) {
System.out
.println("Erro!! Valores inválidos! Por favor introduza os valores de novo.");
invalido = true;
}
} while (invalido);
/*
* resultado inicialmente irá ser igual ao 1º número inserido pelo
* utilizador
*/
resultado = num;
// String multiplicação
multiplicacao = "" + num;
/*
* 2º Ciclo do-while: Atualiza as variáveis multiplicação, resultado e
* nReps até nReps ser igual a 1.
*/
do {
nReps--;
multiplicacao = multiplicacao + " x " + num;
resultado *= num;
} while (nReps != 1);
// Mensagem que irá aparecer na consola.
System.out.println("Resultado : " + multiplicacao + " = " + resultado);
keyboard.close();
}
}
<file_sep>package classcode.p14EDDLinkedLists.p6Maps;
import java.util.HashMap;
import java.util.Map;
public class C01MapTest {
public static void main(String[] args) {
// Map<Integer, Pessoa> map = new Hashtable<Integer, Pessoa>();
Map<Integer, Pessoa> map = new HashMap<Integer, Pessoa>();
Pessoa p1 = new Pessoa("José", 12345611);
Pessoa p2 = new Pessoa("Pedro", 564564566);
Pessoa p3 = new Pessoa("Marco", 745547457);
Pessoa p4 = new Pessoa("André", 46546);
map.put(p1.bi, p1);
map.put(p2.bi, p2);
map.put(p3.bi, p3);
map.put(p4.bi, p4);
map.put(8000, p4);
System.out.println("map.get(46546) -> " + map.get(46546));
System.out.println("map -> " + map);
// hash code test
String s = "a";
System.out.println("hashcode of " + s + " -> " + s.hashCode());
s = "aa";
System.out.println("hashcode of " + s + " -> " + s.hashCode());
}
}
class Pessoa implements Comparable<Pessoa> {
String name;
int bi;
public Pessoa(String name, int bi) {
this.name = name;
this.bi = bi;
}
public String toString() {
return name + " " + bi;
}
public int compareTo(Pessoa p) {
if (p == null)
throw new NullPointerException();
return name.compareTo(p.name);
}
}
<file_sep>package classcode.p10ExceptionHandling;
public class C12UseOfFinallyBlock {
public static void metodo1(int x) throws MyException {
try {
System.out.println("Do something...");
throw new MyException("Erro 1");
} catch (Exception e) {
System.out.println("Exception catched in m1 -> " + e.getMessage());
if (e != null)
throw new MyException("Erro 2");
// new NullPointerException("null");
} finally {
System.out.println("Finally in method 1");
}
}
public static void main(String[] args) throws MyException {
// metodo1(20);
try {
System.out.println("Olá");
// metodo1(20);
// throw new MyException("Erro 3"); // teste 1
// throw new NullPointerException("null"); // teste 2
return;
// } catch (MyException e) {
// System.out
// .println("Exception catched in main -> " + e.getMessage());
} finally {
System.out.println("Finally in main");
}
// System.out.println("End of main");
}
}
<file_sep>package oldClass.tp1;
import java.util.Scanner;
public class P04BaralhadorDeNomesVer1 {
public static void main(String[] args) {
Scanner keyboard = new java.util.Scanner(System.in);
/* <NAME> */
System.out.println("Insert 10 complete names til 120 chars each -> ");
System.out.println("Insert more than 5 names and write end to finish");
String[][] myArray = new String[10][];
String[] aux = new String[10];
// tabela2[0] = new int[10];
int arrayLength = 0;
boolean testName = false;
for (int i = 0; i < 10; i++) {
//String name = keyboard.next();
System.out.println("a");
if (keyboard.hasNext()) {
System.out.println("b\n");
String name = keyboard.next();
aux[i] = name;
arrayLength = i;
System.out.println(name);
} else {
testName = true;
i = 10;
}
// condicao para testar se o nome e valido
int nameLength = 0;
int moreThan4 = 0;
if (testName) {
for (int j = 0; j < arrayLength; j++) {
nameLength += aux[j].length();
if (aux[j].length() >= 4) {
moreThan4 += 1;
}
}
if ((nameLength) > 120 || (moreThan4 < 3)) {
System.out
.println("This name is not Valid! Will be discarted");
System.out.println("Insert again please");
i = -1;
}
testName = false;
}
}
System.out.println(arrayLength);
myArray[0] = new String[arrayLength];
for (int i = 0; i < arrayLength; i++) {
myArray[0][i] = aux[i];
}
for (int i = 0; i < myArray[0].length; i++) {
System.out.print(myArray[0][i] + " ");
}
keyboard.close();
}
}
<file_sep>package classcode.p01IntroJava;
/**
* String demo
*/
public class C09String {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("String demo program - this string is a string");
String str1 = "A Páscoa está próxima!!";
System.out.println("\nstr1 -> " + str1);
// length()
System.out.println("str1.length() -> " + str1.length());
// charAt(int index)
System.out.println("str1.charAt(4) -> " + str1.charAt(4));
// indexOf(char c)
System.out.println("str1.indexOf('a') -> " + str1.indexOf('a'));
// indexOf(char c)
System.out.println("str1.lastIndexOf('a') -> " + str1.lastIndexOf('a'));
// isEmpty()
System.out.println("str1.isEmpty() -> " + str1.isEmpty());
// toUpperCase()
System.out.println("str1.toUpperCase() -> " + str1.toUpperCase());
// subString(int beginIndex, int EndIndex)
String str2 = str1.substring(2, 2 + "Páscoa".length());
System.out
.println("str2 = str1.substring(2, 2 + \"Páscoa\".length()) -> "
+ str2);
// toLowerCase
System.out.println("str2.toLowerCase() -> " + str2.toLowerCase());
// Comparisons
boolean theyAreEquals = str2 == "Páscoa";
System.out.println("\nstr2 == \"Páscoa\" -> " + theyAreEquals);
theyAreEquals = str2.equals("Páscoa");
System.out.println("str2.equals(\"Páscoa\") -> " + theyAreEquals);
// read the documentation of compareTo
System.out.println("\"olá\".compareTo(\"Olá\") -> "
+ "olá".compareTo("Olá"));
System.out.println("\"olá\".compareToIgnoreCase(\"Olá\") -> "
+ "olá".compareToIgnoreCase("Olá"));
}
}
<file_sep>package classcode.p14EDDLinkedLists.p1LinkedList;
import java.util.Scanner;
public class C03StringLinkedListMenu {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
C02StringLinkedList theStringLinkedList = new C02StringLinkedList();
char opcao;
do {
System.out.print("\nLista -> ");
theStringLinkedList.showList();
System.out.println("Menu: ");
System.out.println("a : removeElement");
System.out.println("b : addANodeToHead");
System.out.println("c : deleteHeadNode");
System.out.println("d : addANodeToTail");
System.out.println("e : deleteTailNode");
System.out.println("f : showList");
System.out.println("g : getElementAt");
System.out.println("h : insertAt");
System.out.println("i : removeAt");
System.out.println("j : IndexOf");
System.out.println("x : terminar");
System.out.print(" -> ");
opcao = Character.toLowerCase(in.next().charAt(0));
switch (opcao) {
case 'a':
System.out.print("Introduza um String -> ");
String aux0 = in.next();
String retVal0 = theStringLinkedList.removeElement(aux0);
System.out.println("Foi devolvido o valor -> " + retVal0);
break;
case 'b':
System.out.print("Introduza um String -> ");
String aux1 = in.next();
theStringLinkedList.addANodeToHead(aux1);
break;
case 'c':
String retVal1 = theStringLinkedList.deleteHeadNode();
System.out.println("Foi devolvido o valor -> " + retVal1);
break;
case 'd':
System.out.print("Introduza um String -> ");
String aux2 = in.next();
theStringLinkedList.addANodeToTail(aux2);
break;
case 'e':
String retVal2 = theStringLinkedList.deleteTailNode();
System.out.println("Foi devolvido o valor -> " + retVal2);
break;
case 'f':
theStringLinkedList.showList();
break;
case 'g':
System.out.print("Introduza um int -> ");
int aux3 = in.nextInt();
String retVal3 = theStringLinkedList.getElementAt(aux3);
System.out.println("Foi devolvido o valor -> " + retVal3);
break;
case 'h':
System.out.print("Introduza um String -> ");
String aux4 = in.next();
System.out.print("Introduza um int -> ");
int aux5 = in.nextInt();
boolean retVal4 = theStringLinkedList.insertAt(aux4, aux5);
System.out.println("Foi devolvido o valor -> " + retVal4);
break;
case 'i':
System.out.print("Introduza um int -> ");
int aux6 = in.nextInt();
String retVal5 = theStringLinkedList.removeAt(aux6);
System.out.println("Foi devolvido o valor -> " + retVal5);
break;
case 'j':
System.out.print("Introduza um String -> ");
String aux7 = in.next();
int retVal6 = theStringLinkedList.IndexOf(aux7);
System.out.println("Foi devolvido o valor -> " + retVal6);
break;
case 'x':
break;
default:
System.out.println("opcao Inválida");
} // end switch
} while (opcao != 'x');
in.close();
} // end main
} // end
<file_sep>package oldClass.tp1;
import java.util.Scanner;
public class P03Ifs {
public static void main(String[] args) {
String yes = "yes";
Scanner keyboard = new java.util.Scanner(System.in);
System.out.println("think a letter between A and F, please awnser with yes or no ");
System.out.println("is the letter after C?");
if (keyboard.next().equals(yes)) {
System.out.println("is the letter before F?");
if (keyboard.next().equals(yes)) {
System.out.println("is the letter before E?");
if (keyboard.next().equals(yes)) {
System.out.println("is the letter before D?");
if (keyboard.next().equals(yes)) {
System.out.println("well done, the letter is C");
} else {
System.out.println("well done, the letter is D");
}
} else {
System.out.println("well done, the letter is E");
}
} else {
System.out.println("well done, the letter is F");
}
}
else {
System.out.println("the letter is B?");
if (keyboard.next().equals(yes)) {
System.out.println("well done, the letter is B");
} else {
System.out.println("well done, the letter is A");
}
}
keyboard.close();
}
}
<file_sep>package classcode.p07Inheritance.cenario2Figuras;
import java.awt.Color;
import java.awt.Graphics;
/**
* Class Elipse - suporta uma Elipse
*
*/
class C10Elipse extends C04Figura {
int eixoX, eixoY;
public C10Elipse(C02Ponto2D p1, int eixoX, int eixoY, Color color) {
super(new C02Ponto2D[] { p1.clone() }, color);
this.eixoX = eixoX;
this.eixoY = eixoY;
}
public String getNome() {
return "elipse";
}
public double getArea() {
return eixoX * eixoY * Math.PI;
}
@Override
public String toString() {
return super.toString() + " com eixos x,y de " + eixoX + "," + eixoY;
}
/**
* Draw the polygon into the graphics g
*/
public void paintComponent(Graphics g) {
g.setColor(color);
g.fillOval(getPonto(0).getX(), getPonto(0).getY(), eixoX, eixoY);
g.setColor(Color.black);
g.drawOval(getPonto(0).getX(), getPonto(0).getY(), eixoX, eixoY);
}
/**
*
*/
public static void main(String[] args) {
C10Elipse r1 = new C10Elipse(new C02Ponto2D(100, 100), 20, 30, Color.cyan);
System.out.println("r1 -> " + r1);
}
}<file_sep>package classcode.p09EnumeradosENestedClasses;
public class C04NestedClasses {
// variável static
static int x = 0;
static int x1 = 10;
// variável de instância
int n = 1;
CA ca;
CB cb;
// constructor
public C04NestedClasses(int n) {
// create a instance of the static nested class
ca = new CA();
ca.m1(3);
// create a instance of inner class
// this instance lives inside this instance of C1
// it can access its instance variables
cb = new CB();
cb.m1(n);
}
// static nested class
static class CA {
int x = 9;
void m1(int x) {
x = 20;
// access to x of CA
this.x = 3;
x1 = 20;
// access to x of C04
C04NestedClasses.x = 3;
// n = 4; // erro
}
public String toString() {
return "x = " + x;
}
}
// non-static nested class - a inner class
class CB {
int n = 0;
void m1(int n) {
x = 3;
// access to n of CB
this.n = n;
// access to n of C04
C04NestedClasses.this.n = n;
}
public String toString() {
return "n = " + n;
}
}
public String toString() {
return "static x = " + x + ", n = " + n + ", ca [ " + ca
+ " ], cb = [ " + cb + " ]";
}
/**
* @param args
*/
public static void main(String[] args) {
C04NestedClasses c1 = new C04NestedClasses(10);
System.out.println(c1);
}
}
<file_sep>package classcode.p08AbstractClassesAndInterfaces;
public abstract class C03ProdutoBase {
protected static String PREFIXBASE = " ";
private String name;
/**
* constructor
*/
public C03ProdutoBase(String name) {
this.name = name;
}
/**
* get name
*/
public String getName() {
return name;
}
/**
* get descricao
*/
public abstract String getDescricao();
/**
* get preco
*/
public abstract int getPreco();
/**
* get stock - deve devolver o número de unidades que se podem vender deste
* produto
*/
public abstract int getStock();
/**
* toString - deve devolver uma descrição sumária do produto
*/
public String toString() {
return getName() + ", " + getDescricao() + ", com preço de "
+ getPreco() + ", com stock de " + getStock();
}
}
<file_sep>package classcode.p02FlowDecisionsCycles;
import java.util.Scanner;
public class C03IfDemo3 {
public static void main(String[] args) {
// the keyboard reader
Scanner keyboard = new Scanner(System.in);
// ask and read an integer
System.out.print("Introduza um número inteiro positivo: ");
int num = keyboard.nextInt();
// if with other if inside - nested ifs
if (num >= 0) {
System.out.println("O número " + num + " é um número positivo");
System.out.print("O número " + num + " é um número ");
if (num % 2 == 0)
System.out.println("par");
else
System.out.println("impar");
}
// close the keyboard
keyboard.close();
}
}
<file_sep># MOP
Repository for MOP
<file_sep>package classcode.p08AbstractClassesAndInterfaces;
class C08BigNumber implements C06IWritable, C07IRelatable {
private String number;
/**
*
*/
public C08BigNumber(String number) {
if (!setValue(number))
throw new IllegalArgumentException("Número inválido -> " + number);
}
/**
*
*/
public boolean setValue(String n) {
if (n == null)
return false;
// clean starting and ending spaces
n = n.trim();
// check if only digits
if (!isValidNumber(n))
return false;
this.number = cleanLeftZeros(n);
return true;
}
/**
*
*/
public String getValue() {
return this.toString();
}
/**
*
*/
public String toString() {
return number;
}
/**
*
*/
public void writeOutput(String prefix) {
System.out.println(prefix + this);
}
/**
*
*/
private static boolean isValidNumber(String n) {
for (int i = 0; i < n.length(); i++)
if (!Character.isDigit(n.charAt(i)))
return false;
return true;
}
/**
*
*/
public boolean isEquals(C07IRelatable other) {
if (other == null)
return false;
String o = other.getValue();
if (!isValidNumber(o))
throw new IllegalArgumentException(
"O argumento recebido não contém um número válido -> " + o);
return number.equals(cleanLeftZeros(o));
}
/**
*
*/
private static String cleanLeftZeros(String num) {
int numberOfLeftZeros = 0;
for (int i = 0; i < num.length(); i++) {
if (num.charAt(i) == '0')
numberOfLeftZeros++;
else
break;
}
return num.substring(numberOfLeftZeros);
}
/**
*
*/
public boolean isBiggerThan(C07IRelatable other) {
if (other == null)
return false;
String o = other.getValue();
if (!isValidNumber(o))
throw new IllegalArgumentException(
"O argumento recebido não contém um número válido -> " + o);
o = cleanLeftZeros(o);
if (number.length() != o.length())
return number.length() > o.length();
for (int i = 0; i < number.length(); ++i)
if (number.charAt(i) != o.charAt(i))
return number.charAt(i) > o.charAt(i);
return false;
}
/**
*
*/
public boolean isSmallerThan(C07IRelatable other) {
return !isEquals(other) && !isBiggerThan(other);
}
/**
*
*/
public void add(C07IRelatable other) {
if (other == null)
throw new IllegalArgumentException("O argumento recebido é null");
String o = other.getValue();
if (!isValidNumber(o))
throw new IllegalArgumentException(
"O argumento recebido não contém um número válido -> "
+ other);
o = cleanLeftZeros(o);
// add
String result = "";
int toAdd = 0, n = 0;
for (int i = 0; true; i++) {
if (i >= number.length() && i >= o.length()) {
if (toAdd > 0)
result = toAdd + result;
break;
}
if (i < number.length() && i < o.length())
n = (int) number.charAt(number.length() - 1 - i) - '0'
+ (int) o.charAt(o.length() - 1 - i) - '0' + toAdd;
else if (i < number.length())
n = (int) number.charAt(number.length() - 1 - i) - '0' + toAdd;
else
n = (int) o.charAt(o.length() - 1 - i) - '0' + toAdd;
result = (char) ((n % 10) + '0') + result;
toAdd = n / 10;
}
number = result;
}
/**
* main
*/
public static void main(String[] args) {
C08BigNumber bn1 = new C08BigNumber("00072800000000000999999999");
System.out.println("bn1 -> " + bn1.toString());
C08BigNumber bn2 = new C08BigNumber("000000072800000000000999999999");
System.out.println("bn2 -> " + bn2.toString());
System.out.println("bn1.isEquals(bn2) -> " + bn1.isEquals(bn2));
System.out.println();
C08BigNumber bn3 = new C08BigNumber("0001111");
System.out.println("bn3 -> " + bn3.toString());
bn1.add(bn3);
System.out.println("bn1.add(bn3), bn1 -> " + bn1.toString());
System.out.println();
System.out.println("bn1 instanceof C08BigNumber -> "
+ (bn1 instanceof C08BigNumber));
System.out.println("bn1 instanceof C06IWritable -> "
+ (bn1 instanceof C06IWritable));
System.out.println("bn1 instanceof C07IRelatable -> "
+ (bn1 instanceof C07IRelatable));
System.out.println("bn1 instanceof Object -> "
+ (bn1 instanceof Object));
// System.out.println((int) '9' + (int) '2');
// char x1 = '9';
// char x2 = '2';
// System.out.println(x1 - '0');
}
}
<file_sep>package classcode.p04Arrays;
/**
* Teste aos arrays 2d utilizando métodos
*/
public class C03Array2DWithMethods {
/**
* @param args
*/
public static void main(String[] args) {
// tabela é um array de 10 posições de int[20]
int[][] tabela = new int[10][20];
// inicializar o array com valores aleatórios entre 0 e 99
System.out.println("Inicialização do array.....");
initRandomArray(tabela, 0, 91);
System.out.println();
// mostrar o array
System.out.println("Print do array.....");
printArray2d(tabela);
System.out.println();
// mostrar o array com os headers
int nDigist = howManyDigist(tabela);
System.out.println("Print do array com headers.....");
printArray2dWithHeaders(tabela, nDigist);
System.out.println();
// criar um novo array com soma de 10 nos seus elementos
System.out
.println("Obter um novo array com soma de 10 em cada elemento.....");
int[][] tabela2 = addValue(tabela, 10);
System.out.println();
System.out.println("Print do novo array.....");
nDigist = howManyDigist(tabela2);
printArray2dWithHeaders(tabela2, nDigist);
System.out.println("\nHow many digist -> " + howManyDigist(tabela2));
}
/**
* Inicializar o array com valores aleatórios entre lowerBound e upperBound
*/
public static void initRandomArray(int[][] array, int lowerBound,
int upperBound) {
for (int y = 0; y < array.length; y++) {
for (int x = 0; x < array[0].length; x++) {
// acesso para escrita
array[y][x] = (int) (Math.random() * (upperBound - lowerBound) + lowerBound);
}
}
}
/**
* Fazer print do array com um espaço entre os elementos
*/
public static void printArray2d(int[][] array) {
for (int y = 0; y < array.length; y++) {
for (int x = 0; x < array[0].length; x++) {
// print element
System.out.print(array[y][x] + " ");
}
// change line at the end of each row
System.out.println();
}
}
/**
* FAzer print do array colocando headers e ajustando cada elemento para o
* número de digitos recebido
*/
public static void printArray2dWithHeaders(int[][] array, int ndigist) {
// cosntruir a string de controlo do format
String str = "%0" + ndigist + "d ";
// colocar uma linha de cabeçalho
System.out.print("n coluna -> ");
for (int x = 0; x < array[0].length; x++) {
// System.out.print((x < 10 ? "0" + x : x) + " ");
System.out.format(str, x);
}
System.out.println();
for (int y = 0; y < array.length; y++) {
System.out.print("Linha " + y + " -> ");
for (int x = 0; x < array[0].length; x++) {
// escrever o elemento
System.out.format(str, array[y][x]);
}
// change line at the end of each row
System.out.println();
}
}
/**
* Devolve número de digitos necessário para descrever o valor máxim no
* array, assume que só há valores positivos
*/
private static int howManyDigist(int[][] array) {
int max = maxArray2d(array);
// positive digits
int nPosdigits = 1;
for (int m = max; m > 9; m /= 10)
nPosdigits++;
// return result
return nPosdigits;
}
/**
* Devolve o valor máximo existente no array
*/
public static int maxArray2d(int[][] array) {
int max = array[0][0];
for (int y = 0; y < array.length; y++) {
for (int x = 0; x < array[0].length; x++) {
if (array[y][x] > max)
max = array[y][x];
}
}
return max;
}
/**
* Criar um novo array idêntico ao recebido, mas adicionando value a todos
* os elementos
*
* @param array
* o array recebido
* @param value
* o valor a adicionar
* @return o novo array que é um cópia do array recebido, mas com value
* adicionado a todos os elementos
*/
public static int[][] addValue(int[][] array, int value) {
// criar o array base
int[][] array2 = new int[array.length][];
for (int i = 0; i < array.length; i++) {
// criar cada elemento da 2ª dimensão com o length correcto
array2[i] = new int[array[i].length];
for (int j = 0; j < array[i].length; j++) {
array2[i][j] = array[i][j] + value;
}
}
return array2;
}
}
<file_sep>package classcode.p02FlowDecisionsCycles;
import java.util.Scanner;
/**
* Do-While demo
*/
public class C12DoWhile {
/**
* @param args
*/
public static void main(String[] args) {
// the keyboard reader
Scanner keyboard = new Scanner(System.in);
// mensagem de título
System.out.println("Cálculo da média de números inteiros positivos...");
// variáveis necessárias
// para controlar o ciclo de leitura
boolean numeroNegativo = false;
// para conter o número de números lidos
int numerosLidos = 0;
// para conter a soma dos números lidos
int total = 0;
// ciclo de leitura
do {
// pedir e ler um número
System.out
.print("Introduza um número positivo (ou negativo para terminar) -> ");
int numero = keyboard.nextInt();
// se for negativo sinalizar que é para terminar o ciclo
if (numero < 0)
numeroNegativo = true;
else {
// se for positivo, incrementar o número de números lidos
++numerosLidos;
// adicioná-lo ao total
total += numero;
}
// continuar com o ciclo se não tiver sido encontrado um número
// negativo
} while (!numeroNegativo);
// mostrar os resultados
if (numerosLidos > 0) {
System.out.println("Foram introduzidos " + numerosLidos
+ " números.");
System.out.println("A sua média é -> " + total / numerosLidos);
} else
System.out
.println("Não é possível calcular a média de 0 números!!!");
// close the keyboard
keyboard.close();
}
}
<file_sep>package classcode.p01IntroJava;
import javax.swing.*;
/**
* Message dialog window
*/
public class G01MessageDialogWindow {
/**
* main method
*/
public static void main(String[] args) {
// message dialog with information message type and no title
JOptionPane.showMessageDialog(null, "Hello World!");
}
}
<file_sep>package classcode.p02FlowDecisionsCycles;
import java.util.Scanner;
public class C02IfDemo2 {
/**
* @param args
*/
public static void main(String[] args) {
// the keyboard reader
Scanner keyboard = new Scanner(System.in);
// ask and read an integer
System.out.print("Introduza um número inteiro: ");
int num = keyboard.nextInt();
// if without else part
if (num >= 0)
System.out.println("O número " + num + " é um número positivo");
// close the keyboard
keyboard.close();
}
}
<file_sep>package tps.tp1.pack1Decisoes;
import java.util.Scanner;
public class P02Ifs {
public static void main(String[] args) {
System.out.println("Insira 3 números inteiros:");
Scanner keyboard = new Scanner(System.in);
/*
* variável boolean input que irá verificar se foi inserido números
* inteiros
*/
boolean input = keyboard.hasNextInt();
/*
* inicialização das variáveis maior, meio e menor que iram tomar os
* valores dos três números inteiros introduzidos pelo utilizador. A
* variável maior irá tomar o valor do primeiro número inserido, a meio
* irá tomar o valor do segundo número e finalmente a menor irá ficar
* com o último valor inteiro inserido na consola. Inicialização da
* variável aux.
*/
int maior = keyboard.nextInt();
int meio = keyboard.nextInt();
int menor = keyboard.nextInt();
int aux;
/*
* Se houver input, ou seja, se este for true, irá avaliar analisar qual
* dos 3 números inseridos tem o valor maior, qual tem o menor valor e
* qual tem o valor do meio.
*/
if (input == true) {
/*
* Se o valor da variável maior for menor que o da variável meio
* então teremos que atualizar as variáveis trocando os valores para
* as variáveis corretas, ou seja, o valor da variável maior vai
* ficar na variável meio e o valor da variável meio vai ficar na
* variável maior. Para tal iremos utilizar uma variável auxiliar,
* aux, que irá guardar o valor da variável maior, enquanto que esta
* toma o valor da variável meio.
*/
if (maior < meio) {
aux = maior;
maior = meio;
meio = aux;
}
/*
* Se o valor da variável maior for menor que o da variável menor
* então teremos que atualizar as variáveis trocando os valores para
* as variáveis corretas, ou seja, o valor da variável maior vai
* ficar na variável menor e o valor da variável menor vai ficar na
* variável maior. Para tal iremos utilizar uma variável auxiliar,
* aux, que irá guardar o valor da variável maior, enquanto que esta
* toma o valor da variável menor.
*/
if (maior < menor) {
aux = maior;
maior = menor;
menor = aux;
}
/*
* Se o valor da variável meio for menor que o da variável menor
* então teremos que atualizar as variáveis trocando os valores para
* as variáveis corretas, ou seja, o valor da variável meio vai
* ficar na variável menor e o valor da variável menor vai ficar na
* variável meio. Para tal iremos utilizar uma variável auxiliar,
* aux, que irá guardar o valor da variável meio, enquanto que esta
* toma o valor da variável menor.
*/
if (meio < menor) {
aux = meio;
meio = menor;
menor = aux;
}
/*
* Se os três números forem iguais irá aparecer na consola essa
* informação.
*/
if (maior == meio && maior == menor && meio == menor) {
System.out.println("Os números são iguais");
}
/*
* Caso sejam diferentes irá aparecer na consola qual o número
* maior, qual o do meio, e qual o menor.
*/
else {
System.out.println("O menor valor é " + menor
+ ", o valor do meio é " + meio + " e o maior valor é "
+ maior);
}
}
keyboard.close();
}
}
<file_sep>package classcode.p12Generics;
import java.util.Arrays;
import java.util.Comparator;
public class C07GenericsWithWildcards {
/**
* More use cases of generics with wildcards
*/
public static void main(String[] args) {
// método: static Class<?> Class.forName(String className)
try {
// devolve um objecto que descreve a class indicada na string
Class<?> theClass = Class.forName("classcode.p12Generics.C01Box1");
// com esse objecto podemos perguntar-lhe pelo seu conteúdo
System.out.println("theClass.getName() -> " + theClass.getName());
System.out.println("theClass.getPackage() -> "
+ theClass.getPackage());
System.out.println("theClass.getSimpleName() -> "
+ theClass.getSimpleName());
System.out.println("theClass.getName() -> "
+ theClass.getSuperclass());
System.out.println("Class methods: "
+ Arrays.toString(theClass.getMethods()));
// esta funcionalidade que permite obter a descrição de uma classe
// designa-se de Reflection
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println();
// outro exemplo
// uso de:
// static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)
Dog[] arrayDogs = { new Dog("Biddu"), new Dog("Chispa"),
new Dog("Mogul"), new Dog("Zinga") };
System.out.println("arrayDogs -> " + Arrays.toString(arrayDogs));
int res = Arrays.binarySearch(arrayDogs, new Dog("Mogul"),
Pet.PetComparator.getcomparator());
System.out.println("binarySearch Dog(\"Mogul\") returned -> " + res);
}
}
class Pet {
private String name;
public Pet(String name) {
this.name = name;
}
public String getName() {
return name;
}
static class PetComparator implements Comparator<Pet> {
static Comparator<Pet> COMP = new PetComparator();
public int compare(Pet o1, Pet o2) {
return o1.name.compareTo(o2.name);
}
static public Comparator<Pet> getcomparator() {
return COMP;
};
}
public String toString() {
return getClass().getSimpleName() + " " + name;
}
}
class Dog extends Pet {
public Dog(String name) {
super(name);
}
}
<file_sep>package classcode.p02FlowDecisionsCycles;
import java.util.Scanner;
/**
* While demo
*/
public class C11While {
/**
* @param args
*/
public static void main(String[] args) {
// the keyboard reader
Scanner keyboard = new Scanner(System.in);
// ask the number of integers to read
System.out
.print("Introduza o número de números para calcular a média -> ");
int nNumbersToRead = keyboard.nextInt();
int nNumbersRead = 0;
int total = 0;
// read the numbers
while (nNumbersRead < nNumbersToRead) {
// ask and read one number
System.out.print("Introduza um inteiro -> ");
int value = keyboard.nextInt();
// count with it
++nNumbersRead;
// add it to total
total += value;
}
// check to see if it is possible to show the average
if (nNumbersToRead == 0)
System.out
.println("Não é possível calcular a média de 0 números!!!");
else
System.out.println("A média dos números é -> " + total
/ nNumbersToRead);
// close the keyboard
keyboard.close();
}
}
<file_sep>package classcode.p09EnumeradosENestedClasses;
/**
* Interface ICounter
*
*/
interface ICounter {
int next();
}
/**
*
*/
public class C05LocalInnerClass {
private int count = 0;
/**
* Method that defines an local inner class
*/
ICounter getCounter(final String name) {
// the local inner class:
class LocalCounter implements ICounter {
int localCounter = 0;
public LocalCounter() {
// Local inner class can have a constructor
System.out.println("LocalCounter()");
}
public int next() {
// Access local variable, it must be final
System.out.print(name);
// local counter;
localCounter++;
System.out.print("localCounter -> " + localCounter + " ");
// access class field, don't have to be final
return count++;
}
}
return new LocalCounter();
}
// Method with an anonymous inner class:
ICounter getCounter2(final String name) {
ICounter ic = new ICounter() {
int localCounter = 0;
// Anonymous inner class cannot have a named
// constructor, only an instance initializer:
{
System.out.println("Anonymous ICounter()");
}
public int next() {
// Access local final
System.out.print(name);
localCounter++;
System.out.print("localCounter -> " + localCounter + " ");
return count += 2;
}
};
return ic;
}
public static void main(String[] args) {
C05LocalInnerClass lic = new C05LocalInnerClass();
ICounter c1 = lic.getCounter("Local inner ");
ICounter c2 = lic.getCounter2("Anonymous inner ");
for (int i = 0; i < 5; i++)
System.out.println(c1.next());
for (int i = 0; i < 5; i++)
System.out.println(c2.next());
}
}
<file_sep>package classcode.p15Swing.p04SimpleSwingApps;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
/**
* Demonstra a utilização de BoxLayout.
*
*
* Um Box layout dispõe os componentes numa linha na horizontal (X_axis) ou na
* vertical (Y_axis), e essa linha pode estar em qualquer lado cima, baixo,
* lados,...
*
* @author <NAME>
*
*/
public class C5FrameWithBoxLayout extends JFrame {
private static final long serialVersionUID = -6678839556956235986L;
private JPanel buttonsPanel;
private JPanel boxesPanel;
private JButton buttonXaxis;
private JButton buttonYaxis;
private JButton buttonAlignLeft;
private JButton buttonAlignCenter;
private JButton buttonAlignRight;
private BoxLayout blXaxis;
private BoxLayout blYaxis;
private BoxLayout currentBoxlayout;
int nLabels = 10;
enum AlignType {
ALIGNX, ALIGNY;
}
AlignType currentAlign = AlignType.ALIGNY;
Random rg = new Random();
JLabel[] labels = new JLabel[nLabels];
private JPanel buttonsPanel1;
private JPanel buttonsPanel2;
private JButton buttonAlignRandom;
private JButton buttonAlignTop;
private JButton buttonAlignBottom;
public void init() {
// set title
setTitle("...: My box layout frame :...");
// set size
setSize(700, 300);
// set location
setLocationRelativeTo(null); // to center a frame
// hide and dispose jframe
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// build buttonsPanel
buttonsPanel = new JPanel();
buttonsPanel.setLayout(new GridLayout(2, 1));
add(buttonsPanel, BorderLayout.PAGE_END);
buttonsPanel1 = new JPanel();
buttonsPanel1.setLayout(new FlowLayout());
buttonsPanel.add(buttonsPanel1);
buttonsPanel2 = new JPanel();
buttonsPanel2.setLayout(new FlowLayout());
buttonsPanel.add(buttonsPanel2);
// build boxesPanel
boxesPanel = new JPanel();
boxesPanel.setBorder(new LineBorder(Color.gray));
blYaxis = new BoxLayout(boxesPanel, BoxLayout.Y_AXIS); // top to bottom
blXaxis = new BoxLayout(boxesPanel, BoxLayout.X_AXIS); // left to right
currentBoxlayout = blYaxis;
boxesPanel.setLayout(currentBoxlayout);
System.out.println("BoxLayout: AlignType -> ALIGNY");
add(boxesPanel, BorderLayout.CENTER);
// build JLabels
for (int x = 0; x < nLabels; ++x) {
JLabel label = labels[x] = new JLabel(" Label " + x + " ");
label.setOpaque(true);
label.setBackground(new Color(rg.nextInt(256), rg.nextInt(256), rg
.nextInt(256)));
label.setAlignmentX(Component.CENTER_ALIGNMENT);
label.setAlignmentY(Component.CENTER_ALIGNMENT); // com X_AXIS
boxesPanel.add(label);
}
// build buttonXaxis
buttonXaxis = new JButton("Box x_Axis");
buttonXaxis.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentAlign = AlignType.ALIGNX;
currentBoxlayout = blXaxis;
System.out.println("BoxLayout: AlignType -> ALIGNX");
boxesPanel.setLayout(currentBoxlayout);
// boxesPanel.doLayout();
boxesPanel.validate();
buttonYaxis.setEnabled(true);
buttonXaxis.setEnabled(false);
}
});
buttonsPanel1.add(buttonXaxis);
// build buttonYaxis
buttonYaxis = new JButton("Box y_Axis");
buttonYaxis.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentAlign = AlignType.ALIGNY;
currentBoxlayout = blYaxis;
System.out.println("BoxLayout: AlignType -> ALIGNY");
boxesPanel.setLayout(currentBoxlayout);
boxesPanel.validate();
buttonXaxis.setEnabled(true);
buttonYaxis.setEnabled(false);
}
});
buttonYaxis.setEnabled(false);
buttonsPanel1.add(buttonYaxis);
// build buttonAlignTop
buttonAlignTop = new JButton("Align Top");
buttonAlignTop.setActionCommand("ButtonTop");
buttonsPanel2.add(buttonAlignTop);
buttonAlignTop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlignOnLabels(currentAlign, Component.TOP_ALIGNMENT);
}
});
// build buttonAlignLeft
buttonAlignLeft = new JButton("Align Left");
buttonAlignLeft.setActionCommand("ButtonLeft");
buttonsPanel2.add(buttonAlignLeft);
buttonAlignLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlignOnLabels(currentAlign, Component.LEFT_ALIGNMENT);
}
});
// build buttonAlignCenter
buttonAlignCenter = new JButton("Align Center");
buttonAlignCenter.setActionCommand("ButtonCenter");
buttonsPanel2.add(buttonAlignCenter);
buttonAlignCenter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlignOnLabels(currentAlign, Component.CENTER_ALIGNMENT);
}
});
// build buttonAlignRandom
buttonAlignRandom = new JButton("Align Random");
buttonAlignRandom.setActionCommand("ButtonRandom");
buttonsPanel2.add(buttonAlignRandom);
buttonAlignRandom.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlignOnLabels(currentAlign, -1.0f);
}
});
// build buttonAlignLast
buttonAlignRight = new JButton("Align Right");
buttonAlignRight.setActionCommand("ButtonRight");
buttonsPanel2.add(buttonAlignRight);
buttonAlignRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlignOnLabels(currentAlign, Component.RIGHT_ALIGNMENT);
}
});
// build buttonAlignBottom
buttonAlignBottom = new JButton("Align Bottom");
buttonAlignBottom.setActionCommand("ButtonBottom");
buttonsPanel2.add(buttonAlignBottom);
buttonAlignBottom.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlignOnLabels(currentAlign, Component.BOTTOM_ALIGNMENT);
}
});
// puts the frame visible (is not visible at start)
setVisible(true);
// life goes on
System.out.println("Frame created...");
}
void setAlignOnLabels(AlignType align, float aligment) {
for (int i = 0; i < nLabels; ++i) {
if (align == AlignType.ALIGNX)
labels[i].setAlignmentY(aligment != -1.0f ? aligment : rg
.nextFloat());
else
labels[i].setAlignmentX(aligment != -1.0f ? aligment : rg
.nextFloat());
labels[i].revalidate();
}
}
/**
* Main
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
C5FrameWithBoxLayout frame = new C5FrameWithBoxLayout();
frame.init();
}
});
System.out.println("End of main...");
}
}
<file_sep>package classcode.p06ClassesAndObjects;
/**
*
*/
class Pessoa {
String nome;
int numTelefone;
String morada;
Requisicao[] requisicoes = new Requisicao[1000];
int nRequisicoes = 0;
Ocorrencia[] ocorrencias = new Ocorrencia[1000];
int nOcorrencias = 0;
public Pessoa(String nome, int numTelefone, String morada) {
this.nome = nome;
this.numTelefone = numTelefone;
this.morada = morada;
}
public int getNumTelefone() {
return numTelefone;
}
public void setNumTelefone(int numTelefone) {
this.numTelefone = numTelefone;
}
public String getMorada() {
return morada;
}
public void setMorada(String morada) {
this.morada = morada;
}
public String getNome() {
return nome;
}
public Requisicao[] getRequisicoes() {
return requisicoes;
}
public Ocorrencia[] getOcorrencias() {
return ocorrencias;
}
public boolean addRequisicao(Requisicao r) {
// verificar se há espaço
if (nRequisicoes == requisicoes.length)
return false;
// inserir
requisicoes[nRequisicoes++] = r;
return true;
}
public String toString() {
return getNome() + ", telefone " + getNumTelefone() + ", morada "
+ getMorada();
}
}<file_sep>package classcode.p11StreamsAndFileIO;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Teste ao método printf de PrintWriter
*
*/
public class C04Printf {
public static void main(String[] args) throws IOException {
// printf("%?", val) - o % indica que se segue na string a mostrar um
// argumento que deve ser interpretado com a formatação indicada: d -
// inteiro, x - inteiro em hexadecimal, c - caracter, s - string, b -
// binário, f - float/double, n - imprime '%'. Ver
// "Format string syntax" do help de printf. Pode-se indicar a dimensão
// do campo a escrever, alinhamento à esquerda ou direita, etc.
System.out.println("Execução...");
// PrintWriter pw = new PrintWriter(System.out);
PrintWriter pw = new PrintWriter("f.txt");
// uma string de controlo, simples, só com %n que é o fim de linha
pw.printf("Segunda-feira, dia 13 de Maio de 2013%n");
// uma string de controlo com argumentos de: string, int, string, int
int dia = 13, ano = 2013;
String diaSemana = "Segunda-feira", mes = "Maio";
pw.printf("%s, dia %d de %s de %d%n", diaSemana, dia, mes, ano);
// uma string de controlo com um argumento boolean
boolean isDomingo = false;
pw.printf("Hoje é domingo -> %b%n", isDomingo);
// escrita de um float e de um double
float f = 2.3f;
pw.printf("float f -> %f%n", f);
double d = 4.04;
pw.printf("double d -> %f%n", d);
// formatações
// dimensão do campo, alinhamentos, preenchimento das casas à esquerda,
// com sinal
int dim = 100;
pw.printf("Inteiros -> %6d, %06d, %1$-6d, %+d%n", dim, dim, -dim);
// formatações com números decimais: dimensão total, nº casa decimais
pw.printf("Double 5.1 -> %05.1f%n", d);
pw.printf("Double 5.1 -> %05.1f%n", 10000 * d);
// escrita de uma string com definição dinâmica
dim = 5;
String formatString = "Inteiros -> %0" + dim + "d, %0" + 2 * dim + "d ";
pw.printf(formatString, 100, 200);
pw.close();
}
}
<file_sep>package classcode.p10ExceptionHandling;
import java.util.Scanner;
/**
* Apanhar também as excepções de input. Colocar no input a letra: A
*
*/
public class C04AnotherException {
/**
* main
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Realizacao da operacao de divisao...");
try {
System.out.print("Introduza o dividendo -> ");
input.close();
int dividendo = input.nextInt();
System.out.print("Introduza o divisor -> ");
int divisor = input.nextInt();
// realizar a processamento
int quociente = dividendo / divisor;
// mostrar resultado
System.out.println("Divisao de " + dividendo + " por " + divisor
+ " -> " + quociente);
} catch (Exception e) {
// getSimpleName devolve só o nome da classe
System.err.println("Ocorreu a excepção: "
+ e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
// e como diferenciar as excepções ocorridas?
}
<file_sep>package classcode.p13EDD;
import java.io.Serializable;
public class C09Serializable implements Serializable {
// private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 7707200347726565875L;
// só para mostrar que se deve declarar o serialversionUID
// como em MoP não vamos utilizar a serialização este atributo pode ter um
// valor qualquer, inclusive 1 ou mesmo 0
}
<file_sep>package classcode.p02FlowDecisionsCycles;
import java.util.Scanner;
public class C01IfDemo1 {
public static void main(String[] args) {
// the keyboard reader
Scanner keyboard = new Scanner(System.in);
// ask and read an integer
System.out.print("Introduza um número inteiro: ");
int num = keyboard.nextInt();
// print if it is positive or negative
if (num >= 0)
System.out.println("O número " + num + " é um número positivo");
else
System.out.println("O número " + num + " é um número negativo");
// close the keyboard
keyboard.close();
}
}
<file_sep>package classcode.p15Swing.p04SimpleSwingApps;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
/**
* Calculator with RadioButtons
*
* Novos componentes: JRadionButton, ButtonGroup
*
* Os radioButtons permitem ser seleccionados e desseleccionados. O ButtonGroup
* gere o seu grupo de botões tal que quando se selecciona um elemento do grupo
* o buttonGroup des-selecciona automáticamente o que estava seleccionado
*
* @author <NAME>
*
*/
public class C2CalculatorWithRadioButtons extends JFrame {
private static final long serialVersionUID = 1L;
private FlowLayout layout = null;
private JLabel label1 = null;
private JButton buttonDo = null;
private JLabel label2 = null;
private JTextField text1 = null;
private JTextField text2 = null;
private JTextField textResult = null;
private JLabel labelResult = null;
private JRadioButton addButton = null;;
private JRadioButton subButton = null;
/**
* Este método cria toda a frame e coloca-a visível
*
*/
public void init() {
// set title
setTitle("...: My calculator with radio buttons :...");
// set what happens when close button is pressed
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
layout = new FlowLayout();
getContentPane().setLayout(layout);
// label1 - oper1
label1 = new JLabel("Value1 :");
label1.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add(label1);
// text1 - oper1
text1 = new JTextField("1000", 10);
getContentPane().add(text1);
// the radio buttons
addButton = new JRadioButton("add");
addButton.setActionCommand("add");
addButton.setBackground(Color.green);
addButton.setOpaque(true);
subButton = new JRadioButton("sub");
subButton.setActionCommand("sub");
subButton.setSelected(true);
// panel for the rbuttons
JPanel buttonsPanel = new JPanel(new GridLayout(2, 1));
buttonsPanel.setBorder(new LineBorder(new Color(30, 150, 100), 2));
// Group the radio buttons
ButtonGroup group = new ButtonGroup();
group.add(addButton); // TODO teste, comentar estas duas linhas
group.add(subButton); // TODO teste, comentar estas duas linhas
// add the radioButtons to the panel
buttonsPanel.add(addButton);
buttonsPanel.add(subButton);
getContentPane().add(buttonsPanel);
// label2 - oper2
label2 = new JLabel("Value2 :");
label2.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add(label2);
// text2 - JTextField oper2
text2 = new JTextField("200", 10);
getContentPane().add(text2);
// buttonDo
buttonDo = new JButton(" = ");
getContentPane().add(buttonDo);
// labelResult
labelResult = new JLabel("Result :");
labelResult.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add(labelResult);
// textResult
textResult = new JTextField(10);
getContentPane().add(textResult);
textResult.setEditable(false);
// adjust size to minimum as needed
pack();
// set location
setLocationRelativeTo(null); // to center a frame
// disable resize
setResizable(false);
// set dynamic behavior
// Listener of button execute
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Scanner sc1 = new Scanner(text1.getText());
Scanner sc2 = new Scanner(text2.getText());
if (sc1.hasNextInt() && sc2.hasNextInt()) {
int oper1 = sc1.nextInt();
int oper2 = sc2.nextInt();
int result = 0;
// test radio buttons
if (addButton.isSelected()) {
result = oper1 + oper2;
} else {
result = oper1 - oper2;
}
textResult.setText(Integer.toString(result));
} else {
textResult.setText("Invalid input values!");
}
sc1.close();
sc2.close();
}
};
buttonDo.addActionListener(al);
// TODO teste, descomentar a seguinte linha
addButton.addActionListener(al);
// puts the frame visible and working
setVisible(true);
}
/**
* Main
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
C2CalculatorWithRadioButtons myFrame = new C2CalculatorWithRadioButtons();
myFrame.init();
// life goes on
System.out.println("Frame created...");
}
});
System.out.println("End of main...");
}
}
<file_sep>package classcode.p11StreamsAndFileIO;
import java.io.IOException;
/**
* Mostra na consola o print dos caracteres de 00 a FF
*
*/
public class C01WriteChars {
public static void main(String[] args) throws IOException {
/*
* printf("%?", val) - o % indica que se segue na string a mostrar um
* argumento que deve ser interpretado com a formatação indicada: d -
* inteiro, x - inteiro em hexadecimal, c - caracter, s - string, b -
* binário, f - float, n - imprime '%'. Ver "Format string syntax" do
* help de printf. Pode-se indicar a dimensão do campo a escrever,
* alinhamento à esquerda ou direita, etc.
*/
// Mostrar tabela
System.out.print(" ");
for (int j = 0; j < 16; j++) {
System.out.printf("%X", j) /* ff */;/* dd*/
}
System.out.println();
for (int i = 0; i < 16; i++) { // 16 colunas
System.out.printf("%X ", i);
for (int j = 0; j < 16; j++) { // 16 linhas
if (j < 2)
System.out.print(".");
else
System.out.print((char) (i + j * 16)); // i + j * 16
}
System.out.println();
}
System.out.println();
// agora no outro sentido
System.out.print(" ");
for (int j = 0; j < 16; j++) {
System.out.printf("%X", j);
}
System.out.println();
for (int i = 0; i < 16; i++) {
System.out.printf("%X ", i);
for (int j = 0; j < 16; j++){if(i<2)
System.out.print(".");
else
System.out.print((char) (i * 16 + j));
}
System.out.println();
}
System.out.close();
// int x=0;if(true)if(true){if(true)
// {}if(true);if(true){if(true)
// if
// (true);}
// }
}
}
<file_sep>package classcode.p10ExceptionHandling;
import java.util.Scanner;
/**
* Agora com o lançamento da excepção (de Runtime) dentro de um método e
*
*/
public class C10HandleExceptionsOutsideTheMethod1 {
/**
* Método base
*/
public static int divisao(int dividendo, int divisor) {
if (divisor == 0) {
throw new ArithmeticException("Divisao por zero");
}
int quociente = dividendo / divisor;
return quociente;
}
/**
* método que utiliza o método base
*/
public static int metodo1(int dividendo, int divisor) {
return divisao(dividendo, divisor);
}
/**
* main
*/
public static void main(String[] args) throws ClassNotFoundException {
//metodo1(10, 0);
Scanner keyboard = new Scanner(System.in);
System.out.println("Realizacao da operacao de divisao...");
try {
System.out.print("Introduza o dividendo -> ");
int dividendo = keyboard.nextInt();
System.out.print("Introduza o divisor -> ");
int divisor = keyboard.nextInt();
// realizar a processamento
int quociente = metodo1(dividendo, divisor);
// mostrar resultado
System.out.println("Divisao de " + dividendo + " por " + divisor
+ " -> " + quociente);
} catch (ArithmeticException e) {
System.out.println("Ocorreu a excepcao: "
+ e.getClass().getSimpleName() + ": " + e.getMessage());
}
keyboard.close();
}
// e se for uma excepção que não seja de runtime??
// por exemplo uma excepção Exception???
}
<file_sep>package classcode.p15Swing.p06moreStuff;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;
import classcode.p15Swing.p02buildedLayouts.ProportionalLayout;
/**
* Novidades: JMenu, JMenuItem, setMnemonic, Accelerator e etc
*
* @author <NAME>
*
*/
public class C5MyMenuFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel label1 = null;
private JButton buttonStart = null;
private JButton buttonStop = null;
JPanel panel = null;
JCheckBox repeatCheckBox = null;
private Timer timer = null;
private final Color greenColor = new Color(0, 200, 0);
private final Color redColor = Color.RED;
private int n = 0;
private JRadioButtonMenuItem rbMenuRedColor;
private JRadioButtonMenuItem rbMenuGreenColor;
private JMenu submenuTimerControl;
private JCheckBoxMenuItem cbMenuEnableColorChange;
private JCheckBoxMenuItem cbMenuEnableTimerControl;
private JMenuItem menuStartTimer;
private JMenuItem menuStopTimer;
private JMenuBar menuBar;
private JMenuItem rbMenuRedColorMenuItem;
private JMenuItem rbMenuGreenColorMenuItem;
private String buildLabelText() {
return "Timer fired " + n + " times";
}
/**
* Este método cria toda a frame e coloca-a visível
*
*/
public void init() {
// set title
setTitle("...: My Menu Timer frame :...");
// set size
setSize(400, 200);
// set location
setLocationRelativeTo(null); // to center a frame
// set what happens when close button is pressed
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// build JLabel
label1 = new JLabel(buildLabelText());
label1.setHorizontalAlignment(SwingConstants.CENTER);
label1.setOpaque(true);
label1.setBackground(greenColor);
// add JLabel at center
JPanel jpCenter = new JPanel();
ProportionalLayout cl = new ProportionalLayout(0.0f);
cl.setInsets(0.1f, 0.05f, 0.05f, 0.05f);
jpCenter.setLayout(cl);
jpCenter.add(label1, ProportionalLayout.CENTER);
add(jpCenter, BorderLayout.CENTER);
// programação do timer
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent e) {
++n;
label1.setText(buildLabelText());
if (!timer.isRepeats()) {
// must reverse buttons state (start -> on, stop -> off)
stopTimerActions();
}
}
};
int delay = 1000; // milliseconds, start time and period
timer = new Timer(delay, taskPerformer);
// Painel dos botões
panel = new JPanel(); // Janel default layout -> FlowLayout
TitledBorder tb = new TitledBorder("Control panel");
tb.setTitleJustification(TitledBorder.CENTER);
panel.setBorder(tb);
// Checkbox para indicar se o timer é cíclico ou não
repeatCheckBox = new JCheckBox("Cyclic timer", false);
panel.add(repeatCheckBox);
// buttonStart
buttonStart = new JButton("Start timer");
buttonStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startTimerActions();
timer.start();
}
});
panel.add(buttonStart);
// buttonStop
buttonStop = new JButton("Stop timer");
buttonStop.setEnabled(false);
buttonStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.stop();
stopTimerActions();
}
});
panel.add(buttonStop);
// adicionar o painel do botões à frame principal
add(panel, BorderLayout.PAGE_END);
// build menu
buildMenu();
// puts the frame visible (is not visible at start)
setVisible(true);
}
private void startTimerActions() {
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
timer.setRepeats(repeatCheckBox.isSelected());
menuStartTimer.setEnabled(false);
menuStopTimer.setEnabled(true);
}
private void stopTimerActions() {
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
menuStartTimer.setEnabled(true);
menuStopTimer.setEnabled(false);
}
private void buildMenu() {
JMenu menu;
JMenuItem menuItem;
ActionListener al = null;
// Menu Action Listener
al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JMenuItem mi = (JMenuItem) (e.getSource());
String menuItemText = mi.getText();
System.out.println("Menu item click -> " + menuItemText + " - "
+ e.getSource().getClass().getSimpleName() + ", id -> "
+ e.getID());
if (menuItemText.equals("Start timer")) {
startTimerActions();
timer.start();
}
if (menuItemText.equals("Stop timer")) {
timer.stop();
stopTimerActions();
}
if (menuItemText.equals("Red center Label")) {
System.out.println("Red center Label event .......");
label1.setBackground(redColor);
}
if (menuItemText.equals("Green center label")) {
label1.setBackground(greenColor);
}
if (menuItemText.equals("Enable color change")) {
boolean enable = ((JCheckBoxMenuItem) mi).isSelected();
rbMenuRedColor.setEnabled(enable);
rbMenuGreenColor.setEnabled(enable);
}
if (menuItemText.equals("Enable timer control")) {
boolean enable = ((JCheckBoxMenuItem) mi).isSelected();
submenuTimerControl.setEnabled(enable);
}
if (menuItemText.equals("Reset counter")) {
n = 0;
label1.setText(buildLabelText());
}
if (menuItemText.equals("Set Red menu item")) {
System.out.println("Set Red menu item");
// ver e.gedID
ActionEvent ae = new ActionEvent(rbMenuRedColor, 1001, "");
actionPerformed(ae);
}
if (menuItemText.equals("Set Green menu item")) {
System.out.println("Set Green menu item");
ActionEvent ae = new ActionEvent(rbMenuGreenColor, 1001, "");
actionPerformed(ae);
}
System.out.println("menu event");
}
};
// Create the menu bar.
menuBar = new JMenuBar();
// Build the first menu.
menu = new JMenu("Actions");
menu.setMnemonic(KeyEvent.VK_A);
menuBar.add(menu);
// a group of JMenuItems
menuItem = new JMenuItem("Reset counter", KeyEvent.VK_E);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1,
ActionEvent.ALT_MASK));
menuItem.addActionListener(al);
menu.add(menuItem);
menu.addSeparator();
// a group of radio button menu items
ButtonGroup group = new ButtonGroup();
rbMenuRedColor = new JRadioButtonMenuItem("Red center Label");
rbMenuRedColor.setMnemonic(KeyEvent.VK_R);
rbMenuRedColor.addActionListener(al);
group.add(rbMenuRedColor);
menu.add(rbMenuRedColor);
rbMenuGreenColor = new JRadioButtonMenuItem("Green center label");
rbMenuGreenColor.setSelected(true);
rbMenuGreenColor.setMnemonic(KeyEvent.VK_G);
rbMenuGreenColor.addActionListener(al);
group.add(rbMenuGreenColor);
menu.add(rbMenuGreenColor);
// a group of check box menu items
menu.addSeparator();
cbMenuEnableColorChange = new JCheckBoxMenuItem("Enable color change");
cbMenuEnableColorChange.setSelected(true);
cbMenuEnableColorChange.setMnemonic(KeyEvent.VK_C);
cbMenuEnableColorChange.addActionListener(al);
menu.add(cbMenuEnableColorChange);
cbMenuEnableTimerControl = new JCheckBoxMenuItem("Enable timer control");
cbMenuEnableTimerControl.setSelected(true);
cbMenuEnableTimerControl.setMnemonic(KeyEvent.VK_T);
cbMenuEnableTimerControl.addActionListener(al);
menu.add(cbMenuEnableTimerControl);
// a submenu
menu.addSeparator();
submenuTimerControl = new JMenu("Timer control");
submenuTimerControl.setMnemonic(KeyEvent.VK_L);
menuStartTimer = new JMenuItem("Start timer");
menuStartTimer.setMnemonic(KeyEvent.VK_A);
menuStartTimer.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,
ActionEvent.ALT_MASK));
menuStartTimer.addActionListener(al);
submenuTimerControl.add(menuStartTimer);
menuStopTimer = new JMenuItem("Stop timer");
menuStopTimer.setMnemonic(KeyEvent.VK_O);
menuStopTimer.setEnabled(false);
menuStopTimer.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3,
ActionEvent.ALT_MASK));
menuStopTimer.addActionListener(al);
submenuTimerControl.add(menuStopTimer);
menu.add(submenuTimerControl);
// Build second menu in the menu bar.
menu = new JMenu("Menu2");
menu.setMnemonic(KeyEvent.VK_M);
menuBar.add(menu);
rbMenuRedColorMenuItem = new JMenuItem("Set Red menu item");
rbMenuRedColorMenuItem.setMnemonic(KeyEvent.VK_R);
rbMenuRedColorMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_R, ActionEvent.ALT_MASK));
menu.add(rbMenuRedColorMenuItem);
rbMenuRedColorMenuItem.addActionListener(al);
rbMenuGreenColorMenuItem = new JMenuItem("Set Green menu item");
rbMenuGreenColorMenuItem.setMnemonic(KeyEvent.VK_G);
rbMenuGreenColorMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_G, ActionEvent.ALT_MASK));
menu.add(rbMenuGreenColorMenuItem);
rbMenuGreenColorMenuItem.addActionListener(al);
// set Menu Bar on JFrame
setJMenuBar(menuBar);
}
/**
* Main
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
C5MyMenuFrame myFrame = new C5MyMenuFrame();
myFrame.init();
// life goes on
System.out.println("Frame created...");
}
});
System.out.println("End of main...");
}
}
<file_sep>package classcode.p15Swing.p04SimpleSwingApps;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.TitledBorder;
/**
* Assuntos: os vários Borders
*
*
* Um bom conjunto de exemplos de Border:
* http://www.java2s.com/Code/Java/Swing-JFC/Border.htm
*
* @author <NAME>
*
*/
public class C6SomeBorders {
/**
* Main
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
System.out.println("End of main...");
}
/**
* Create and Show GUI
*/
public static void createAndShowGUI() {
// create a JFrame
JFrame frame = new JFrame();
// set title
frame.setTitle("...: My borders frame :...");
// set size and location
frame.setSize(600, 400);
// to center a frame
frame.setLocationRelativeTo(null);
// set default close operation
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
final int nBorders = 9;
// build gridLayout
GridLayout gl = new GridLayout(nBorders, 1);
frame.getContentPane().setLayout(gl);
// set content pane background color
frame.getContentPane().setBackground(new Color(200, 150, 200));
JPanel[] panels = new JPanel[nBorders];
JLabel[] labels = new JLabel[nBorders];
// criar Jpanels, JLabels e
for (int y = 0; y < nBorders; ++y) {
panels[y] = new JPanel(new BorderLayout());
labels[y] = new JLabel(" ---- ");
labels[y].setHorizontalAlignment(SwingConstants.CENTER);
labels[y].setOpaque(true);
labels[y].setBackground(new Color(100, 150, 150));
panels[y].add(labels[y]);
frame.getContentPane().add(panels[y]);
}
gl.setVgap(5);
// Line border
panels[0].setBorder(new LineBorder(Color.ORANGE, 4));
labels[0].setText("Line border");
// Titled border
panels[1].setBorder(new TitledBorder("title"));
panels[1].setBorder(new TitledBorder(new LineBorder(Color.ORANGE, 4),
"title"));
labels[1].setText("Titled border");
// Empty border
panels[2].setBorder(new EmptyBorder(0, 0, 10, 10));
labels[2].setText("Empty border");
// Bevel border
panels[3].setBorder(new BevelBorder(BevelBorder.RAISED));
labels[3].setText("Bevel border");
// Soft Bevel border
panels[4].setBorder(new SoftBevelBorder(BevelBorder.RAISED));
labels[4].setText("Soft Bevel border");
// Etched border
panels[5].setBorder(new EtchedBorder());
labels[5].setText("Etched border");
// Matte border
panels[6].setBorder(new MatteBorder(0, 0, 10, 10, Color.blue));
labels[6].setText("Matte border");
// Compound border
Border lineBorder = LineBorder.createBlackLineBorder();
Border bevelBorder = BorderFactory.createRaisedBevelBorder();
panels[7].setBorder(new CompoundBorder(bevelBorder, lineBorder));
labels[7].setText("Compound border");
Border bevelBorder2 = BorderFactory.createLoweredBevelBorder();
panels[8].setBorder(new CompoundBorder(bevelBorder, bevelBorder2));
labels[8].setText("Compound2 border");
// puts the frame visible (is not visible at start)
frame.setVisible(true);
// life goes on
System.out.println("Frame created...");
}
}
<file_sep>package classcode.p13EDD;
import java.util.Arrays;
import java.util.Iterator;
/**
* Exemplo do for-each
*/
public class C04ForEach {
public static void printIterable(Iterable<String> container) {
System.out.print("[");
boolean first = true;
for (String str : container) {
if (first)
first = false;
else
System.out.print(", ");
System.out.print(str);
}
System.out.println("]");
}
// uma segunda versão que pode receber um qualquer tipo
public static <T> void printIterable2(Iterable<T> container) {
System.out.print("[");
boolean first = true;
for (T str : container) {
if (first)
first = false;
else
System.out.print(", ");
System.out.print(str);
}
System.out.println("]");
}
// uma segunda versão que pode receber um qualquer tipo
public static <T> void printIterable3(Iterable<T> container) {
System.out.print("[");
boolean first = true;
for (Iterator<T> it = container.iterator(); it.hasNext();) {
T str = it.next();
if (first)
first = false;
else
System.out.print(", ");
System.out.print(str);
}
System.out.println("]");
}
/**
* main
*/
public static void main(String[] args) {
Iterable<String> it = Arrays.asList("um", "dois", "três", "quatro");
printIterable(it);
// printIterable2
System.out.println("printIterable2");
printIterable2(it);
printIterable2(Arrays.asList(10, 20, 30));
// printIterable(Arrays.asList(10, 20, 30));
printIterable3(Arrays.asList(10, 20, 30));
}
}
class Funcionario {
}
class Especialista extends Funcionario {
}
<file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_20) on Tue Apr 21 10:32:28 BST 2015 -->
<title>PercursoComposto</title>
<meta name="date" content="2015-04-21">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="PercursoComposto";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":10,"i10":9,"i11":10,"i12":10,"i13":10,"i14":10,"i15":10};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../tps/tp2/pack2Percursos/package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/PercursoComposto.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?tps/tp2/pack2Percursos/PercursoComposto.html" target="_top">Frames</a></li>
<li><a href="PercursoComposto.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">tps.tp2.pack2Percursos</div>
<h2 title="Class PercursoComposto" class="title">Class PercursoComposto</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">java.lang.Object</a></li>
<li>
<ul class="inheritance">
<li>tps.tp2.pack2Percursos.PercursoComposto</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">PercursoComposto</span>
extends <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></pre>
<div class="block">Classe que suporta um percurso composto por vários percursos simples</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>private <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#nome">nome</a></span></code>
<div class="block">Nome do percurso, deve respeitar a regra de validação dos nomes em
percurso simples</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>private int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#nPercursos">nPercursos</a></span></code>
<div class="block">Nº de percursos</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>private <a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a>[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#percursos">percursos</a></span></code>
<div class="block">Array com os percursos simples.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#PercursoComposto-tps.tp2.pack2Percursos.PercursoComposto-">PercursoComposto</a></span>(<a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html" title="class in tps.tp2.pack2Percursos">PercursoComposto</a> pc)</code>
<div class="block">Copy constructor, deve criar uma cópia do percurso recebido.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#PercursoComposto-java.lang.String-tps.tp2.pack2Percursos.PercursoSimples:A-int-">PercursoComposto</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> nome,
<a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a>[] percursos,
int maxPercursos)</code>
<div class="block">Constructor que recebe o nome, um array de percursos e o máximo de
percursos a suportar.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#PercursoComposto-java.lang.String-tps.tp2.pack2Percursos.PercursoSimples-int-">PercursoComposto</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> nome,
<a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a> percurso,
int maxPercursos)</code>
<div class="block">Constructor que recebe apenas um percurso, além do nome e do nº máximo de
percursos.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#addicionarPercursoNoFinal-tps.tp2.pack2Percursos.PercursoSimples-">addicionarPercursoNoFinal</a></span>(<a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a> percurso)</code>
<div class="block">Deve adicionar o percurso no final, desde que este esteja em sequência e
haja espaço</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#addicionarPercursoNoInicio-tps.tp2.pack2Percursos.PercursoSimples-">addicionarPercursoNoInicio</a></span>(<a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a> percurso)</code>
<div class="block">Deve adicionar o percurso no início, desde que este esteja em sequência e
haja espaço</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html" title="class in tps.tp2.pack2Percursos">PercursoComposto</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#clone--">clone</a></span>()</code>
<div class="block">Deve criar uma cópia profunda do percurso corrente</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>private int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#findLocalidade-java.lang.String-">findLocalidade</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> localidade)</code>
<div class="block">Deve devolver o índice do percurso em que a localidade é início, ou -1
caso não encontre</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#getDeclive--">getDeclive</a></span>()</code>
<div class="block">Devolve o declive do percurso, que deve ser o somatório dos declives dos
seus percursos</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#getDistancia--">getDistancia</a></span>()</code>
<div class="block">Devolve a distância do percurso, que deve ser o somatório das distâncias
dos seus percursos</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#getFim--">getFim</a></span>()</code>
<div class="block">Devolve o fim do percurso</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#getInicio--">getInicio</a></span>()</code>
<div class="block">Devolve o início do percurso</div>
</td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#getNome--">getNome</a></span>()</code>
<div class="block">Devolve o nome do percurso</div>
</td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#getSubidaAcumulada--">getSubidaAcumulada</a></span>()</code>
<div class="block">Devolve o declive do percurso, que deve ser o somatório dos declives dos
seus percursos, mas só se deve considerar os declives positivos</div>
</td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#main-java.lang.String:A-">main</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[] args)</code>
<div class="block">Main, para testes</div>
</td>
</tr>
<tr id="i11" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#print-java.lang.String-">print</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> prefix)</code>
<div class="block">Imprime na consola o percurso.</div>
</td>
</tr>
<tr id="i12" class="altColor">
<td class="colFirst"><code><a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a>[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#removerPercursosNoFimDesde-java.lang.String-">removerPercursosNoFimDesde</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> localidade)</code>
<div class="block">Deve remover e devolver todos os percursos desde o ponto da localidade
recebida.</div>
</td>
</tr>
<tr id="i13" class="rowColor">
<td class="colFirst"><code><a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a>[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#removerPercursosNoInicioAte-java.lang.String-">removerPercursosNoInicioAte</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> localidade)</code>
<div class="block">Deve remover e devolver todos os percursos desde o início até ao ponto da
localidade recebida.</div>
</td>
</tr>
<tr id="i14" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#setNome-java.lang.String-">setNome</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> nome)</code>
<div class="block">Altera o nome do percurso</div>
</td>
</tr>
<tr id="i15" class="rowColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html#toString--">toString</a></span>()</code>
<div class="block">Devolve uma string com uma descriução do percurso, tal como:
"NORTE_SUL de Sagres para Lisboa, com 345000 metros, com 0 de declive e com 2 percursos"</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></h3>
<code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#equals-java.lang.Object-" title="class or interface in java.lang">equals</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#finalize--" title="class or interface in java.lang">finalize</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#getClass--" title="class or interface in java.lang">getClass</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#hashCode--" title="class or interface in java.lang">hashCode</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#notify--" title="class or interface in java.lang">notify</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#notifyAll--" title="class or interface in java.lang">notifyAll</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#wait--" title="class or interface in java.lang">wait</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#wait-long-" title="class or interface in java.lang">wait</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#wait-long-int-" title="class or interface in java.lang">wait</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="nome">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>nome</h4>
<pre>private <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> nome</pre>
<div class="block">Nome do percurso, deve respeitar a regra de validação dos nomes em
percurso simples</div>
</li>
</ul>
<a name="percursos">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>percursos</h4>
<pre>private <a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a>[] percursos</pre>
<div class="block">Array com os percursos simples. Os elementos devem ser colocados nos
índices menores. Tem de ter pelo menos um percurso. Não admite
localidades repetidas. Os percursos têm de estar em sequência, ou seja,
onde termina o percurso de índice 0 tem de ser onde se inicia o percurso
de índice 1 e assim sucessivamente ...</div>
</li>
</ul>
<a name="nPercursos">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>nPercursos</h4>
<pre>private int nPercursos</pre>
<div class="block">Nº de percursos</div>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="PercursoComposto-java.lang.String-tps.tp2.pack2Percursos.PercursoSimples-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>PercursoComposto</h4>
<pre>public PercursoComposto(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> nome,
<a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a> percurso,
int maxPercursos)</pre>
<div class="block">Constructor que recebe apenas um percurso, além do nome e do nº máximo de
percursos. Este constructor deve chamar o constructor que a ele se segue.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>nome</code> - Nome do percurso</dd>
<dd><code>percurso</code> - Percurso a ser guardado</dd>
<dd><code>maxPercursos</code> - Nº máximo de percursos suportado</dd>
</dl>
</li>
</ul>
<a name="PercursoComposto-java.lang.String-tps.tp2.pack2Percursos.PercursoSimples:A-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>PercursoComposto</h4>
<pre>public PercursoComposto(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> nome,
<a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a>[] percursos,
int maxPercursos)</pre>
<div class="block">Constructor que recebe o nome, um array de percursos e o máximo de
percursos a suportar. Em caso de argumentos inválidos deve ser lançada a
excepção IllegalArgumentException com uma mensagem a indicar o erro
ocorrido e o argumento inválido.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>nome</code> - Nome do percurso</dd>
<dd><code>percursos</code> - Percursos a serem guardados. O array não pode conter nulls,
tem de conter pelo menos um percurso e os seus percursos devem
estar em sequência.</dd>
<dd><code>maxPercursos</code> - Nº máximo de percursos suportado</dd>
</dl>
</li>
</ul>
<a name="PercursoComposto-tps.tp2.pack2Percursos.PercursoComposto-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>PercursoComposto</h4>
<pre>public PercursoComposto(<a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html" title="class in tps.tp2.pack2Percursos">PercursoComposto</a> pc)</pre>
<div class="block">Copy constructor, deve criar uma cópia do percurso recebido. Essa cópia
deve ser uma cópia profunda.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>pc</code> - Percurso a copiar</dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="clone--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clone</h4>
<pre>public <a href="../../../tps/tp2/pack2Percursos/PercursoComposto.html" title="class in tps.tp2.pack2Percursos">PercursoComposto</a> clone()</pre>
<div class="block">Deve criar uma cópia profunda do percurso corrente</div>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#clone--" title="class or interface in java.lang">clone</a></code> in class <code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></dd>
</dl>
</li>
</ul>
<a name="addicionarPercursoNoFinal-tps.tp2.pack2Percursos.PercursoSimples-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addicionarPercursoNoFinal</h4>
<pre>public boolean addicionarPercursoNoFinal(<a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a> percurso)</pre>
<div class="block">Deve adicionar o percurso no final, desde que este esteja em sequência e
haja espaço</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>percurso</code> - Percurso a adicionar</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>True se adicionou</dd>
</dl>
</li>
</ul>
<a name="addicionarPercursoNoInicio-tps.tp2.pack2Percursos.PercursoSimples-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addicionarPercursoNoInicio</h4>
<pre>public boolean addicionarPercursoNoInicio(<a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a> percurso)</pre>
<div class="block">Deve adicionar o percurso no início, desde que este esteja em sequência e
haja espaço</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>percurso</code> - Percurso a adicionar</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>True se adicionou</dd>
</dl>
</li>
</ul>
<a name="removerPercursosNoFimDesde-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>removerPercursosNoFimDesde</h4>
<pre>public <a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a>[] removerPercursosNoFimDesde(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> localidade)</pre>
<div class="block">Deve remover e devolver todos os percursos desde o ponto da localidade
recebida. Exemplo: percurso com a-b/b-c/c-d/d-e,
removerPercursoNoFimDesde(c), deve resultar no percurso com a-b/b-c e
deve devolver c-d/d-e.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>localidade</code> - Local a partir do qual se deve remover os percursos</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Os percursos removido ou null caso não remova nada</dd>
</dl>
</li>
</ul>
<a name="removerPercursosNoInicioAte-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>removerPercursosNoInicioAte</h4>
<pre>public <a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos">PercursoSimples</a>[] removerPercursosNoInicioAte(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> localidade)</pre>
<div class="block">Deve remover e devolver todos os percursos desde o início até ao ponto da
localidade recebida. Exemplo: percurso com a-b/b-c/c-d/d-e,
removerPercursoNoInicioAte(c), deve resultar no percurso com c-d/d-e e
devolver a-b/b-c.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>localidade</code> - Local até à qual se deve remover os percursos</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Os percursos removido ou null caso não remova nada</dd>
</dl>
</li>
</ul>
<a name="findLocalidade-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>findLocalidade</h4>
<pre>private int findLocalidade(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> localidade)</pre>
<div class="block">Deve devolver o índice do percurso em que a localidade é início, ou -1
caso não encontre</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>localidade</code> - Local a procurar</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>o índice do percurso que tem a localidade recebida como início ou
null caso não a encontre</dd>
</dl>
</li>
</ul>
<a name="getInicio--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getInicio</h4>
<pre>public <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> getInicio()</pre>
<div class="block">Devolve o início do percurso</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>O local de início do percurso</dd>
</dl>
</li>
</ul>
<a name="getFim--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getFim</h4>
<pre>public <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> getFim()</pre>
<div class="block">Devolve o fim do percurso</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>O local de fim do percurso</dd>
</dl>
</li>
</ul>
<a name="getDistancia--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDistancia</h4>
<pre>public int getDistancia()</pre>
<div class="block">Devolve a distância do percurso, que deve ser o somatório das distâncias
dos seus percursos</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>A distância do percurso</dd>
</dl>
</li>
</ul>
<a name="getDeclive--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDeclive</h4>
<pre>public int getDeclive()</pre>
<div class="block">Devolve o declive do percurso, que deve ser o somatório dos declives dos
seus percursos</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>O declive do percurso</dd>
</dl>
</li>
</ul>
<a name="getSubidaAcumulada--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getSubidaAcumulada</h4>
<pre>public int getSubidaAcumulada()</pre>
<div class="block">Devolve o declive do percurso, que deve ser o somatório dos declives dos
seus percursos, mas só se deve considerar os declives positivos</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>O declive acumulado do percurso mas só considerando os declives
positivos</dd>
</dl>
</li>
</ul>
<a name="getNome--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getNome</h4>
<pre>public <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> getNome()</pre>
<div class="block">Devolve o nome do percurso</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>O nome do percurso</dd>
</dl>
</li>
</ul>
<a name="setNome-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setNome</h4>
<pre>public void setNome(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> nome)</pre>
<div class="block">Altera o nome do percurso</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>nome</code> - O novo nome do percurso</dd>
</dl>
</li>
</ul>
<a name="toString--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>toString</h4>
<pre>public <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> toString()</pre>
<div class="block">Devolve uma string com uma descriução do percurso, tal como:
"NORTE_SUL de Sagres para Lisboa, com 345000 metros, com 0 de declive e com 2 percursos"</div>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#toString--" title="class or interface in java.lang">toString</a></code> in class <code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>O string que descreve o percurso</dd>
</dl>
</li>
</ul>
<a name="print-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>print</h4>
<pre>public void print(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> prefix)</pre>
<div class="block">Imprime na consola o percurso. Deve mostrar na primeiro linha o prefixo
seguido da informação do toString deste objecto. Depois deve mostrar os
seus percursos, um por linha, chamando os seus métodos de print, mas
passando como prefixo o prefixo recebido e prefixado de 3 espaços.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>prefix</code> - Prefixo a colocar antes da informação do toString e também na
parte de mostrar os percursos.</dd>
</dl>
</li>
</ul>
<a name="main-java.lang.String:A-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>main</h4>
<pre>public static void main(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[] args)</pre>
<div class="block">Main, para testes</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>args</code> - Argumentos do main</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../tps/tp2/pack2Percursos/package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/PercursoComposto.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../tps/tp2/pack2Percursos/PercursoSimples.html" title="class in tps.tp2.pack2Percursos"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?tps/tp2/pack2Percursos/PercursoComposto.html" target="_top">Frames</a></li>
<li><a href="PercursoComposto.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
<file_sep>package classcode.p14EDDLinkedLists.p4DoubleLinkedList;
import java.util.ListIterator;
/**
* Com esta demo pretende-se demonstrar que a utilização de iteradores gera
* excepções de concurrent modification quando um iterador está a iterarar e
* ocorre uma alteração na lista fora da interface Iterator e no iterador em
* questão.
*
* @author <NAME>
*
*/
public class C03DLinkedListWithListIteratorDemo {
public static void main(String[] args) {
C02DLinkedListWithListIterator<String> stringList = new C02DLinkedListWithListIterator<String>();
ListIterator<String> it = stringList.listIterator();
System.out.println("Lista de String ...");
it.add("Hello");
it.next();
it.add("Good-bye");
System.out.println("Listagem da lista: " + stringList);
System.out.println("Listagem invertida da lista: "
+ stringList.toStringInverted());
System.out.println();
//it.next(); // erro porque a inserção foi antes do elemento, logo o
// current esta no fim da lista
// remove all elements
ListIterator<String> it2 = stringList.listIterator();
System.out.println("Remoção de todos os elementos da lista.");
while(it2.hasNext()) {
String elem = it2.next();
it2.remove();
System.out.println("Removeu o elemento -> " + elem);
}
}
}
<file_sep>package classcode.p05Recursion;
import java.util.Scanner;
/**
* Conta quantos bits a 1 existem num inteiro
*
* Sugestão: método recursivo para mostrar os bits de um inteiro
*
* @author ateofilo
*
*/
public class C02Nums {
/**
* @param args
*/
public static void main(String[] args) {
// the keyboard reader
Scanner keyboard = new Scanner(System.in);
System.out.println("Teste a algoritmos recursivos...");
System.out.print("Introduza um inteiro positivo -> ");
int number = keyboard.nextInt();
// Count down
System.out.print("Count down de " + number + " -> ");
countDown(number);
System.out.println();
// Count up
System.out.print("Count up de " + number + " -> ");
countUp(number);
System.out.println();
// close keyboard
keyboard.close();
}
/**
* Prints a count down
*/
public static void countDown(int n) {
// stop case
if (n <= 0)
return;
// write num
System.out.print(n + " ");
// do count down (n -1)
countDown(n - 1);
}
/**
* Prints a count up
*/
public static void countUp(int n) {
// stop case
if (n <= 0)
return;
// do count up(n-1)
countUp(n - 1);
// write num
System.out.print(n + " ");
}
}
<file_sep>package classcode.p14EDDLinkedLists.p3LinkedListWithIterator;
/**
* Linked list with a notion of "current node." The current node can be changed
* to the next node with the method goToNext. At any time after the iteration is
* Initialised, one node is the current node, until the iteration has moved
* beyond the end of the list.
*
* A lista tem a noção de iteração. Lista com head, current e previous.
*
* New methods: resetIteration goToNext moreToIterate getDataAtCurrent
* resetDataAtCurrent insertNodeAfterCurrent deleteCurrentNode
*
*/
public class C02StringLinkedListWithIterator {
private ListNode head;
private ListNode current;
private ListNode previous;
public C02StringLinkedListWithIterator() {
head = null;
current = null;
previous = null;
}
/**
* Retorna o número de nós da lista.
*/
public int length() {
int count = 0;
ListNode position = head;
while (position != null) {
position = position.link;
count++;
}
return count;
}
public void addANodeToStart(String addData) {
head = new ListNode(addData, head);
if (current != null && current == head.link)
// if current is at old start node
previous = head;
}
public boolean contains(String target) {
return (Find(target) != null);
}
/**
* Returns a reference to the first node containing the target data. If
* target is not in the list, null is returned.
*/
private ListNode Find(String target) {
ListNode position;
position = head;
String dataAtPosition;
while (position != null) {
dataAtPosition = position.data;
if (dataAtPosition.equals(target))
return position;
position = position.link;
}
// target was not found
return null;
}
public void showList() {
ListNode position;
position = head;
while (position != null) {
System.out.println(position.data);
position = position.link;
}
}
public String[] arrayCopy() {
String[] a = new String[length()];
ListNode position = head;
int i = 0;
while (position != null) {
a[i] = position.data;
i++;
position = position.link;
}
return a;
}
public void resetIteration() {
current = head;
previous = null;
}
public void goToNext() {
if (current != null) {
previous = current;
current = current.link;
} else if (head != null) {
System.out
.println("Iterated too many times or uninitialized iteration.");
System.exit(0);
} else {
System.out.println("Iterating with an empty list.");
System.exit(0);
}
}
public boolean moreToIterate() {
return (current != null);
}
public String getDataAtCurrent() {
if (current != null)
return (current.data);
else {
throw new IllegalStateException();
}
}
public void resetDataAtCurrent(String newData) {
if (current != null) {
current.data = newData;
} else {
System.out.println("Setting data when current is not at any node.");
System.exit(0);
}
}
/**
* Inserts node with newData after the current node. The current node is the
* same after invocation as it is before invocation. Should not be used with
* an empty list. Should not be used when the current node has iterated past
* the entire list.
*/
public void insertNodeAfterCurrent(String newData) {
ListNode newNode = new ListNode();
newNode.data = newData;
if (current != null) {
newNode.link = current.link;
current.link = newNode;
} else if (head != null) {
System.out.println("Inserting when iterator is past all "
+ "nodes or uninitialized iterator.");
System.exit(0);
} else {
System.out.println("Using insertNodeAfterCurrent with empty list.");
System.exit(0);
}
}
/**
* Deletes the current node. After the invocation, the current node is the
* node after the deleted node or null if there is no next node.
*/
public void deleteCurrentNode() {
if (current != null) {
if (previous != null) {
// nota at head node
previous.link = current.link;
current = current.link;
} else {
// at head node
head = current.link;
current = head;
}
} else { // current == null
System.out
.println("Deleting with uninitialized current or an empty list.");
System.exit(0);
}
}
private class ListNode {
private String data;
private ListNode link;
public ListNode() {
link = null;
data = null;
}
public ListNode(String newData, ListNode linkValue) {
data = newData;
link = linkValue;
}
}
}
<file_sep>package classcode.p10ExceptionHandling;
import java.util.Scanner;
/**
* Tratamento da excepção. Colocar no input: 10 e 0
*
*/
public class C03CatchAnException {
/**
* main
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Realizacao da operacao de divisao...");
System.out.print("Introduza o dividendo -> ");
int dividendo = keyboard.nextInt();
System.out.print("Introduza o divisor -> ");
int divisor = keyboard.nextInt();
try {
// realizar o processamento
int quociente = dividendo / divisor;
// mostrar resultado
System.out.println("Divisao de " + dividendo + " por " + divisor
+ " -> " + quociente);
} catch (Exception e) {
// System.out.println("Erro: nao é possível dividir por zero");
System.err.println("Ocorreu a excepcao: "
+ e.getClass().getSimpleName() + ": " + e.getMessage());
System.err.println("Exception: " + e);
}
System.out.println("Fim do programa... ");
keyboard.close();
}
// e se o utilizador introduzir "letras"
}
<file_sep>package classcode.p11StreamsAndFileIO;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class ex1read {
public static int obterValorPago(String fileName, int numAluno,
String data1, String data2) throws IOException {
int valorTotal = 0;
boolean inDate = false;
Scanner fileScan = new Scanner(new File("file1.txt"));
while (fileScan.hasNextLine()) {
String line = fileScan.nextLine();
Scanner lineScan = new Scanner(line);
// ver se a linha e null
if (lineScan.hasNext()) {
String auxDate = lineScan.next();
if (auxDate.equals(data1)) {
inDate = true;
}
if (inDate) {
while (lineScan.hasNextInt()) {
if (lineScan.nextInt() == numAluno) {
valorTotal += lineScan.nextInt();
}
}
lineScan.close();
if (auxDate.equals(data2)) {
inDate = false;
break;
}
}
}
}
fileScan.close();
return valorTotal;
}
public static void main(String[] args) throws IOException {
System.out.println(obterValorPago("file1.txt", 40010, "2014/01/01",
"2014/01/02"));
}
}<file_sep>package oldClass.tp1;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
/**
* Classe que é a frame onde tud ocorre
*
*/
public class P03ColorFrame extends JFrame {
private static final long serialVersionUID = -330888082383077655L;
private MyLabel label1;
private JButton bnColorStart;
private JButton bnColorEnd;
/**
* Method that creates the frame
*/
protected void init() {
setTitle("...: ColorFrame :...");
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// panel central
JPanel jpCentral = new JPanel(new ProportionalLayout(0.1f));
jpCentral.setBackground(Color.ORANGE);
jpCentral.setOpaque(true);
add(jpCentral, BorderLayout.CENTER);
// label central
label1 = new MyLabel();
jpCentral.add(label1, ProportionalLayout.CENTER);
// buttons panel
JPanel jpButtons = new JPanel();
add(jpButtons, BorderLayout.SOUTH);
// button start color
bnColorStart = new JButton("Start color");
bnColorStart.setBackground(Color.GREEN);
bnColorStart.setOpaque(true);
bnColorStart.setHorizontalAlignment(SwingConstants.CENTER);
jpButtons.add(bnColorStart);
// button end color
bnColorEnd = new JButton("End color");
bnColorEnd.setBackground(Color.MAGENTA);
bnColorEnd.setOpaque(true);
bnColorEnd.setHorizontalAlignment(SwingConstants.CENTER);
jpButtons.add(bnColorEnd);
// listener start color button
bnColorStart.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Color newColor = JColorChooser.showDialog(P03ColorFrame.this,
"Choose Start Color", bnColorStart.getBackground());
if (newColor != null) {
bnColorStart.setBackground(newColor);
label1.repaint();
}
}
});
// listener end color button
bnColorEnd.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Color newColor = JColorChooser.showDialog(P03ColorFrame.this,
"Choose End Color", bnColorEnd.getBackground());
if (newColor != null) {
bnColorEnd.setBackground(newColor);
label1.repaint();
}
}
});
// set frame visible
setVisible(true);
}
/**
* Main method - the execution starts here
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
P03ColorFrame frame = new P03ColorFrame();
frame.init();
}
});
}
/**
* Auxiliary class that extends JLabel
*/
class MyLabel extends JLabel {
private static final long serialVersionUID = -4402584053051810107L;
/**
* Method that paints the label
*/
public void paint(Graphics g) {
super.paint(g);
System.out.println("Paint...");
drawColors(g, getWidth(), getHeight(),
bnColorStart.getBackground(), bnColorEnd.getBackground());
}
/**
* Should draw all the drawing area with lines with color varying from
* StartColor to EndColor. To change the drawing color use:
* Graphics.setColor(Color newColor). To draw a line use:
* Graphics.drawLine(int x1, int y1, int x2, int y2)
*
* @param g
* the graphics where we should draw the lines
* @param dimX
* x dimension of drawing area
* @param dimY
* y dimension of drawing area
* @param startColor
* start color, should be at left
* @param endColor
* end color, should be at right
*/
private void drawColors(Graphics g, int dimX, int dimY,
Color startColor, Color endColor) {
// indices rgb da cor inicial
double red = startColor.getRed();
double green = startColor.getGreen();
double blue = startColor.getBlue();
double deltaRed = endColor.getRed() - startColor.getRed();
double deltaGreen = endColor.getGreen() - startColor.getGreen();
double deltaBlue = endColor.getBlue() - startColor.getBlue();
// for para iterativamente ir mudando de cor
for (int i = 0; i < dimX; i++) {
// inicializacao de uma cor que ira ser mudada ao longo do for
Color auxColor = new Color((int) red, (int) green, (int) blue);
g.setColor(auxColor);
g.drawLine(i, 0, i, dimY);
// actualizacao dos niveis rgb de cada cor
red += deltaRed / dimX;
green += deltaGreen / dimX;
blue += deltaBlue / dimX;
}
}
}
}
<file_sep>package classcode.p13EDD;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class C07ListIterator {
public static void printIterable(Iterable<String> container) {
Iterator<String> it = container.iterator();
System.out.print("[");
while (it.hasNext()) {
System.out.print(it.next());
if (it.hasNext())
System.out.print(", ");
}
System.out.println("]");
}
public static void printReverse(List<String> container) {
ListIterator<String> it = container.listIterator(container.size());
// come to the beginning
System.out.print("Reversed -> [");
while (it.hasPrevious()) {
System.out.print(it.previous());
if (it.hasPrevious())
System.out.print(", ");
}
System.out.println("]");
// boolean add(Object e);
it.add("seis");
it.add("sete");
printIterable(container);
}
public static void main(String[] args) {
List<String> container = new ArrayList<String>(Arrays.asList("um",
"dois", "trÍs", "quatro"));
printIterable(container);
printReverse(container);
// boolean add(Object e);
System.out.println("add seis -> " + container.add(".."));
printIterable(container);
}
}
<file_sep>package classcode.p07Inheritance;
import java.util.Date;
/*
* Exemplo de herança - instanceof
*
* Exemplo do a classe Date
*/
public class C02 {
public String toString() {
return "sou um C02";
}
public static void main(String[] args) {
// criar o array para objectos C02
C02[] elems = new C02[100];
// criar objectos e colocá-los no array
C03 c3 = new C03();
elems[0] = new C02();
elems[1] = new C03();
elems[2] = c3;
// ===============================================
// contagem dos C02 e C03 existentes
//
int nC02 = 0, nC03 = 0;
for (int i = 0; i < elems.length; i++) {
if (elems[i] != null) {
// use of instanceof operator
if (elems[i] instanceof C02) {
nC02++;
}
if (elems[i] instanceof C03) {
nC03++;
}
// toString will be called independently of the kind of object,
// because this method is defined for both classes at class
// Object
System.out.println(elems[i]);
}
}
System.out.println("nC02 -> " + nC02);
System.out.println("nC03 -> " + nC03);
System.out.println();
// ===============================================
// listagem dos C03 existentes
//
System.out.println("Listagem dos C03 existentes:");
for (int i = 0; i < elems.length; i++) {
if (elems[i] != null) {
if (elems[i] instanceof C03) {
// use of cast operator - could throw
// java.lang.ClassCastException if the cast can not be done
C03 aux = (C03) elems[i];
// C01Bclass aux2 = (C01Bclass) (Object) elems[i];
System.out.println(aux + " created at -> "
+ aux.getCreationDataAndTime());
// ((C03) elems[i]).getCreationDataAndTime();
}
}
}
} // end of main
} // end of C02 class
class C03 extends C02 {
// each C03 will keep its creation date and time
Date creationDate = new Date();
public String toString() {
return "sou um C03";
}
public String getCreationDataAndTime() {
return creationDate.toString();
}
}
class C1 {
public C1() {
super();
}
public C1(int x) {
}
// final
// public
void m1() {
}
}
class C2 extends C1 {
public C2() {
System.out.println();
}
void m1() {
}
}
<file_sep>package classcode.p05Recursion;
import java.util.Scanner;
/**
* Conta quantos bits a 1 existem num inteiro
*
* Sugestão: método recursivo para mostrar os bits de um inteiro
*
* @author ateofilo
*
*/
public class C04CountBits {
/**
* @param args
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Contagem do número de bits a 1 num inteiro...");
System.out.print("Introduza um inteiro -> ");
int number = keyboard.nextInt();
System.out.println("Inteiro " + number
+ " em binário (by toBinaryString) -> "
+ Integer.toBinaryString(number));
// show the bits of number
System.out.print("Inteiro " + number
+ " em binário (by showBits) -> ");
showBits(number);
System.out.println();
// show2 the bits of number
System.out.print("Inteiro " + number
+ " em binário (by showBits2) -> ");
showBits2(number);
System.out.println();
// count active bits in number
int nActiveBits = countActiveBits(number);
System.out.println("O " + number + " contém " + nActiveBits
+ " bits a 1");
keyboard.close();
}
/**
* show bits - supports negative numbers
*/
public static void showBits(int n) {
// second argument is a mask with the initial value of 1 in highest
// value bit
showBits(n, 0x80000000);
}
/**
* Show bits
*/
private static void showBits(int n, int mask) {
// stop case, the mask is empty
if (mask == 0)
return;
// AND mask with n, if is different than zero, that bit is active
System.out.print("" + ((n & mask) != 0 ? '1' : '0'));
// process the remaining bits, mask shift to the right
showBits(n, mask >>> 1);
}
/**
* show bits2 - supports negative numbers Second version, based on nbits and
* get value before recursion but print value after recursion. A nice
* example of recursion.
*/
public static void showBits2(int n) {
showBits2(n, 32);
}
/**
* Show bits2
*/
private static void showBits2(int n, int nBitsLeft) {
// if negative argument throw exception
if (nBitsLeft < 0)
throw new IllegalArgumentException(
"Show bits internal: nbitsLeft negativo: " + nBitsLeft);
// stop case
if (nBitsLeft == 0)
return;
// get last bit (lowest value bit), save it in char, this bit will be
// the last one to be printed
char lastBit = ((n & 1) == 0) ? '0' : '1';
// process next bits
showBits2(n >> 1, nBitsLeft - 1);
// output the saved bit
System.out.print(lastBit);
}
/**
* Count the number of active bits - supports negative numbers
*/
public static int countActiveBits(int n) {
// stop case
if (n == 0)
return 0;
// extract if last bit, 1 if active, 0 is not
int oneIfLastBitIsActive = n & 1;
// shift right, with new left bits with zero
return oneIfLastBitIsActive + countActiveBits(n >>> 1);
}
}
<file_sep>package classcode.p11StreamsAndFileIO;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Ler as linhas de um ficheiro de texto com scanner
*/
public class C06ReadFileWithScanner {
public static void main(String[] args) {
// Leitura do ficheiro
String inputFileName = "file10.txt";
Scanner fileScan = null;
try {
fileScan = new Scanner(new File(inputFileName));
String line = null;
int nLines = 0;
System.out.println("Conte˙do do ficheiro:");
// ciclo de leituras de linhas do ficheiro
// enquanto houver linhas...
while (fileScan.hasNextLine()) {
// ler linha
line = fileScan.nextLine();
// mostrar linha
System.out.println("[" + line.length() + "]" + line);
// contabilizar o n║ de linhas
++nLines;
}
System.out.println("\nForam lidas " + nLines + " linhas");
} catch (FileNotFoundException e) {
System.err.println(e);
} finally {
if (fileScan != null) {
fileScan.close();
}
}
}
}
<file_sep>package classcode.p10ExceptionHandling;
import java.util.Scanner;
/**
* Mostra do trace do stack da excepção. Utiliza a excepção:
* DivideByZeroException
*
*/
public class C14StackTrace {
public static int divisao(int dividendo, int divisor)
throws DivideByZeroException {
if (divisor == 0) {
throw new DivideByZeroException("Divisao por zero");
}
int quociente = dividendo / divisor;
return quociente;
}
public static int divisao2(int dividendo, int divisor)
throws DivideByZeroException {
return divisao(dividendo, divisor);
}
/**
* main
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Realizacao da operacao de divisao...");
System.out.print("Introduza o dividendo -> ");
int dividendo = keyboard.nextInt();
System.out.print("Introduza o divisor -> ");
int divisor = keyboard.nextInt();
try {
// realizar a processamento
// int quociente = dividendo / divisor;
// int quociente = divisao(dividendo,divisor);
int quociente = divisao2(dividendo, divisor);
// mostrar resultado
System.out.println("Divisao de " + dividendo + " por " + divisor
+ " -> " + quociente);
} catch (Exception e) {
System.out.println("Ocorreu a excepcao: "
+ e.getClass().getSimpleName() + ": " + e.getMessage());
StackTraceElement elements[] = e.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
System.out.println(elements[i].getFileName() + ": "
+ elements[i].getClassName() + " "
+ elements[i].getMethodName() + "()" + " line: "
+ elements[i].getLineNumber());
}
}
keyboard.close();
}
}
<file_sep>package classcode.p08AbstractClassesAndInterfaces;
/**
* Interface que permite comparar dois objectos de classes que a implementem. Os
* números suportados são compostos só por dígitos.
*/
public interface C07IRelatable {
String getValue();
boolean isEquals(C07IRelatable other);
boolean isBiggerThan(C07IRelatable other);
boolean isSmallerThan(C07IRelatable other);
}
<file_sep>package classcode.p10ExceptionHandling;
import java.util.Scanner;
/**
* Tratamento da situação de erro por código normal. Colocar no input: 10 e 0
*
*/
public class C02SolveSituationByIf {
/**
* main
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Realizacao da operacao de divisao...");
System.out.print("Introduza o dividendo -> ");
int dividendo = keyboard.nextInt();
System.out.print("Introduza o divisor -> ");
int divisor = keyboard.nextInt();
if (divisor != 0) {
// realizar a processamento
int quociente = dividendo / divisor;
// mostrar resultado
System.out.println("Divisao de " + dividendo + " por " + divisor
+ " -> " + quociente);
} else {
System.out.println("Erro: nao é possível dividir por zero");
}
keyboard.close();
}
// agora vamos utilizar excepções
}
<file_sep>package classcode.p07Inheritance.cenario3Escola;
/**
* cenário de utilização da hierarquia de classes definida: classe Pessoa,
* classe Aluno e classe Docente
*/
public class C04Escola {
// nome da escola
private String nomeEscola;
// array de pessoas na escola
private C01Pessoa[] pessoas = new C01Pessoa[1000];
private int nPessoas = 0;
// constructor
public C04Escola(String nomeEscola) {
this.nomeEscola = nomeEscola;
}
// general methods
public String getNomeEscola() {
return nomeEscola;
}
/*
* Contar o nº de docentes. Utiliza
*/
public int getNumDocentes() {
int nDocentes = 0;
for (int i = 0; i < nPessoas; i++) {
if (pessoas[i] instanceof C03Docente)
nDocentes++;
}
return nDocentes;
}
public int getNumAlunos() {
int nAlunos = 0;
for (int i = 0; i < nPessoas; i++) {
if (pessoas[i] instanceof C02Aluno)
nAlunos++;
}
return nAlunos;
}
public int getNumDocentesOuAlunos(boolean isDocente) {
int num = 0;
for (int i = 0; i < nPessoas; i++) {
if ((isDocente && pessoas[i] instanceof C03Docente)
|| (!isDocente && pessoas[i] instanceof C02Aluno))
num++;
}
return num;
}
public void printAll() {
for (int i = 0; i < nPessoas; i++) {
System.out.println(pessoas[i]);
}
}
public String toString() {
return "escola " + getNomeEscola() + ", com " + getNumDocentes()
+ " docentes e com " + getNumAlunos() + " alunos";
}
public boolean addDocente(C03Docente doc) {
if (nPessoas == pessoas.length)
return false;
pessoas[nPessoas++] = doc;
return true;
}
public boolean addAluno(C02Aluno al) {
if (nPessoas == pessoas.length)
return false;
pessoas[nPessoas++] = al;
return true;
}
public boolean addPessoa(C01Pessoa p) {
if (nPessoas == pessoas.length)
return false;
pessoas[nPessoas++] = p;
return true;
}
/**
* main
*/
public static void main(String[] args) {
// criar Escola
C04Escola esc = new C04Escola("ISEE");
// criar docentes e colocá-los na escola
C03Docente d1 = new C03Docente("<NAME>", 1,
"Engenharia de Materiais");
esc.addDocente(d1);
// criar alunos e colocá-los na escola
C02Aluno a1 = new C02Aluno("<NAME>", 2,
"Engenharia Física Tecnológica");
esc.addAluno(a1);
C02Aluno a2 = new C02Aluno("<NAME>", 3,
"Engenharia Física Tecnológica");
esc.addAluno(a2);
C02Aluno a3 = new C02Aluno("<NAME>", 4,
"Engenharia Física Tecnológica");
esc.addPessoa(a3);
// fazer o print de todas as pessoas na escola
esc.printAll();
}
}
<file_sep>package classcode.p15Swing.p04SimpleSwingApps;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
/**
* Calculator with comboBox
*
* Novos componentes: JComboBox
*
* @author <NAME>
*
*/
public class C4CalculatorWithComboBox extends JFrame {
private static final long serialVersionUID = 1L;
private FlowLayout layout = null;
private JLabel label1 = null;
private JButton buttonDo = null;
private JLabel label2 = null;
private JTextField text1 = null;
private JTextField text2 = null;
private JTextField textResult = null;
private JLabel labelResult = null;
private JComboBox<String> comboOpers = null;
/**
* Este método cria toda a frame e coloca-a visível
*
*/
public void init() {
// set title
setTitle("...: My calculator with a ComboBox :...");
// set what happens when close button is pressed
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
layout = new FlowLayout();
getContentPane().setLayout(layout);
// label1 - oper1
label1 = new JLabel("Value1 :");
label1.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add(label1);
// text1 - oper1
text1 = new JTextField("1000", 10);
getContentPane().add(text1);
// the Combobox
comboOpers = new JComboBox<String>();
comboOpers.addItem("add");
comboOpers.addItem("sub");
comboOpers.addItem("mul");
comboOpers.addItem("div");
// put one option initially selected - the ADD option
comboOpers.setSelectedIndex(0); // -1
getContentPane().add(comboOpers);
// label2 - oper2
label2 = new JLabel("Value2 :");
label2.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add(label2);
// text2 - JTextField oper2
text2 = new JTextField("200", 10);
getContentPane().add(text2);
// buttonDo
buttonDo = new JButton(" = ");
getContentPane().add(buttonDo);
// labelResult
labelResult = new JLabel("Result :");
labelResult.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add(labelResult);
// textResult
textResult = new JTextField(10);
getContentPane().add(textResult);
textResult.setEditable(false);
// adjust size to minimum as needed
pack();
// set location at center
setLocationRelativeTo(null);
// disable resize
setResizable(false);
// set dynamic behavior
// Listener for execution
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Scanner sc1 = new Scanner(text1.getText());
Scanner sc2 = new Scanner(text2.getText());
if (sc1.hasNextInt() && sc2.hasNextInt()) {
int oper1 = sc1.nextInt();
int oper2 = sc2.nextInt();
int result = 0;
if (((String) comboOpers.getSelectedItem()).equals("add")) {
result = oper1 + oper2;
} else {
result = oper1 - oper2;
}
textResult.setText(Integer.toString(result));
} else {
textResult.setText("Invalid input values!");
}
sc1.close();
sc2.close();
}
};
buttonDo.addActionListener(al);
// TODO:remove comment from next line, watch the results and understand
// this situation
comboOpers.addActionListener(al);
// puts the frame visible
setVisible(true);
}
/**
* Main
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
C4CalculatorWithComboBox myFrame = new C4CalculatorWithComboBox();
myFrame.init();
// life goes on
System.out.println("Frame created...");
}
});
System.out.println("End of main...");
}
}
<file_sep>package oldClass.tp1;
import java.util.Random;
import java.util.Scanner;
public class P05Xadrez {
public static void main(String[] args) {
// init scanner
Scanner keyboard = new java.util.Scanner(System.in);
//ciclo para repetir tabuleiro
while (true) {
//tamanho do tabuleiro
int size = 8;
// inicializacao de um array de 8 por 8
char[][] xadrez = new char[size][size];
// init random
Random random = new Random();
// atribuiçao das coordenadas aleatorias da Torre1
int xTorre1 = random.nextInt(size);
int yTorre1 = random.nextInt(size);
xadrez[xTorre1][yTorre1] = 'T';
// init numero de ataques
int totalAttacks = 0;
// atribuiçao das coordenadas aleatorias do Bispo1
int xBispo1 = random.nextInt(size);
int yBispo1 = random.nextInt(size);
boolean bispo1 = false;
// ciclo para verificar se o bispo nao esta a ser atacado pela
// torre
while (!bispo1) {
// caso esteja a ser atacado
if ((yBispo1 == (yTorre1 + (xTorre1 - xBispo1)))
|| (yBispo1 == (yTorre1 + (xBispo1 - xTorre1)))
|| yBispo1 == yTorre1 || xBispo1 == xTorre1) {
// novas coordenadas random seram avaliadas
xBispo1 = random.nextInt(size);
yBispo1 = random.nextInt(size);
} else {
// caso nao esteja a ser atacado o programa prossegue
xadrez[xBispo1][yBispo1] = 'B';
bispo1 = true;
}
}
// coordenadas aleatorias para o Bispo2
int xBispo2 = random.nextInt(size);
int yBispo2 = random.nextInt(size);
boolean bispo2 = false;
// mesmo procedimento que foi feito para o bispo1
while (!bispo2) {
// neste caso e avaliado se o Bispo2 esta a ser atacado pela
// Torre1
// e pelo Bispo1
if ((yBispo2 == (yTorre1 + (xTorre1 - xBispo2)))
|| (yBispo2 == (yTorre1 + (xBispo2 - xTorre1)))
|| (yBispo2 == yTorre1 || xBispo2 == xTorre1)
|| (yBispo2 == (yBispo1 + (xBispo1 - xBispo2)))
|| (yBispo2 == (yBispo1 + (xBispo2 - xBispo1)))) {
xBispo2 = random.nextInt(size);
yBispo2 = random.nextInt(size);
} else {
// caso nao, o progrmaa prossegue
xadrez[xBispo2][yBispo2] = 'B';
bispo2 = true;
}
}
int xTorre2 = random.nextInt(size);
int yTorre2 = random.nextInt(size);
boolean torre2 = false;
// mesmo procedimento que foi feito para as outras peças
while (!torre2) {
// neste caso e avaliado se a Torre2 esta a ser atacada pela
// Torre1
// e pelo Bispo1 e Bispo2
if ((yBispo2 == (yTorre2 + (xTorre2 - xBispo2)))
|| (yBispo2 == (yTorre2 + (xBispo2 - xTorre2)))
|| (yBispo2 == yTorre2 || xBispo2 == xTorre2)
|| (yBispo1 == (yTorre2 + (xTorre2 - xBispo1)))
|| (yBispo1 == (yTorre2 + (xBispo1 - xTorre2)))
|| (yBispo1 == yTorre2 || xBispo1 == xTorre2)
|| (yTorre2 == yTorre1 || xTorre2 == xTorre1)) {
xTorre2 = random.nextInt(size);
yTorre2 = random.nextInt(size);
} else {
// caso nao, o progrmaa prossegue
xadrez[xTorre2][yTorre2] = 'T';
torre2 = true;
}
}
// ciclo para avaliar todas as casa vazias se tem ataques
for (int i = 0; i < xadrez.length; i++) {
for (int j = 0; j < xadrez[i].length; j++) {
// so serao avaliadas casas vazias
if (xadrez[i][j] != 'B' && xadrez[i][j] != 'T') {
// se for atacada pelo Bispo2
if ((yBispo2 == (j + (i - xBispo2)))
|| (yBispo2 == (j + (xBispo2 - i)))) {
// incrementa 1 na variavel de total de ataques
totalAttacks += 1;
}
// se for atacada pelo Bispo1
if ((yBispo1 == (j + (i - xBispo1)))
|| (yBispo1 == (j + (xBispo1 - i)))) {
// incrementa 1 na variavel de total de ataques
totalAttacks += 1;
}
// se for atacada pela Torre1
if ((j == yTorre1 || i == xTorre1)) {
// incrementa 1 na variavel de total de ataques
totalAttacks += 1;
}
// se for atacada pela Torre2
if ((j == yTorre2 || i == xTorre2)) {
// incrementa 1 na variavel de total de ataques
totalAttacks += 1;
}
// se o total de ataques for 0
if (totalAttacks == 0) {
// nessa casa aparecerá o char 'o'
xadrez[i][j] = 'o';
}
// se o total de ataques for 1
if (totalAttacks == 1) {
// nessa casa aparecerá o char '-'
xadrez[i][j] = '-';
}
// se o total de ataques for 2
if (totalAttacks >= 2) {
// nessa casa aparecerá o char '+'
xadrez[i][j] = '+';
}
// reinicio da varial totalAttacks
totalAttacks = 0;
}
}
}
// x
System.out.println(" -------------------------------");
for (int i = 0; i < xadrez.length; i++) {
// y
for (int j = 0; j < xadrez[i].length; j++) {
if(j==0)System.out.print("| " + xadrez[i][j]);
else
System.out.print(" | " + xadrez[i][j]);
}
System.out.print(" |");
System.out.println("");
}
System.out.println(" -------------------------------");
if (keyboard.nextLine().equalsIgnoreCase("fim"))
break;
}
keyboard.close();
}
}
<file_sep>package classcode.p04Arrays;
/**
* Teste a um array 2d esfarrapado, ou seja um array em que a 2ª dimensão pode
* variar para cada elemento da 1ª dimensão
*/
public class C02Array2DEsfarrapado {
/**
* @param args
*/
public static void main(String[] args) {
// criar a primeira dimesão
int[][] tabela2 = new int[11][];
// criar a segunda dimensão, que é variável e inicializar o array
for (int i = 0; i < tabela2.length; i++) {
// a 2ª dimensão varia
tabela2[i] = new int[i < 6 ? i + 1 : 11 - i];
// inicializar o elementos do array
for (int j = 0; j < tabela2[i].length; j++) {
tabela2[i][j] = (int) (Math.random() * 100);
}
}
// mostrar o array na consola
for (int i = 0; i < tabela2.length; i++) {
for (int x = 0; x < tabela2[i].length; x++) {
System.out.print(tabela2[i][x] + " ");
}
System.out.println();
}
}
}
<file_sep>package classcode.p15Swing.p02buildedLayouts;
/**
* Center layout - este layout coloca o único componente no centro e packed
*
* ATENÇÃO: este é um exemplo de um layout manager construído por nós.
* Em MoP não estamos interessados em construir layout managers.
* Este exemplo apenas mostra que eu era necessário fazer para se construir um.
*
* Contudo este layout manager fica disponível para utilização.
*
* By: <NAME>, em desenvolvimento
*/
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager2;
public class CenterLayout implements LayoutManager2 {
public CenterLayout() {
}
/* Required by LayoutManager - deprecated */
public void addLayoutComponent(String name, Component comp) {
// System.out.println("CL: called addLayoutComponent with::: " + name
// + " " + comp);
}
/* Required by LayoutManager. */
public void addLayoutComponent(Component comp, Object constraints) {
// System.out.println("CL: called addLayoutComponent with " + comp + " "
// + constraints);
}
/* Required by LayoutManager. */
public void removeLayoutComponent(Component comp) {
// System.out.println("CL: removeLayoutComponent called");
}
public Component getLayoutComponent(Object constraints) {
// System.out.println("CL: getLayoutComponent called");
return null;
}
public Component getLayoutComponent(Container target, Object constraints) {
// System.out
// .println("CL: Unimplemented method getLayoutComponent has called ------");
return null;
}
/* Required by LayoutManager. */
public Dimension preferredLayoutSize(Container parent) {
// System.out.println("CL: preferredLayoutSize called");
Dimension dim = new Dimension(0, 0);
Component c = parent.getComponent(0);
// setSizes(parent);
if (c != null) {
dim = c.getPreferredSize();
}
// Always add the container's insets!
Insets insets = parent.getInsets();
dim.width += insets.left + insets.right;
dim.height += insets.top + insets.bottom;
return dim;
}
/* Required by LayoutManager. */
public Dimension minimumLayoutSize(Container parent) {
// System.out.println("CL: minimumLayoutSize called");
Dimension dim = new Dimension(0, 0);
Component c = parent.getComponent(0);
// setSizes(parent);
if (c != null) {
dim = c.getPreferredSize();
}
// Always add the container's insets!
Insets insets = parent.getInsets();
dim.width += insets.left + insets.right;
dim.height += insets.top + insets.bottom;
return dim;
}
/* Required by LayoutManager. */
/*
* This is called when the panel is first displayed, and every time its size
* changes. Note: You CAN'T assume preferredLayoutSize or minimumLayoutSize
* will be called -- in the case of applets, at least, they probably won't
* be.
*/
public void layoutContainer(Container parent) {
// System.out.println("CL: layoutContainer(Container parent) called");
Insets insets = parent.getInsets();
Dimension dimParent = parent.getSize();
Component comp = parent.getComponent(0);
// the component
if (comp != null && comp.isVisible()) {
Dimension preferedSize = comp.getPreferredSize();
if (dimParent.width < preferedSize.width + insets.left
+ insets.right)
preferedSize.width = dimParent.width - insets.left
- insets.right;
if (dimParent.height < preferedSize.height + insets.top
+ insets.bottom)
preferedSize.height = dimParent.height - insets.top
- insets.bottom;
int x = (dimParent.width - insets.left - insets.right - preferedSize.width) / 2;
int y = (dimParent.height - insets.top - insets.bottom - preferedSize.height) / 2;
// Set the component's size and position.
comp.setBounds(x + insets.left, y + insets.top, preferedSize.width,
preferedSize.height);
}
}
public String toString() {
// System.out.println("CL: toString called");
return getClass().getName();
}
public void repaint(Container parent) {
// System.out.println("CL: repaint called");
// setSizes(parent);
}
public Dimension maximumLayoutSize(Container target) {
// System.out.println("CL: maximumLayoutSize called");
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
public float getLayoutAlignmentX(Container target) {
// System.out.println("CL: getLayoutAlignmentX called");
return 0.5f;
}
public float getLayoutAlignmentY(Container target) {
// System.out.println("CL: getLayoutAlignmentY called");
return 0.5f;
}
public void invalidateLayout(Container target) {
// System.out.println("CL: invalidateLayout called");
}
}
<file_sep>package classcode.p02FlowDecisionsCycles;
/**
* Switch com Strings - o compilador tem de estar com Compiler Compliance Level
* de 1.7. Ir a Project->Properties->Java Compiler.
*
* @author ateofilo
*
*/
public class C09SwitchComStrings {
/**
* @param args
*/
public static void main(String[] args) {
// the initial season
String estacao = "Inverno";
// show it
System.out.println("Estação corrente -> " + estacao);
// set the next season
switch (estacao) {
case "Inverno":
estacao = "Primavera";
break;
case "Primavera":
estacao = "Verão";
break;
case "Verão":
estacao = "Outono";
break;
case "Outono":
estacao = "Inverno";
default:
System.out
.println("O nome inicial não corresponde a uma estação do ano");
System.out.println("O programa vai terminar!!!");
System.exit(1);
}
System.out.println("Próxima estação -> " + estacao);
}
}
<file_sep>package tps.tp4;
import java.io.File;
import java.io.FileNotFoundException;
public class TabuleiroDim7 extends Tabuleiro {
private static final long serialVersionUID = 6784824663872156802L;
public TabuleiroDim7(File file) throws FileNotFoundException {
super(7, 7, file);
}
}<file_sep>package classcode.p15Swing.p01layoutframes;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
/**
* Null layout manager. Posicionamento fixo.
*
* Assunto: null layout manager
*
* @author <NAME>
*
*/
public class C7MyNullFrame {
/**
* Main
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
System.out.println("End of main...");
}
/**
* Create and Show GUI
*/
public static void createAndShowGUI() {
// create a JFrame
JFrame frame = new JFrame();
// set title
frame.setTitle("...: My nulll layout frame :...");
// set size
frame.setSize(400, 200);
// set location at center
frame.setLocationRelativeTo(null);
// dispose on close
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
Random rg = new Random();
frame.setLayout(null);
// frame.setLayout(new FlowLayout());
// criar as labels
JLabel label1 = C6FrameWithPanels.createJLabel("-- um ---", rg);
label1.setBounds(0, 0, 100, 50);
JLabel label2 = C6FrameWithPanels.createJLabel("-- dois ---", rg);
label2.setBounds(25, 25, 100, 50);
JLabel label3 = C6FrameWithPanels.createJLabel("-- três ---", rg);
label3.setBounds(100, 100, 100, 40);
JLabel label4 = C6FrameWithPanels.createJLabel("-- quatro ---", rg);
label4.setBounds(200, 200, 100, 30);
JLabel label5 = C6FrameWithPanels.createJLabel("-- cinco ---", rg);
label5.setBounds(300, 300, 100, 20);
// colocá-las no contentPane
frame.add(label1);
frame.add(label3);
frame.add(label4);
frame.add(label5);
frame.add(label2);
// puts the frame visible (is not visible at start)
frame.setVisible(true);
// life goes on
System.out.println("Frame created...");
}
}
<file_sep>package tps.tp3;
public abstract class Percurso implements IPercurso {
/**
* nome do percurso, deve conter só letras, digitos e espaços, deve começar
* por uma letra e ter pelo menos mais uma letra ou dígito
*/
private String nome;
public Percurso(String nome) {
if(!validarNomeDeLocal(nome)){
throw new IllegalArgumentException("Nome inválido -> " + nome);
}
this.nome = nome;
}
/* (non-Javadoc)
* @see tps.tp3.IPercurso#getNome()
*/
@Override
public String getNome() {
return nome;
}
/* (non-Javadoc)
* @see tps.tp3.IPercurso#getInicio()
*/
//@Override
//public abstract String getInicio();
/**
* ... Métodos abstactos - colocar aqui
*/
/* (non-Javadoc)
* @see tps.tp3.IPercurso#getFim()
*/
//@Override
//public abstract String getFim();
/* (non-Javadoc)
* @see tps.tp3.IPercurso#getDistancia()
*/
//@Override
//public abstract int getDistancia();
/* (non-Javadoc)
* @see tps.tp3.IPercurso#getDeclive()
*/
//@Override
//public abstract int getDeclive();
/* (non-Javadoc)
* @see tps.tp3.IPercurso#getLocalidades()
*/
//@Override
//public abstract String[] getLocalidades();
/* (non-Javadoc)
* @see tps.tp3.IPercurso#getDescricao()
*/
//@Override
//public abstract String getDescricao();
/**
* Deve validar se contém só letras, digitos e espaços, deve começar por uma
* letra e ter pelo menos mais uma letra ou dígito
*
* @param local
* Nome a validar
*/
protected static boolean validarNomeDeLocal(String local) {
// se tiver menos que dois char
if (local.length() < 2)
return false;
// se o primeiro char nao for uma letra
if (!(Character.isLetter(local.charAt(0))))
return false;
// se os restantes chars nao forem letras, digitos, espacos ou
// underscore
for (int i = 1; i < local.length(); i++) {
if (!(Character.isLetter(local.charAt(i))
|| Character.isDigit(local.charAt(i))
|| local.charAt(i) == ' ')) {
return false;
}
}
return true;
}
/* (non-Javadoc)
* @see tps.tp3.IPercurso#toString()
*/
@Override
public String toString() {
return "percurso " + getDescricao() + " " + getNome() + " de "
+ getInicio() + " para " + getFim() + ", com " + getDistancia()
+ " metros e com " + getDeclive() + " de declive";
}
/* (non-Javadoc)
* @see tps.tp3.IPercurso#print(java.lang.String)
*/
@Override
public void print(String prefix) {
System.out.println(prefix + this);
}
}<file_sep>package classcode.p10ExceptionHandling;
public class C01ExceptionInConstructor {
/**
* main
*/
public static void main(String[] args) {
// teste 3 - descomentar
// String s = null;
// s.toString();
System.out.println("Início do main...");
System.out.println("Vamos criar o o objecto.");
// teste 1
MultipleStrings ms = new MultipleStrings(-1);
// teste 2- comentar a linha anterior e descomentar a linha seguinte
// MultipleStrings ms = new MultipleStrings(10);
System.out.println("Objecto criado. Vamos inserir strings.");
ms.addString("um");
ms.addString("dois");
System.out.print("Conteúdo do objecto: ");
System.out.println(ms);
}
}
class MultipleStrings {
String[] strings;
int nStrings = 0;
/**
* Constructor
*/
MultipleStrings(int nStrings) {
if (nStrings < 0) {
// criar uma excepção da classe RuntimException
RuntimeException e = new RuntimeException(
"Construtor de MultipleStrings chamado com n de String menor que zero -> "
+ nStrings);
System.out.println("Excepção criada -> " + e);
// lançar a excepção
throw e;
}
strings = new String[nStrings];
}
/**
* adiciona uma string se houver espaço
*/
public boolean addString(String s) {
if (nStrings > strings.length)
return false;
strings[nStrings++] = s;
return true;
}
/**
* devolve a representação do objecto numa string
*/
public String toString() {
// uso de StringBuilder para optimizar a construção da string
StringBuilder sb = new StringBuilder(100);
sb.append("[");
for (int i = 0; i < nStrings; i++) {
if (i > 0)
sb.append(", ");
sb.append(strings[i]);
}
sb.append("]");
return sb.toString();
}
}
<file_sep>package classcode.p15Swing.p01layoutframes;
import java.awt.Color;
import java.awt.FlowLayout;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
/**
* Demonstra a utilização de FlowLayout. Um flow layout dispõe os componentes em
* linha, mas muda os componentes de linha quando necessário. Os componentes
* podem ficar alinhados à esquerda, direita e centro.
*
* Assuntos: FlowLayout, LineBorder
*
*
* @author <NAME>
*
*/
public class C4FrameWithFlowLayout {
/**
* Main
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
System.out.println("End of main...");
}
/**
* Create and Show GUI
*/
public static void createAndShowGUI() {
// create a JFrame
JFrame frame = new JFrame();
// set title
frame.setTitle("...: My flow layout frame :...");
// set size
frame.setSize(400, 200);
// set location
frame.setLocationRelativeTo(null); // to center a frame
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
FlowLayout fl = new FlowLayout();
frame.setLayout(fl);
int nLabels = 10;
Random rg = new Random();
JLabel[] labels = new JLabel[nLabels];
// criar JLabels
for (int x = 0; x < nLabels; ++x) {
JLabel label = labels[x] = new JLabel(" Label " + x + " ");
label.setOpaque(true);
label.setBackground(new Color(rg.nextInt(256), rg.nextInt(256), rg
.nextInt(256)));
frame.add(label);
}
JLabel label = new JLabel(" Redimensionar lateralmente a janela ");
// colocar um rebordo a azul para que se veja os contornos
label.setBorder(new LineBorder(Color.BLUE, 2, true));
frame.add(label);
// fl.setAlignment(FlowLayout.LEFT);
// frame.setMinimumSize(new Dimension(300, 300));
// frame.setResizable(false);
// puts the frame visible (is not visible at start)
frame.setVisible(true);
// life goes on
System.out.println("Frame created...");
}
}
<file_sep>package classcode.p08AbstractClassesAndInterfaces;
public class C02Cclass extends C01Bclass {
private int cc;
C02Cclass(int n) {
super(n); // calls Bclass(int)
val2 = n;
cc = n;
}
public int metodo1(int x) {
int z = getVal() + x + cc;
return z;
}
}
<file_sep>package classcode.p07Inheritance.cenario2Figuras;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.util.Arrays;
/**
* Classe Figura - Esta classe é um contentor de pontos.
*
*/
public class C04Figura {
C02Ponto2D[] pontos;
private int nPontos;
Color color;
public C04Figura(Color color) {
pontos = null;
nPontos = 0;
this.color = color;
}
public C04Figura(C02Ponto2D[] pontos, Color color) {
setPontos(pontos);
this.color = color;
}
public C02Ponto2D[] getPontos() {
// TODO
return new C02Ponto2D[0];
}
public void setPontos(C02Ponto2D[] pontos) {
this.pontos = Arrays.copyOf(pontos, pontos.length);
nPontos = pontos.length;
}
public C02Ponto2D getPonto(int index) {
if (index < 0 || index >= pontos.length)
return null;
return pontos[index].clone();
}
public boolean setPonto(C02Ponto2D ponto, int index) {
if (index < 0 || index >= pontos.length)
return false;
pontos[index] = ponto.clone();
return true;
}
public double getArea() {
return 0;
}
public String getNome() {
return null;
}
public String toString() {
StringBuilder s = new StringBuilder(getNome());
s.append(" [");
for (int i = 0; i < nPontos; i++) {
s.append(pontos[i]);
if (i < nPontos - 1)
s.append(", ");
}
s.append("]");
return s.toString();
}
/**
* Draw the polygon into the graphics g
*/
public void paintComponent(Graphics g) {
Polygon p = new Polygon();
for (int i = 0; i < pontos.length; i++) {
p.addPoint(pontos[i].getX(), pontos[i].getY());
}
g.setColor(color);
g.fillPolygon(p);
g.setColor(Color.black);
g.drawPolygon(p);
}
}
<file_sep>package tps.tp1.pack3Arrays;
import java.util.Random;
import java.util.Scanner;
public class P04BaralhadorDeNomes {
public static void main(String[] args) {
// palavra fim em array de char
char[] palavraFim = new char[] { 'f', 'i', 'm' };
// bool para por true quando a palavra fim aparecer
boolean igual = false;
// init random
Random random = new Random();
// init scanner
Scanner keyboard = new java.util.Scanner(System.in);
System.out
.println("Insira entre 5 a 10 nomes completos com limite de 120 caracteres cada.");
System.out.println("Escreva fim para para terminar!");
// string auxiliar com o número máximo de nomes
String[] auxArray = new String[10];
// variáveis auxiliares
int nameLenght;
int moreThan;
String subName;
int i = 0;
// ciclo for para colocar os nomes dentro do array de strings
for (i = 0; i < auxArray.length; i++) {
nameLenght = 0;
moreThan = 0;
// variável onde os nomes sao guardados
String name = keyboard.nextLine();
// trim para anular os espaços laterais entre os nomes
name.trim();
// for que analisa se a palavra introduzida foi um fim
if (name.length() == 3) {
// novo array com o tamanho 3
char[] palavraEscrita = new char[name.length()];
for (int d = 0; d < name.length(); d++) {
char c = name.charAt(d);
// condicao para todas as letras ficarem a minuscula
if (c >= 65 && c <= 90) {
c = (char) (c + 32);
palavraEscrita[d] = c;
} else if (c >= 97 && c <= 122) {
palavraEscrita[d] = c;
}
}
// ciclo que percorre a palavra fim e compara com a palavra de 3
// letras que foi inserida
for (int j = 0; j < palavraFim.length; j++) {
if (palavraEscrita[j] == palavraFim[j]) {
igual = true;
} else {
igual = false;
break;
}
}
}
// se a palavra for fim o ciclo para inserir nomes e parado
if (igual == true) {
if (i >= 5) {
break;
} else {
System.out.println("por favor insira pelo menos 5 nomes");
}
}
// análise para ver se o nome irá ser aceite
// init de um scanner só para uma string de nome
Scanner scanString = new java.util.Scanner(name);
// ciclo para percorrer todas as palavras da string nome
while (scanString.hasNext()) {
subName = scanString.next();
// condição que testa quantos nomes tem 4 ou mais letras
if ((subName.length()) >= 4)
moreThan += 1;
// variável que guarda a quantidade de caracteres que um nome
// tem
nameLenght += subName.length();
}
// condição para averiguar se o nome poderá ser aceite
if ((nameLenght <= 120) && (moreThan >= 3)) {
auxArray[i] = name;
} else {
System.out.println("Nome não aceite");
System.out.println("Por favor introduza novamente");
i -= 1;
}
scanString.close();
}
keyboard.close();
// novo array de nomes com o comprimento correcto
String[] myArray = new String[i];
for (int j = 0; j < i; j++) {
myArray[j] = auxArray[j];
}
// print dos nomes que foram aceites
System.out.println("");
System.out.println("Os nomes aceites são: ");
for (i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
// init de arrays que vao comportar os varios nomes pedidos
String[] firstName = new String[myArray.length];
String[] lastName = new String[myArray.length];
String[] middleName = new String[myArray.length];
// ciclo que percorre as strings nome e guarda o número de espaços entre
// os varios subnomes de cada nome
for (i = 0; i < myArray.length; i++) {
int auxArrayLenght = 1;
for (int j = 0; j < myArray[i].length(); j++) {
if (myArray[i].charAt(j) == ' ') {
auxArrayLenght += 1;
}
}
// init de um array com o número de subnomes que cada nome tem
auxArray = new String[auxArrayLenght];
// init de um novo scanner para ler cada string
Scanner scanString = new java.util.Scanner(myArray[i]);
// ciclo que guarda cada subnome num array
for (int j = 0; j < auxArrayLenght; j++) {
auxArray[j] = scanString.next();
}
// cada primeiro nome é guardado aqui
firstName[i] = auxArray[0];
// cada último nome e guardado aqui
lastName[i] = auxArray[(auxArray.length) - 1];
int randomQ = random.nextInt((auxArray.length) - 2) + 1;
while (auxArray[randomQ].length() < 3) {
randomQ = random.nextInt((auxArray.length) - 2) + 1;
}
// cada nome do meio random é guardado aqui
// um de cada nome
middleName[i] = auxArray[randomQ];
scanString.close();
}
// init de um novo array para os novos nomes gerados
// cada linha do array bidimensional comportará um nome gerado
String[][] newNames = new String[myArray.length][3];
// ciclo onde são postos os vários nomes de forma random
for (int j = 0; j < myArray.length; j++) {
newNames[j][0] = firstName[random.nextInt(firstName.length - 1)];
newNames[j][1] = middleName[random.nextInt(middleName.length - 1)];
newNames[j][2] = lastName[random.nextInt(lastName.length - 1)];
}
System.out.println("");
System.out.println("");
System.out.println("new names ->");
// ciclo onde são apresentados os novos nomes
for (int j = 0; j < newNames.length; j++) {
for (int j2 = 0; j2 < 3; j2++) {
System.out.print(newNames[j][j2] + " ");
}
System.out.println(" ");
}
}
}
<file_sep>package classcode.p06ClassesAndObjects;
import java.util.Arrays;
/**
*
*/
public class Livro {
private String titulo;
private String dataEdicao = "2015/05/13";
private String[] autores;
private int numPaginas;
private String editora;
private Requisicao requisicao = null;
public Livro(String newTitulo, String dataEdicao, String[] autores,
int numPaginas, String editora) {
if (!isTituloValid(newTitulo))
throw new IllegalArgumentException("Titulo inválido -> " + titulo);
if (!isAutoresValid(autores))
throw new IllegalArgumentException("Autores inválidos -> "
+ Arrays.toString(autores));
if (!isNumPaginasValid(numPaginas))
throw new IllegalArgumentException(
"O número de páginas não pode ser negativo -> "
+ numPaginas);
if (!isPersonNameValid(editora))
throw new IllegalArgumentException("Editora inválida -> " + editora);
// validar os autores
titulo = newTitulo;
this.dataEdicao = dataEdicao;
this.autores = autores;
this.numPaginas = numPaginas;
this.editora = editora;
}
public Livro(String newTitulo, String dataEdicao, String autor,
int numPaginas) {
this(newTitulo, dataEdicao, new String[] { autor }, numPaginas,
"desconhecido");
}
public Requisicao getRequisicao() {
return requisicao;
}
public void setRequisicao(Requisicao requisicao) {
this.requisicao = requisicao;
}
public String getTitulo() {
return titulo;
}
public String getDataEdicao() {
return dataEdicao;
}
public String[] getAutores() {
return autores;
}
public int getNumPaginas() {
return numPaginas;
}
public String getEditora() {
return editora;
}
private boolean isAutoresValid(String[] autores) {
if (autores == null || autores.length == 0)
return false;
for (int i = 0; i < autores.length; i++) {
if (!isPersonNameValid(autores[i]))
return false;
}
return true;
}
private boolean isNumPaginasValid(int numPaginas) {
return numPaginas > 0;
}
private boolean isPersonNameValid(String name) {
if (name == null || name.length() == 0)
return false;
// valido: letras, espaços
for (int i = 0; i < name.length(); i++) {
if (!Character.isLetter(name.charAt(i)) && name.charAt(i) != ' ')
return false;
}
return true;
}
private boolean isTituloValid(String titulo) {
if (titulo == null || titulo.length() == 0)
return false;
// valido: letras, digitos, :, -, espaços
for (int i = 0; i < titulo.length(); i++) {
if (!Character.isLetter(titulo.charAt(i))
&& !Character.isDigit(titulo.charAt(i))
&& titulo.charAt(i) != ':' && titulo.charAt(i) != '-'
&& titulo.charAt(i) != ' ')
return false;
}
return true;
}
public String toString() {
return titulo + ", data de edição " + dataEdicao + ", páginas "
+ numPaginas + ", autores " + Arrays.toString(autores)
+ (editora != null ? ", editora " + editora : "");
}
public String toSimpleString() {
return titulo;
}
public static void main(String[] args) {
// Livro l1 = new Livro();
// l1.titulo = "Viagem ao sol";
// l1.dataEdicao = "2010/02/03";
// l1.editora = "PortoEdições";
//
// Livro l2 = new Livro();
// l2.titulo = "Viagem à lua";
// l2.dataEdicao = "2013/06/23";
//
// System.out.println("Livro 1 -> " + l1);
// System.out.println("Livro 2 -> " + l2);
Livro l3 = new Livro("Viagem ao sol", "2010/02/03", new String[] {
"<NAME>", "<NAME>" }, 100, "PortoEdições");
Livro l4 = new Livro("Viagem à lua", "2013/06/23", "<NAME>", 300);
System.out.println("Livro 3 -> " + l3.toSimpleString());
System.out.println("Livro 4 -> " + l4);
}
}
<file_sep>package classcode.p01IntroJava;
import javax.swing.*;
/**
* Message dialog window
*/
public class G02MessageDialogWindow {
/**
* main method
*/
public static void main(String[] args) {
// message dialog with plain message type
JOptionPane.showMessageDialog(null, "Hello World!",
"MyMessageDialog - Plain message", JOptionPane.PLAIN_MESSAGE);
// message dialog with information message type
JOptionPane.showMessageDialog(null, "Hello World!",
"MyMessageDialog - Information Message",
JOptionPane.INFORMATION_MESSAGE);
// message dialog with warning message type
JOptionPane.showMessageDialog(null, "Hello World!",
"MyMessageDialog - Warning message",
JOptionPane.WARNING_MESSAGE);
// message dialog with error message type
JOptionPane.showMessageDialog(null, "Hello World!",
"MyMessageDialog - Error message", JOptionPane.ERROR_MESSAGE);
}
}
<file_sep>package classcode.p00aulas;
public class soma {
public static void main(String[] args) {
//System.out.println(soma(54,3));
}
/*public static int soma(int xVal, int yVal){
if(yVal == 0) return xVal;
if(yVal > 0) return soma(xVal+1, yVal-1);
return soma(xVal-1, yVal+1);
}*/
}
<file_sep>package tps.tp4;
import java.io.File;
import java.io.FileNotFoundException;
public class TabuleiroDim6 extends Tabuleiro {
private static final long serialVersionUID = 6784824663872156802L;
public TabuleiroDim6(File file) throws FileNotFoundException {
super(6, 6, file);
}
}<file_sep>package tps.tp4;
import java.util.ArrayList;
public class Trajecto {
private ArrayList<Elemento> colocados = new ArrayList<Elemento>();
private Tabuleiro tabuleiro;
private int estadoPeca;
public Trajecto(Tabuleiro tabuleiro) {
this.tabuleiro = tabuleiro;
this.estadoPeca = 0;
}
public int getEstadoPeca() {
return estadoPeca;
}
public void aumentaEstadoPeca() {
estadoPeca++;
}
public void setElemento(Elemento elemento) {
colocados.add(elemento);
}
public void apagaElemento(Elemento elemento) {
colocados.remove(elemento);
}
public Elemento getElemento(int x, int y) {
for (Elemento elementoColocado : colocados) {
if (elementoColocado.equals(tabuleiro.getQuadricula(x, y)
.getElemento())) {
return elementoColocado;
}
}
return null;
}
public ArrayList<Elemento> getColocados() {
return colocados;
}
public Elemento getUltimoElemento() {
if (colocados != null && !colocados.isEmpty()) {
return colocados.get(colocados.size() - 1);
}
return null;
}
public Elemento getPenultimoElemento() {
if (colocados != null && colocados.size() >= 2) {
return colocados.get(colocados.size() - 2);
}
return null;
}
public void setUltimoElemento(Elemento elemento) {
colocados.set(colocados.size() - 1, elemento);
}
public boolean estaVazio() {
if (colocados.isEmpty()) {
return true;
}
return false;
}
}
<file_sep>package classcode.p02FlowDecisionsCycles;
import java.util.Scanner;
/**
* for demo, continue demo
*
* TODO Este código não está terminado, falta corrigir o aspecto dos números
* negativos
*/
public class C14forDemo2 {
/**
* main method - ler 10 inteiros positivos e calculara sua média
* */
public static void main(String[] args) {
// the keyboard reader
Scanner keyboard = new Scanner(System.in);
int sum = 0;
// read 10 positive integers
for (int i = 0; i < 10; i++) {
// read a positive > 0 number
System.out.print("Introduza o número positivo nº " + (i + 1)
+ " -> ");
int number = keyboard.nextInt();
if (number < 0) {
System.out.println("O número " + number
+ " não é um nº inteiro positivo!!");
continue;
}
sum += number;
}
// show a count up
System.out.print("A média dos números introduzidos é -> " + (sum / 10));
// close the keyboard
keyboard.close();
}
}
<file_sep>package classcode.p09EnumeradosENestedClasses;
public class C01Enum {
public static void main(String[] args) {
// variável, toString, ordinal, valueOf
Estacao est = Estacao.PRIMAVERA;
System.out.println("Estação est -> " + est);
System.out.println("Ordinal de " + est + " -> " + est.ordinal());
est = Estacao.valueOf("VERAO");
System.out.println("Estacao.valueOf(\"VERAO\") -> " + est);
est = Estacao.INVERNO;
System.out.println(est == Estacao.INVERNO ? "Que frio!"
: "Bom tempo...");
// values
Estacao[] estacoes = Estacao.values();
System.out.println("\nListagem das estações:");
for (int i = 0; i < estacoes.length; i++) {
System.out.println("Estacao[" + i + "] -> " + estacoes[i]);
}
}
}
enum Estacao {
PRIMAVERA, VERAO, OUTONO, INVERNO
// PRIMAVERA(), VERAO(), OUTONO(), INVERNO()
}<file_sep>package classcode.p15Swing.p08Painting;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import classcode.p15Swing.p02buildedLayouts.CenterLayout;
import classcode.p15Swing.p02buildedLayouts.ProportionalLayout;
/**
* Painting - desenhar livremente sobre um componente
*
* @author <NAME>
*
*/
public class C1MyCustomTextPanelPaintingFrame extends JFrame {
private static final long serialVersionUID = 1L;
private static Random rg = new Random();
GridLayout gl = null;
JLabel label1 = null;
JButton buttonLeft = null;
JButton buttonRight = null;
JButton buttonBottom = null;
JButton buttonTop = null;
private JPanel buttonsPanel;
private MyPanel myPanel = null;
private JPanel buttonsOuterPanel;
/**
* Este método cria toda a frame e coloca-a visível
*
*/
public void init() {
// set title
setTitle("...: My first Painting frame :...");
// set size
// setSize(400, 200);
setMinimumSize(new Dimension(400, 200));
// set location
setLocationRelativeTo(null); // to center a frame
// set what happens when close button is pressed
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
ProportionalLayout cl = new ProportionalLayout(0.1f, 0.2f, 0.1f, 0.1f);
setLayout(cl);
// buttonsPanel
buttonsPanel = new JPanel();
buttonsOuterPanel = new JPanel(new CenterLayout());
buttonsOuterPanel.add(buttonsPanel);
add(buttonsOuterPanel, ProportionalLayout.SOUTH);
myPanel = new MyPanel("This is my custom Panel!");
myPanel.setBorder(BorderFactory.createLineBorder(Color.blue));
add(myPanel, ProportionalLayout.CENTER);
// button1
buttonLeft = new JButton(" left ");
buttonsPanel.add(buttonLeft);
buttonLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myPanel.moveToLeft();
}
});
buttonRight = new JButton("right");
buttonsPanel.add(buttonRight);
buttonRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myPanel.moveToRight();
}
});
buttonBottom = new JButton("bottom");
buttonsPanel.add(buttonBottom);
buttonBottom.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myPanel.moveToBottom();
}
});
buttonTop = new JButton(" top ");
buttonsPanel.add(buttonTop);
buttonTop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myPanel.moveToTop();
}
});
// puts the frame visible (is not visible at start)
setVisible(true);
}
/**
* Main
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
C1MyCustomTextPanelPaintingFrame myFrame = new C1MyCustomTextPanelPaintingFrame();
myFrame.init();
// life goes on
System.out.println("Frame created...");
}
});
System.out.println("End of main...");
}
public static Color randomColor() {
return new Color(rg.nextInt(255), rg.nextInt(255), rg.nextInt(255));
}
}
class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
String str = null;
int x = 10;
int y = 20;
int step = 5;
public MyPanel(String str) {
this.str = str;
setBorder(BorderFactory.createLineBorder(Color.red));
}
public Dimension getPreferredSize() {
return new Dimension(250, 200);
}
// method callback that should paint the component
public void paintComponent(Graphics g) {
// first draw the super component
// that means, draw the background object
super.paintComponent(g);
// Draw drawings on this object
g.drawString(str, x, y);
g.setColor(C1MyCustomTextPanelPaintingFrame.randomColor());
g.drawLine(x, y + 10, x + 140, y + 10);
g.setColor(C1MyCustomTextPanelPaintingFrame.randomColor());
g.drawRoundRect(x, y + 20, 140, 10, 20, 3);
g.setColor(C1MyCustomTextPanelPaintingFrame.randomColor());
g.fillOval(x, y + 40, 140, 40);
g.setColor(C1MyCustomTextPanelPaintingFrame.randomColor());
g.drawOval(x, y + 40, 140, 40);
}
public void drawString(String str) {
this.str = str;
this.repaint();
}
public void moveToLeft() {
x -= step;
repaint();
}
public void moveToRight() {
x += step;
repaint();
}
public void moveToBottom() {
y += step;
repaint();
}
public void moveToTop() {
y -= step;
repaint();
}
}
<file_sep>package tps.tp3;
public interface IPercurso {
/**
* Devolve o nome do percurso
*/
public abstract String getNome();
/**
* Devolve o local de início do percurso
*/
public abstract String getInicio();
/**
* ... Métodos abstactos - colocar aqui
*/
/**
* Devolve o local de fim do percurso
*/
public abstract String getFim();
/**
* Devolve a distancia do percurso
*/
public abstract int getDistancia();
/**
* Devolve o declive do percurso
*/
public abstract int getDeclive();
/**
* Devolve a descricao do percurso
*/
public abstract String[] getLocalidades();
/**
* Devolve a descricao do percurso
*/
public abstract String getDescricao();
/**
* ToString, deve devolver uma String tal como:
* "A2 de Lisboa para Faro, com 278000 metros e com 0 de declive"
*/
public abstract String toString();
/**
* Print, deve imprimir na consola o prefixo seguido da informação que se
* obtém com o toString
*
* @param prefix
* Prefixo a colocar antes da informação do toString
*/
public abstract void print(String prefix);
}<file_sep>package classcode.p10ExceptionHandling;
import java.util.Scanner;
/**
* Mostra a corrência de uma excepção do Java Colocar no input: 10 e 0
*
*/
public class C00ShowOccurOfException {
/**
* main
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// teste 2
// Scanner scan2 = null;
// scan2.next();
//
System.out.println("Realizacao da operacao de divisao...");
System.out.print("Introduza o dividendo -> ");
int dividendo = keyboard.nextInt();
System.out.print("Introduza o divisor (introduza 0) -> ");
int divisor = keyboard.nextInt();
// realizar a processamento
int quociente = dividendo / divisor;
// mostrar resultado
System.out.println("Divisao de " + dividendo + " por " + divisor
+ " -> " + quociente);
keyboard.close();
}
}
<file_sep>package classcode.p12Generics;
/**
* Uma classe genérica com dois tipos genéricos e com um método que delcara uma
* argumento de outro tipo genérico
*/
public class C03Box3<T, U> {
private T obj1;
private U obj2;
public C03Box3(T t, U u) {
obj1 = t;
obj2 = u;
}
public void set1(T t) {
obj1 = t;
}
public void set2(U u) {
obj2 = u;
}
public T get1() {
return obj1;
}
public U get2() {
return obj2;
}
/**
* Método que declara um tipo genérico que é utilizado dentro dele
*/
public <V> V inspect(V o) {
System.out.println("T: " + obj1.getClass().getName());
System.out.println("V: " + o.getClass().getName());
return o;
}
/**
* main
*/
public static void main(String[] args) {
C03Box3<Integer, String> box = new C03Box3<Integer, String>(100, "Olá");
box.set1(30);
System.out.println(box.get2() + " " + box.get1());
// utilização do método que declara um tipo extra genérico
// indicação explicita do tipo
// float f1 = box.<Float> inspect(new Float(3.9f));
float f1 = box.<Float> inspect(3.9f);
// indicação implicita do tipo
// String s =
box.inspect(f1);
// utilização de outro tipo, recordar que o tipo só é válido na chamada
// ao método, pelo que cada chamada pode utilziar um tipo diferente
// String s =
box.inspect("olá");
// situações incompatíveis
// box.<Float> inspect(10); // ERRO
// String s = box.inspect(f1);
}
}
<file_sep>package classcode.p15Swing.p07MyModelViewController;
import java.util.Scanner;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* A classe Weather é um Model.
*
* Mas o seu "main" é um controller e um Viewer
*
*/
public class Weather implements IChangeNotifier {
private int value = 0;
private ChangeNotifier cw = new ChangeNotifier();
public Weather(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
fireStateChanged();
}
// métodod auxiliar - eventualmente desnecessário, caso se aceda
// directamente a cw
protected void fireStateChanged() {
cw.fireStateChanged(new ChangeEvent(this));
}
public void addChangeListener(ChangeListener l) {
cw.addChangeListener(l);
}
// main
public static void main(String[] args) {
System.out.println("..: Text mode application :...");
Weather weatherLisbon = new Weather(25);
Scanner input = new Scanner(System.in);
boolean quit = false;
do {
System.out.println("Weather in Lisbon is -> "
+ weatherLisbon.getValue());
System.out.println("1 - change weather in Lisbon");
System.out.println("0 - quit");
System.out.print("-> ");
if (input.hasNextInt()) {
int option = input.nextInt();
// clear the remainder part of the line
input.nextLine();
switch (option) {
case 0:
quit = true;
break;
case 1:
System.out.print("New temperature in Lisbon -> ");
if (input.hasNextInt()) {
int newTemp = input.nextInt();
input.nextLine();
weatherLisbon.setValue(newTemp);
} else {
System.out.println("Invalid temperature -> "
+ input.nextLine());
}
break;
default:
System.out.println("Invalid option -> " + option);
}
} else {
System.out.println("Invalid option -> " + input.nextLine());
}
} while (!quit);
input.close();
}
}
<file_sep>package classcode.p03IntroMethods;
import java.util.*;
/**
* A program that read two positive integers a show the the lowest common
* multiple
*
*/
public class C02LowestCommonMultipleV2 {
/**
* Main method
*/
public static void main(String[] args) {
// the keyboard reader
Scanner keyboard = new Scanner(System.in);
// read the first number
System.out.println("Entering the first number...");
int n1 = readPositiveNonZeroInteger(keyboard);
System.out.println();
// read the second number
System.out.println("Entering the second" + " number...");
int n2 = readPositiveNonZeroInteger(keyboard);
System.out.println();
// show data
System.out.println("First number -> " + n1);
System.out.println("Second number -> " + n2);
System.out.println();
// calculate and return the lowest common multiple
int lcm = lowestCommonMultiple(n1, n2);
// show the result
System.out.println("The lowest common multiple between " + n1 + " and "
+ n2 + " is " + lcm);
// int lcm2 = lowestCommonMultiple(lcm, lowestCommonMultiple(10, 51));
//
// // show the result
// System.out.println("The lowest common multiple between " + n1 +
// " and "
// + n2 + " is " + lcm);
//
// close keyboard
keyboard.close();
}
/**
* Method that ask and read a positive integer number greater than zero and
* returns it
*
* @param keyboard
* receives the keyboard reader
* @return a positive greater than zero integer
*/
public static int readPositiveNonZeroInteger(Scanner keyboard) {
// local variables
boolean done = false;
int number = 0;
// reading cycle
do {
// ask and read a number
System.out.print("Enter the a integer number bigger than 0 -> ");
if (keyboard.hasNextInt()) {
number = keyboard.nextInt();
if (number > 0)
done = true;
else
System.out.println("The number is not bigger than zero -> "
+ number);
} else {
// not an integer
System.out.println("What you wrote was not an integer!!! -> "
+ keyboard.next());
}
// remove the garbage introduced by the user
keyboard.nextLine();
} while (!done);
// return the number
return number;
}
/**
* Method that calculate the lowest common multiple between n1 and n2
*
* @param n1
* one value
* @param n2
* another value
* @return the lowest common multiple between n1 and n2
*/
public static int lowestCommonMultiple(int n1, int n2) {
// use auxiliary variables
int n1aux = n1, n2aux = n2;
// go and stop when both are equal
while (n1aux != n2aux) {
// find the lowest of them, in it add its base value
if (n1aux < n2aux)
n1aux += n1;
else
n2aux += n2;
}
// return one of n1aux or n2aux, they are equal
return n1aux;
}
/**
* Method that calculate the lowest common multiple between three number
*
* @param n1
* first value
* @param n2
* second value
* @param n3
* third value
* @return the lowest common multiple between n1, n2 and n3
*/
public static int lowestCommonMultiple(int n1, int n2, int n3) {
// TODO
return 0;
}
}<file_sep>package tps.tp2.pack1Recursive;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import tps.tp1.pack2Ciclos.ProportionalLayout;
public class P03HanoiTowers {
private JFrame frame;
private Rod leftRod = null;
private Rod centerRod = null;
private Rod rigthRod = null;
private JPanel pcentral;
private JSpinner jsNumberOfTowers;
private JButton buttonStart;
private JButton buttonCreate;
private JSpinner jsMovementsDelay;
private int movementsDelay;
private JButton buttonCancel;
private boolean isActive = true;
/**
* Build the frame and starts the scenario
*/
public void init() {
frame = new JFrame("...: Towers of Hanoi :...");
frame.setSize(650, 300);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
ProportionalLayout pl = new ProportionalLayout(0.1f, 0.2f, 0.1f, 0.1f);
frame.setLayout(pl);
// main panel
pcentral = new JPanel(new GridLayout(1, 0));
pcentral.setBackground(Color.green);
pcentral.setOpaque(true);
frame.add(pcentral, ProportionalLayout.CENTER);
// panel buttons and buttons
JPanel buttons = new JPanel();
frame.add(buttons, ProportionalLayout.SOUTH);
// spinner to control the number of discs
SpinnerNumberModel snm = new SpinnerNumberModel(2, 1, 20, 1);
jsNumberOfTowers = new JSpinner(snm);
jsNumberOfTowers.setToolTipText("Number of discs");
buttons.add(jsNumberOfTowers);
// Create button
buttonCreate = new JButton("Create");
buttonCreate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createScenario((int) (jsNumberOfTowers.getValue()));
jsNumberOfTowers.setEnabled(false);
buttonStart.setEnabled(true);
buttonCreate.setEnabled(false);
buttonCancel.setEnabled(true);
}
});
buttons.add(buttonCreate);
// Start button
buttonStart = new JButton("Start");
buttonStart.setEnabled(false);
buttonStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jsMovementsDelay.setEnabled(false);
movementsDelay = (int) (jsMovementsDelay.getValue());
startScenario();
buttonStart.setEnabled(false);
}
});
buttons.add(buttonStart);
// Cancel button
buttonCancel = new JButton("Cancel");
buttonCancel.setEnabled(false);
buttonCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jsMovementsDelay.setEnabled(true);
jsNumberOfTowers.setEnabled(true);
buttonCreate.setEnabled(true);
buttonStart.setEnabled(false);
buttonCancel.setEnabled(false);
isActive = false;
}
});
buttons.add(buttonCancel);
// spinner to control the movements delay
SpinnerNumberModel snm2 = new SpinnerNumberModel(500, 100, 2000, 100);
jsMovementsDelay = new JSpinner(snm2);
jsMovementsDelay
.setToolTipText("Delay between movements, in milliseconds");
buttons.add(jsMovementsDelay);
frame.setVisible(true);
}
/**
* Do the initial actions
*/
private void createScenario(int nDiscs) {
// clear old stuff
pcentral.removeAll();
// create new Rods
leftRod = new Rod("left", nDiscs);
centerRod = new Rod("center", nDiscs);
rigthRod = new Rod("rigth", nDiscs);
// put them on frame
pcentral.add(leftRod);
pcentral.add(centerRod);
pcentral.add(rigthRod);
// do update main panel with new components
pcentral.doLayout();
buildInitialDiscs((int) jsNumberOfTowers.getValue());
}
/**
* Creates the initial discs on the left Rod
*/
private void buildInitialDiscs(int nDiscs) {
for (int i = 0; i < nDiscs; i++) {
leftRod.addDisc(new Disc(nDiscs - i));
}
}
/**
* Start action, create a Thread to do the animation
*/
private void startScenario() {
isActive = true;
Thread t = new Thread(new Runnable() {
public void run() {
// solve
try {
int nMoves = moveHanoiDiscs(leftRod.getNDiscs(), leftRod,
rigthRod, centerRod);
System.out.println("Terminated with " + nMoves
+ " movements.");
} catch (InterruptedException e) {
// execution has canceled, nothing to do, just continue
}
// activate buttons
doneActions();
}
});
t.start();
}
/**
* Solves the Hanoi Towers in a recursive manner.
*
*
* @param nDiscs
* @param startRod
* , the start rod/pole for this movement
* @param endRod
* , the final rod/pole for this movement
* @param auxRod
* , the auxiliary rod/pole for this movement
*
* @return the number of movements
* @throws InterruptedException
*/
private int moveHanoiDiscs(int nDiscs, Rod startRod, Rod endRod, Rod auxRod)
throws InterruptedException {
// ======================================================
// TODO ESTE É O ÚNICO MÉTODO QUE DEVEM ALTERAR
// ======================================================
// não alterar as duas linhas seguintes
if (!isActive)
cancelExecution();
if (nDiscs == 1) {
Disc p = startRod.remDisc();
endRod.addDisc(p);
// necessário para dar um delay entre movimentos
Thread.sleep(movementsDelay);
return 1;
}
// metodo chamado para passar todos os discos menos o ultimo para a
// segunda parcela usando a ultima como auxiliar
moveHanoiDiscs(nDiscs - 1, startRod, auxRod, endRod);
// zona do codigo onde se retira o disco que falta na primeira parcela
// para a ultima parcela
moveHanoiDiscs(1, startRod, endRod, auxRod);
// metodo chamado para passar todos os discos que estao na segunda
// parcela para a terceira usando a primeira como auxiliar
moveHanoiDiscs(nDiscs - 1, auxRod, endRod, startRod);
return (int) Math.pow(2, nDiscs) - 1;
}
/**
* Cancel the current execution
*/
private void cancelExecution() {
// terminate simulation
Thread.currentThread().interrupt();
}
/**
* End execution actions - buttons actions
*/
private void doneActions() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
// activate buttons
jsNumberOfTowers.setEnabled(true);
buttonCreate.setEnabled(true);
buttonCancel.setEnabled(false);
jsMovementsDelay.setEnabled(true);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Método main
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
P03HanoiTowers bmapTrans = new P03HanoiTowers();
bmapTrans.init();
}
});
}
}
/**
* Class that supports a Disc
*
*/
class Disc {
private int size;
/**
* Constructor
*/
public Disc(int size) {
this.size = size;
}
/**
* Get the size of the disc
*/
public int getSize() {
return size;
}
}
/**
* Class that supports a Rod - uma haste
*
*/
class Rod extends JLabel {
private static final long serialVersionUID = 1L;
String name;
Disc[] discs;
int nDiscsOnRod = 0;
/**
* Constructor
*/
public Rod(String rodName, int maxSize) {
discs = new Disc[maxSize];
name = rodName;
}
/**
* Get the number of discs
*/
public int getNDiscs() {
return nDiscsOnRod;
}
/**
* Get the rod name
*/
public String getRodName() {
return name;
}
/**
* Add a disc, following the rule that it should not be placed on top of a
* bigger disc
*/
public void addDisc(Disc p) {
if (nDiscsOnRod > 0 && discs[nDiscsOnRod - 1].getSize() < p.getSize())
throw new IllegalStateException("We cannot put a disc of size "
+ p.getSize() + " on top of a disc of size "
+ discs[nDiscsOnRod - 1].getSize());
discs[nDiscsOnRod++] = p;
repaint();
}
/**
* Removes the top disc, if any
*/
public Disc remDisc() {
if (nDiscsOnRod == 0)
throw new IllegalStateException(
"We cannot remove a disc from an empty rod");
Disc p = discs[nDiscsOnRod - 1];
nDiscsOnRod--;
repaint();
return p;
}
/**
* Update the graphical aspect of the Rod
*/
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.MAGENTA);
g.fillRect(getWidth() / 2 - 2, getHeight() / 10, 4,
(int) (getHeight() * 0.9));
// draw discs
for (int i = 0; i < nDiscsOnRod; i++) {
int discSize = discs[i].getSize();
drawDisc(discSize, i, discs.length, g);
}
}
/**
* Draw a disc
*/
private void drawDisc(int size, int discNumber, int nDiscs, Graphics g) {
int discSize = (int) ((getHeight() - (double) getHeight() / 5) / nDiscs);
discSize = discSize > 20 ? 20 : discSize;
int discWidth = (int) ((getWidth() - (double) getWidth() / 10) * size / nDiscs);
g.setColor(Color.ORANGE);
g.fillRect((getWidth() - discWidth) / 2, getHeight() - discSize
* (1 + discNumber), discWidth, discSize);
g.setColor(Color.RED);
g.drawRect((getWidth() - discWidth) / 2, getHeight() - discSize
* (1 + discNumber), discWidth, discSize);
}
/**
* Get a String description of the Rod
*/
@Override
public String toString() {
return getRodName() + " " + getNDiscs();
}
}
<file_sep>package classcode.p14EDDLinkedLists.p3LinkedListWithIterator;
public class C01LinkedListException extends Exception {
private static final long serialVersionUID = -6207783708871573380L;
public C01LinkedListException() {
this(null);
}
public C01LinkedListException(String message) {
super("Linked List Exception" + message);
}
}
<file_sep>package classcode.p09EnumeradosENestedClasses;
public class C03EnumWithMoreState {
public static void main(String[] args) {
// values
TShirt2[] tshirts = TShirt2.values();
System.out.println("Listagem das tshirts:");
for (int i = 0; i < tshirts.length; i++) {
System.out.println("tshirt[" + i + "] -> " + tshirts[i]);
}
}
}
enum TShirt2 {
S(5.0f) {
// definição dos métodos abstractos
String getComment() {
return "too small";
}
},
M(6.0f) {
// int x = 0;
String getComment() {
// m1();
return "small";
}
// private void m1() {
// // ...
// }
},
L(6.5f) {
String getComment() {
return "large";
}
},
XL(8.0f) {
String getComment() {
return "too large";
}
};
private float price;
private TShirt2(float price) {
this.price = price;
}
public String toString() {
return super.toString() + ", " + price + ", " + getComment();
}
// método abstracto
abstract String getComment();
}<file_sep>package tps.tp3;
/**
* Classe que suporta um percurso simples
*
*/
public class PercursoSimples extends Percurso {
/**
* Nome do ponto de início do percurso
*/
private String inicio;
/**
* Nome do ponto de fim do percurso
*/
private String fim;
/**
* Distância em metros do percurso
*/
private int distancia;
/**
* Declive em metros, positivo, se fim mais alto que início
*/
private int declive;
/**
* Constructor. Deve validar o nome, inicio e fim com o método de validação
* validarNomeDelocal. A distância tem de ser positiva (>0)
*
* @param nome
* Nome do percurso
* @param inicio
* Local do início do percurso
* @param fim
* Local de im do percurso
* @param distancia
* Distancia do percurso
* @param declive
* Declive do percurso
*/
public PercursoSimples(String nome, String inicio, String fim,
int distancia, int declive) {
super(nome);
if (!validarNomeDeLocal(inicio))
throw new IllegalArgumentException("Nome de inicio inválido -> "
+ inicio);
if (!validarNomeDeLocal(fim))
throw new IllegalArgumentException("Nome de inicio inválido -> "
+ fim);
if(distancia <0)
throw new IllegalArgumentException("Distancia menor ou igual a zero -> "
+ distancia);
this.inicio=inicio;
this.fim = fim;
this.distancia= distancia;
this.declive=declive;
}
/**
* Construtor de cópia, deve chamar o constructor acima
*
* @param p
* O percurso a copiar
*/
public PercursoSimples(PercursoSimples p) {
this(p.getNome(), p.getInicio(), p.getFim(), p.getDistancia(), p
.getDeclive());
}
/**
* Deve criar uma cópia do percurso recebido
*/
public PercursoSimples clone() {
return new PercursoSimples(this.getNome(), this.getInicio(),
this.getFim(), this.getDistancia(), this.getDeclive());
}
/**
* Devolve o início do percurso
*/
public String getInicio() {
return inicio;
}
/**
* Devolve o fim do percurso
*/
public String getFim() {
return fim;
}
/**
* Devolve a distância do percurso
*/
public int getDistancia() {
return distancia;
}
/**
* Devolve o declive do percurso
*/
public int getDeclive() {
return declive;
}
/**
* Equals, deve devolver true se o percurso é do tipo PercursoSimples, se
* tem o mesmo nome, o mesmo início e o mesmo fim.
*
* @param percurso
* Percurso a comparar
*/
public boolean equals(Object percurso) {
boolean condition = false;
if((percurso != null)&&(percurso instanceof PercursoSimples)){
PercursoSimples auxPercurso = (PercursoSimples) percurso;
if(getNome().equals(auxPercurso.getNome()) && getInicio().equals(auxPercurso.getInicio()) && getFim().equals(auxPercurso.getFim())){
condition = true;
}
}
return condition;
}
/**
* Main, para realizar testes aos métodos
*/
public static void main(String[] args) {
PercursoSimples ps1 = new PercursoSimples("A2", "Lisboa", "Faro",
278_000, 0);
ps1.print("ps1 -> ");
PercursoSimples ps2 = new PercursoSimples("A1", "Lisboa", "Porto",
317_000, 0);
ps2.print("ps2 -> ");
boolean ps1ps2 = ps1.equals(ps2);
System.out.println("ps1.equals(ps2) -> " + ps1ps2);
System.out.println("ps1 toString -> " + ps1);
}
@Override
public String[] getLocalidades() {
return new String[] { getInicio(), getFim() };
}
public String getDescricao() {
return "simples";
}
}
<file_sep>package classcode.p12Generics;
import java.util.Arrays;
import java.util.Collection;
public class C08TestExtendsWildcard {
Pessoa[] pessoal = new Pessoa[100];
int nPessoas = 0;
// pode receber arrays de Pessoa ou classes derivadas
public boolean addAll(Pessoa[] pessoas) {
if (pessoal.length < pessoas.length + nPessoas)
return false;
for (Pessoa p : pessoas)
pessoal[nPessoas++] = p;
return true;
}
// com genéricos - desnecessário
public <T extends Pessoa> boolean addAll2(T[] pessoas) {
if (pessoal.length < pessoas.length + nPessoas)
return false;
for (Pessoa p : pessoas)
pessoal[nPessoas++] = p;
return true;
}
// com classes contentoras de pessoas- não aceita Collection de Aluno
public boolean addAll(Collection<Pessoa> pessoas) {
Pessoa[] novasPessoas = pessoas.toArray(pessoal);
return addAll(novasPessoas);
}
// agora já aceita
public boolean addAll2(Collection<? extends Pessoa> pessoas) {
Pessoa[] novasPessoas = pessoas.toArray(pessoal);
return addAll(novasPessoas);
}
// o mesmo método mas escrito de outra forma
public <T extends Pessoa> boolean addAll3(Collection<T> pessoas) {
Pessoa[] novasPessoas = pessoas.toArray(pessoal);
return addAll(novasPessoas);
}
public String toString() {
return Arrays.toString(Arrays.copyOf(pessoal, nPessoas));
}
public static void main(String[] args) {
Pessoa[] people = { new Pessoa("Ana", 111111) };
C06Aluno[] students = { new C06Aluno("Luís", 111112, 1000, 3) };
C08TestExtendsWildcard staff = new C08TestExtendsWildcard();
staff.addAll(people);
staff.addAll(students);
staff.addAll2(students);
Collection<Pessoa> cp = Arrays.asList(new Pessoa("Ana", 111111));
Collection<C06Aluno> ca = Arrays.asList(new C06Aluno("Luís", 111112,
1000, 3));
staff.addAll(cp);
// staff.addAll(ca); // ERRO DE COMPILAÇÂO
staff.addAll2(cp);
staff.addAll2(ca);
System.out.println("done");
}
}
<file_sep>/*
* Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle or the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package classcode.p15Swing.p09MoreStuff;
/**
* TabbedPaneDemo.java requires one additional file:
* images/middle.gif.
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;
import classcode.p15Swing.p02buildedLayouts.CenterLayout;
import classcode.p15Swing.p02buildedLayouts.ProportionalLayout;
public class C07TabbedPaneDemo extends JPanel {
private static final long serialVersionUID = 1L;
private Random rg = new Random();
public C07TabbedPaneDemo() {
super(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane();
ImageIcon icon = createImageIcon("images/middle.gif");
ImageIcon icon2 = createImageIcon("images/middle2.gif");
ImageIcon icon3 = createImageIcon("images/middle3.gif");
ImageIcon icon4 = createImageIcon("images/middle4.gif");
JComponent panel1 = makePanel1("Panel #1");
tabbedPane.addTab("Tab 1", icon, panel1, "Does nothing");
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
JComponent panel2 = makePanel2("Panel #2");
tabbedPane.addTab("Tab 2", icon2, panel2, "Does twice as much nothing");
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
JComponent panel3 = makePanel3("Panel #3");
tabbedPane.addTab("Tab 3", icon3, panel3, "Still does nothing");
tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
JComponent panel4 = makePanel4("Panel #4");
panel4.setPreferredSize(new Dimension(410, 50));
tabbedPane.addTab("Tab 4", icon4, panel4, "Does nothing at all");
tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
// Add the tabbed pane to this panel.
add(tabbedPane);
// The following line enables to use scrolling tabs.
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
}
protected JComponent makeTextPanel(String text) {
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
}
protected JComponent makePanel1(String text) {
JPanel panel = new JPanel(false);
panel.setLayout(new ProportionalLayout(0.15f));
JLabel filler = new JLabel(text);
filler.setBorder(new LineBorder(Color.green, 5, true));
filler.setHorizontalAlignment(JLabel.CENTER);
panel.add(filler);
return panel;
}
protected JComponent makePanel2(String text) {
JPanel panel = new JPanel(new ProportionalLayout(0.05f, 0.1f, 0.1f,
0.1f));
JLabel label = new JLabel(text);
label.setBorder(new LineBorder(Color.blue, 5, true));
label.setHorizontalAlignment(JLabel.CENTER);
panel.add(label, ProportionalLayout.CENTER);
JPanel panelParentControl = new JPanel(new CenterLayout());
JPanel panelControl = new JPanel();
panelControl.add(new JButton("Adicionar"));
panelControl.add(new JButton("Remover"));
panelParentControl.add(panelControl);
panel.add(panelParentControl, ProportionalLayout.SOUTH);
return panel;
}
// protected JComponent makePanel2(String text) {
// JPanel panel = new JPanel(false);
// panel.setLayout(new BorderLayout());
//
// JPanel panelCenter = new JPanel(new ProportionalLayout(0.1f, 0.1f,
// 0.3f, 0.3f));
// JLabel filler = new JLabel(text);
// filler.setBorder(new LineBorder(Color.blue, 5, true));
// filler.setHorizontalAlignment(JLabel.CENTER);
// panelCenter.add(filler);
//
// panel.add(panelCenter, ProportionalLayout.CENTER);
//
// JPanel panelParentControl = new JPanel(new CenterLayout());
// JPanel panelControl = new JPanel();
// panelControl.add(new JButton("Adicionar"));
// panelControl.add(new JButton("Remover"));
//
// panelParentControl.add(panelControl);
//
// panel.add(panelParentControl, ProportionalLayout.SOUTH);
// return panel;
// }
protected JComponent makePanel3(String text) {
JPanel panel = new JPanel(false);
panel.setLayout(new ProportionalLayout(0.1f, 0.1f, 0.1f, 0.1f));
int nCells = 10;
JPanel panelx = new JPanel(new GridLayout(1, nCells));
for (int i = 0; i < nCells; i++) {
JLabel label = new JLabel();
label.setBackground(new Color(rg.nextInt(256), rg.nextInt(256), rg
.nextInt(256)));
label.setOpaque(true);
panelx.add(label);
}
panel.add(panelx);
return panel;
}
protected JComponent makePanel4(String text) {
JPanel panel = new JPanel(false);
panel.setLayout(new GridLayout(1, 2));
panel.add(makePanel2("esq"));
panel.add(makePanel2("dir"));
return panel;
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = C07TabbedPaneDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event dispatch thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("TabbedPaneDemo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Add content to the window.
frame.add(new C07TabbedPaneDemo(), BorderLayout.CENTER);
// Display the window.
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event dispatch thread:
// creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
<file_sep>package classcode.p01IntroJava;
import java.util.Scanner;
public class C02MySecondClass {
public static void main(String[] args) {
Scanner keyboard = new java.util.Scanner(System.in);
System.out.println("inteiro -> ");
int val = keyboard.nextInt();
System.out.println("o inteiro lido foi " + val);
keyboard.close();
}
}
<file_sep>package classcode.p07Inheritance.cenario1Pontos;
/**
* Class Ponto2D - suporta um ponto num espaço a duas dimensões. Exemplifica
* herança. Chamada ao construtor super; chamada a métodos sobrepostos
* (getDescricao e toString)
*
*/
public class Ponto2D extends Ponto1D {
int y;
//
// ## Métodos ## ----------------------
public Ponto2D(int x, int y) {
super(x);
this.y = y;
//super.x = x;
}
public String getDescricao() {
return super.getDescricao() + ", y -> " + y;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
/**
*
*/
public static void main(String[] args) {
Ponto2D p1 = new Ponto2D(3, 5);
System.out.println(p1);
System.out.println();
// utilização dos métodos getX e setX definidos na classe base
p1.x = p1.x * 2;
System.out.println("x = x * 2 -> " + p1);
p1.y = p1.y * 2;
System.out.println("y = y * 2 -> " + p1);
}
}
<file_sep>package classcode.p14EDDLinkedLists.p3LinkedListWithIterator;
import java.util.Iterator;
/**
* Com esta demo pretende-se demonstrar que a utilização de iteradores gera
* excepções de concurrent modification quando um iterador está a iterarar e
* ocorre uma alteração na lista fora da interface Iterator e no iterador em
* questão.
*
* @author <NAME>
*
*/
public class C07StringLinkedListWithSelfIterator4Demo {
public static void main(String[] args) {
C06StringLinkedListWithSelfIterator4<String> stringList = new C06StringLinkedListWithSelfIterator4<String>();
System.out.println("Lista de String ...");
stringList.addANodeToStart("Hello");
stringList.addANodeToStart("Good-bye");
System.out.println("\nListagem da lista:");
stringList.showList();
Iterator<String> it1 = stringList.iterator();
@SuppressWarnings("unused")
Iterator<String> it2 = stringList.iterator();
it1.next();
it1.remove();
// it2.next(); // teste1 - depois, comentar para ver teste 2
// excepção devido a alteração através de iterador concorrente
stringList.addANodeToStart("Hello");
it1.next(); // teste 2 - excepção por alteração concorrente
// mas devido a inserção directa na lista
}
}
<file_sep>package classcode.p07Inheritance.cenario2Figuras;
/**
* Class Ponto3D - suporta um ponto num espaço a três dimensões
*
*/
public class C03Ponto3D extends C02Ponto2D {
int z;
//
// ## Métodos ## ----------------------
public C03Ponto3D(int x, int y, int z) {
super(x, y);
this.z = z;
}
public int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
public String getDescricao() {
return super.getDescricao() + ", z -> " + getZ();
}
/**
*
*/
public static void main(String[] args) {
C03Ponto3D p1 = new C03Ponto3D(3, 5, 7);
System.out.println(p1);
System.out.println();
// utilização dos métodos getX e setX definidos na classe base de todas
p1.setX(p1.getX() * 2);
System.out.println("x = x * 2 -> " + p1);
// utilização dos métodos getY e setY definidos na classe super
p1.setY(p1.getY() * 2);
System.out.println("y = y * 2 -> " + p1);
p1.setZ(p1.getZ() * 2);
System.out.println("z = z * 2 -> " + p1);
}
}
<file_sep>package classcode.p14EDDLinkedLists.p2GenericLinkedList;
import java.util.*;
public class C02GenericListDemo {
public static void main(String[] args) {
C01GenericLinkedList<String> stringList = new C01GenericLinkedList<String>();
System.out.println("Lista de String ...");
stringList.addANodeToStart("Hello");
stringList.addANodeToStart("Good-bye");
System.out.println("\nListagem da lista:");
stringList.showList();
String aux = stringList.deleteHeadNode();
System.out.println("\nFoi removido o elemento -> " + aux);
System.out.println("\nListagem da lista:");
stringList.showList();
System.out.println("\nLista de Integer ...");
C01GenericLinkedList<Integer> numberList = new C01GenericLinkedList<Integer>();
int i;
for (i = 0; i < 10; i++)
numberList.addANodeToStart(i);
ArrayList<Integer> v = numberList.ArrayListCopy();
int position;
int vectorSize = v.size();
for (position = 0; position < vectorSize; position++)
System.out.println(v.get(position));
}
}
<file_sep>package classcode.p00aulas;
public class fibonacci {
public static void main(String[] args) {
//fibonacci(10);
fibonacciR(10);
}
/*public static int fibonacci(int val) {
int aux = 0;
int current = 1;
int actual = 0;
for (int i = 0; i < val - 2; i++) {
if (i == 0) {
System.out.println(0);
}
if (i == 1) {
System.out.println(1);
}
actual = aux + current;
aux = current;
current = actual;
System.out.println(actual);
}
return current;
}*/
public static int fibonacciR(int val){
if(val == 0) return 0;
if(val == 1) return 1;
return fibonacciR(fibonacciR(val-1) + fibonacciR(val-2));
}
}
<file_sep>package classcode.p15Swing.p02buildedLayouts;
/*
* CustomLayoutDemo.java requires the class:
* CenterLayout.java
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
/**
* CenterLayoutDemo - os botões diminuem ou aumentam a dimensão dos insets
*
* Asuntos: CenterLayout
*
* @author <NAME>
*
*/
public class XProportionalLayoutDemo {
public static void addComponentsToPane(Container pane) {
ProportionalLayout lm = new ProportionalLayout(0.20f);
pane.setLayout(lm);
int[] colors = { 0x0588B4 /* Center */, 0x0969B8 /* Norte */,
0x0969B8 /* Sul */, 0x69A7DB/* Oeste */, 0x69A7DB /* Este */};
final JLabel labelCenter = new JLabel();
labelCenter.setVerticalAlignment(SwingConstants.CENTER);
labelCenter.setHorizontalAlignment(SwingConstants.CENTER);
labelCenter.setBackground(new Color(colors[0]));
labelCenter.setOpaque(true);
labelCenter.setPreferredSize(new Dimension(100, 100));
pane.add(labelCenter);
final JLabel labelN = new JLabel();
labelN.setVerticalAlignment(SwingConstants.CENTER);
labelN.setHorizontalAlignment(SwingConstants.CENTER);
labelN.setPreferredSize(new Dimension(100, 50));
labelN.setBackground(new Color(colors[1]));
labelN.setOpaque(true);
pane.add(labelN, BorderLayout.NORTH);
final JLabel labelS = new JLabel();
labelS.setVerticalAlignment(SwingConstants.CENTER);
labelS.setHorizontalAlignment(SwingConstants.CENTER);
labelS.setPreferredSize(new Dimension(100, 50));
labelS.setBackground(new Color(colors[2]));
labelS.setOpaque(true);
pane.add(labelS, BorderLayout.SOUTH);
final JLabel labelW = new JLabel();
labelW.setVerticalAlignment(SwingConstants.CENTER);
labelW.setHorizontalAlignment(SwingConstants.CENTER);
labelW.setPreferredSize(new Dimension(50, 100));
labelW.setBackground(new Color(colors[3]));
labelW.setOpaque(true);
pane.add(labelW, BorderLayout.WEST);
final JLabel labelE = new JLabel();
labelE.setVerticalAlignment(SwingConstants.CENTER);
labelE.setHorizontalAlignment(SwingConstants.CENTER);
labelE.setPreferredSize(new Dimension(50, 100));
labelE.setBackground(new Color(colors[4]));
labelE.setOpaque(true);
pane.add(labelE, BorderLayout.EAST);
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI(int x, int y) {
// Create and set up the window.
JFrame frame = new JFrame("Proportional Layout Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Set up the content pane.
addComponentsToPane(frame.getContentPane());
// Display the window.
// frame.pack();
frame.setSize(x, y);
// frame.setMinimumSize(new Dimension(200, 200));
// to center a frame
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI(300, 300);
createAndShowGUI(200, 200);
}
});
}
}
<file_sep>package classcode.p12Generics;
/**
* Uma Box genérica - ou seja, permite definir Boxes dos vários tipos
*/
public class C02Box2<T> {
private T t; // T stands for "Type"
public C02Box2(T t) {
set(t);
}
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
public static void main(String[] args) {
/***********************************************
* a box of integer
*/
// boxing - passar automáticamente de int para Integer
C02Box2<Integer> integerBox = new C02Box2<Integer>(100);
integerBox.set(10);
// integerBox.set("ola");
Integer i1 = 200;
integerBox.set(i1);
Integer theValue = integerBox.get(); // no cast!
System.out.println(theValue);
/***********************************************
* a box of integers
*/
C02Box2<String> strBox = new C02Box2<String>("olá");
String value = strBox.get();
System.out.println(value);
/***********************************************
* a box of box of string
*/
C02Box2<C02Box2<String>> strBBox = new C02Box2<C02Box2<String>>(strBox);
C02Box2<String> b = strBBox.get();
System.out.println(b.get());
}
}
<file_sep>package classcode.p15Swing.p03eventframes;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
import classcode.p15Swing.p02buildedLayouts.ProportionalLayout;
/**
* Um só listener para os dois botões.
*
* Agora a classe é ela própria uma JFrame.
*
*
* @author <NAME>
*
*/
public class C5MyButtonsFrame extends JFrame {
private static final long serialVersionUID = 1L;
FlowLayout fl = null;
JLabel label1 = null;
JButton button1 = null;
JButton button2 = null;
JPanel buttonsPanel = null;
/**
* Este método cria toda a frame e coloca-a visível
*
*/
public void init() {
// set title
setTitle("...: My fifth buttons frame :...");
// set size
setSize(400, 200);
// set location
setLocationRelativeTo(null); // to center a frame
// set what happens when close button is pressed
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
ProportionalLayout cl = new ProportionalLayout(0.0f);
cl.setInsets(0.2f, 0.1f, 0.2f, 0.2f);
setLayout(cl);
JPanel panelTop = new JPanel();
panelTop.setLayout(new BorderLayout());
// build JLabel
label1 = new JLabel("Hello!!!");
label1.setHorizontalAlignment(SwingConstants.CENTER);
label1.setBorder(new LineBorder(new Color(100, 210, 80)));
panelTop.add(label1, BorderLayout.CENTER);
// build button's panel
JPanel panelButtons = new JPanel();
// build JButton1
button1 = new JButton("Button1");
// este ActionCommand permite identificar o botão
button1.setActionCommand("Button1");
panelButtons.add(button1);
// build JButton2
button2 = new JButton("Button2");
button2.setActionCommand("Button2");
panelButtons.add(button2);
panelTop.add(panelButtons, BorderLayout.PAGE_END);
add(panelTop);
// set dynamic part =======================================
ActionListener actionListener = new ActionListener() {
int n1 = 0, n2 = 0;
public void actionPerformed(ActionEvent e) {
JButton jb = (JButton) e.getSource();
int n;
if (jb.getActionCommand().equals("Button1"))
n = ++n1;
else
n = ++n2;
jb.setText(jb.getActionCommand() + " - " + (n));
label1.setText("Hello!! That's me "
+ ((JButton) e.getSource()).getActionCommand() + " - "
+ n);
System.out.println(" Action event from button "
+ jb.getActionCommand());
}
};
button1.addActionListener(actionListener);
button2.addActionListener(actionListener);
// puts the frame visible (is not visible at start)
setVisible(true);
}
/**
* Main
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
System.out.println("End of main...");
}
public static void createAndShowGUI() {
C5MyButtonsFrame myFrame = new C5MyButtonsFrame();
myFrame.init();
// life goes on
System.out.println("Frame created...");
}
}
|
af053f4e906f05e760a097ad0779e69d2e1da48b
|
[
"Markdown",
"Java",
"HTML"
] | 120 |
Java
|
joaoolival/MOP
|
934050d1a725494c888a831ab2f449d47dd39b0d
|
d06c350c10e60d8d45291e745d7eba71d33fbf44
|
refs/heads/master
|
<repo_name>isawzz/simplesimpleserver<file_sep>/styling.js
//styles
function styling() {
let dMain = mBy('dMain');
let dTitle = mBy('dTitle');
let dChat = mBy('dChat');
mStyleX(dTitle, {paleft: 20});
return;
let styles = {bg: 'random'};
for (const d of [dMain, dTitle, dChat]) {
mStyleX(d, styles);
}
return;
mStyleX(dTitle, {display: 'inline-block', align: 'center', bg: 'random'});
mStyleX(dChat, {display: 'inline-block', align: 'center', bg: 'random'});
mCenterFlex(dMain);
}
//styling();
<file_sep>/servehtml.js
const path = require('path');
const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
app.use(express.static(path.resolve(__dirname,'')));
let port = process.env.PORT || 3000;
server.listen(port,()=>console.log(`listening on ${port}`));
<file_sep>/servertest.js
const path = require('path');
const express = require("express");
const app = express();
app.use(express.static(path.resolve(__dirname,'')));
const http = require("http");
const server = http.createServer(app);
const io = require('socket.io')(server);
io.on('connection',client=>{
handleConnection(client);
client.on('disconnect',()=>handleDisconnect(client));
client.on('fromClient',x=>handleFromClient(client,x));
client.on('ping',x=>handlePing(client,x));
});
let port = process.env.PORT || 3000;
server.listen(port,()=>console.log(`listening on ${port}`));
function handleConnection(client){
console.log('...connected:',client.id);
io.emit('fromServer',{msg:`user ${client.id} joined`});
}
function handleDisconnect(client){
console.log('user disconnected:',client.id);
io.emit('fromServer',{msg:`user ${client.id} left`});
}
function handleFromClient(client,x){
console.log('from client:',client.id,x.msg);
}
function handlePing(client,x){
console.log('ping from:',client.id);
client.emit('ping');
}
|
b9e9c6bee83c62db9e6425be1c6b31ad854c877e
|
[
"JavaScript"
] | 3 |
JavaScript
|
isawzz/simplesimpleserver
|
895fefa011e732c70aaf4317de6091a260b385ab
|
a55f5bdd2c658778e8d2fd6775857f0520756cdc
|
refs/heads/master
|
<file_sep>export default {
cityHandle(state, val) {
state.city = val
try{
localStorage.city = val
}catch(e) {
console.log(e.message)
}
}
}<file_sep>export default {
cityHandle(ctx, val) {
ctx.commit('cityHandle', val)
}
}
|
bc5c46323cf10d7937f718124437bbe950ad1236
|
[
"JavaScript"
] | 2 |
JavaScript
|
william-1992/meituan
|
6bb8d5e4f5a3c2587dd6450e3fc181f0114652c6
|
34cc5456682577e3513387c14039731d503a4393
|
refs/heads/master
|
<repo_name>kwonsjay/ChatApp<file_sep>/router.js
var fs = require('fs');
var path = require('path');
var mime = require('mime');
function serve(response, filePath) {
fs.readFile(filePath, function(error, data) {
if (error) {
console.log(error);
}
else {
response.writeHead(200, {
"Content-Type": mime.lookup(path.basename(filePath))
});
response.end(data);
}
});
}
function route(request, response) {
if (request.url == "/") {
serve(response, "public/index.html");
}
else {
serve(response, "public" + request.url);
}
}
exports.route = route;
|
d3ddb2fd174c0b240bdee6c390bbca609ece3224
|
[
"JavaScript"
] | 1 |
JavaScript
|
kwonsjay/ChatApp
|
575a047de4870ba4b7898ef2b6aff70ceb4141d2
|
869c4ad373805a8b094318491b59284f827d6213
|
refs/heads/master
|
<repo_name>zyzy11/axiosModulePackaging<file_sep>/request.js
/**** request.js ****/
/**axios封装 为了保证通用性 此文件建议不进行任何改动 */
// 导入axios
import axios from 'axios'
import qs from 'qs'
let _ = require('lodash');
//1. 创建新的axios实例,
const service = axios.create({
// 公共接口
baseURL: process.env.BASE_API,
// 超时时间 单位是ms,这里设置了3s的超时时间
timeout: 3 * 1000,
showLoading: true,//是否开启loading动画
});
/**请求时显示加载动画 函数声明(挂在service里面是为了跟着service一起被公布出去便于拓展) S*/
service.loadingTool = {};
service.loadingTool.needLoadingRequestCount = 0;
service.loadingTool.startLoading = function () {
//故意不写逻辑
//通过requestEx.js拓展重写此函数 开启loading动画函数
}
service.loadingTool.showFullScreenLoading = function () {
if (service.loadingTool.needLoadingRequestCount === 0) {
service.loadingTool.startLoading()
}
service.loadingTool.needLoadingRequestCount++
}
service.loadingTool.tryHideFullScreenLoading = function () {
if (service.loadingTool.needLoadingRequestCount <= 0) return
service.loadingTool.needLoadingRequestCount--
if (service.loadingTool.needLoadingRequestCount === 0) {
_.debounce(function () {
if (typeof (service.loadingTool.tryCloseLoading) == 'function' && service.loadingTool.needLoadingRequestCount === 0) {
service.loadingTool.tryCloseLoading();
}
}, 300)()//防止函数抖动,当有多个loading的时候避免间隔闪烁
}
}
service.loadingTool.tryCloseLoading = function () {
//故意不写逻辑
//通过requestEx.js拓展重写此函数 关闭loading动画函数
}
/**请求时显示加载动画 E*/
/**额外拓展开始 S */
service.loadingTool.setRequestConfig = function(config){
//自定义请求的config配置
return config;
}
service.loadingTool.onloadSucceedEx = function(){
//请求成功时 执行额外的检查 例如 登录检查 特殊判断
//带data参数(返回数据)
}
service.loadingTool.onloadErrorEx = function(errStr){
//请求失败时时 执行额外的检查 例如 登录检查 特殊判断
alert(errStr);
}
/**额外拓展开始 E */
// 2.请求拦截器
service.interceptors.request.use(config => {
if (config.showLoading) {//开启loading
service.loadingTool.showFullScreenLoading()
}
//发请求前做的一些处理,数据转化,配置请求头,设置token,设置loading等,根据需求去添加
config.headers = {
Pragma: 'no-cache',//兼容ie(避免IE存在在当前页面没刷新的情况下再次请求接口直接拿缓存)
'Content-Type': 'application/x-www-form-urlencoded',//配置请求头
'Content-Security-Policy': "default-src 'self'; child-src http:" //csp头部设置
}
//注意使用token的时候需要引入cookie方法或者用本地localStorage等方法,推荐js-cookie
const user = window.$ && window.$.getLoginUser() ? window.$.getLoginUser() : null;
const token = user && user.Token ? user.Token : '';//这里取token之前,你肯定需要先拿到token,存一下
if (token) {
config.params = { 'token': token } //如果要求携带在参数中
config.headers.token = token; //如果要求携带在请求头中
}
// 如果有登录用户信息,则统一设置 token
if (config.method == 'post') {
config.data.token = config.data.token && config.data.token.length > 0 ? config.data.token : token;
//使用qs转换post请求的data
config.data = qs.stringify(config.data);
}
else if (config.method == 'get') {
config.params.token = config.params.token && config.params.token.length > 0 ? config.params.token : token;
}
if(typeof service.loadingTool.setRequestConfig=='function'){
config = service.loadingTool.setRequestConfig(config);
}
return Promise.resolve(config)
}, error => {
Promise.reject(error)
})
// 3.响应拦截器
service.interceptors.response.use(response => {
//接收到响应数据并成功后的一些共有的处理,关闭loading等
// 对响应数据做点什么
if (response.config.showLoading) {//关闭loading
service.loadingTool.tryHideFullScreenLoading()
}
let data = response.data;
if(typeof service.loadingTool.tryCloseLoading=='function'){
service.loadingTool.onloadSucceedEx(data);
}
return data
}, error => {
var errStr = '';
/***** 接收到异常响应的处理开始 *****/
if (error && error.response) {
// 1.公共错误处理
// 2.根据响应码具体处理
errStr = error.message;
} else {
// 超时处理
if (JSON.stringify(error).includes('timeout')) {
errStr = '服务器响应超时,请刷新当前页';
}
errStr = '连接服务器失败';
}
if(typeof service.loadingTool.onloadErrorEx=='function'){
service.loadingTool.onloadErrorEx(errStr)
}
// Message.error(error.message)
/***** 处理结束 *****/
//如果不需要错误处理,以上的处理过程都可省略
return Promise.resolve(error.response)
})
//4.导入文件
export default service<file_sep>/README.md
# axiosModulePackaging
axios封装组件(vue版), vue项目 可以直接引用
# request.js 文件(建议不修改)
最底层的封装(不建议改动),想让它保持最纯净的状态,需要拓展需要在requestEx.js文件中进行函数重写拓展(后续会说到)
# requestEx.js 文件(可以随意修改)
属于request.js拓展文件 这个文件中可以针对request.js进行重写拓展. 比如 加载动画(loading),请求头部的设置等等...
# http.js 文件(可以随意修改)
针对四种请求的封装,对于get post 这种常用类型增加了 加载动画的开关(loading)
# sysApi.js 文件(定义服务管理的文件,名字可以自定义)
针对服务端提供的服务统一集合管理(如同后端的服务层的思想),虽然比起直接调用axios要麻烦点点,当时通过本人项目的检验,这一套封装能够使你更好的管理请求服务,并且能统一请求的行为
# 一些重要的事情
1.里面引入的文件位置可能使用的各位需要自行根据项目路径更改(import xx from xx)
2.当然必须引入axios组件就不用多说了
3.xxApi.js文件当然是多个的
# 聊聊闲话
欢迎指出问题,欢迎反驳
<file_sep>/sysApi.js
import http from '../ResourceUtils/http'
//
/**
* 对请求像后端服务接口一样规范起来在统一文件夹统一位置进行接口服务的封装
* @parms resquest 当前api全局请求地址 解决多个站点服务访问问题
*/
let resquest = "/sysWebService";//配置依据vue.config.js根据代理命名而来
const sysApi = {
/**get请求 */
getListAPI(params){
return http.get(`${resquest}//Service/RoleRightMge.svrx/GetUserRights`,params)
},
/*各类型请求的例子 */
// post请求
postFormAPI(params){
return http.post(`${resquest}/postForm.json`,params)
},
// put 请求
putSomeAPI(params){
return http.put(`${resquest}/putSome.json`,params)
},
// delete 请求
deleteListAPI(params){
return http.delete(`${resquest}/deleteList.json`,params)
},
}
//导出
export default sysApi<file_sep>/requestEx.js
import service from './request';
import { Loading } from 'element-ui'
import { MessageBox } from 'element-ui';
import AppConfig from '../../public/static/App_Resources/js/AppSelfConfig';
/**此js是拓展request.js 让 request.js尽可能少引用其他东西 尽可能的通用便于在多个项目中使用
* 如项目中针对request有特定定制逻辑
* 必须在此js中拓展或重写request.js中的一些函数(检查错误方面不是很全面,需要自己重写函数时多注意!!!!!)
* 总之此文件可以随意根据项目需求进行复写定制化axios的封装
*/
/**重写axios的一些函数 */
if(service.loadingTool){
//重写自定义请求的config配置
// service.loadingTool.setRequestConfig = function(config){
// config.headers = {
// Pragma: 'no-cache',//兼容ie(避免IE存在在当前页面没刷新的情况下再次请求接口直接拿缓存)
// 'Content-Type': 'application/x-www-form-urlencoded',//配置请求头
// 'Content-Security-Policy': "default-src 'self'; child-src http:" //csp头部设置
// }
// return config;
// }
//开启动画 重写loading动画
service.loadingTool.startLoading = function(){
service.loadingTool.loading = Loading.service({
lock: true,
text: '加载中……',
// background: 'rgba(0, 0, 0, 0.5)'//黑色背景
})
};
//关闭动画 重写loading动画
service.loadingTool.tryCloseLoading = function(){
if (service.loadingTool.loading) {
service.loadingTool.loading.close()
}
}
//重写请求成功后
service.loadingTool.onloadSucceedEx = function(data){
//请求成功时 执行额外的检查 例如 登录检查 特殊判断
if (data.ErrorCode === -3 || data.Msg === "未登录或登录超时") {
MessageBox.alert('登录超时!请重新登录', '提示信息', {
type: 'error',
dangerouslyUseHTMLString: true,
callback: function () {
//!!!!!!!!!!!!!跨站点所有这样写 其他项目用声明注释
window.location.href = AppConfig.loginPageUrl.replace(
"{{port}}",
window.port
);
}
});
}else if(data.ErrorCode !== 0){
MessageBox.alert(data.Message, {
type: 'error',
dangerouslyUseHTMLString: true,
});
}
}
//重写请求失败后
service.loadingTool.onloadErrorEx = function(errStr){
//请求失败时时 执行额外的检查 例如 登录检查 特殊判断
MessageBox.alert(errStr, '提示信息', {
type: 'error',
dangerouslyUseHTMLString: true
});
}
}
//4.导入文件
export default service;
|
68a303a4dc3df77d2def1a6b9f9e43a3d7017bc2
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
zyzy11/axiosModulePackaging
|
a32138a8e51c04688a8965b63c59e9130774ee2c
|
6df5e126331c27d84046535966afbc08d82b7bdc
|
refs/heads/main
|
<repo_name>Kaarunja/Hospital-Management-System-<file_sep>/README.md
# Hospital-Management-System-
Team Software Project
|
201ba48225acdbce0a4256ca7373d61097e348ba
|
[
"Markdown"
] | 1 |
Markdown
|
Kaarunja/Hospital-Management-System-
|
a430fc7488c7487e1a8ff069c963860e5e920400
|
43d30721fca2a3815f7ef9fb5bd80a86aeb2602d
|
refs/heads/main
|
<repo_name>OakLabsInc/docker-java-demo<file_sep>/README.md
# Docker Java Demo
This project is meant to demonstrate the use of docker-compose and a Dockerfile to build a java application and then start up the container.
## Prerequisites
In order to run this application you need to install two tools: **Docker** & **Docker Compose**.
Instructions how to install **Docker** on [Ubuntu](https://docs.docker.com/install/linux/docker-ce/ubuntu/), [Windows](https://docs.docker.com/docker-for-windows/install/), [Mac](https://docs.docker.com/docker-for-mac/install/).
**Docker Compose** is already included in installation packs for *Windows* and *Mac*, so only Ubuntu users needs to follow [this instructions](https://docs.docker.com/compose/install/).
## Build and Start
This command should build the maven project and deploy it to the container.
``` bash
docker-compose up --build
```
## Start Only
After the app has been built, it can be just started.
``` bash
docker-compose up
```
## Stop
Always stop the last docker compose start command before issuing another.
> make sure to stop every `docker-compose up` command
``` bash
docker-compose down
```
## Test build
If all went well, you should be able to view the data results at this url:
**http://localhost:8081/springbootapp/employees**
<file_sep>/app/Dockerfile
FROM maven:3.6.1-jdk-8-alpine AS build
RUN mkdir -p /workspace
WORKDIR /workspace
COPY . /workspace
RUN mvn package spring-boot:repackage
FROM amazoncorretto:8-alpine
COPY --from=build /workspace/target/spring-boot-app-0.0.1-SNAPSHOT.war /app.war
ENV JAVA_HOME /usr/
EXPOSE 8081
CMD java -jar -Dspring.profiles.active=default /app.war<file_sep>/app/src/main/resources/myData.sql
insert into employee(name) values ('ana');
insert into employee(name) values ('john');
insert into employee(name) values ('richardo');
|
a7e32d83ebfab16b417a56e456b81aa0b6866e90
|
[
"Markdown",
"SQL",
"Dockerfile"
] | 3 |
Markdown
|
OakLabsInc/docker-java-demo
|
7f2f88d59b0a82936b176949f45d04b704592063
|
7a45621eb7ac6bc9215994716c1675d0a94661bd
|
refs/heads/master
|
<file_sep>"""
<NAME>
09/09/2016
This program aims to create a shopping list.
Users can show completed or needed items, add their own items and
check off the required items into the completed category.
Github: https://github.com/ErikCronin/ShoppingList
"""
def main():
shopping_list = open("items.csv", "r+")
list_of_items = marked_func(shopping_list)
print("Shopping List 1.0 - by <NAME>")
menu_choice = menu_choice_func()
while menu_choice != "Q":
# List Required Items
if menu_choice == "R":
required_items(list_of_items, "r")
# List Completed Items
elif menu_choice == "C":
required_items(list_of_items, "c")
# Add New Items
elif menu_choice == "A":
item_name = str(input("Enter the name of the new item: "))
item_price = str(input("Enter the price of the new item: "))
item_priority = str(input("Enter the priority of the new item: "))
new_item_list = item_name + "," + item_price + "," + item_priority + ",r"
list_of_items.append(new_item_list)
print(item_name, "has been added to the list")
# Mark an item as completed
elif menu_choice == "M":
ask_question = True
while ask_question:
required_items(list_of_items, "r")
while True:
try:
mark_completion = int(input("Enter the number of an item to be marked as completed. "))
break
except ValueError:
print("You did not enter a number. Please enter a number.")
write_list = list_of_writable_items(list_of_items, "r")
completed_list = list_of_writable_items(list_of_items, "c")
if mark_completion < len(write_list):
print("Item number", mark_completion, "has been marked off")
write_list[mark_completion] += "c"
completed_list.append(write_list[mark_completion])
write_list.remove(write_list[mark_completion])
list_of_items = write_list + completed_list
ask_question = False
else:
print("Invalid input!")
# Error Check
else:
print("Invalid Input! Please try again.")
menu_choice = menu_choice_func()
shopping_list = open("items.csv", "w")
for item in list_of_items:
shopping_list.writelines(item + '\n')
shopping_list.close()
print("Shopping list has been saved.\nHave a nice day :)")
# Function for choosing menu option
def menu_choice_func():
menu_select = input("Menu:\nR - List Required Items\n"
"C - List Completed Items\nA - Add New Item\n"
"M - Mark an Item as Completed\nQ - Quit\n"
"Please choose an option: ")
menu_select = menu_select.upper()
return menu_select
# Function to show required items (r) or completed items (c)
def required_items(shopping_list, status):
line_number = 0
for line_str in shopping_list:
if line_str[-1] == status:
line_str = line_str.split(",")
line_str[1] = float(line_str[1])
print("{:1}. {:20} ${:10.2f} ({:s})".format(line_number, line_str[0], line_str[1], line_str[2]))
line_number += 1
return line_str
# Function to load shopping list into internal memory
def marked_func(shopping_list):
list_of_items = []
for item in shopping_list:
item = item.strip("\n")
list_of_items.append(item)
return list_of_items
# Function to add items to completed list
def list_of_writable_items(shopping_list, status):
write_list = []
for line_str in shopping_list:
if line_str[-1] == status:
write_list.append(line_str)
return write_list
main()
|
f06d506f4ac55351bbf9b650e69f3a29c88e62fc
|
[
"Python"
] | 1 |
Python
|
ErikCronin/ShoppingList
|
13de349d49e1f2dd860aef6af3e05cda40b379c2
|
e0edaabd762e5d2a19977359774708f9c88ea0d3
|
refs/heads/master
|
<file_sep><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
body #modal-body{
width:100px;
</style>
<?php
include_once '../lib/DbManager.php';
include '../body/header.php';
//print_r($_GET);exit;
//$search_item="";
$search_item = $_GET;
//print_r($search_item);exit;
//echo $search_item['yearId'];exit;
$where = " where 1=1 ";
//echo $search_item['yearId'];exit;
//if (!empty($search_item['new_registration_id_from'])) {
if (!empty($search_item['new_registration_id_from']) && !empty($search_item['new_registration_id_to'])) {
//$where = $where . "AND learners_registration_id >=" . $search_item['new_registration_id_from'] ." AND learners_registration_id<=" . $search_item['new_registration_id_to'] . " ";}
$where = $where . "AND learners_registration_id BETWEEN " . $search_item['new_registration_id_from'] ." AND " . $search_item['new_registration_id_to'] . " ";
}
else if(!empty($search_item['new_registration_id_from'])){
$where = $where . "AND learners_registration_id =" . $search_item['new_registration_id_from'] . " ";
}
//}
if(!empty($search_item['year_id'])){
$where =$where."AND year =". $search_item['year_id']." ";
}
if(!empty($search_item['year']))
{
$where =$where."AND year =". $search_item['year']." ";
}
if(!empty($search_item['batches_id']))
{
$where = $where."AND batches_id=".$search_item['batches_id']." ";
}
if(!empty($search_item['study_groups_id']))
{
$where = $where."AND learners.study_groups_id=".$search_item['study_groups_id']." ";
}
if(!empty($search_item['force_id']))
{
$where = $where."AND learners.force_id=".$search_item['force_id']." ";
}
if(!empty($search_item['study_centers_id']))
{
$where = $where."AND learners.study_centers_id=".$search_item['study_centers_id']." ";
}
if(!empty($search_item['statuses_id']))
{
$where = $where."AND learners.statuses_id=".$search_item['statuses_id']." ";
}
//echo $where;exit;
$query = "
SELECT
learners.learners_id,
learners.learners_registration_id,
learners.learners_name,
learners.dateofbirth,
study_centers.study_centers_name,
subjects.subjects_name,
subjects.subjects_code,
subjects.subjects_id,
subjects.full_marks,
registered_subjects.learners_session_id,
registered_subjects.registered_subjects_id
FROM
learners
LEFT JOIN registered_subjects ON registered_subjects.learners_id = learners.learners_id
LEFT JOIN subjects ON registered_subjects.subjects_id = subjects.subjects_id
LEFT JOIN study_centers ON learners.current_study_centers_id = study_centers.study_centers_id"
.$where;
//echo $query;exit;
$items = rs2array(sql($query));
//print_r($items);exit;
if($items)
{
$students = array();
$student = array();
$courses = array();
$is_first_time = 1;
foreach ( $items as $row ){
$course = array();
if(!in_array($row[0], $student)){
if($is_first_time != 1){
$student['course'] = $courses;
$courses = array();
$students[] = $student;
$student = array();
}
$is_first_time = 0;
$student['learners_id'] = $row[0];
$student['learners_registration_id'] = $row[1];
$student['learners_name'] = $row[2];
$student['dateofbirth'] = $row[3];
$student['study_centers_name'] = $row[4];
}
if( $row[5] != "" ){
$course['subjects_name'] = $row[5];
$course['subjects_code'] = $row[6];
$course['subjects_id'] = $row[7];
$course['full_marks'] = $row[8];
$course['learners_session_id'] = $row[9];
$course['registered_subjects_id'] =$row[10];
$courses[] = $course;
}
}
$student['course'] = $courses;
$students[] = $student;
$largeval=0;
foreach ($students as $aitem)
{
if(count($aitem['course'])>$largeval){$largeval=count($aitem['course']);}
}
//echo $largeval;exit;
//echo '<pre>';
//print_r($students);
//exit();
}
?>
<fieldset class="center_fieldset" style="width:95%;">
<legend> Learners List</legend>
<table class="common_view">
<thead>
<tr class="fitem">
<th field="group">#</th>
<th field="group">Learners Info</th>
<th field="group">Study Center</th>
<th field="quantity">Year</th>
<?php $x=1; for($i=0;$i<7;$i++){echo "<th field='group'>Course".$x++."</th>";} ?>
</tr>
</thead>
<tbody>
<?php
$sl=1;
if($students){foreach ($students as $astudent)
{
$thecourses = $astudent['course'];
?>
<tr>
<td rowspan="4"><?php echo $sl++; ?></td>
<td><?php echo $astudent['learners_id']; ?></td>
<td rowspan="4"><?php echo $astudent['study_centers_name'];?></td>
<td rowspan="2">1st Year Courses</td>
<?php
$counter1=0;
foreach ($astudent['course'] as $asc)
{
if($asc['learners_session_id']==1){
$counter1++;
?>
<td rowspan="2" class="subject_name" subject_id='<?php echo $asc['registered_subjects_id']; ?>' data-toggle="modal" data-target="#myModal"><?php echo $asc['subjects_name']; ?>
</td>
<?php
}
}
for($k=0;$k<(7-$counter1);$k++)
{
echo '<td rowspan="2">--</td>';
}
?>
</tr>
<tr>
<td><?php echo $astudent['learners_registration_id']; ?></td>
</tr>
<tr>
<td><?php echo $astudent['learners_name']; ?></td>
<td rowspan="2">2nd Year Courses</td>
<?php
$counter = 0;
foreach ($thecourses as $asc2)
{
if($asc2['learners_session_id']==2){
$counter++;
?>
<td rowspan="2" class="subject_name" subject_id='<?php echo $asc2['registered_subjects_id']; ?>' data-toggle="modal" data-target="#myModal"><?php echo $asc2['subjects_name']; ?>
</td>
<?php
}}
for($j=0;$j<(7-$counter);$j++)
{
echo '<td rowspan="2">--</td>';
}
?>
</tr>
<tr>
</tr>
<?php }} ?>
</tbody>
</table>
</fieldset>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<span id="modal_info"></span>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php
include '../body/footer.php';
?>
<script>
$('.subject_name').on('click',function(){
//$("#myModal").modal('show');
//alert();
var subject_id = $(this).attr('subject_id');
var subject_name = $(this).html();
//alert(subject_name);
//$(".modal-title").html(subject_name);
//alert(subject_id);
$.ajax({
//alert(subject_id);
type : "POST",
url : 'course_detail_modal.php',
data : {subject_id : subject_id},
success : function(data){
//alert(data);
$('#modal_info').html(data);
//$('#subjectmodal').html(data);
$("#myModal").modal('show');
// alert(data);
}
});
});
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script><file_sep><?php
include_once '../lib/DbManager.php';
include '../body/header.php';
//print_r($_GET);exit;
//$search_item="";
$search_item = $_GET;
//print_r($search_item);exit;
//echo $search_item['yearId'];exit;
$where = " where 1=1 ";
//echo $search_item['yearId'];exit;
//if (!empty($search_item['new_registration_id_from'])) {
if (!empty($search_item['new_registration_id_from']) && !empty($search_item['new_registration_id_to'])) {
//$where = $where . "AND learners_registration_id >=" . $search_item['new_registration_id_from'] ." AND learners_registration_id<=" . $search_item['new_registration_id_to'] . " ";}
$where = $where . "AND learners_registration_id BETWEEN " . $search_item['new_registration_id_from'] ." AND " . $search_item['new_registration_id_to'] . " ";
}
else if(!empty($search_item['new_registration_id_from'])){
$where = $where . "AND learners_registration_id =" . $search_item['new_registration_id_from'] . " ";
}
//}
if(!empty($search_item['year_id'])){
$where =$where."AND year =". $search_item['year_id']." ";
}
if(!empty($search_item['year']))
{
$where =$where."AND year =". $search_item['year']." ";
}
if(!empty($search_item['batches_id']))
{
$where = $where."AND batches_id=".$search_item['batches_id']." ";
}
if(!empty($search_item['study_groups_id']))
{
$where = $where."AND learners.study_groups_id=".$search_item['study_groups_id']." ";
}
if(!empty($search_item['force_id']))
{
$where = $where."AND learners.force_id=".$search_item['force_id']." ";
}
if(!empty($search_item['study_centers_id']))
{
$where = $where."AND learners.study_centers_id=".$search_item['study_centers_id']." ";
}
if(!empty($search_item['statuses_id']))
{
$where = $where."AND learners.statuses_id=".$search_item['statuses_id']." ";
}
//echo $where;exit;
$query = "SELECT
learners.learners_registration_id,
learners.learners_id,
learners.learners_name,
learners.fathers_name,
study_centers.study_centers_name
FROM
learners
LEFT JOIN study_centers ON learners.current_study_centers_id = study_centers.study_centers_id"
.$where;
//echo $query;exit;
$items = rs2array(sql($query));
//print_r($items);exit;
?>
<fieldset class="center_fieldset" style="width:95%;">
<legend> Learners List</legend>
<table class="common_view">
<thead>
<tr class="fitem">
<th>Learners Registration</th>
<th field="group">Learner ID </th>
<th field="quantity">Learner Name</th>
<th field="quantity">Father's Name </th>
<th field="group">Current Study Center</th>
</tr>
</thead>
<tbody>
<?php
foreach ($items as $item)
{
?>
<tr>
<td><?php echo $item[0]; ?></td>
<td><?php echo $item[1]; ?></td>
<td><?php echo $item[2]; ?></td>
<td><?php echo $item[3]; ?></td>
<td><?php echo $item[4]; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</fieldset>
<?php
include '../body/footer.php';
?><file_sep><?php
include_once '../lib/DbManager.php';
include '../body/header.php';
$studyGroupList = rs2array(sql("SELECT
study_groups_id,
study_groups_name
FROM
study_groups
WHERE statuses_id = 1"));
$center_List = rs2array(sql("SELECT
study_centers_id,
CONCAT(study_centers_name,'-',study_centers_codes)
FROM
study_centers
WHERE statuses_id = 1 " . ($search_previlege == 1 ? "" : " AND study_centers_id = '$user_study_centers_id'")));
$batcheList = rs2array(sql("SELECT
batches_code,
description
FROM
batches
WHERE statuses_id = 1
ORDER BY batches_code"));
$report_for_lists = rs2array(sql("SELECT * FROM report_for"));
//print_r($report_for_lists);exit;
?>
<div class="easyui-panel" style="background:#FFF" title="Learners List Summery">
<span class="subject_info" style="display:none;"></span>
<form action="" method="POST" id='theForm' class="form" >
<h1>Search Learners Summery List </h1>
<fieldset class="center_fieldset">
<legend>Search Panel</legend>
<table>
<tr>
<th>Study Year <font style="color:#FF0000;font-weight: bolder">*</font></th>
<th>:</th>
<td>
<?php generateYear('yearId',NULL,'required academic_year',2,1);//comboBox('yearId', $yearList, 'NULL', false, 'required academic_year'); ?>
</td>
</tr>
<tr>
<th>Batch <font style="color:#FF0000;font-weight: bolder">*</font></th>
<th>:</th>
<td ><?php comboBox('batches_id', $batcheList, 'NULL', TRUE, 'required batch'); ?></td>
</tr>
<tr>
<th>Group</th>
<th>:</th>
<td><?php comboBox('study_groups_id', $studyGroupList, $selected['study_groups_id'], TRUE) ?></td>
</tr>
<tr>
<th>Force <font style="color:#FF0000;font-weight: bolder">*</font></th>
<th>:</th>
<td><?php userWiseForceList();?></td>
</tr>
<tr>
<th>Study Center <font style="color:#FF0000;font-weight: bolder">*</font></th>
<th>:</th>
<td><?php comboBox('study_centers_id', $center_List, $selected['study_centers_id'], TRUE); ?></td>
</tr>
<tr>
<th>Report For</th>
<th>:</th>
<td>
<select name="report_for" id="report_for">
<?php
foreach ($report_for_lists as $arepor_for){
?>
<option value="<?php echo $arepor_for['0']; ?>" data-url="<?php echo $arepor_for[2]; ?>"><?php echo $arepor_for[1]; ?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>Registration ID</td>
<td>:</td>
<td>
<input type="text" id="registration_id_from" class = "learners_reg_id" name="registration_id_from" style="width: 39%" value="<?php if(getParam("registration_id_from") != "") echo getParam("registration_id_from");?>">
<input type="checkbox" class="between" value="1" id="registration_check" name="between" <?php if(getParam("between") == "1") echo "checked";?>>Between
<input type="text" id="registration_id_to" class = "learners_reg_id" name="registration_id_to" style="width: 39%" value="<?php if(getParam("registration_id_to") != "") echo getParam("registration_id_to");?>">
</td>
</tr>
<tr>
<td colspan="3">
<button id="btn" name="next" value="processNext" class="button">Search</button>
</td>
</tr>
</table>
</fieldset>
</form>
<span id="search_result"></span>
</div>
<script>
$( "#btn" ).on('click',function(event){
event.preventDefault();
var search_by_registration = $('#registration_check').is(":checked");
if($('#registration_id_from').val())
{
//alert(($('#registration_id_from').val()));
var registration_id_from = $('#registration_id_from').val();
var new_registration_id_from = registration_id_from.replace(/-/g,"");
if(search_by_registration)
{
var registration_id_to = $('#registration_id_to').val();
var new_registration_id_to = registration_id_to.replace(/-/g,"");
}
//var url = $('#report_for :selected').attr('data-url');
$.ajax({
type: "GET",
url: 'learners_list_without_header.php',
data: {'new_registration_id_from':new_registration_id_from,'new_registration_id_to':new_registration_id_to},
//dataType: "json",
success: function(data){
$('#search_result').html(data);
//$(".post-votes-count").text("100");
}
});
}
else{
var year_id = $("#yearIdID").val();
var batches_id = $("#batches_idID").val();
var force_id=3;
var study_groups_id = $("#study_groups_idID").val();
var study_centers_id = $("#study_centers_idID").val();
var report_for = $('#report_for :selected').val();
var url = $('#report_for :selected').attr('data-url');
$.ajax({
type: "POST",
url: url,
data: {'year_id':year_id,'batches_id':batches_id,'study_groups_id':study_groups_id,'study_centers_id':study_centers_id,'force_id':force_id},
//dataType: "json",
success: function(data){
$('#search_result').html(data);
//$(".post-votes-count").text("100");
}
});
}
});
</script>
<script>
$(document).ready(function (){
$(".between").change(function (){
if($(".between").is(":checked"))
{
$("#registration_id_from").attr("required","required");
$("#registration_id_to").attr("required","required");
$("#registration_id_to").removeAttr("disabled");
$("#registration_id_to").focus();
}else
{
$("#registration_id_from").removeAttr("required");
$("#registration_id_to").removeAttr("required");
$("#registration_id_to").attr("disabled","disabled");
}
});
});
$('#view_result').click(function(){
var reg_id = $('#registration_id_from').val();
$.ajax({
url:'ajax_generate_result.php',
data:{registration_id:reg_id},
success: function(data){
$('#result_panel').html(data);
}
});
});
$('#registration_id_from').on('keyup',function(){
var form_val = ($(this).val());
var length = form_val.length;
if(length<=11){$('#registration_id_to').val(form_val);}
});
</script>
<?php
include '../body/footer.php';
?>
<file_sep><?php
include_once '../lib/DbManager.php';
include '../body/header.php';
include 'learners_list_without_header.php';
include '../body/footer.php';
?>
<file_sep><?php
include_once '../lib/DbManager.php';
//include '../body/header.php';
$registered_subjects_id = $_POST['subject_id'];
//print_r($_POST);exit;
$query = "SELECT
registered_subjects.earned_subjective_marks,
registered_subjects.earned_objective_marks,
registered_subjects.earned_practical_marks,
registered_subjects.earned_total_marks,
registered_subjects.earned_grade,
registered_subjects.exam_attend_type,
registered_subjects.number_of_reexam,
registered_subjects.remarks,
statuses.statuses_name,
learners.learners_registration_id,
learners.learners_name,
learners.learners_id,
learners.exam_year,
subjects.subjects_name,
subjects.subjects_code
FROM
registered_subjects
inner join statuses ON statuses.statuses_id = registered_subjects.exam_status
inner join learners ON learners.learners_id = registered_subjects.learners_id
INNER JOIN subjects ON subjects.subjects_id=registered_subjects.subjects_id
where registered_subjects_id=".$registered_subjects_id;
//echo $query;exit;
//$res = query($query);
//print_r($res);exit;
$row = find($query);
//print_r($row);exit;
//str_split($row->learners_registration_id);
$reg_id = $row->learners_registration_id;
//echo $reg_id;exit;
$row->earned_total_marks = $row->earned_subjective_marks + $row->earned_objective_marks + $row->earned_practical_marks;
$row->learners_registration_id = substr($reg_id, 0,2)."-". substr($reg_id, 2,1)."-". substr($reg_id, 3,2)."-".substr($reg_id, 5,3)."-".substr($reg_id,-3);
?>
<h4 class="modal-title" id="modal_head"><?php echo "Registration Id: ".$row->learners_registration_id."<br>Student Name :".$row->learners_name."<br>Course Name :".$row->subjects_name."(".$row->subjects_code.")"; ?></h4>
<div id='modal_body' class="modal-body">
<table class="table table-active">
<tbody>
<tr>
<th align="left">Subject Info</th>
<th>Description</th>
</tr>
<tr>
<th style="text-align: left" field="group">Subjective Marks</th>
<td><?php echo $row->earned_subjective_marks; ?></td>
</tr>
<?php
if(!empty($row->earned_objective_marks))
{
?>
<tr>
<th style="text-align: left" field="group">Objective Marks</th>
<td><?php echo $row->earned_objective_marks; ?></td>
</tr>
<?php } ?>
<?php
if(!empty($row->earned_objective_marks))
{
?>
<tr>
<th style="text-align: left" field="quantity">Practical Marks</th>
<td><?php echo $row->earned_practical_marks; ?></td>
</tr>
<?php } ?>
<tr>
<th style="text-align: left" >Grade</th>
<td><?php echo $row->earned_grade; ?></td>
</tr>
<tr>
<th style="text-align: left" >Total Marks</th>
<td><?php echo $row->earned_total_marks; ?></td>
</tr>
<tr>
<th style="text-align: left">Exam Year</th>
<td><?php echo $row->exam_year; ?></td>
</tr>
<tr>
<th style="text-align: left">Exam Type</th>
<td><?php if($row->exam_attend_type==0) {echo "Regular";} else{echo "Irregular(".$row->number_of_reexam.")";}?></td>
</tr>
<tr>
<th style="text-align: left" >Remarks</th>
<td><?php echo $row->remarks; ?></td>
</tr>
</tbody>
</table>
</div>
<file_sep><?php
include_once '../lib/DbManager.php';
//print_r($_POST);exit;
$search_item = $_POST;
//print_r($search_item);exit;
//echo $search_item['yearId'];exit;
$where = " where 1=1 ";
//echo $search_item['yearId'];exit;
if(!empty($search_item['year_id']))
{
$where =$where."AND year =". $search_item['year_id']." ";
}
if(!empty($search_item['batches_id']))
{
$where = $where."AND batches_id=".$search_item['batches_id']." ";
}
if(!empty($search_item['study_groups_id']))
{
$where = $where."AND learners.study_groups_id=".$search_item['study_groups_id']." ";
}
if(!empty($search_item['force_id']))
{
$where = $where."AND learners.force_id=".$search_item['force_id']." ";
}
if(!empty($search_item['study_centers_id']))
{
$where = $where."AND learners.study_centers_id=".$search_item['study_centers_id']." ";
}
//echo $where;exit;
$query = "SELECT study_centers.study_centers_name AS Study_Center_Name,study_centers.study_centers_id,
SUM(
CASE WHEN learners.statuses_id=1 THEN 1 ELSE 0 END
) AS Number_Of_Active_Learners,
SUM(
CASE WHEN learners.statuses_id=2 THEN 1 ELSE 0 END
) AS Number_Of_Inactive_Learners
FROM
learners
INNER JOIN study_centers ON learners.study_centers_id = study_centers.study_centers_id"
.$where.
"GROUP BY study_centers.study_centers_id";
//echo $query;exit;
$items = rs2array(sql($query));
//print_r($items);exit;
?>
<fieldset class="center_fieldset" style="width:95%;">
<legend> Learners Summery By Study Center</legend>
<table class="common_view">
<thead>
<tr class="fitem">
<th field="group">Study Center Name </th>
<th field="quantity">Number Of Active Learners</th>
<th field="quantity">Number Of Inactive Learners </th>
</tr>
</thead>
<tbody>
<?php
foreach ($items as $item)
{
//print_r($item);exit;
?>
<tr>
<td><?php echo $item[0]; ?></td>
<td><a target="_blank" href="learners_list.php?year_id=<?php echo $search_item['year_id']; ?>&batches_id=<?php echo $search_item['batches_id']; ?>&study_groups_id=<?php echo $search_item['study_groups_id']; ?>&study_centers_id=<?php echo $item[1]; ?>&force_id=<?php echo $search_item['force_id']; ?>"><?php echo $item[2];?></a></td>
<td><a target="_blank" href="learners_list.php?statuses_id=2&year_id=<?php echo $search_item['year_id']; ?>&batches_id=<?php echo $search_item['batches_id']; ?>&study_groups_id=<?php echo $search_item['study_groups_id']; ?>&study_centers_id=<?php echo $item[1]; ?>&force_id=<?php echo $search_item['force_id']; ?>"><?php echo $item[3]; ?></a></td>
</tr>
<?php } ?>
</tbody>
</table>
</fieldset>
|
1cb0a577008f9b837158d6a8367a55e79ccc5dae
|
[
"PHP"
] | 6 |
PHP
|
mahbub-shohag/bou
|
6fef69b417975790b9175f366c688198fdde28c1
|
db92d7cbbb8f636d6ba5385132a72ef7c1bc5864
|
refs/heads/master
|
<repo_name>NeroJz/eentrance<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/pojo/EntranceLog.java
package hk.com.uatech.eticket.eticket.pojo;
public class EntranceLog {
private int success_count;
private int fialed_count;
private Entrance[] success_list;
private Entrance[] no_ticket_list;
private Entrance[] insert_error_list;
public int getSuccess_count() {
return success_count;
}
public void setSuccess_count(int success_count) {
this.success_count = success_count;
}
public int getFialed_count() {
return fialed_count;
}
public void setFialed_count(int fialed_count) {
this.fialed_count = fialed_count;
}
public Entrance[] getSuccess_list() {
return success_list;
}
public void setSuccess_list(Entrance[] success_list) {
this.success_list = success_list;
}
public Entrance[] getNo_ticket_list() {
return no_ticket_list;
}
public void setNo_ticket_list(Entrance[] no_ticket_list) {
this.no_ticket_list = no_ticket_list;
}
public Entrance[] getInsert_error_list() {
return insert_error_list;
}
public void setInsert_error_list(Entrance[] insert_error_list) {
this.insert_error_list = insert_error_list;
}
}
<file_sep>/README.md
# Handheld QR Code Scanner
An android application to scan QR code.
This project implements QR code scanning using camera. The scanned text is validated
by calling the RESTful API. Implementing these features allow to explore the use of
Retrofit2 and RxJava2 libraries in order to handle the asynchronous and event-based
response returned by the API.
## Gettting Started
### Prerequisites
This application requires minimum Java 8+ or Android API 21+.
## Libraries
**[GSON](https://github.com/google/gson)** is Java library that can be used to convert Java Object into JSON representation. <br/>
**[Retrofit2](https://github.com/square/retrofit)** is a type-safe HTTP client for Android and Java. It uses for RESTful API calling.<br/>
**[RxJava2](https://github.com/ReactiveX/RxJava)** is a library for composing asynchronous and event-based programs by using observable sequences.<br/>
**[Zing](https://github.com/pethoalpar/ZxingExample)** is a library for reading a barcode.<br/>
**[Scalars Converter](https://github.com/square/retrofit/tree/master/retrofit-converters/scalars)** supports converting strings and both primitives and their boxed types to text/plain bodies.
### Build with
- [Android Studio](https://developer.android.com/studio)
- [Gradle](https://spring.io/guides/gs/gradle/)
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/pojo/Counter.java
package hk.com.uatech.eticket.eticket.pojo;
public class Counter {
private int remain_ticket;
private int total_scanned;
private int total_ticket;
public int getRemain_ticket() {
return remain_ticket;
}
public void setRemain_ticket(int remain_ticket) {
this.remain_ticket = remain_ticket;
}
public int getTotal_scanned() {
return total_scanned;
}
public void setTotal_scanned(int total_scanned) {
this.total_scanned = total_scanned;
}
public int getTotal_ticket() {
return total_ticket;
}
public void setTotal_ticket(int total_ticket) {
this.total_ticket = total_ticket;
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/Item.java
package hk.com.uatech.eticket.eticket;
import java.io.Serializable;
@SuppressWarnings("serial")
/**
* Created by alex_ on 08/09/2017.
*/
public class Item implements Serializable{ //介面為物件序列化,可將物件變成二進位串流,就可儲存成檔案,也可以直接將物件丟進輸出入串流做傳送
private long id;
private String refNo;
private String seatId;
private String seatStatus;
private String ticketType;
//private Colors color;
public Item(){
refNo = "";
seatId = "";
seatStatus = "";
ticketType = "";
//color = Colors.LIGHTGREY;
}
public Item(long id,String refNo,String seatId,String ticketType, String seatStatus){
this.id=id;
this.refNo=refNo;
this.seatId=seatId;
this.ticketType = ticketType;
this.seatStatus=seatStatus;
}
public void setId(long id){
this.id=id;
}
public long getId(){
return this.id;
}
public void setRefNo(String refNo){
this.refNo=refNo;
}
public String getRefNo(){
return this.refNo;
}
public void setSeatStatus(String seatStatus){
this.seatStatus=seatStatus;
}
public String getSeatStatus(){
return this.seatStatus;
}
public void setSeatId(String seatId){
this.seatId=seatId;
}
public String getSeatId(){
return this.seatId;
}
public void setTicketType(String ticketType){
this.ticketType=ticketType;
}
public String getTicketType(){
return this.ticketType;
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/pojo/Log.java
package hk.com.uatech.eticket.eticket.pojo;
import java.util.List;
public class Log {
List<String> in;
List<String> out;
public List<String> getIn() {
return in;
}
public void setIn(List<String> in) {
this.in = in;
}
public List<String> getOut() {
return out;
}
public void setOut(List<String> out) {
this.out = out;
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/PrintDocumentAdapterWrapper.java
package hk.com.uatech.eticket.eticket;
import android.app.Activity;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
/**
* Created by alex_ on 28/08/2017.
*/
public class PrintDocumentAdapterWrapper extends PrintDocumentAdapter {
private final PrintDocumentAdapter delegate;
private final Activity activity;
public PrintDocumentAdapterWrapper(PrintDocumentAdapter adapter, Activity activity){
super();
this.delegate = adapter;
this.activity = activity;
}
public void onFinish(){
delegate.onFinish();
//insert hook here
activity.finish();
}
public void onWrite (PageRange[] pages,
ParcelFileDescriptor destination,
CancellationSignal cancellationSignal,
WriteResultCallback callback) {
delegate.onWrite(pages, destination, cancellationSignal, callback);
}
public void onLayout (PrintAttributes oldAttributes,
PrintAttributes newAttributes,
CancellationSignal cancellationSignal,
LayoutResultCallback callback,
Bundle extras) {
delegate.onLayout(oldAttributes, newAttributes, cancellationSignal, callback, extras);
}
//override all other methods with a trivial implementation calling to the delegate
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/pojo/Price.java
package hk.com.uatech.eticket.eticket.pojo;
public class Price {
private String ticket_amount;
private String lounge_price;
private String discount;
public String getTicket_amount() {
return ticket_amount;
}
public void setTicket_amount(String ticket_amount) {
this.ticket_amount = ticket_amount;
}
public String getLounge_price() {
return lounge_price;
}
public void setLounge_price(String lounge_price) {
this.lounge_price = lounge_price;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/delegate/showtime/ShowtimeNotifier.java
/**
* ShowNotifier to notify changes of task
* Author: JZ
* Date: 24-02-2020
* Version: 0.0.1
*/
package hk.com.uatech.eticket.eticket.delegate.showtime;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileInputStream;
import hk.com.uatech.eticket.eticket.database.Show;
import hk.com.uatech.eticket.eticket.pojo.ShowPojo;
public class ShowtimeNotifier {
private ShowtimeEvent se;
private static String FILE_NAME = "show_test.json";
private final String DIRECTORY = "/ETicket";
public ShowtimeNotifier(ShowtimeEvent event) {
se = event;
}
/**
* Read JSON file from external storage
* and the data into SQLite
* @param context
*/
public void doWork(Context context) {
File directory = new File(Environment.getExternalStorageDirectory(), DIRECTORY);
File file = new File(directory, FILE_NAME);
if(!file.exists()) {
Log.d(ShowtimeNotifier.class.toString(), "File not existed!");
delegate();
return;
}
try {
FileInputStream is = new FileInputStream(file);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String json_text = new String(buffer, "UTF-8");
Gson gson = new Gson();
ShowPojo shows = gson.fromJson(json_text, ShowPojo.class);
if(shows != null && shows.getShow().length > 0) {
Show model = new Show(context);
// Clear existing data
model.clear();
// Insert new data
model.add_shows(shows.getShow());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
delegate();
}
}
private void delegate() {
if(se != null) {
se.completeHandler();
}
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/pojo/GateSeatInfo.java
package hk.com.uatech.eticket.eticket.pojo;
public class GateSeatInfo {
private String seat_no;
private String isRefunded;
private String isScannedIn;
private Price price;
private Ticket ticket;
private Log log;
private String is_concession;
public String getSeat_no() {
return seat_no;
}
public void setSeat_no(String seat_no) {
this.seat_no = seat_no;
}
public String getIsRefunded() {
return isRefunded;
}
public void setIsRefunded(String isRefunded) {
this.isRefunded = isRefunded;
}
public String getIsScannedIn() {
return isScannedIn;
}
public void setIsScannedIn(String isScannedIn) {
this.isScannedIn = isScannedIn;
}
public Price getPrice() {
return price;
}
public void setPrice(Price price) {
this.price = price;
}
public Ticket getTicket() {
return ticket;
}
public void setTicket(Ticket ticket) {
this.ticket = ticket;
}
public Log getLog() {
return log;
}
public String getIs_concession() {
return is_concession;
}
public void setIs_concession(String is_concession) {
this.is_concession = is_concession;
}
public boolean isConcession() {
return is_concession.equals("1");
}
public void setLog(Log log) {
this.log = log;
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/delegate/DelegateType.java
package hk.com.uatech.eticket.eticket.delegate;
public enum DelegateType {
ENTRANCE_LOG
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/pojo/EntranceLogInput.java
package hk.com.uatech.eticket.eticket.pojo;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class EntranceLogInput {
private Entrance[] entrances;
public Entrance[] getEntrances() {
return entrances;
}
public void setEntrances(Entrance[] entrances) {
this.entrances = entrances;
}
public void addEntrance(Entrance[] seconds) {
List<Entrance> append = new ArrayList<Entrance>(this.entrances.length + seconds.length);
Collections.addAll(append, this.entrances);
Collections.addAll(append, seconds);
this.entrances = append.toArray(new Entrance[append.size()]);
}
public JSONObject toJSON() throws JSONException {
JSONObject obj = new JSONObject();
JSONArray jsonArray = new JSONArray();
if(entrances.length > 0) {
for(Entrance item : entrances) {
jsonArray.put(item.toJSON());
}
obj.put("entrances", jsonArray);
}
return obj;
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/pojo/Movie.java
package hk.com.uatech.eticket.eticket.pojo;
public class Movie {
private String duration;
private Name name;
private String id;
private String attribute;
private String category;
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/preferences/SettingActivity.java
package hk.com.uatech.eticket.eticket.preferences;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import hk.com.uatech.eticket.eticket.Item;
import hk.com.uatech.eticket.eticket.ListAdapter;
import hk.com.uatech.eticket.eticket.OfflineDatabase;
import hk.com.uatech.eticket.eticket.R;
import hk.com.uatech.eticket.eticket.database.Entrance;
import hk.com.uatech.eticket.eticket.delegate.DelegateType;
import hk.com.uatech.eticket.eticket.delegate.entrance_log.EntranceLogEvent;
import hk.com.uatech.eticket.eticket.delegate.entrance_log.EntranceLogNotifier;
import hk.com.uatech.eticket.eticket.network.NetworkRepository;
import hk.com.uatech.eticket.eticket.network.ResponseType;
import hk.com.uatech.eticket.eticket.pojo.EntranceLog;
import hk.com.uatech.eticket.eticket.pojo.EntranceLogInput;
import hk.com.uatech.eticket.eticket.pojo.GateHouse;
import hk.com.uatech.eticket.eticket.pojo.House;
import hk.com.uatech.eticket.eticket.utils.Utils;
public class SettingActivity extends AppCompatActivity implements NetworkRepository.QueryCallback, EntranceLogEvent {
private Button btnUpload;
private String previousRefNo = "";
private ProgressDialog loading = null;
List<String> list;
List<String> listvalue;
List<String> listSelected;
ListView listview;
List<Boolean> listShow; // 這個用來記錄哪幾個 item 是被打勾的
private String houseSetting;
private String accessMode;
private String setupMode = "";
private List<String> refNos;
private int offlinePointer = -1;
private int successCount = 0;
private int failCount = 0;
private EditText edtGracePeriodFrom;
private EditText edtGracePeriodTo;
private EditText edtPrintName1;
private EditText edtPrintName2;
private EditText edtPrintName3;
private EditText edtPrintName4;
private EditText edtPrintName5;
private EditText edtIPAddress;
private EditText edtEntrance;
private EditText edtFb;
private EditText edtPrintIP1;
private EditText edtPrintIP2;
private EditText edtPrintIP3;
private EditText edtPrintIP4;
private EditText edtPrintIP5;
private EditText edtPrintId1;
private EditText edtPrintId2;
private EditText edtPrintId3;
private EditText edtPrintId4;
private EditText edtPrintId5;
private EditText edtNetwork;
private EditText edtNetworkUser;
private EditText edtNetworkPassword;
private EditText edtOfflinePassword;
private EditText edtUseShare;
private EditText edtUsePrinter;
private EditText edtCinemaID;
private EditText edtPrefixCode;
private Gson gson = new Gson();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
edtGracePeriodFrom = (EditText) findViewById(R.id.edtGracePeriodFrom);
edtGracePeriodTo = (EditText) findViewById(R.id.edtGracePeriodTo);
edtPrintName1 = (EditText) findViewById(R.id.printerName1);
edtPrintName2 = (EditText) findViewById(R.id.printerName2);
edtPrintName3 = (EditText) findViewById(R.id.printerName3);
edtPrintName4 = (EditText) findViewById(R.id.printerName4);
edtPrintName5 = (EditText) findViewById(R.id.printerName5);
edtIPAddress = (EditText) findViewById(R.id.ipaddress);
edtEntrance = (EditText) findViewById(R.id.entrance);
edtFb = (EditText) findViewById(R.id.fb);
edtPrintIP1 = (EditText) findViewById(R.id.printerIP1);
edtPrintIP2 = (EditText) findViewById(R.id.printerIP2);
edtPrintIP3 = (EditText) findViewById(R.id.printerIP3);
edtPrintIP4 = (EditText) findViewById(R.id.printerIP4);
edtPrintIP5 = (EditText) findViewById(R.id.printerIP5);
edtPrintId1 = (EditText) findViewById(R.id.deptId1);
edtPrintId2 = (EditText) findViewById(R.id.deptId2);
edtPrintId3 = (EditText) findViewById(R.id.deptId3);
edtPrintId4 = (EditText) findViewById(R.id.deptId4);
edtPrintId5 = (EditText) findViewById(R.id.deptId5);
edtNetwork = (EditText) findViewById(R.id.network);
edtNetworkUser = (EditText) findViewById(R.id.networkuser);
edtNetworkPassword = (EditText) findViewById(R.id.networkpassword);
edtOfflinePassword = (EditText) findViewById(R.id.offlinepassword);
edtUseShare = (EditText) findViewById(R.id.useshare);
edtUsePrinter = (EditText) findViewById(R.id.useprinter);
btnUpload = (Button) findViewById(R.id.btnUpload);
LinearLayout bglayer = (LinearLayout) findViewById(R.id.bglayer);
TextView textView4 = (TextView) findViewById(R.id.textView4);
CheckBox showScan = (CheckBox) findViewById(R.id.showScan);
CheckBox verifySeatStatus = (CheckBox) findViewById(R.id.verifySeatStatus);
CheckBox verifySettings = (CheckBox) findViewById(R.id.verifySettings);
CheckBox checkUploadByRole = (CheckBox) findViewById(R.id.chbByRole);
CheckBox checkUploadByPermission = (CheckBox) findViewById(R.id.chbByPermission);
String gracePeriodFrom = PreferencesController.getInstance().getGracePeriodFrom();
String gracePeriodTo = PreferencesController.getInstance().getGracePeriodTo();
houseSetting = PreferencesController.getInstance().getHousing();
if (getIntent().getExtras() != null) {
setupMode = getIntent().getExtras().getString("setupMode", "");
}
((TextView) findViewById(R.id.textView12)).setText("");
String printName1 = PreferencesController.getInstance().getPrinterName1();
String printName2 = PreferencesController.getInstance().getPrinterName2();
String printName3 = PreferencesController.getInstance().getPrinterName3();
String printName4 = PreferencesController.getInstance().getPrinterName4();
String printName5 = PreferencesController.getInstance().getPrinterName5();
String useshare = PreferencesController.getInstance().getUseShare();
String useprinter = PreferencesController.getInstance().getUsePrinter();
String printIP1 = PreferencesController.getInstance().getPrinterIp1();
String printIP2 = PreferencesController.getInstance().getPrinterIp2();
String printIP3 = PreferencesController.getInstance().getPrinterIp3();
String printIP4 = PreferencesController.getInstance().getPrinterIp4();
String printIP5 = PreferencesController.getInstance().getPrinterIp5();
String printId1 = PreferencesController.getInstance().getPrinterId1();
String printId2 = PreferencesController.getInstance().getPrinterId2();
String printId3 = PreferencesController.getInstance().getPrinterId3();
String printId4 = PreferencesController.getInstance().getPrinterId4();
String printId5 = PreferencesController.getInstance().getPrinterId5();
String network = PreferencesController.getInstance().getNetwork();
String networkUser = PreferencesController.getInstance().getNetworkUser();
String networkPassword = PreferencesController.getInstance().getNetworkPassword();
String offlinepassword = PreferencesController.getInstance().getOfflinePassword();
// Set cinemaID if existed
edtCinemaID = (EditText) findViewById(R.id.tvCinemaID);
String cinemaID = PreferencesController.getInstance().getCinemaId();
if("".equals(cinemaID)) {
cinemaID = Utils.getConfigValue(getApplicationContext(), "cinema_id");
}
edtCinemaID.setText(cinemaID);
// Set Prefix Code if existed
edtPrefixCode = (EditText) findViewById(R.id.edtPrefixCode);
String prefixCode = PreferencesController.getInstance().getPrefixCode();
if("".equals(prefixCode)) {
prefixCode = Utils.getConfigValue(getApplicationContext(), "prefix_code");
}
edtPrefixCode.setText(prefixCode);
btnUpload = (Button) findViewById(R.id.btnUpload);
accessMode = PreferencesController.getInstance().getAccessMode();
String serverIP = PreferencesController.getInstance().getServerIpAddress();
/**
* Test
*/
// String dummyIP = new String("http://192.168.127.12");
// edtIPAddress.setText(dummyIP);
edtIPAddress.setText(serverIP);
edtEntrance.setText(PreferencesController.getInstance().getEntrance());
edtFb.setText(PreferencesController.getInstance().getFb());
showScan.setChecked(PreferencesController.getInstance().isShowScan());
showScan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
PreferencesController.getInstance().setIsShowScan(b);
}
});
verifySeatStatus.setChecked(PreferencesController.getInstance().isUsePasswordForChangeSeat());
verifySeatStatus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
PreferencesController.getInstance().setUsePasswordChangeSeat(b);
}
});
verifySettings.setChecked(PreferencesController.getInstance().isUsePasswordForSettings());
verifySettings.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
PreferencesController.getInstance().setUsePasswordSettings(b);
}
});
checkUploadByPermission.setChecked(PreferencesController.getInstance().isCheckByPermission());
checkUploadByPermission.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
PreferencesController.getInstance().setCheckByPermission(b);
}
});
checkUploadByRole.setChecked(PreferencesController.getInstance().isCheckByRole());
checkUploadByRole.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
PreferencesController.getInstance().setCheckByRole(b);
}
});
if ("Y".equals(setupMode)) {
btnUpload.setEnabled(false);
bglayer.setBackgroundColor(Color.rgb(230, 255, 250));
textView4.setText("Allowed House(s) - Not support in first set up Mode");
} else if ("offline".equals(accessMode)) {
btnUpload.setEnabled(false);
bglayer.setBackgroundColor(Color.rgb(255, 179, 179));
textView4.setText("Allowed House(s) - Not support in Offline Mode");
} else {
// need to check any record
OfflineDatabase database = new OfflineDatabase(SettingActivity.this);
int totalRec = database.getCount();
if (totalRec > 0) {
btnUpload.setEnabled(true);
btnUpload.setText("Upload (" + String.valueOf(totalRec) + ")");
} else {
btnUpload.setText("Upload (0)");
btnUpload.setEnabled(false);
}
textView4.setText("Allowed House(s)");
try {
// Get the String from Text Control
//String urlString = "http://192.168.127.12/thirdparty/api/e-entrance/staffAuth";
if (loading == null) {
loading = new ProgressDialog(this);
loading.setCancelable(true);
loading.setMessage("Loading");
loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
JSONObject jv = new JSONObject();
jv.put("test", "test");
loading.show();
//JSONObject jsonObject = getJSONObjectFromURL(urlString, jsonvalue);
// NetworkRepository.getInstance().getHouseList(jv.toString(), this);
NetworkRepository.getInstance().getGateAllHouse(this);
} catch (Exception e) {
e.printStackTrace();
}
}
listview = (ListView) findViewById(R.id.houselist);
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
CheckedTextView chkItem = (CheckedTextView) v.findViewById(R.id.check1);
chkItem.setChecked(!chkItem.isChecked());
String selected = listSelected.get(position);
listSelected.set(position, "Y".equals(selected) ? "N" : "Y");
listShow.set(position, chkItem.isChecked());
}
}
);
btnUpload.setOnClickListener(new ImageView.OnClickListener() {
@Override
public void onClick(View v) {
if ((PreferencesController.getInstance().isCheckByRole()
&& "MANAGER".equals(PreferencesController.getInstance().getUserRank()))
|| (PreferencesController.getInstance().isCheckByPermission()
&& PreferencesController.getInstance().isUploadingEnabled())) {
previousRefNo = "";
AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
builder.setTitle("Confirm");
builder.setMessage("Confirm to upload the offline transaction?");
if (loading == null) {
loading = new ProgressDialog(v.getContext());
loading.setCancelable(true);
loading.setMessage("Loading");
loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
loading.show();
successCount = 0;
failCount = 0;
/* Comment out temporary */
try {
Entrance entrance = new Entrance(SettingActivity.this);
JSONArray jsonArr = entrance.getEntranceList();
JSONObject jsonVal = new JSONObject();
if(jsonArr.length() > 0) {
jsonVal.put("entrance", jsonArr);
NetworkRepository.getInstance().getGateImportEntranceLog(jsonVal.toString(), SettingActivity.this);
}
} catch (Exception e) {
if(loading != null) {
loading.dismiss();
}
dialog.dismiss();
Toast.makeText(
getApplicationContext(),
"Failed to upload file.",
Toast.LENGTH_SHORT
).show();
return;
}
dialog.dismiss();
// First, form the Array for the sqllite data
/**
* Original Code
*/
/*
OfflineDatabase db = new OfflineDatabase(SettingActivity.this);
refNos = db.getDistinctRefNo();
JSONObject jsonvalue;
if (refNos != null) {
if (refNos.size() > 0) {
jsonvalue = getJsonForConfirmation(offlinePointer + 1);
if (jsonvalue != null) {
NetworkRepository.getInstance().confirmTicket(jsonvalue.toString(), SettingActivity.this);
} else {
Toast.makeText(
SettingActivity.this,
"Upload Successful",
Toast.LENGTH_SHORT)
.show();
// Finial, remove all records from db
db.removeAllRecords();
// Also, need to disable the button
btnUpload.setEnabled(false);
}
dialog.dismiss();
}
}
*/
/**
* End of Original Code
*/
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
} else {
Toast.makeText(SettingActivity.this, "unauthorized", Toast.LENGTH_SHORT).show();
}
}
});
findViewById(R.id.btnSave).setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
String graceFrom = edtGracePeriodFrom.getEditableText().toString();
String graceTo = edtGracePeriodTo.getEditableText().toString();
String printName1 = edtPrintName1.getEditableText().toString();
String printName2 = edtPrintName2.getEditableText().toString();
String printName3 = edtPrintName3.getEditableText().toString();
String printName4 = edtPrintName4.getEditableText().toString();
String printName5 = edtPrintName5.getEditableText().toString();
String serverIP = edtIPAddress.getEditableText().toString();
String entrance = edtEntrance.getEditableText().toString();
String fb = edtFb.getEditableText().toString();
String printIP1 = edtPrintIP1.getEditableText().toString();
String printIP2 = edtPrintIP2.getEditableText().toString();
String printIP3 = edtPrintIP3.getEditableText().toString();
String printIP4 = edtPrintIP4.getEditableText().toString();
String printIP5 = edtPrintIP5.getEditableText().toString();
String printId1 = edtPrintId1.getEditableText().toString();
String printId2 = edtPrintId2.getEditableText().toString();
String printId3 = edtPrintId3.getEditableText().toString();
String printId4 = edtPrintId4.getEditableText().toString();
String printId5 = edtPrintId5.getEditableText().toString();
String network = edtNetwork.getEditableText().toString();
String networkuser = edtNetworkUser.getEditableText().toString();
String networkpassword = edtNetworkPassword.getEditableText().toString();
String offlinepassword = edtOfflinePassword.getEditableText().toString();
String useshare = edtUseShare.getEditableText().toString();
String useprinter = edtUsePrinter.getEditableText().toString();
// Get cinemaID from edit text field
String cinemaID = edtCinemaID.getEditableText().toString();
try {
Integer.parseInt(graceFrom);
Integer.parseInt(graceTo);
} catch (NumberFormatException e) {
Toast.makeText(getApplicationContext(),
"Grace Period should be integer only",
Toast.LENGTH_SHORT)
.show();
return;
}
String housing = "";
String housingName = "";
if (listSelected != null) {
for (int z = 0; z < listSelected.size(); z++) {
String isSelected = listSelected.get(z);
if ("Y".equals(isSelected)) {
String id = listvalue.get(z);
if (!"".equals(housing)) {
housing += ",";
housingName += ",";
}
housing += id;
housingName += list.get(z);
}
}
}
PreferencesController.getInstance().setGracePeriodFrom(graceFrom);
PreferencesController.getInstance().setGracePeriodTo(graceTo);
PreferencesController.getInstance().setPrinterName1(printName1);
PreferencesController.getInstance().setPrinterName2(printName2);
PreferencesController.getInstance().setPrinterName3(printName3);
PreferencesController.getInstance().setPrinterName4(printName4);
PreferencesController.getInstance().setPrinterName5(printName5);
PreferencesController.getInstance().setPrinterIp1(printIP1);
PreferencesController.getInstance().setPrinterIp2(printIP2);
PreferencesController.getInstance().setPrinterIp3(printIP3);
PreferencesController.getInstance().setPrinterIp4(printIP4);
PreferencesController.getInstance().setPrinterIp5(printIP5);
PreferencesController.getInstance().setPrinterId1(printId1);
PreferencesController.getInstance().setPrinterId2(printId2);
PreferencesController.getInstance().setPrinterId3(printId3);
PreferencesController.getInstance().setPrinterId4(printId4);
PreferencesController.getInstance().setPrinterId5(printId5);
PreferencesController.getInstance().setNetwork(network);
PreferencesController.getInstance().setServerIpAddress(serverIP);
PreferencesController.getInstance().setEntrance(entrance);
PreferencesController.getInstance().setFb(fb);
PreferencesController.getInstance().setNetworkUser(networkuser);
PreferencesController.getInstance().setNetworkPassword(networkpassword);
PreferencesController.getInstance().setOfflinePassword(offlinepassword);
PreferencesController.getInstance().setUseShare(useshare);
PreferencesController.getInstance().setUsePrinter(useprinter);
// Save cinema id
PreferencesController.getInstance().setCinemaId(cinemaID);
// Save Prefix Code
String prefixCode = edtPrefixCode.getEditableText().toString();
PreferencesController.getInstance().setPrefixCode(prefixCode);
if ("Y".compareTo(setupMode) != 0 &&
"offline".compareTo(accessMode) != 0) {
PreferencesController.getInstance().setHousing(housing);
PreferencesController.getInstance().setHousingName(housingName);
}
finish();
}
});
findViewById(R.id.btnBack).setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
edtGracePeriodFrom.setText(gracePeriodFrom);
edtGracePeriodTo.setText(gracePeriodTo);
edtUseShare.setText(useshare);
edtUsePrinter.setText(useprinter);
edtPrintName1.setText(printName1);
edtPrintName2.setText(printName2);
edtPrintName3.setText(printName3);
edtPrintName4.setText(printName4);
edtPrintName5.setText(printName5);
edtPrintIP1.setText(printIP1);
edtPrintIP2.setText(printIP2);
edtPrintIP3.setText(printIP3);
edtPrintIP4.setText(printIP4);
edtPrintIP5.setText(printIP5);
edtPrintId1.setText(printId1);
edtPrintId2.setText(printId2);
edtPrintId3.setText(printId3);
edtPrintId4.setText(printId4);
edtPrintId5.setText(printId5);
edtNetwork.setText(network);
edtNetworkUser.setText(networkUser);
edtNetworkPassword.setText(networkPassword);
edtOfflinePassword.setText(offlinepassword);
}
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = (ListAdapter) listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0) {
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, LayoutParams.WRAP_CONTENT));
}
view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
@Override
public void onResponse(ResponseType responseType, String result) {
loading.dismiss();
switch (responseType) {
case CONFIRM_TICKET:
if (result.isEmpty()) {
Toast.makeText(getApplicationContext(),
"Login Fail, please try again",
Toast.LENGTH_SHORT)
.show();
} else if (result.startsWith("ERROR - ADD THIS TO SKIP ALL ERERRO MESSAGE")) {
Toast.makeText(getApplicationContext(),
result,
Toast.LENGTH_SHORT)
.show();
} else {
boolean resultIsFail = false;
if (result.startsWith("ERROR")) {
resultIsFail = true;
failCount++;
} else {
successCount++;
}
Log.d("Return", result);
try {
// Success and load the list
OfflineDatabase db = new OfflineDatabase(SettingActivity.this);
// Success and may need to clear the previous one db record
if (!resultIsFail) {
if ("".compareTo(previousRefNo) != 0) {
db.removeRecordsByRefNo(previousRefNo);
previousRefNo = "";
}
}
JSONObject jsonvalue;
if (refNos != null) {
if (refNos.size() > 0) {
jsonvalue = getJsonForConfirmation(0);
if (jsonvalue != null) {
NetworkRepository.getInstance().confirmTicket(jsonvalue.toString(), this);
} else {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(SettingActivity.this, "Upload Complete (Fail: " + String.valueOf(failCount) + ", Success: " + String.valueOf(successCount) + ") ", duration);
toast.show();
btnUpload.setEnabled(false);
if (loading != null)
loading.dismiss();
}
}
}
} catch (Exception ec) {
Toast.makeText(getApplicationContext(),
"Error: " + ec.getMessage(),
Toast.LENGTH_SHORT)
.show();
return;
}
}
break;
case HOUSE_LIST:
if (result.isEmpty()) {
Toast.makeText(getApplicationContext(),
"Login Fail, please try again",
Toast.LENGTH_SHORT)
.show();
} else if (result.startsWith("ERROR")) {
String displayErr = result;
displayErr = displayErr.replace("ERROR (400) : ", "");
displayErr = displayErr.replace("ERROR (401) : ", "");
displayErr = displayErr.replace("ERROR (402) : ", "");
Toast.makeText(getApplicationContext(), displayErr, Toast.LENGTH_SHORT).show();
} else {
Log.d("Return", result);
JSONObject jsonObj;
//
try {
// Success and load the list
listShow = new ArrayList<>();
list = new ArrayList<>();
listvalue = new ArrayList<>();
listSelected = new ArrayList<>();
String[] arrSel = houseSetting.split(",");
jsonObj = new JSONObject(result);
// Get Cinema Name
String cinemaName = jsonObj.getString("cinemaName");
if (cinemaName != null) {
((TextView) findViewById(R.id.textView12)).setText(cinemaName);
}
JSONArray arr = jsonObj.getJSONArray("houseList");
if (arr != null) {
for (int x = 0; x < arr.length(); x++) {
JSONObject obj = arr.getJSONObject(x);
list.add(obj.getString("houseName"));
listvalue.add(obj.getString("houseId"));
boolean found = false;
for (String anArrSel : arrSel) {
if (obj.getString("houseId").equals(anArrSel)) {
found = true;
break;
}
}
if (found) {
listShow.add(true);
listSelected.add("Y");
} else {
listShow.add(false);
listSelected.add("N");
}
}
}
if (arr != null && arr.length() > 0) {
ListAdapter adapterItem = new ListAdapter(this, list, listShow);
listview.setAdapter(adapterItem);
adapterItem.notifyDataSetChanged();
setListViewHeightBasedOnChildren(listview);
}
} catch (Exception ec) {
Toast.makeText(
getApplicationContext(),
"Error: " + ec.getMessage(),
Toast.LENGTH_SHORT)
.show();
return;
}
}
break;
/**
* Callbacks for the Turnstile
* Author: Jz
* Date: 05-03-2020
* Version: 0.0.1
*/
case GATE_ALL_HOUSE:
if(result.isEmpty()) {
Toast.makeText(getApplicationContext(),
"Login Fail, please try again",
Toast.LENGTH_SHORT).show();
} else if(result.startsWith("ERROR")) {
String displayErr = result;
displayErr = displayErr.replace("ERROR (400) : ", "");
displayErr = displayErr.replace("ERROR (401) : ", "");
displayErr = displayErr.replace("ERROR (402) : ", "");
Toast.makeText(getApplicationContext(), displayErr, Toast.LENGTH_SHORT).show();
} else {
try {
GateHouse data = gson.fromJson(result, GateHouse.class);
listShow = new ArrayList<>();
list = new ArrayList<>();
listvalue = new ArrayList<>();
listSelected = new ArrayList<>();
String[] arrSel = houseSetting.split(",");
if(data != null && data.getHouse().length > 0) {
for(House house : data.getHouse()) {
list.add(house.getName().getEn());
listvalue.add(house.getId());
boolean found = false;
for (String anArrSel : arrSel) {
if (house.getId().equals(anArrSel)) {
found = true;
break;
}
}
if (found) {
listShow.add(true);
listSelected.add("Y");
} else {
listShow.add(false);
listSelected.add("N");
}
/*
if("".equals(houseSetting)) {
listShow.add(true);
listSelected.add("Y");
} else {
if (found) {
listShow.add(true);
listSelected.add("Y");
} else {
listShow.add(false);
listSelected.add("N");
}
}
*/
}
}
if (data != null && data.getHouse().length > 0) {
ListAdapter adapterItem = new ListAdapter(this, list, listShow);
listview.setAdapter(adapterItem);
adapterItem.notifyDataSetChanged();
setListViewHeightBasedOnChildren(listview);
}
}catch (Exception ec) {
Toast.makeText(
getApplicationContext(),
"Error: " + ec.getMessage(),
Toast.LENGTH_SHORT)
.show();
return;
}
}
break;
case GATE_IMPORT_ENTRANCE_LOG:
if(loading != null) {
loading.dismiss();
}
if(result.isEmpty() || result.startsWith("ERROR")) {
Toast.makeText(
getApplicationContext(),
"Error in importing the data!",
Toast.LENGTH_SHORT
).show();
return;
}
try {
EntranceLog entranceLog = gson.fromJson(result, EntranceLog.class);
List<hk.com.uatech.eticket.eticket.pojo.Entrance> entrances = new ArrayList<hk.com.uatech.eticket.eticket.pojo.Entrance>();
JSONArray jsonArray = new JSONArray();
if(entranceLog.getInsert_error_list().length > 0) {
for(hk.com.uatech.eticket.eticket.pojo.Entrance item : entranceLog.getInsert_error_list()) {
jsonArray.put(item.toJSON());
}
}
if(entranceLog.getNo_ticket_list().length > 0) {
for(hk.com.uatech.eticket.eticket.pojo.Entrance item: entranceLog.getNo_ticket_list()) {
jsonArray.put(item.toJSON());
}
}
JSONObject jsonVal = new JSONObject();
if(jsonArray.length() == 0) {
this.completeHandler(DelegateType.ENTRANCE_LOG);
} else {
jsonVal.put("entrances", jsonArray);
// Save to SD card
EntranceLogNotifier notifier = new EntranceLogNotifier(this);
EntranceLogInput logInput = gson.fromJson(jsonVal.toString(), EntranceLogInput.class);
notifier.save(SettingActivity.this, logInput);
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_SHORT).show();
}
loading.dismiss();
break;
}
}
@Nullable
private JSONObject getJsonForConfirmation(int startPosition) {
boolean canStart = false;
OfflineDatabase db = new OfflineDatabase(SettingActivity.this);
JSONObject jsonvalue = new JSONObject();
int countSelected = 0;
for (int u = startPosition; u < refNos.size(); u++) {
offlinePointer = u;
try {
jsonvalue.put("refNo", refNos.get(offlinePointer));
jsonvalue.put("method", "A");
jsonvalue.put("type", "B");
previousRefNo = refNos.get(offlinePointer);
// Get the Items by Refno
List<Item> items = db.getRecordByRefNo(refNos.get(offlinePointer));
JSONArray jsonArr = new JSONArray();
countSelected = 0;
if (items != null) {
for (int y = 0; y < items.size(); y++) {
if ("Invalid".compareTo(items.get(y).getSeatStatus()) == 0) {
countSelected++;
JSONObject seat = new JSONObject();
seat.put("seatId", items.get(y).getSeatId());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
seat.put("timestamp", currentDateandTime);
seat.put("action", "C");
jsonArr.put(seat);
}
}
}
jsonvalue.put("confirmSeat", jsonArr);
} catch (Exception ex) {
}
canStart = countSelected > 0;
}
return canStart ? jsonvalue : null;
}
@Override
public void completeHandler(DelegateType delegateType) {
switch (delegateType) {
case ENTRANCE_LOG:
Entrance entrance = new Entrance(SettingActivity.this);
entrance.removeAllRecords();
OfflineDatabase db = new OfflineDatabase(SettingActivity.this);
refNos = db.getDistinctRefNo();
JSONObject jsonvalue;
if (refNos != null) {
if (refNos.size() > 0) {
Toast.makeText(
SettingActivity.this,
"Upload Successful",
Toast.LENGTH_SHORT)
.show();
// Finial, remove all records from db
db.removeAllRecords();
// Also, need to disable the button
// and reset its text
int totalRec = db.getCount();
btnUpload.setEnabled(false);
btnUpload.setText("Upload (" + String.valueOf(totalRec) + ")");
}
}
break;
}
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/qrCode/DecryptQR.java
/**
* DecryptQR Service
* Perform OPENSSL decryption of scanned QR code.
*
*
* Author: JZ
* Date: 13-02-2020
* Version: 0.0.1
*/
package hk.com.uatech.eticket.eticket.qrCode;
import android.util.Base64;
import android.util.Log;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import hk.com.uatech.eticket.eticket.preferences.PreferencesController;
public class DecryptQR {
static final String ENCRYPTION_KEY = "123";
static final String ALGORITHM = "AES";
static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
/**
* Perform decode of scanned data
* @param input [String - scanned data]
* @return String
*/
public static String decode(String input) {
try {
byte[] encrypted = Base64.decode(input, Base64.NO_WRAP);
byte[] iv = Arrays.copyOfRange(encrypted, 0, 16);
byte[] hMac = Arrays.copyOfRange(encrypted, 16, 48);
byte[] chiperVal = Arrays.copyOfRange(encrypted, 48, encrypted.length);
String mHash = getMD5();
SecretKeySpec secretKeySpec = new SecretKeySpec(mHash.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec);
byte[] cipherByte = cipher.doFinal(chiperVal);
return new String(cipherByte);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* Get MD5 encryption of secret key
* @return
* @throws NoSuchAlgorithmException
*/
protected static String getMD5() throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
String prefix = PreferencesController.getInstance().getPrefixCode();
String encryption_key = prefix + ENCRYPTION_KEY;
byte[] hashInBytes = md.digest(encryption_key.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hashInBytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/database/Model.java
package hk.com.uatech.eticket.eticket.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import hk.com.uatech.eticket.eticket.DBHelper;
public class Model {
public static SQLiteDatabase db;
public Model(Context context) {
db = DBHelper.getDatabase(context);
}
public void close() {
db.close();
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/network/model/Domain.java
package hk.com.uatech.eticket.eticket.network.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Domain {
@SerializedName("id")
@Expose
private String id;
@SerializedName("domain")
@Expose
private String domain;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/database/Entrance.java
/**
* Entrance model
* Author: Jz
* Date: 02-03-2020
* Version: 0.0.1
*/
package hk.com.uatech.eticket.eticket.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import hk.com.uatech.eticket.eticket.EntraceStep3Activity;
import hk.com.uatech.eticket.eticket.Item;
import hk.com.uatech.eticket.eticket.pojo.SeatInfo;
import hk.com.uatech.eticket.eticket.pojo.TicketTrans;
import hk.com.uatech.eticket.eticket.preferences.PreferencesController;
public class Entrance extends Model{
// TABLE NAME
public static final String TABLE_NAME = "entrance";
// COLUMNS
public static final String TRANS_ID = "trans_id";
public static final String IS_CONCESSION = "is_concession";
public static final String INOUT_DATETIME = "inout_datetime";
public static final String TYPE = "type";
public static final String CREATED_DATE = "created_date";
public static final String CREATE_TABLE =
"CREATE TABLE " +
TABLE_NAME + " (" +
TRANS_ID + " TEXT NOT NULL, " +
IS_CONCESSION + " INTEGER DEFAULT 0, " +
INOUT_DATETIME + " TEXT NOT NULL," +
TYPE + " TEXT NOT NULL," +
CREATED_DATE + " TEXT NOT NULL)";
public static final String DROP_TABLE =
"DROP TABLE IF EXISTS " + TABLE_NAME;
public Entrance(Context context) { super(context); }
/**
* Get total records in a table
*/
public void totalRows() {
Cursor cursor = db.query(TABLE_NAME,
null,
null,
null,
null,
null,
null);
if(cursor != null && cursor.getCount() > 0) {
Log.d(Entrance.class.toString(), String.valueOf(cursor.getCount()));
int i=1;
while (cursor.moveToNext()) {
String trans_id = cursor.getString(cursor.getColumnIndex(TRANS_ID));
String inout = cursor.getString(cursor.getColumnIndex(INOUT_DATETIME));
String type = cursor.getString(cursor.getColumnIndex(TYPE));
Log.d(Entrance.class.toString(), i + "---" +trans_id + "---" + inout + "---" + type);
i++;
}
}
}
public JSONArray getEntranceList() throws JSONException {
JSONArray results = new JSONArray();
Cursor cursor = db.query(TABLE_NAME,
null,
null,
null,
null,
null,
null);
if(cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String trans_id = cursor.getString(cursor.getColumnIndex(TRANS_ID));
int is_concession = cursor.getString(cursor.getColumnIndex(IS_CONCESSION)).equals("1") ? 1 : 0;
String inout_dt = cursor.getString(cursor.getColumnIndex(INOUT_DATETIME));
String type = cursor.getString(cursor.getColumnIndex(TYPE));
String cinemaID = PreferencesController.getInstance().getCinemaId();
JSONObject entrance_json_obj = new hk.com.uatech.eticket.eticket.pojo.Entrance(trans_id, is_concession, inout_dt, type).toJSON();
entrance_json_obj.put("cinema_id", cinemaID);
results.put(entrance_json_obj);
}
}
return results;
}
public void removeAllRecords() {
int result = 0;
String sql = "delete FROM " + TABLE_NAME;
db.execSQL(sql);
}
/**
* Add records based on individual seat status
* status - [Valid (Not Admitted (out)), Invalid (Admitted (in))]
* @param trans_id
* @param seats
*/
public void add(String trans_id, List<SeatInfo> seats) {
db.beginTransaction();
try {
ContentValues values = new ContentValues();
for(SeatInfo seat : seats) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String inoutDT = sdf.format(new Date());
values.put(TRANS_ID, trans_id);
values.put(IS_CONCESSION, seat.isConcession());
values.put(INOUT_DATETIME, inoutDT);
if(seat.getSeatStatus().equalsIgnoreCase("invalid")) {
values.put(TYPE, "out");
} else if(seat.getSeatStatus().equalsIgnoreCase("valid")) {
values.put(TYPE, "in");
}
values.put(CREATED_DATE, inoutDT);
db.insert(TABLE_NAME, null, values);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
// totalRows();
}
}
/**
* Add records with TYPE
* @param trans_id
* @param seats
* @param type
*/
public void add(String trans_id, List<SeatInfo> seats, String type) {
db.beginTransaction();
try {
ContentValues values = new ContentValues();
for(SeatInfo seat : seats) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String inoutDT = sdf.format(new Date());
values.put(TRANS_ID, trans_id);
values.put(IS_CONCESSION, seat.isConcession());
values.put(INOUT_DATETIME, inoutDT);
values.put(TYPE, type);
values.put(CREATED_DATE, inoutDT);
db.insert(TABLE_NAME, null, values);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
// totalRows();
}
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/pojo/Login.java
package hk.com.uatech.eticket.eticket.pojo;
public class Login {
private String resultCode;
private String resultMsg;
private int isManager;
private int staff_id;
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getResultMsg() {
return resultMsg;
}
public void setResultMsg(String resultMsg) {
this.resultMsg = resultMsg;
}
public int getIsManager() {
return isManager;
}
public boolean isManager() {
return isManager == 1 ? true : false;
}
public void setIsManager(int isManager) {
this.isManager = isManager;
}
public int getStaff_id() {
return staff_id;
}
public void setStaff_id(int staff_id) {
this.staff_id = staff_id;
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/delegate/entrance_log/EntranceLogNotifier.java
package hk.com.uatech.eticket.eticket.delegate.entrance_log;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import hk.com.uatech.eticket.eticket.delegate.DelegateType;
import hk.com.uatech.eticket.eticket.pojo.Entrance;
import hk.com.uatech.eticket.eticket.pojo.EntranceLog;
import hk.com.uatech.eticket.eticket.pojo.EntranceLogInput;
public class EntranceLogNotifier {
private EntranceLogEvent event;
private final String FILE_NAME = "entrance_log_";
private final String DIR = "/ETicket";
private final String FILE_EXT = ".json";
public EntranceLogNotifier(EntranceLogEvent event) {
this.event = event;
}
public void save(Context context, EntranceLogInput logInput) throws Exception {
File dir = new File(Environment.getExternalStorageDirectory(), DIR);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String currentDate = dateFormat.format(new Date());
File file = new File(dir, FILE_NAME + currentDate + FILE_EXT);
try {
if(file.exists()) {
readFile(file, logInput);
} else {
writeFile(file, logInput);
}
} catch (Exception e) {
Log.d(EntranceLogNotifier.class.toString(), e.getMessage());
throw e;
} finally {
if(this.event != null) {
this.event.completeHandler(DelegateType.ENTRANCE_LOG);
}
}
}
private void readFile(File file, EntranceLogInput logInput) throws IOException, JSONException {
FileInputStream is = new FileInputStream(file);
int fileSize = is.available();
byte[] buffer = new byte[fileSize];
is.read(buffer);
is.close();
String str = new String(buffer, "UTF-8");
Gson gson = new Gson();
EntranceLogInput entrances = gson.fromJson(str, EntranceLogInput.class);
if(entrances != null && entrances.getEntrances().length > 0) {
logInput.addEntrance(entrances.getEntrances());
}
writeFile(file, logInput);
}
private void writeFile(File file, EntranceLogInput logInput)
throws IOException, JSONException {
FileOutputStream os = new FileOutputStream(file);
if(logInput != null) {
os.write(logInput.toJSON().toString().getBytes());
}
os.close();
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/App.java
package hk.com.uatech.eticket.eticket;
import android.app.Application;
import android.content.Context;
import hk.com.uatech.eticket.eticket.preferences.PreferencesController;
public class App extends Application {
public static App instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
PreferencesController.getInstance().init(this);
}
@Override
public Context getApplicationContext() {
return super.getApplicationContext();
}
public static App getInstance() {
return instance;
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/preferences/PreferencesController.java
package hk.com.uatech.eticket.eticket.preferences;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import hk.com.uatech.eticket.eticket.R;
import hk.com.uatech.eticket.eticket.utils.Utils;
public class PreferencesController {
private static final PreferencesController instance = new PreferencesController();
private SharedPreferences sharedPreferences;
private static final String KEY_GRACE_FROM = "grace_period_from";
private static final String KEY_GRACE_TO = "grace_period_to";
private static final String KEY_HOUSING = "housing";
private static final String KEY_HOUSING_NAME = "housingName";
private static final String KEY_PRINTER_NAME_1 = "printer_name_1";
private static final String KEY_PRINTER_NAME_2 = "printer_name_2";
private static final String KEY_PRINTER_NAME_3 = "printer_name_3";
private static final String KEY_PRINTER_NAME_4 = "printer_name_4";
private static final String KEY_PRINTER_NAME_5 = "printer_name_5";
private static final String KEY_USE_SHARE = "use_share";
private static final String KEY_USE_PRINTER = "use_printer";
private static final String KEY_PRINTER_IP_1 = "printer_ip_1";
private static final String KEY_PRINTER_IP_2 = "printer_ip_2";
private static final String KEY_PRINTER_IP_3 = "printer_ip_3";
private static final String KEY_PRINTER_IP_4 = "printer_ip_4";
private static final String KEY_PRINTER_IP_5 = "printer_ip_5";
private static final String KEY_PRINTER_ID_1 = "printer_id_1";
private static final String KEY_PRINTER_ID_2 = "printer_id_2";
private static final String KEY_PRINTER_ID_3 = "printer_id_3";
private static final String KEY_PRINTER_ID_4 = "printer_id_4";
private static final String KEY_PRINTER_ID_5 = "printer_id_5";
private static final String KEY_NETWORK = "network";
private static final String KEY_NETWORK_USER = "network_user";
private static final String KEY_NETWORK_PASSWORD = "<PASSWORD>";
private static final String KEY_OFFLINE_PASSWORD = "<PASSWORD>";
private static final String KEY_ACCESS_MODE = "access_mode";
private static final String KEY_ENTRANCE = "entrance";
private static final String KEY_FB = "fb";
private static final String KEY_SHOW_SCAN = "show_scan";
private static final String KEY_ACCESS_TOKEN = "access_token";
private static final String KEY_SERVER_IP_ADDRESS = "server_ip_address";
private static final String KEY_USER_PASSWORD = "<PASSWORD>";
private static final String KEY_USER_RANK = "user_rank";
private static final String KEY_USE_PASSWORD_SETTINGS = "use_password_settings";
private static final String KEY_USE_PASSWORD_CHANGE_SEAT = "use_password_change_seat";
private static final String KEY_SETTINGS_ENABLED = "settings_enabled";
private static final String KEY_UPLOAD_ENABLED = "upload_enabled";
private static final String KEY_CHECK_UPLOAD_BY_ROLE = "upload_by_role";
private static final String KEY_CHECK_UPLOAD_BY_PERMISSION = "upload_by_permission";
private static String SAMBA_PATH;
private static String SAMBA_USERNAME;
private static String SAMBA_PASSWORD;
private static String OFFLINE_PASSWORD;
private static final String CINEMA_ID = "cinema_id";
private static final String PREFIX_CODE = "prefix_code";
public static PreferencesController getInstance() {
return instance;
}
public void init(Context context) {
sharedPreferences = context.getSharedPreferences("E-TICKET", Context.MODE_PRIVATE);
setDefaults(context);
}
private synchronized void setDefaults(Context context) {
SAMBA_PATH = Utils.getConfigValue(context, "samba_path");
SAMBA_USERNAME = Utils.getConfigValue(context, "samba_username");
SAMBA_PASSWORD = Utils.getConfigValue(context, "samba_password");
OFFLINE_PASSWORD = Utils.getConfigValue(context, "offline_password");
}
public String getGracePeriodFrom() {
return sharedPreferences.getString(KEY_GRACE_FROM, "30");
}
public void setGracePeriodFrom(String value) {
sharedPreferences.edit().putString(KEY_GRACE_FROM, value).apply();
}
public String getGracePeriodTo() {
return sharedPreferences.getString(KEY_GRACE_TO, "30");
}
public void setGracePeriodTo(String value) {
sharedPreferences.edit().putString(KEY_GRACE_TO, value).apply();
}
public String getHousing() {
return sharedPreferences.getString(KEY_HOUSING, "");
}
public void setHousing(String value) {
sharedPreferences.edit().putString(KEY_HOUSING, value).apply();
}
public String getHousingName() {
return sharedPreferences.getString(KEY_HOUSING_NAME, "");
}
public void setHousingName(String value) {
sharedPreferences.edit().putString(KEY_HOUSING_NAME, value).apply();
}
public String getUseShare() {
return sharedPreferences.getString(KEY_USE_SHARE, "Y");
}
public void setUseShare(String value) {
sharedPreferences.edit().putString(KEY_USE_SHARE, value).apply();
}
public String getUsePrinter() {
return sharedPreferences.getString(KEY_USE_PRINTER, "Y");
}
public void setUsePrinter(String value) {
sharedPreferences.edit().putString(KEY_USE_PRINTER, value).apply();
}
public String getPrinterName1() {
return sharedPreferences.getString(KEY_PRINTER_NAME_1, "001 - By Hot Dog");
}
public void setPrinterName1(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_NAME_1, value).apply();
}
public String getPrinterName2() {
return sharedPreferences.getString(KEY_PRINTER_NAME_2, "002 - By Sandwich Fridge");
}
public void setPrinterName2(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_NAME_2, value).apply();
}
public String getPrinterName3() {
return sharedPreferences.getString(KEY_PRINTER_NAME_3, "003 - By Hot Cabinet");
}
public void setPrinterName3(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_NAME_3, value).apply();
}
public String getPrinterName4() {
return sharedPreferences.getString(KEY_PRINTER_NAME_4, "004 - By Drinks");
}
public void setPrinterName4(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_NAME_4, value).apply();
}
public String getPrinterName5() {
return sharedPreferences.getString(KEY_PRINTER_NAME_5, "005 - By Consolidation Table");
}
public void setPrinterName5(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_NAME_5, value).apply();
}
public String getPrinterId1() {
return sharedPreferences.getString(KEY_PRINTER_ID_1, "1");
}
public void setPrinterId1(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_ID_1, value).apply();
}
public String getPrinterId2() {
return sharedPreferences.getString(KEY_PRINTER_ID_2, "2");
}
public void setPrinterId2(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_ID_2, value).apply();
}
public String getPrinterId3() {
return sharedPreferences.getString(KEY_PRINTER_ID_3, "3");
}
public void setPrinterId3(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_ID_3, value).apply();
}
public String getPrinterId4() {
return sharedPreferences.getString(KEY_PRINTER_ID_4, "4");
}
public void setPrinterId4(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_ID_4, value).apply();
}
public String getPrinterId5() {
return sharedPreferences.getString(KEY_PRINTER_ID_5, "5");
}
public void setPrinterId5(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_ID_5, value).apply();
}
public String getPrinterIp1() {
return sharedPreferences.getString(KEY_PRINTER_IP_1, "10.81.9.11");
}
public void setPrinterIp1(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_IP_1, value).apply();
}
public String getPrinterIp2() {
return sharedPreferences.getString(KEY_PRINTER_IP_2, "10.81.9.12");
}
public void setPrinterIp2(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_IP_2, value).apply();
}
public String getPrinterIp3() {
return sharedPreferences.getString(KEY_PRINTER_IP_3, "10.81.9.13");
}
public void setPrinterIp3(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_IP_3, value).apply();
}
public String getPrinterIp4() {
return sharedPreferences.getString(KEY_PRINTER_IP_4, "10.81.9.14");
}
public void setPrinterIp4(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_IP_4, value).apply();
}
public String getPrinterIp5() {
return sharedPreferences.getString(KEY_PRINTER_IP_5, "10.81.9.15");
}
public void setPrinterIp5(String value) {
sharedPreferences.edit().putString(KEY_PRINTER_IP_5, value).apply();
}
public String getNetwork() {
return sharedPreferences.getString(KEY_NETWORK, SAMBA_PATH);
}
public void setNetwork(String value) {
sharedPreferences.edit().putString(KEY_NETWORK, value).apply();
}
public String getNetworkUser() {
return sharedPreferences.getString(KEY_NETWORK_USER, SAMBA_USERNAME);
}
public void setNetworkUser(String value) {
sharedPreferences.edit().putString(KEY_NETWORK_USER, value).apply();
}
public String getNetworkPassword() {
return sharedPreferences.getString(KEY_NETWORK_PASSWORD, SAMBA_PASSWORD);
}
public void setNetworkPassword(String value) {
sharedPreferences.edit().putString(KEY_NETWORK_PASSWORD, value).apply();
}
public String getOfflinePassword() {
return sharedPreferences.getString(KEY_OFFLINE_PASSWORD, OFFLINE_PASSWORD);
}
public void setOfflinePassword(String value) {
sharedPreferences.edit().putString(KEY_OFFLINE_PASSWORD, value).apply();
}
public String getAccessMode() {
return sharedPreferences.getString(KEY_ACCESS_MODE, "online");
}
public void setAccessMode(String value) {
sharedPreferences.edit().putString(KEY_ACCESS_MODE, value).apply();
}
public String getAccessToken() {
return sharedPreferences.getString(KEY_ACCESS_TOKEN, "");
}
public void setAccessToken(String value) {
sharedPreferences.edit().putString(KEY_ACCESS_TOKEN, value).apply();
}
public String getServerIpAddress() {
return sharedPreferences.getString(KEY_SERVER_IP_ADDRESS, "");
}
public void setServerIpAddress(String value) {
sharedPreferences.edit().putString(KEY_SERVER_IP_ADDRESS, value).apply();
}
public String getEntrance() {
return sharedPreferences.getString(KEY_ENTRANCE, "");
}
public void setEntrance(String value) {
sharedPreferences.edit().putString(KEY_ENTRANCE, value).apply();
}
public String getFb() {
return sharedPreferences.getString(KEY_FB, "");
}
public void setFb(String value) {
sharedPreferences.edit().putString(KEY_FB, value).apply();
}
public boolean isShowScan() {
return sharedPreferences.getBoolean(KEY_SHOW_SCAN, true);
}
public void setIsShowScan(boolean value) {
sharedPreferences.edit().putBoolean(KEY_SHOW_SCAN, value).apply();
}
public String getUserPassword() {
return sharedPreferences.getString(KEY_USER_PASSWORD, "");
}
public void setUserPassword(String value) {
sharedPreferences.edit().putString(KEY_USER_PASSWORD, value).apply();
}
public String getUserRank() {
return sharedPreferences.getString(KEY_USER_RANK, "");
}
public void setUserRank(String value) {
sharedPreferences.edit().putString(KEY_USER_RANK, value).apply();
}
public boolean isUsePasswordForSettings() {
return sharedPreferences.getBoolean(KEY_USE_PASSWORD_SETTINGS, false);
}
public void setUsePasswordSettings(boolean value) {
sharedPreferences.edit().putBoolean(KEY_USE_PASSWORD_SETTINGS, value).apply();
}
public boolean isUsePasswordForChangeSeat() {
return sharedPreferences.getBoolean(KEY_USE_PASSWORD_CHANGE_SEAT, false);
}
public void setUsePasswordChangeSeat(boolean value) {
sharedPreferences.edit().putBoolean(KEY_USE_PASSWORD_CHANGE_SEAT, value).apply();
}
public boolean isSettingsEnabled() {
return sharedPreferences.getBoolean(KEY_SETTINGS_ENABLED, false);
}
public void setSettingsEnabled(boolean value) {
sharedPreferences.edit().putBoolean(KEY_SETTINGS_ENABLED, value).apply();
}
public boolean isUploadingEnabled() {
return sharedPreferences.getBoolean(KEY_UPLOAD_ENABLED, false);
}
public void setUploadingEnabled(boolean value) {
sharedPreferences.edit().putBoolean(KEY_UPLOAD_ENABLED, value).apply();
}
public boolean isCheckByRole() {
return sharedPreferences.getBoolean(KEY_CHECK_UPLOAD_BY_ROLE, true);
}
public void setCheckByRole(boolean value) {
sharedPreferences.edit().putBoolean(KEY_CHECK_UPLOAD_BY_ROLE, value).apply();
}
public boolean isCheckByPermission() {
return sharedPreferences.getBoolean(KEY_CHECK_UPLOAD_BY_PERMISSION, false);
}
public void setCheckByPermission(boolean value) {
sharedPreferences.edit().putBoolean(KEY_CHECK_UPLOAD_BY_PERMISSION, value).apply();
}
/**
* Set / Get cinema id
* @return
*/
public String getCinemaId() {
return sharedPreferences.getString(CINEMA_ID, "");
}
public void setCinemaId(String value) {
sharedPreferences.edit().putString(CINEMA_ID, value).apply();
}
/**
* Set / Get Prefix Code
* @return string
*/
public String getPrefixCode() { return sharedPreferences.getString(PREFIX_CODE, ""); }
public void setPrefixCode(String value) {
sharedPreferences.edit().putString(PREFIX_CODE, value).apply();
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/PrinterUtils.java
package hk.com.uatech.eticket.eticket;
import android.app.Activity;
import androidx.annotation.Nullable;
import com.epson.epos2.Epos2Exception;
import com.epson.epos2.printer.Printer;
import com.epson.epos2.printer.PrinterStatusInfo;
public class PrinterUtils {
@Nullable
public static Printer initializeObject(final Activity activity, int printerName, int printerLang) {
Printer printer = null;
try {
printer = new Printer(printerName,
printerLang,
activity);
} catch (Exception e) {
String ex = e.getMessage();
return null;
}
printer.setReceiveEventListener(new com.epson.epos2.printer.ReceiveListener() {
@Override
public void onPtrReceive(Printer printer, int i, PrinterStatusInfo printerStatusInfo, String s) {
//System.out.println("setReceiveEventListener 4 - Called");
activity.runOnUiThread(new Runnable() { // This runnable is created
@Override // from lambda by SAM convention
public void run() {
new Runnable() { // This Runnable is instantiated
@Override // inside the lambda but never runs.
public void run() {
System.out.println("run");
}
};
}
});
}
});
return printer;
}
public static boolean connectPrinter(Printer printer, String ip) {
if (printer == null) {
System.out.println("ConnectPrinter - Return 1");
return false;
}
try {
String printerNameStr = "TCP:" + ip;
printer.connect(printerNameStr, Printer.PARAM_DEFAULT);
} catch (Exception e) {
//ShowMsg.showException(e, "connect", mContext);
String tmp = e.getMessage();
//System.out.println("connectPrinter5 - Return 2");
System.out.println(e.getMessage());
return false;
}
return true;
}
public static void disconnectPrinter(Activity activity, Printer printer) {
System.out.println("disconnectPrinter - 0");
if (printer == null) {
System.out.println("disconnectPrinter - 1");
return;
}
try {
printer.endTransaction();
} catch (final Exception e) {
System.out.println("disconnectPrinter - 2");
activity.runOnUiThread(new Runnable() {
@Override
public synchronized void run() {
}
});
}
try {
System.out.println("disconnectPrinter - 2a");
PrinterStatusInfo aa = printer.getStatus();
int ttt = aa.getConnection();
System.out.print("ttt: " + String.valueOf(ttt));
printer.disconnect();
} catch (Epos2Exception ee) {
System.out.println("disconnectPrinter - 2ee");
System.out.println(String.valueOf(ee.getErrorStatus()));
} catch (final Exception e) {
System.out.println("disconnectPrinter - 2e");
System.out.println(e.getMessage());
activity.runOnUiThread(new Runnable() {
@Override
public synchronized void run() {
//ShowMsg.showException(e, "disconnect", mContext);
}
});
}
System.out.println("disconnectPrinter - 3");
finalizeObject(printer);
System.out.println("disconnectPrinter - 4");
}
public static void finalizeObject(Printer printer) {
if (printer == null) {
System.out.println("finalizeObject - return");
return;
}
try {
printer.clearCommandBuffer();
printer.setReceiveEventListener(null);
printer = null;
} catch (Exception efinal) {
}
}
public static boolean beginTran(Printer printer) {
boolean isBeginTransaction = false;
try {
printer.beginTransaction();
isBeginTransaction = true;
} catch (Exception e) {
//ShowMsg.showException(e, "beginTransaction", mContext);
}
if (!isBeginTransaction) {
try {
printer.disconnect();
} catch (Epos2Exception e) {
// Do nothing
// System.out.println("beginTran1 - Return 3");
return false;
}
}
return true;
}
public static void endTran(Activity activity, Printer printer) {
try {
printer.endTransaction();
printer.clearCommandBuffer();
} catch (final Exception e) {
//System.out.println("endTran1 - 1");
activity.runOnUiThread(new Runnable() {
@Override
public synchronized void run() {
// ShowMsg.showException(e, "endTransaction", mContext);
}
});
}
}
}
<file_sep>/app/src/main/java/hk/com/uatech/eticket/eticket/EntranceStep2Activity.java
package hk.com.uatech.eticket.eticket;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.os.StrictMode;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
//import com.android.internal.util.Predicate;
import com.epson.epos2.Epos2Exception;
import com.epson.epos2.printer.Printer;
import com.epson.epos2.printer.PrinterStatusInfo;
import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.ResultPoint;
import com.journeyapps.barcodescanner.BarcodeCallback;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import com.journeyapps.barcodescanner.DefaultDecoderFactory;
import com.mysql.jdbc.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import hk.com.uatech.eticket.eticket.database.Entrance;
import hk.com.uatech.eticket.eticket.network.NetworkRepository;
import hk.com.uatech.eticket.eticket.network.ResponseType;
import hk.com.uatech.eticket.eticket.pojo.Counter;
import hk.com.uatech.eticket.eticket.pojo.SeatInfo;
import hk.com.uatech.eticket.eticket.pojo.TicketTrans;
import hk.com.uatech.eticket.eticket.preferences.PreferencesController;
import hk.com.uatech.eticket.eticket.qrCode.QRActivity;
import hk.com.uatech.eticket.eticket.utils.Utils;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
public class EntranceStep2Activity extends QRActivity implements NetworkRepository.QueryCallback /*, ReceiveListener */ {
enum ScanStatus {
NONE,
REDEEMED,
VALID,
INVALID,
}
private static boolean IS_DEBUG = false;
private Printer mPrinter = null;
private final int MY_PERMISSIONS_CAMERA = 10099;
private final boolean isLocalDebug = false;
private final boolean isLocalSkipPrint = false;
private static final int PRINTERS_COUNT = 5;
private List<Printer> mPrinters = new ArrayList<>(PRINTERS_COUNT);
private List<String> mPrinterIPList = new ArrayList<>();
private int printerName = Printer.TM_M30;
private int printerLang = Printer.MODEL_CHINESE;
private boolean isFirstTimeUpdate = false;
private boolean containsFood = false;
private ArrayList containsComboFoods = new ArrayList();
private final int REQ_CODE = 16500;
private ProgressDialog loading = null;
public List ticketTypeList = new ArrayList();
public List ticketList = new ArrayList();
public List ticketIdList = new ArrayList();
public List ticketState = new ArrayList();
// List for Print Out
public List printFoodref = new ArrayList();
public List printItemId = new ArrayList();
public List printCategory = new ArrayList();
public List printQuantity = new ArrayList();
public List printEngDesc = new ArrayList();
public List printChiDesc = new ArrayList();
public List printDept = new ArrayList();
public List printRemark = new ArrayList();
public List printSeat = new ArrayList();
// For Consolidate
public List cprintFoodref = new ArrayList();
public List cprintItemId = new ArrayList();
public List cprintCategory = new ArrayList();
public List cprintQuantity = new ArrayList();
public List cprintEngDesc = new ArrayList();
public List cprintChiDesc = new ArrayList();
public List cprintDept = new ArrayList();
public List cprintRemark = new ArrayList();
public List cprintSeat = new ArrayList();
public List printerADept = new ArrayList();
public List printerAIp = new ArrayList();
public List printerAName = new ArrayList();
public List printerADesc = new ArrayList();
public String consolidateIp = "";
public String consolidateName = "";
public String consolidateDesc = "";
public ArrayList foodOrderIds = new ArrayList();
public ArrayList foodOrderStatuses = new ArrayList();
public ArrayList foodOrderIds2 = new ArrayList();
private int currentFoodRefNoPointer = 0;
private int currentFoodRefNoActionPointer = 0;
private ArrayList orderTypes = new ArrayList();
private TableLayout tl;
private GridView gvAdult;
private GridView gvBigi;
private GridView gvChild;
private GridView gvSenior;
private ImageView accept;
private ImageView reject;
private ImageView update;
private ImageAdapter imageAdultAdapter;
private ImageAdapter imageBigiAdapter;
private ImageAdapter imageChildAdapter;
private ImageAdapter imageSeniorAdapter;
private String encryptRefNo = "";
private String refType = "";
private String jsonSource = "";
private String movieTransId = "";
private String accessMode = "";
private boolean outsideGracePeriod = false;
private DecoratedBarcodeView barcodeView;
private String lastText;
private ImageView imgValid;
private ImageView imgInvalid;
private View cardBack;
private TextView scanStatus;
// TicketTran Info
private TicketTrans ticketTrans;
private List<SeatInfo> checkedItems = new ArrayList<SeatInfo>();
private ScanStatus scan_status = ScanStatus.NONE;
private BarcodeCallback callback = new BarcodeCallback() {
@Override
public void barcodeResult(BarcodeResult result) {
if (result.getText() == null || result.getText().equals(lastText)) {
return;
}
lastText = result.getText();
barcodeView.setStatusText(result.getText());
getIntent().putExtra("json", lastText);
handleQrCode(lastText, true);
}
@Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entrance_step2);
IS_DEBUG = Utils.isDebug(getApplicationContext());
tl = (TableLayout) findViewById(R.id.detailview);
barcodeView = (DecoratedBarcodeView) findViewById(R.id.zxing_barcode_scanner);
Collection<BarcodeFormat> formats = Arrays.asList(BarcodeFormat.QR_CODE, BarcodeFormat.CODE_39);
barcodeView.getBarcodeView().setDecoderFactory(new DefaultDecoderFactory(formats));
barcodeView.decodeContinuous(callback);
scanStatus = (TextView) findViewById(R.id.scanStatus);
init();
}
public void debugMsg1() {
String debugLogContent = "Check ArrayList\r\n";
debugLogContent += "printFoodref(s):\r\n";
debugLogContent += "------------------\r\n";
if (printFoodref != null) {
for (int ll = 0; ll < printFoodref.size(); ll++) {
debugLogContent += "" + printFoodref.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
debugLogContent += "printItemId(s):\r\n";
debugLogContent += "------------------\r\n";
if (printItemId != null) {
for (int ll = 0; ll < printItemId.size(); ll++) {
debugLogContent += "" + printItemId.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
debugLogContent += "printCategory(s):\r\n";
debugLogContent += "------------------\r\n";
if (printCategory != null) {
for (int ll = 0; ll < printCategory.size(); ll++) {
debugLogContent += "" + printCategory.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
debugLogContent += "printQuantity(s):\r\n";
debugLogContent += "------------------\r\n";
if (printQuantity != null) {
for (int ll = 0; ll < printQuantity.size(); ll++) {
debugLogContent += "" + printQuantity.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
debugLogContent += "printEngDesc(s):\r\n";
debugLogContent += "------------------\r\n";
if (printEngDesc != null) {
for (int ll = 0; ll < printEngDesc.size(); ll++) {
debugLogContent += "" + printEngDesc.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
debugLogContent += "printChiDesc(s):\r\n";
debugLogContent += "------------------\r\n";
if (printChiDesc != null) {
for (int ll = 0; ll < printChiDesc.size(); ll++) {
debugLogContent += "" + printChiDesc.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
debugLogContent += "printDept(s):\r\n";
debugLogContent += "------------------\r\n";
if (printDept != null) {
for (int ll = 0; ll < printDept.size(); ll++) {
debugLogContent += "" + printDept.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
debugLogContent += "printSeat(s):\r\n";
debugLogContent += "------------------\r\n";
if (printSeat != null) {
for (int ll = 0; ll < printSeat.size(); ll++) {
debugLogContent += "" + printSeat.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
debugLogContent += "printRemark(s):\r\n";
debugLogContent += "------------------\r\n";
if (printRemark != null) {
for (int ll = 0; ll < printRemark.size(); ll++) {
debugLogContent += "" + printRemark.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
debugLogContent += "printerADept(s):\r\n";
debugLogContent += "------------------\r\n";
if (printerADept != null) {
for (int ll = 0; ll < printerADept.size(); ll++) {
debugLogContent += "" + printerADept.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
debugLogContent += "printerAIp(s):\r\n";
debugLogContent += "------------------\r\n";
if (printerAIp != null) {
for (int ll = 0; ll < printerAIp.size(); ll++) {
debugLogContent += "" + printerAIp.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
debugLogContent += "printerAName(s):\r\n";
debugLogContent += "------------------\r\n";
if (printerAName != null) {
for (int ll = 0; ll < printerAName.size(); ll++) {
debugLogContent += "" + printerAName.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
debugLogContent += "printerADesc(s):\r\n";
debugLogContent += "------------------\r\n";
if (printerADesc != null) {
for (int ll = 0; ll < printerADesc.size(); ll++) {
debugLogContent += "" + printerADesc.get(ll).toString() + "\r\n";
}
}
debugLogContent += "------------------\r\n";
MainActivity.appendLog(debugLogContent);
}
private void init() {
if (loading == null) {
loading = new ProgressDialog(EntranceStep2Activity.this);
loading.setCancelable(true);
loading.setMessage("Loading");
loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
ticketIdList.clear();
ticketList.clear();
ticketState.clear();
ticketTypeList.clear();
loading.show();
View actionPanel = findViewById(R.id.detailActionPanel);
View navPanel = findViewById(R.id.navPanel);
View mainPanel = findViewById(R.id.mainPanel);
if (getIntent().getBooleanExtra("showScanner", false)) {
barcodeView.setVisibility(View.VISIBLE);
actionPanel.setVisibility(View.GONE);
navPanel.setVisibility(View.GONE);
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_CAMERA);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_CAMERA);
}
}
} else {
barcodeView.setVisibility(View.GONE);
actionPanel.setVisibility(View.VISIBLE);
navPanel.setVisibility(View.VISIBLE);
}
if (StringUtils.isNullOrEmpty(getIntent().getExtras().getString("json"))) {
mainPanel.setVisibility(View.GONE);
loading.dismiss();
return;
} else {
mainPanel.setVisibility(View.VISIBLE);
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String gracePeriodFrom = PreferencesController.getInstance().getGracePeriodFrom();
String gracePeriodTo = PreferencesController.getInstance().getGracePeriodTo();
accessMode = PreferencesController.getInstance().getAccessMode();
LinearLayout bgLayer = (LinearLayout) findViewById(R.id.bglayer);
if ("offline".equals(accessMode)) {
//tv.setVisibility(View.VISIBLE);
// bgLayer.setBackgroundColor(Color.rgb(255, 179, 179));
} else {
//tv.setVisibility(View.GONE);
// bgLayer.setBackgroundColor(Color.rgb(244, 244, 244));
}
int gpFrom = Integer.parseInt(gracePeriodFrom);
int gpTo = Integer.parseInt(gracePeriodTo);
// Get the object
final String jsonstr = getIntent().getExtras().getString("json");
JSONObject jsonObj;
foodRefNo = getIntent().getExtras().getString("foodRefNo");
encryptRefNo = getIntent().getExtras().getString("encryptRefNo");
refType = getIntent().getExtras().getString("refType");
jsonSource = jsonstr;
//
// Populate the ticket trans variable
if(jsonSource != null && !jsonSource.equals(" ")) {
Gson gson = new Gson();
ticketTrans = gson.fromJson(jsonSource, TicketTrans.class);
}
// Log.d(EntranceStep2Activity.class.toString(), String.valueOf(ticketTrans.getLogIn().size()));
// Log.d(EntranceStep2Activity.class.toString(), String.valueOf(ticketTrans.getLogOut().size()));
TableLayout tlEnter = (TableLayout) findViewById(R.id.tlEnterDetail);
TextView tvClickEnter = (TextView) findViewById(R.id.tvClickEnter);
ArrayList<String> compareWith = new ArrayList<String>(Arrays.asList(ticketTrans.getSeats().split(",")));
if(ticketTrans != null && ticketTrans.getLogIn().size() > 0) {
for(String strDate: ticketTrans.getLogIn().keySet()) {
TableRow tableRow = new TableRow(this);
LayoutParams tableRowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tableRow.setLayoutParams(tableRowParams);
TextView dateTv = createDateTextView(strDate);
List<String> seatNo = ticketTrans.getLogIn().get(strDate);
TextView seatsTv = createSeatTextView(strDate, seatNo, compareWith);
if(!seatsTv.getText().toString().equals("")) {
tableRow.addView(dateTv);
tableRow.addView(seatsTv);
tlEnter.addView(tableRow);
}
}
} else {
tlEnter.setVisibility(View.GONE);
tvClickEnter.setVisibility(View.GONE);
}
TableLayout tlExit = (TableLayout) findViewById(R.id.tlExitDetail);
TextView tvClickExit = (TextView) findViewById(R.id.tvClickExit);
if(ticketTrans != null && ticketTrans.getLogOut().size() > 0) {
for(String strDate : ticketTrans.getLogOut().keySet()) {
TableRow tr = new TableRow(this);
LayoutParams trLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tr.setLayoutParams(trLayoutParams);
TextView dateTv = createDateTextView(strDate);
List<String> seatNo = ticketTrans.getLogOut().get(strDate);
TextView seatsTv = createSeatTextView(strDate, seatNo, compareWith);
if(!seatsTv.getText().toString().equals("")) {
tr.addView(dateTv);
tr.addView(seatsTv);
tlExit.addView(tr);
}
}
} else {
tlExit.setVisibility(View.GONE);
tvClickExit.setVisibility(View.GONE);
}
boolean hasConcession = false;
boolean hasNormal = false;
int totalConcession = 0;
int totalNormal = 0;
int scanned_concession = 0;
int scanned_normal = 0;
for(SeatInfo seat : ticketTrans.getSeatInfoList()) {
if(seat.getAction() == ScanType.REFUND) continue;
if(seat.isConcession() && seat.getAction() != ScanType.REFUND) {
hasConcession = true;
totalConcession += 1;
if(seat.getAction() == ScanType.IN) {
scanned_concession += 1;
}
} else {
hasNormal = true;
totalNormal += 1;
if(seat.getAction() == ScanType.IN) {
scanned_normal += 1;
}
}
}
TableRow trTotalRemainingConcession = (TableRow) findViewById(R.id.trTotalRemainingConcession);
TableRow trTotalRemainingNormal = (TableRow) findViewById(R.id.trTotalRemainingNormal);
if(!hasConcession) {
trTotalRemainingConcession.setVisibility(View.GONE);
} else {
TextView tvTotalRemaining = (TextView) findViewById(R.id.tvTotalRemainingConcession);
int remain = totalConcession - scanned_concession;
String info = remain + " / " + totalConcession;
tvTotalRemaining.setText(info);
}
if(!hasNormal) {
trTotalRemainingNormal.setVisibility(View.GONE);
} else {
TextView tvTotalRemaining = (TextView) findViewById(R.id.tvTotalRemainingNormal);
int remain = totalNormal - scanned_normal;
String info = remain + " / " + totalNormal;
tvTotalRemaining.setText(info);
}
/*
TableRow trTotalRemaining = (TableRow) findViewById(R.id.trTotalRemaining);
// Set Total / Remaining info
if(ticketTrans == null || ticketTrans.getCounter() == null) {
trTotalRemaining.setVisibility(View.GONE);
} else {
TextView tvTotalRemaining = (TextView) findViewById(R.id.tvTotalRemaining);
Counter counter = ticketTrans.getCounter();
String info = counter.getRemain_ticket() + " / " + counter.getTotal_ticket();
tvTotalRemaining.setText(info);
}
*/
String movieTitle = "";
String movieCategory = "";
String cinemaName = "";
String cinemaName2 = "";
String showDate = "";
String showTime = "";
String displayFileDateTime = "";
String displayFilmDate = "";
String displayFilmTime = "";
String seatIds = "";
String resultMsg = "";
String fullSeat = "";
// For Food
List foodIds = new ArrayList();
List foodValues = new ArrayList();
List foodQty = new ArrayList();
int totalSeats = 0;
int validSeats = 0;
try {
jsonObj = new JSONObject(jsonstr);
resultMsg = jsonObj.getString("resultMsg");
JSONArray trans = jsonObj.getJSONArray("transInfoList");
JSONArray seats = jsonObj.getJSONArray("seatInfoList");
if (seats != null) {
totalSeats = seats.length();
}
JSONObject tran = trans.getJSONObject(0);
// Check whether the information is valid or invalid
movieTransId = tran.getString("transId");
movieTitle = tran.getString("movieTitle");
movieCategory = tran.getString("movieCategory");
cinemaName = tran.getString("houseName");
cinemaName2 = tran.getString("cinemaName");
showDate = tran.getString("showDate");
showTime = tran.getString("showTime");
// 20170929, change to get the food Order Id from Json
try {
JSONArray aFood = tran.getJSONArray("fbOrderId");
if (aFood != null) {
for (int z = 0; z < aFood.length(); z++) {
foodOrderIds.add(aFood.get(z).toString());
}
}
} catch (Exception efoodOrder) {
// Nothing to do
}
final String strType = getIntent().getExtras().getString("scanType");
ScanType scanType = ScanType.valueOf(strType);
// For Seat Info
if (seats != null) {
for (int y = 0; y < seats.length(); y++) {
JSONObject seat = seats.getJSONObject(y);
// Get the food information
JSONArray foods = null;
try {
foods = seat.getJSONArray("fnbList");
} catch (JSONException je) {
foods = null;
}
if (foods != null) {
for (int z = 0; z < foods.length(); z++) {
boolean findInArray = false;
String tmpValue = foods.getJSONObject(z).getString("fnbId");
String tmpFoodName = foods.getJSONObject(z).getString("fnbName");
int tmpFoodQty = foods.getJSONObject(z).getInt("fnbQty");
for (int t = 0; t < foodIds.size(); t++) {
if (foodIds.get(t).toString().compareTo(tmpValue) == 0) {
findInArray = true;
String tmpQtyToChange = foodQty.get(t).toString();
if (tmpFoodQty == 1) {
tmpQtyToChange += "," + seat.getString("seatId");
foodQty.set(t, tmpQtyToChange);
} else {
// Get the original qty
String tmpArr[] = tmpQtyToChange.split(",");
if (tmpArr.length > 0) {
tmpQtyToChange = "";
String reformat = "";
for (int t1 = 0; t1 < tmpArr.length; t1++) {
String tmpArr2[] = tmpArr[t1].split(" ");
reformat = tmpArr[t1];
if (seat.getString("seatId").compareTo(tmpArr2[0]) == 0) {
int orgQty = 0;
if (tmpArr2.length > 1) {
// pattern is "A6 x 2"
// reformat =
orgQty = Integer.parseInt(tmpArr2[2]);
} else {
// patter is "A6"
orgQty = 1;
}
orgQty += tmpFoodQty;
reformat = seat.getString("seatId") + " x " + String.valueOf(orgQty);
}
if (tmpQtyToChange.length() > 0) {
tmpQtyToChange += ",";
}
tmpQtyToChange += reformat;
}
}
//tmpQtyToChange += "," + seat.getString("seatId") + " x " + String.valueOf(tmpFoodQty);
foodQty.set(t, tmpQtyToChange);
}
break;
}
}
if (!findInArray) {
foodIds.add(tmpValue);
foodValues.add(tmpFoodName);
if (tmpFoodQty == 1) {
foodQty.add(seat.getString("seatId"));
} else {
String tmpQty = seat.getString("seatId") + " x " + String.valueOf(tmpFoodQty);
foodQty.add(tmpQty);
}
}
}
}
if (foodIds != null && foodIds.size() > 0) {
containsFood = true;
} else {
containsFood = false;
}
// Concat the Seat ID
if (seat.getString("seatId") != "") {
if (seatIds != "")
seatIds += ",";
seatIds += seat.getString("seatId");
}
// Ticket Type
String ticketType = seat.getString("ticketType");
String seatStatus = seat.getString("seatStatus");
int seatIcon = 0;
Counter counter = ticketTrans.getCounter();
// If scanned ticket type (normal/concession)
// equals to seat ticket type (normal/concession)
// set seat is selected
/*
if(scanType == ScanType.IN || scanType == ScanType.NONE) {
if(ticketTrans.isConcession() == seat.getBoolean("isConcession") &&
"Valid".compareTo(seatStatus) == 0) {
seatIcon = 2;
validSeats++;
setSeatChecked(true, y);
} else {
seatIcon = 0;
setSeatChecked(false, y);
}
} else if(scanType == ScanType.OUT) {
if(ticketTrans.isConcession() == seat.getBoolean("isConcession") &&
"Invalid".compareTo(seatStatus) == 0) {
seatIcon = 2;
validSeats++;
setSeatChecked(true, y);
} else {
seatIcon = 0;
setSeatChecked(false, y);
}
}
*/
/*
if(scanType == ScanType.IN &&
ScanType.valueOf(seat.getString("action")) == ScanType.OUT &&
ticketTrans.isConcession() == seat.getBoolean("isConcession")) {
seatIcon = 2;
validSeats++;
setSeatChecked(true, y);
}else if(scanType == ScanType.IN &&
ScanType.valueOf(seat.getString("action")) == ScanType.NONE &&
ticketTrans.isConcession() == seat.getBoolean("isConcession")) {
seatIcon = 2;
validSeats++;
setSeatChecked(true, y);
} else if(scanType == ScanType.OUT &&
ScanType.valueOf(seat.getString("action")) == ScanType.IN &&
ticketTrans.isConcession() == seat.getBoolean("isConcession")) {
seatIcon = 2;
validSeats++;
setSeatChecked(true, y);
} else {
seatIcon = 0;
setSeatChecked(false, y);
}
*/
if((scanType == ScanType.IN &&
((ScanType.valueOf(seat.getString("action")) == ScanType.OUT) ||
ScanType.valueOf(seat.getString("action")) == ScanType.NONE) ||
(scanType == ScanType.OUT &&
ScanType.valueOf(seat.getString("action")) == ScanType.IN)) &&
ticketTrans.isConcession() == seat.getBoolean("isConcession")) {
seatIcon = 2;
validSeats++;
setSeatChecked(true, y);
} else {
seatIcon = 0;
setSeatChecked(false, y);
}
/**
if ("Valid".compareTo(seatStatus) == 0) {
//seatIcon = 1;
// Original is 1, but after chaing the requirement @20170822, all valid seat should be selected
seatIcon = 2;
validSeats++;
setSeatChecked(true, y);
} else if ("Invalid".compareTo(seatStatus) == 0) {
seatIcon = 0;
setSeatChecked(false, y);
} else {
seatIcon = 2;
setSeatChecked(true, y);
}
*/
// Check whether the ticket already exist or not
boolean findInTypeArray = false;
int ticketTypeInd = -1;
for (ticketTypeInd = 0; ticketTypeInd < ticketTypeList.size(); ticketTypeInd++) {
String tmpTicketType = ticketTypeList.get(ticketTypeInd).toString();
if (tmpTicketType != null && tmpTicketType.compareTo(ticketType) == 0) {
findInTypeArray = true;
break;
}
}
if (!findInTypeArray) {
// Not Found
ticketTypeList.add(ticketType);
ticketTypeInd = ticketTypeList.size() - 1;
ArrayList newList = new ArrayList();
ArrayList newIdList = new ArrayList();
ArrayList newState = new ArrayList();
ticketList.add(newList);
ticketIdList.add(newIdList);
ticketState.add(newState);
}
// Add the list
ArrayList tmpList = (ArrayList) ticketList.get(ticketTypeInd);
ArrayList tmpIdList = (ArrayList) ticketIdList.get(ticketTypeInd);
ArrayList tmpState = (ArrayList) ticketState.get(ticketTypeInd);
tmpList.add(seatIcon);
tmpIdList.add(seat.getString("seatId"));
if(scanType == ScanType.IN || scanType == ScanType.NONE) {
if ("Valid".compareTo(seatStatus) == 0) {
tmpState.add(1);
} else {
tmpState.add(0);
}
} else {
if ("Invalid".compareTo(seatStatus) == 0) {
tmpState.add(1);
} else {
tmpState.add(0);
}
}
ticketList.set(ticketTypeInd, tmpList);
ticketIdList.set(ticketTypeInd, tmpIdList);
ticketState.set(ticketTypeInd, tmpState);
}
}
// Get full seat info
// fullSeat = tran.getString("fullSeat");
} catch (Exception ec) {
// Show Message
Context context = getApplicationContext();
CharSequence text = ec.getMessage(); //"Login Fail, please try again";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return;
}
LinearLayout ticketContainer = (LinearLayout) findViewById(R.id.ticketContainer);
ticketContainer.removeAllViews();
((TextView) findViewById(R.id.movieTitle)).setText(movieTitle);
((TextView) findViewById(R.id.cinemaName)).setText(cinemaName);
((TextView) findViewById(R.id.movieTransId)).setText(movieTransId);
((TextView) findViewById(R.id.cinemaName2)).setText(cinemaName2);
((TextView) findViewById(R.id.movieCategory)).setText(movieCategory);
// If scanned ticket is Concession
ArrayList<String> lst_concession = new ArrayList<String>();
ArrayList<String> lst_normal = new ArrayList<String>();
for(SeatInfo seat : ticketTrans.getSeatInfoList()) {
if(seat.isConcession()) {
lst_concession.add(seat.getSeatId());
}else{
lst_normal.add(seat.getSeatId());
}
}
if(lst_concession.size() > 0) {
String str_concession = TextUtils.join(", ", lst_concession);
((TextView) findViewById(R.id.concession_seats)).setText(str_concession);
} else {
(findViewById(R.id.tblRowConcession)).setVisibility(View.GONE);
}
if(lst_normal.size() > 0) {
String str_normal = TextUtils.join(", ", lst_normal);
((TextView) findViewById(R.id.normal_seats)).setText(str_normal);
} else {
(findViewById(R.id.tblRowNormal)).setVisibility(View.GONE);
}
// ((TextView) findViewById(R.id.seatIds)).setText(seatIds);
// ((TextView) findViewById(R.id.seatIds)).setText(fullSeat);
TableLayout dtlTbl = (TableLayout) findViewById(R.id.detailview);
if (foodIds.size() > 0) {
for (int i = 0; i < foodIds.size(); i++) {
TableRow.LayoutParams paramsExample = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TableRow tr = new TableRow(this);
tr.setPadding(0, 5, 0, 0);
tr.setLayoutParams(new TableRow.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
TextView tvFoodName = new TextView(this);
tvFoodName.setTextSize(14);
tvFoodName.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
tvFoodName.setText(foodValues.get(i).toString());
tvFoodName.setTextColor(Color.parseColor("#aaaaaa"));
tvFoodName.setEms(10);
tvFoodName.setLayoutParams(paramsExample);
TextView tvFoodDesc = new TextView(this);
tvFoodDesc.setTextSize(14);
tvFoodDesc.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
tvFoodDesc.setTextColor(Color.parseColor("#a9987a"));
tvFoodDesc.setText(foodQty.get(i).toString());
tvFoodDesc.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END);
tvFoodDesc.setEms(10);
tvFoodDesc.setLayoutParams(paramsExample);
tr.addView(tvFoodName);
tr.addView(tvFoodDesc);
dtlTbl.addView(tr);
}
}
boolean isValid = true;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US); //new SimpleDateFormat("dd MMM yyyy (E) hh:mma");
//DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
//DateTime dt = formatter.parseDateTime(string);
Date dt;
Date currentDt = new Date();
if ("".compareTo(showDate) == 0 || "".compareTo(showTime) == 0) {
// Nothing to do
} else {
try {
//dt = format.parse("10 August 2017 (Thu)" + " " + "12:20pm");
dt = format.parse(showDate + " " + showTime);
displayFileDateTime = dt.toString();
/**
* Test Case
*/
if(IS_DEBUG) {
// Calendar cal = Calendar.getInstance();
// cal.setTime(new Date());
// cal.add(Calendar.MINUTE, 5);
// dt = cal.getTime();
}
/**
* End of test case
*/
SimpleDateFormat displayFormat = new SimpleDateFormat("dd MMM yyyy (E) hh:mma", java.util.Locale.US);
displayFileDateTime = displayFormat.format(dt);
SimpleDateFormat displayFormatDate = new SimpleDateFormat("dd MMM yyyy (E)", java.util.Locale.US);
displayFilmDate = displayFormatDate.format(dt);
SimpleDateFormat displayFormatTime = new SimpleDateFormat("hh:mma", java.util.Locale.US);
displayFilmTime = displayFormatTime.format(dt);
long diff = currentDt.getTime() - dt.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
//long hours = minutes / 60;
if (minutes > 0) {
// Current Date is greater than the show date time
if (minutes > gpTo) {
isValid = false;
}
} else {
if (Math.abs(minutes) > gpFrom) {
isValid = false;
}
}
} catch (Exception exdate) {
Log.d("exception", "exception");
}
}
imgValid = (ImageView) findViewById(R.id.imgValid);
imgInvalid = (ImageView) findViewById(R.id.imgInvalid);
cardBack = findViewById(R.id.card_back);
boolean isInvalid = resultMsg.compareToIgnoreCase("success") == 0;
outsideGracePeriod = !isValid;
if (TextUtils.isEmpty(showDate)) {
changeMode(!isInvalid);
} else {
changeMode(isValid);
}
final String strType = getIntent().getExtras().getString("scanType");
ScanType scanType = ScanType.valueOf(strType);
if(scanType == ScanType.OUT) {
if(validSeats > 0) {
scan_status = ScanStatus.VALID;
changeMode(true);
} else {
scan_status = ScanStatus.INVALID;
changeMode(false);
}
} else {
if(!outsideGracePeriod && validSeats == 0) {
scan_status = ScanStatus.REDEEMED;
// imgInvalid.setImageResource(R.mipmap.redeemed);
imgValid.setVisibility(View.GONE);
changeMode(false);
}else if(!outsideGracePeriod && validSeats > 0) {
scan_status = ScanStatus.VALID;
changeMode(true);
} else {
scan_status = ScanStatus.INVALID;
changeMode(false);
}
}
((TextView) findViewById(R.id.showDate2)).setText(displayFilmDate);
((TextView) findViewById(R.id.showDate)).setText(displayFilmDate);
((TextView) findViewById(R.id.showTime)).setText(displayFilmTime);
((TextView) findViewById(R.id.showTime2)).setText(displayFilmTime);
// Invisible the Detail TableView
tl = (TableLayout) findViewById(R.id.detailview);
tl.setVisibility(View.GONE);
ImageView ivDetail = (ImageView) findViewById(R.id.detail);
ivDetail.setOnClickListener(new ImageView.OnClickListener() {
@Override
public void onClick(View v) {
// Show / Hide the Detail View
if (tl.getVisibility() == View.VISIBLE) {
tl.setVisibility(View.GONE);
} else {
tl.setVisibility(View.VISIBLE);
}
}
});
ImageView acceptIV = (ImageView) findViewById(R.id.accept);
if(scanType == ScanType.IN) {
acceptIV.setImageResource(R.mipmap.scan_in);
} else if(scanType == ScanType.OUT) {
acceptIV.setImageResource(R.mipmap.scan_out);
}
findViewById(R.id.accept).setOnClickListener(new ImageView.OnClickListener() {
@Override
public void onClick(View v) {
showAcceptDialog();
}
});
findViewById(R.id.reject).setOnClickListener(new ImageView.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
View update = findViewById(R.id.update);
update.setOnClickListener(new ImageView.OnClickListener() {
@Override
public void onClick(View v) {
if (PreferencesController.getInstance().isUsePasswordForChangeSeat()) {
if ("MANAGER".equals(PreferencesController.getInstance().getUserRank())) {
showPasswordDialog();
} else {
Toast.makeText(
EntranceStep2Activity.this,
"unauthorized",
Toast.LENGTH_LONG)
.show();
}
} else {
// if ("MANAGER".equals(PreferencesController.getInstance().getUserRank())) {
// editSeatStatus();
// } else {
// Toast.makeText(
// EntranceStep2Activity.this,
// "unauthorized",
// Toast.LENGTH_LONG)
// .show();
// }
editSeatStatus();
}
//
// if ("MANAGER".equals(PreferencesController.getInstance().getUserRank())) {
// if (PreferencesController.getInstance().isUsePasswordForChangeSeat()) {
// showPasswordDialog();
// } else {
// editSeatStatus();
// }
// } else {
// if ("offline".compareTo(accessMode) == 0) {
// Toast.makeText(
// EntranceStep2Activity.this,
// "Sorry, User don't have the access right to edit in Offline Mode",
// Toast.LENGTH_LONG)
// .show();
//
// } else {
// // Show Login Dialog
// showLoginDialog();
// }
//
// }
}
});
// Hide the Update button or not
if (validSeats == totalSeats) {
//update.setVisibility(View.GONE);
update.setEnabled(false);
isFirstTimeUpdate = true;
}
for (int x = 0; x < ticketTypeList.size(); x++) {
String ticketTypeName = ticketTypeList.get(x).toString();
int paddingPixel = 10;
float density = EntranceStep2Activity.this.getResources().getDisplayMetrics().density;
int paddingDp = (int) (paddingPixel * density);
TextView tv = new TextView(EntranceStep2Activity.this);
LayoutParams paramsTV = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(paramsTV);
tv.setEms(10);
//tv.setInputType();
//tv.setPadding(paddingDp, paddingDp, paddingDp, 0);
tv.setPadding(paddingDp, 5, paddingDp, 0);
tv.setText(ticketTypeName);
tv.setTextColor(Color.parseColor("#aaaaaa"));
tv.setTextSize(14);
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
GridView gv = new GridView(EntranceStep2Activity.this);
// gv.setNumColumns();
gv.setLayoutParams(params);
gv.setHorizontalSpacing(3);
gv.setPadding(paddingDp, 0, paddingDp, 0);
gv.setColumnWidth(120);
//gv.setNumColumns(GridView.AUTO_FIT);
gv.setNumColumns(8);
gv.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
// set the onitemclicklistener
setOnClick(gv, x);
ArrayList tmpList = (ArrayList) ticketList.get(x);
ImageAdapter adapter = new ImageAdapter(this, tmpList);
//gvAdult.setAdapter(imageAdultAdapter);
gv.setAdapter(adapter);
adapter.notifyDataSetChanged();
int noOfLine = tmpList.size();
noOfLine = (noOfLine / 8);
if ((tmpList.size()) % 8 > 0)
noOfLine++;
if (noOfLine > 1) {
int totalHeight = 0;
totalHeight = 116 * noOfLine;
ViewGroup.LayoutParams params4 = gv.getLayoutParams();
params.height = totalHeight;
gv.setLayoutParams(params4);
}
ticketContainer.addView(tv);
ticketContainer.addView(gv);
}
// Last, to check for the FOOD
if (isFirstTimeUpdate && containsFood) {
// Contain Food Information, need to call the FB API listOrder to get the F&B order tail
if (loading == null) {
loading = new ProgressDialog(EntranceStep2Activity.this);
loading.setCancelable(true);
loading.setMessage("Loading");
loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
loading.show();
JSONObject jsonvalue = new JSONObject();
try {
if (foodOrderIds.size() > 0) {
currentFoodRefNoPointer = 0;
jsonvalue.put("refNo", foodOrderIds.get(currentFoodRefNoPointer).toString());
}
} catch (Exception ejson) {
ejson.printStackTrace();
}
NetworkRepository.getInstance().listOrder(jsonvalue.toString(), this);
} else {
loading.dismiss();
}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(EntranceStep2Activity.this.getCurrentFocus().getWindowToken(), 0);
View view = this.getCurrentFocus();
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = new View(this);
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
private void changeMode(boolean isValid) {
if (isValid) {
playSuccess();
imgValid.setVisibility(View.VISIBLE);
imgInvalid.setVisibility(View.GONE);
// cardBack.setBackgroundColor(getResources().getColor(R.color.valid));
} else {
playBuzzer();
if (getIntent().getBooleanExtra("showScanner", false)) {
scanStatus.setVisibility(View.VISIBLE);
scanStatus.setText("Invalid ticket");
}
imgInvalid.setVisibility(View.VISIBLE);
imgValid.setVisibility(View.GONE);
// cardBack.setBackgroundColor(getResources().getColor(R.color.invalid));
}
}
@Override
public void onResponse(ResponseType responseType, String result) {
super.onResponse(responseType, result);
boolean canDismiss = true;
switch (responseType) {
case LIST_ORDER:
if (result == "") {
Context context = getApplicationContext();
CharSequence text = "Error occur during FB_LIST, please contact administrator";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else if (result.startsWith("ERROR")) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
String displayErr = result;
displayErr = displayErr.replace("ERROR (400) : ", "");
displayErr = displayErr.replace("ERROR (401) : ", "");
displayErr = displayErr.replace("ERROR (402) : ", "");
Toast toast = Toast.makeText(context, displayErr, duration);
toast.show();
} else {
Log.d("Return", result);
JSONObject jsonObj;
//
try {
jsonObj = new JSONObject(result);
// Parse the food information
if (jsonObj != null) {
orderTypes.add(jsonObj.getString("orderType"));
foodOrderIds2.add(jsonObj.getString("orderId"));
foodOrderStatuses.add(jsonObj.getString("orderStatus"));
String orderType = jsonObj.getString("orderType");
if ("V".compareTo(orderType) == 0) {
JSONArray pr = jsonObj.getJSONArray("orderDetail");
if (pr != null) {
int cd = 0;
for (int j = 0; j < pr.length(); j++) {
JSONObject obj = (JSONObject) pr.get(j);
boolean foundDept = false;
for (int m = 0; m < printDept.size(); m++) {
if ((obj.getString("dept").compareTo(printDept.get(m).toString()) == 0) && foodOrderIds.get(currentFoodRefNoPointer).toString().compareTo(printFoodref.get(m).toString()) == 0) {
foundDept = true;
break;
}
}
if (!foundDept) {
cd++;
}
// Check having the same record or not (Department, EngDesc)
boolean found = false;
int updateIndex = -1;
int orgQty = -1;
for (int l = 0; l < printItemId.size(); l++) {
if (
(foodOrderIds.get(currentFoodRefNoPointer).toString().compareTo(printFoodref.get(l).toString()) == 0) &&
(printSeat.get(l).toString().compareTo(obj.getString("seatId")) == 0) &&
(printDept.get(l).toString().compareTo(obj.getString("dept")) == 0) &&
(printEngDesc.get(l).toString().compareTo(obj.getString("engDesc")) == 0)
) {
found = true;
updateIndex = l;
orgQty = Integer.parseInt(printQuantity.get(l).toString());
break;
}
}
if (obj.getString("itemId") == null || "null".compareTo(obj.getString("itemId")) == 0 || "".compareTo(obj.getString("itemId")) == 0) {
if (!foundDept) {
cd--;
}
} else {
if (found) {
int newQty = Integer.parseInt(obj.getString("quantity")) + orgQty;
printQuantity.set(updateIndex, String.valueOf(newQty));
} else {
printFoodref.add(foodOrderIds.get(currentFoodRefNoPointer).toString());
printItemId.add(obj.getString("itemId"));
printCategory.add(obj.getString("category"));
printQuantity.add(obj.getString("quantity"));
printEngDesc.add(obj.getString("engDesc"));
printChiDesc.add(obj.getString("cnDesc"));
//printDept.add(obj.getString("dept"));
String tmpDept = "";
if ("0".compareTo(obj.getString("dept")) == 0) {
printDept.add("1");
tmpDept = "1";
} else {
printDept.add(obj.getString("dept"));
tmpDept = obj.getString("dept");
}
printSeat.add(obj.getString("seatId"));
printRemark.add(obj.getString("remarks"));
// Check and add the printer if needed
boolean needAddPrinter = true;
JSONArray arrP = obj.getJSONArray("printer");
if (arrP.length() > 0) {
for (int jj = 0; jj < arrP.length(); jj++) {
JSONObject jObj = arrP.getJSONObject(jj);
if (jObj != null) {
if (jObj.getString("desc").toLowerCase().indexOf("consolidation") >= 0) {
if ("".compareTo(consolidateIp) == 0) {
consolidateIp = jObj.getString("ip");
consolidateName = jObj.getString("name");
consolidateDesc = jObj.getString("desc");
}
} else {
// Not Consolidate Table
for (int zz = 0; zz < printerADept.size(); zz++) {
if (tmpDept.compareTo(printerADept.get(zz).toString()) == 0) {
needAddPrinter = false;
break;
}
}
if (needAddPrinter) {
printerADept.add(tmpDept);
String tmpIP = jObj.getString("ip");
if (isLocalDebug) {
tmpIP = tmpIP.replaceAll("172.16.31.10", "192.168.1.36");
}
printerAIp.add(tmpIP /*jObj.getString("ip")*/);
printerAName.add(jObj.getString("name"));
printerADesc.add(jObj.getString("desc"));
}
}
}
}
}
}
}
}
if (cd > 1) {
containsComboFoods.add("Y");
} else {
containsComboFoods.add("N");
}
// For Consolidate Food
for (int j = 0; j < pr.length(); j++) {
JSONObject obj = (JSONObject) pr.get(j);
boolean foundDept = false;
for (int m = 0; m < cprintDept.size(); m++) {
if ((obj.getString("dept").compareTo(cprintDept.get(m).toString()) == 0) && foodOrderIds.get(currentFoodRefNoPointer).toString().compareTo(cprintFoodref.get(m).toString()) == 0) {
foundDept = true;
break;
}
}
if (!foundDept) {
cd++;
}
// Check having the same record or not (Department, EngDesc)
boolean found = false;
int updateIndex = -1;
int orgQty = -1;
for (int l = 0; l < cprintItemId.size(); l++) {
if (
(foodOrderIds.get(currentFoodRefNoPointer).toString().compareTo(cprintFoodref.get(l).toString()) == 0) &&
(cprintDept.get(l).toString().compareTo(obj.getString("dept")) == 0) &&
(cprintSeat.get(l).toString().compareTo(obj.getString("seatId")) == 0) &&
(cprintEngDesc.get(l).toString().compareTo(obj.getString("engDesc")) == 0)
) {
found = true;
updateIndex = l;
orgQty = Integer.parseInt(cprintQuantity.get(l).toString());
break;
}
}
if (obj.getString("itemId") == null || "null".compareTo(obj.getString("itemId")) == 0 || "".compareTo(obj.getString("itemId")) == 0) {
if (!foundDept) {
cd--;
}
} else {
if (found) {
int newQty = Integer.parseInt(obj.getString("quantity")) + orgQty;
cprintQuantity.set(updateIndex, String.valueOf(newQty));
} else {
cprintFoodref.add(foodOrderIds.get(currentFoodRefNoPointer).toString());
cprintItemId.add(obj.getString("itemId"));
cprintCategory.add(obj.getString("category"));
cprintQuantity.add(obj.getString("quantity"));
cprintEngDesc.add(obj.getString("engDesc"));
cprintChiDesc.add(obj.getString("cnDesc"));
//printDept.add(obj.getString("dept"));
String tmpDept = "";
if ("0".compareTo(obj.getString("dept")) == 0) {
cprintDept.add("1");
tmpDept = "1";
} else {
cprintDept.add(obj.getString("dept"));
tmpDept = obj.getString("dept");
}
cprintSeat.add(obj.getString("seatId"));
cprintRemark.add(obj.getString("remarks"));
}
}
}
}
}
// Check to call the API again
if ((currentFoodRefNoPointer + 1) < foodOrderIds.size()) {
JSONObject jsonvalue = new JSONObject();
try {
if (foodOrderIds.size() > 0) {
currentFoodRefNoPointer++;
jsonvalue.put("refNo", foodOrderIds.get(currentFoodRefNoPointer).toString());
}
} catch (Exception ejson) {
ejson.printStackTrace();
}
NetworkRepository.getInstance().listOrder(jsonvalue.toString(), this);
canDismiss = false;
}
}
} catch (Exception ejson) {
ejson.printStackTrace();
}
}
if (loading != null) {
if (canDismiss) {
loading.dismiss();
}
}
break;
case FB_ORDER_ACTION:
if (TextUtils.isEmpty(result)) {
CharSequence text = "Error occur, please contact administrator";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
} else if (result.startsWith("ERROR")) {
String displayErr = result;
displayErr = displayErr.replace("ERROR (400) : ", "");
displayErr = displayErr.replace("ERROR (401) : ", "");
displayErr = displayErr.replace("ERROR (402) : ", "");
Toast toast = Toast.makeText(getApplicationContext(), displayErr, Toast.LENGTH_SHORT);
toast.show();
} else {
// Check result
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Save Successful", duration);
toast.show();
finish();
}
//Intent intent2 = new Intent();
// intent2.setClass(EntranceStep2Activity.this, PrintActivity.class);
//startActivity(intent2);
//startActivityForResult(intent2, 12334);
if (loading != null) {
loading.dismiss();
}
break;
case FB_ORDERACTION_4_UAT:
Toast.makeText(
getApplicationContext(),
"Save Successful",
Toast.LENGTH_SHORT).show();
finish();
if (loading != null) {
loading.dismiss();
}
break;
case AUTH:
if (TextUtils.isEmpty(result)) {
Context context = getApplicationContext();
CharSequence text = "Error occur, please contact administrator";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else if (result.startsWith("ERROR")) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Manger Login / Password Incorrect", duration);
toast.show();
showLoginDialog();
} else {
JSONObject jsonObjVer;
// Check is manager grade login
try {
jsonObjVer = new JSONObject(result);
if (jsonObjVer.getInt("isManager") == 1) {
// Check result
Intent intent = new Intent();
intent.setClass(EntranceStep2Activity.this, EntraceStep3Activity.class);
intent.putExtra("json", jsonSource);
intent.putExtra("encryptRefNo", encryptRefNo);
intent.putExtra("refType", refType);
// startActivityForResult(intent, ;
startActivityForResult(intent, REQ_CODE);
} else {
// Show Message
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Manger Login / Password Incorrect", duration);
toast.show();
showLoginDialog();
}
} catch (Exception ec) {
// Show Message
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Manger Login / Password Incorrect", duration);
toast.show();
showLoginDialog();
}
}
if (loading != null) {
loading.dismiss();
}
break;
case ORDER_ACTION:
case CONFIRM_TICKET:
if (getIntent().getBooleanExtra("showScanner", false)) {
scanStatus.setVisibility(View.VISIBLE);
if (loading!=null) {
loading.dismiss();
}
if (TextUtils.isEmpty(result)
|| result.startsWith("ERROR")) {
scanStatus.setText("Admission: Fail");
} else {
scanStatus.setText("Seat status updated");
}
} else {
if (TextUtils.isEmpty(result)) {
Context context = getApplicationContext();
CharSequence text = "Login Fail, please try again";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
if (loading != null) {
loading.dismiss();
}
} else if (result.startsWith("ERROR")) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
String displayErr = result;
displayErr = displayErr.replace("ERROR (400) : ", "");
displayErr = displayErr.replace("ERROR (401) : ", "");
displayErr = displayErr.replace("ERROR (402) : ", "");
Toast toast = Toast.makeText(context, displayErr, duration);
toast.show();
if (loading != null) {
loading.dismiss();
}
} else {
Log.d("Return", result);
try {
SharedPreferences sp = getSharedPreferences("E-TICKET", MODE_PRIVATE);
String orderType = "";
String foodOrderIdForSamba = "";
String foodOrderStatus = "";
if (orderTypes.size() > 0) {
orderType = orderTypes.get(currentFoodRefNoActionPointer).toString();
foodOrderStatus = foodOrderStatuses.get(currentFoodRefNoActionPointer).toString();
foodOrderIdForSamba = foodOrderIds2.get(currentFoodRefNoActionPointer).toString();
if (isLocalDebug) {
foodOrderStatus = "P";
}
}
if (isFirstTimeUpdate && containsFood && ("V".compareTo(orderType) == 0) && ("P".compareTo(foodOrderStatus) == 0)) {
if (loading != null) {
loading.show();
}
// Print the Item
// Form the Content for Each Department
// Loop by different food ref no
if (printDept != null && printDept.size() > 0) {
ArrayList arrD = new ArrayList();
ArrayList arrItem = new ArrayList();
ArrayList arrRemarks = new ArrayList();
ArrayList arrDepartName = new ArrayList();
ArrayList arrSeats = new ArrayList();
ArrayList arrQtys = new ArrayList();
int ii = 0;
for (int z = 0; z < printDept.size(); z++) {
if (printFoodref.get(z).toString().compareTo(foodOrderIds.get(currentFoodRefNoActionPointer).toString()) != 0) {
continue;
}
String printerip = "";
String departmentName = "";
boolean found = false;
for (int x = 0; x < printerADept.size(); x++) {
String tmpPrinterName = printerADept.get(x).toString(); // sp.getString("printer_id_" + x, "");
if (tmpPrinterName.compareTo(printDept.get(z).toString()) == 0) {
printerip = printerAIp.get(x).toString(); // sp.getString("printer_ip_" + x, "");
departmentName = printerADesc.get(x).toString(); // sp.getString("printer_name_" + x, "");
break;
}
}
String t1 = printDept.get(z).toString();
String remarks = "";
String itemdesc = "";
itemdesc = printEngDesc.get(z).toString(); // + " X " + printQuantity.get(z).toString() + "\n";
remarks = printRemark.get(z).toString() + "\n";
if (!found) {
ii = arrD.size();
arrD.add(t1);
arrItem.add(itemdesc);
arrRemarks.add(remarks);
arrDepartName.add(departmentName);
arrSeats.add(printSeat.get(z).toString());
arrQtys.add(printQuantity.get(z));
}
}
// Found Distinct Department
ArrayList arrTrimPrintDept = new ArrayList();
for (int z = 0; z < printDept.size(); z++) {
if (printFoodref.get(z).toString().compareTo(foodOrderIds.get(currentFoodRefNoActionPointer).toString()) != 0) {
continue;
}
boolean foundDept = false;
for (int zz = 0; zz < arrTrimPrintDept.size(); zz++) {
if (arrTrimPrintDept.get(zz).toString().compareTo(printDept.get(z).toString()) == 0) {
foundDept = true;
break;
}
}
if (!foundDept) {
arrTrimPrintDept.add(printDept.get(z).toString());
}
}
//for (int z = 0; z < printDept.size() ; z++) {
for (int z = 0; z < arrTrimPrintDept.size(); z++) {
String printerip = "";
String departmentName = "";
boolean found = false;
for (int x = 0; x < printerADept.size(); x++) {
String tmpPrinterName = printerADept.get(x).toString(); // sp.getString("printer_id_" + x, "");
if (tmpPrinterName.compareTo(arrTrimPrintDept.get(z).toString()) == 0) {
printerip = printerAIp.get(x).toString(); // sp.getString("printer_ip_" + x, "");
departmentName = printerADesc.get(x).toString(); // sp.getString("printer_name_" + x, "");
break;
}
}
/*
for (int x = 1; x <= 5; x++) {
String tmpPrinterName = sp.getString("printer_id_" + x, "");
if (tmpPrinterName.compareTo(arrTrimPrintDept.get(z).toString()) == 0) {
printerip = sp.getString("printer_ip_" + x, "");
departmentName = sp.getString("printer_name_" + x, "");
break;
}
}
*/
// Print the document
if ("".compareTo(printerip) != 0) {
// Get the department name
// String departmentName = MainActivity.getConfigValue(EntranceStep2Activity.this, "department_name_" + arrD.get(z).toString());
try {
//SharedPreferences sp = getSharedPreferences("E-TICKET", MODE_PRIVATE);
String chkUsePrinter = sp.getString("use_printer", "");
if ("Y".compareTo(chkUsePrinter) == 0) {
boolean chkPrint = runPrintDepartmentReceipt(foodOrderIds.get(currentFoodRefNoActionPointer).toString(), foodOrderIds2.get(currentFoodRefNoActionPointer).toString(), printerip, departmentName, arrItem, arrQtys, arrRemarks, arrDepartName, arrSeats);
}
/*
//testPrint(EntranceStep2Activity.this, encryptRefNo, printerip, departmentName, arrItem, arrRemarks);
// Intent intent = new Intent(EntranceStep2Activity.this, PrinterService.class);
//startService(intent);
if (!chkPrint) {
couldPrintLoopExit = true;
couldStartReprint = false;
boolean showReprintDialog = true;
do {
if (showReprintDialog) {
if (loading != null)
loading.dismiss();
mHandler.post(new Runnable() {
public void run() {
new AlertDialog.Builder(EntranceStep2Activity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
couldStartReprint = true;
}
})
.setNegativeButton("No", null)
.show();
}
}
);
showReprintDialog = false;
}
Thread.sleep(1000);
if (couldStartReprint) {
loading.show();
chkPrint = runPrintDepartmentReceipt(foodOrderIds.get(currentFoodRefNoActionPointer).toString(), foodOrderIds2.get(currentFoodRefNoActionPointer).toString(), printerip, departmentName, arrItem, arrQtys, arrRemarks, arrDepartName, arrSeats);
if (chkPrint) {
couldPrintLoopExit = false;
} else {
showReprintDialog = true;
couldPrintLoopExit = true;
couldStartReprint = false;
}
}
} while (couldPrintLoopExit);
}
*/
} catch (Exception ep) {
Context context = getApplicationContext();
CharSequence text = "Error: (" + ep.getMessage() + ")";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}
// Finially, print the consolidate receipt
String containsComboFood = containsComboFoods.get(currentFoodRefNoActionPointer).toString();
if ("Y".compareTo(containsComboFood) == 0) {
arrDepartName.clear();
arrItem.clear();
arrRemarks.clear();
arrSeats.clear();
arrQtys.clear();
String departmentName = ""; /*MainActivity.getConfigValue(EntranceStep2Activity.this, "department_name_5"); */
String consolidatePrinter = "";
consolidatePrinter = consolidateIp;
departmentName = consolidateDesc;
for (int z = 0; z < cprintDept.size(); z++) {
if (cprintFoodref.get(z).toString().compareTo(foodOrderIds.get(currentFoodRefNoActionPointer).toString()) != 0) {
continue;
}
// Check if the same seat first
boolean sameSeat = false;
int index = 0;
for (int l1 = 0; l1 < arrSeats.size(); l1++) {
if (arrSeats.get(l1).toString().compareTo(cprintSeat.get(z).toString()) == 0) {
sameSeat = true;
index = l1;
break;
}
}
String itemdesc = ""; //arrItem.get(ii).toString();
String remarks = ""; //arrRemarks.get(ii).toString();
itemdesc += cprintEngDesc.get(z).toString() + " X " + cprintQuantity.get(z).toString() + "\n";
if ("".compareTo(cprintRemark.get(z).toString()) != 0)
remarks += cprintRemark.get(z).toString() + "\n";
if (sameSeat) {
// Next, need to check the food item
String tmpQtyToChange = arrItem.get(index).toString();
String tmpArr[] = tmpQtyToChange.split("\n");
int tmpFoodQty = 0;
if (tmpArr.length > 0) {
tmpQtyToChange = "";
tmpFoodQty = 0;
String reformat = "";
//String reformatRemark = "";
boolean needInsertAdd = true;
for (int t1 = 0; t1 < tmpArr.length; t1++) {
String tmpArr2[] = tmpArr[t1].split(" ");
if (tmpArr2.length > 3) {
String vqty = tmpArr2[tmpArr2.length - 1];
String vitem = "";
for (int zz = 0; zz < tmpArr2.length - 2; zz++) {
vitem += tmpArr2[zz].toString();
if (zz != (tmpArr2.length) - 3) {
vitem += " ";
}
}
tmpArr2 = new String[3];
tmpArr2[0] = vitem;
tmpArr2[1] = "X";
tmpArr2[2] = vqty;
}
reformat = tmpArr[t1];
if (cprintEngDesc.get(z).toString().trim().compareTo(tmpArr2[0].trim()) == 0) {
int orgQty = 0;
if (tmpArr2.length > 1) {
// pattern is "A6 x 2"
// reformat =
orgQty = Integer.parseInt(tmpArr2[2]);
} else {
// patter is "A6"
orgQty = 1;
}
orgQty += tmpFoodQty;
reformat = cprintEngDesc.get(z).toString() + " X " + String.valueOf(orgQty);
needInsertAdd = false;
}
tmpQtyToChange += reformat;
if (reformat.length() >= 0) {
tmpQtyToChange += "\n";
}
}
if (needInsertAdd) {
tmpQtyToChange += itemdesc;
}
//String orgRemark = arrRemarks.get(index).toString();
arrItem.set(index, tmpQtyToChange);
String tmpRemarkToChange = "";
if ("".compareTo(arrRemarks.get(index).toString()) != 0) {
tmpRemarkToChange = arrRemarks.get(index).toString() + "\n" + remarks;
} else {
tmpRemarkToChange = remarks;
}
arrRemarks.set(index, tmpRemarkToChange);
}
} else {
index = arrSeats.size();
arrSeats.add(cprintSeat.get(z).toString());
arrRemarks.add(remarks);
arrDepartName.add(departmentName);
arrItem.add(itemdesc);
arrQtys.add(cprintQuantity.get(z).toString());
}
//arrItem.add(itemdesc);
//arrRemarks.add(remarks);
//arrDepartName.add(departmentName);
}
if (!TextUtils.isEmpty(consolidatePrinter)) {
try {
// runPrintDepartmentReceipt(encryptRefNo, consolidatePrinter, departmentName, arrItem, arrRemarks);
String chkUsePrinter = sp.getString("use_printer", "");
if ("Y".equals(chkUsePrinter)) {
if (!runPrintDepartmentReceipt(
foodOrderIds.get(currentFoodRefNoActionPointer).toString(),
foodOrderIds2.get(currentFoodRefNoActionPointer).toString(),
consolidatePrinter,
departmentName,
arrItem,
arrQtys,
arrRemarks,
arrDepartName,
arrSeats)) {
Toast.makeText(getApplicationContext(),
"runPrintDepartmentRecipt with ConsolidationPrinter fail [" + consolidateDebugMsg + "]",
Toast.LENGTH_SHORT)
.show();
}
}
//testPrint(EntranceStep2Activity.this, encryptRefNo, consolidatePrinter, departmentName, arrItem, arrRemarks);
} catch (Exception ep) {
Toast.makeText(
getApplicationContext(),
"Error: (" + ep.getMessage() + ")",
Toast.LENGTH_SHORT)
.show();
}
}
}
}
try {
// Original is foodRefNo
String chkUseShare = sp.getString("use_share", "");
if ("Y".equals(chkUseShare)) {
String sambaRet = mssqlLogUpdate(
foodOrderIds.get(currentFoodRefNoActionPointer).toString(),
foodOrderIdForSamba);
if (!TextUtils.isEmpty(sambaRet)) {
Toast.makeText(getApplicationContext(), sambaRet, Toast.LENGTH_LONG)
.show();
}
}
} catch (Exception eSamba) {
eSamba.printStackTrace();
Toast.makeText(
getApplicationContext(),
eSamba.getMessage(),
Toast.LENGTH_LONG)
.show();
}
// Call the FB API to update the result
JSONObject jsonvalue = new JSONObject();
try {
jsonvalue.put("refNo", foodOrderIds.get(currentFoodRefNoActionPointer).toString()); /* Original is foodRefNo */
jsonvalue.put("type", "S");
//jsonvalue.put("refNo", movieTransId);
} catch (Exception ejson) {
ejson.printStackTrace();
}
currentFoodRefNoActionPointer++;
if (currentFoodRefNoActionPointer >= foodOrderIds.size()) {
// Last Times
NetworkRepository.getInstance().orderActionFb(jsonvalue.toString(), this);
} else {
// Still inside the loop
NetworkRepository.getInstance().orderAction(jsonvalue.toString(), this);
}
} else {
// Check result
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Save Successful", duration);
toast.show();
if (loading != null) {
loading.dismiss();
}
finish();
}
} catch (Exception ec) {
// Show Message
Context context = getApplicationContext();
CharSequence text = "Error: (" + ec.getMessage() + ")";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
if (loading != null) {
loading.dismiss();
}
return;
}
}
}
break;
case ORDERACTION_4_UAT:
case CONFIRM_TICKET_4UAT:
Log.d("Return", result);
//JSONObject jsonObj;
//
try {
// Finally , added the print action
// if need to print, we need to print and call the update API
SharedPreferences sp = getSharedPreferences("E-TICKET", MODE_PRIVATE);
String orderType = "";
String foodOrderIdForSamba = "";
String foodOrderStatus = "";
if (orderTypes.size() > 0) {
orderType = orderTypes.get(currentFoodRefNoActionPointer).toString();
foodOrderIdForSamba = foodOrderIds2.get(currentFoodRefNoActionPointer).toString();
foodOrderStatus = foodOrderStatuses.get(currentFoodRefNoActionPointer).toString();
}
if (isFirstTimeUpdate && containsFood && ("V".compareTo(orderType) == 0) && ("P".compareTo(foodOrderStatus) == 0)) {
if (loading != null) {
loading.show();
}
// Print the Item
// Form the Content for Each Department
// Loop by different food ref no
if (printDept != null && printDept.size() > 0) {
ArrayList arrD = new ArrayList();
ArrayList arrItem = new ArrayList();
ArrayList arrRemarks = new ArrayList();
ArrayList arrDepartName = new ArrayList();
ArrayList arrSeats = new ArrayList();
ArrayList arrQtys = new ArrayList();
for (int z = 0; z < printDept.size(); z++) {
if (printFoodref.get(z).toString().compareTo(foodOrderIds.get(currentFoodRefNoActionPointer).toString()) != 0) {
continue;
}
String departmentName = "";
boolean found = false;
for (int x = 1; x <= 5; x++) {
String tmpPrinterName = sp.getString("printer_id_" + x, "");
if (tmpPrinterName.compareTo(printDept.get(z).toString()) == 0) {
departmentName = sp.getString("printer_name_" + x, "");
break;
}
}
String t1 = printDept.get(z).toString();
String remarks = "";
String itemdesc = "";
itemdesc = printEngDesc.get(z).toString(); // + " X " + printQuantity.get(z).toString() + "\n";
remarks = printRemark.get(z).toString() + "\n";
if (!found) {
arrD.add(t1);
arrItem.add(itemdesc);
arrRemarks.add(remarks);
arrDepartName.add(departmentName);
arrSeats.add(printSeat.get(z).toString());
arrQtys.add(printQuantity.get(z));
}
}
// Found Distinct Department
ArrayList arrTrimPrintDept = new ArrayList();
for (int z = 0; z < printDept.size(); z++) {
if (printFoodref.get(z).toString().compareTo(foodOrderIds.get(currentFoodRefNoActionPointer).toString()) != 0) {
continue;
}
boolean foundDept = false;
for (int zz = 0; zz < arrTrimPrintDept.size(); zz++) {
if (arrTrimPrintDept.get(zz).toString().compareTo(printDept.get(z).toString()) == 0) {
foundDept = true;
break;
}
}
if (!foundDept) {
arrTrimPrintDept.add(printDept.get(z).toString());
}
}
//for (int z = 0; z < printDept.size() ; z++) {
for (int z = 0; z < arrTrimPrintDept.size(); z++) {
String printerip = "";
String departmentName = "";
for (int x = 1; x <= 5; x++) {
String tmpPrinterName = sp.getString("printer_id_" + x, "");
if (tmpPrinterName.compareTo(arrTrimPrintDept.get(z).toString()) == 0) {
printerip = sp.getString("printer_ip_" + x, "");
departmentName = sp.getString("printer_name_" + x, "");
break;
}
}
// Print the document
if (!TextUtils.isEmpty(printerip)) {
// Get the department name
// String departmentName = MainActivity.getConfigValue(EntranceStep2Activity.this, "department_name_" + arrD.get(z).toString());
try {
String chkUsePrinter = sp.getString("use_printer", "");
if ("Y".equals(chkUsePrinter)) {
runPrintDepartmentReceipt(foodOrderIds.get(currentFoodRefNoActionPointer).toString(), foodOrderIds2.get(currentFoodRefNoActionPointer).toString(), printerip, departmentName, arrItem, arrQtys, arrRemarks, arrDepartName, arrSeats);
}
} catch (Exception ep) {
Context context = getApplicationContext();
CharSequence text = "Error: (" + ep.getMessage() + ")";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}
// Finially, print the consolidate receipt
String containsComboFood = containsComboFoods.get(currentFoodRefNoActionPointer).toString();
if ("Y".equals(containsComboFood)) {
arrDepartName.clear();
arrItem.clear();
arrRemarks.clear();
arrSeats.clear();
arrQtys.clear();
String departmentName = ""; /*MainActivity.getConfigValue(EntranceStep2Activity.this, "department_name_5"); */
String consolidatePrinter = "";
consolidatePrinter = consolidateIp;
departmentName = consolidateDesc;
for (int z = 0; z < cprintDept.size(); z++) {
if (cprintFoodref.get(z).toString().compareTo(foodOrderIds.get(currentFoodRefNoActionPointer).toString()) != 0) {
continue;
}
// Check if the same seat first
boolean sameSeat = false;
int index = 0;
for (int l1 = 0; l1 < arrSeats.size(); l1++) {
if (arrSeats.get(l1).toString().compareTo(cprintSeat.get(z).toString()) == 0) {
sameSeat = true;
index = l1;
break;
}
}
String itemdesc = ""; //arrItem.get(ii).toString();
String remarks = ""; //arrRemarks.get(ii).toString();
itemdesc += cprintEngDesc.get(z).toString() + " X " + cprintQuantity.get(z).toString() + "\n";
if ("".compareTo(cprintRemark.get(z).toString()) != 0)
remarks += cprintRemark.get(z).toString() + "\n";
if (sameSeat) {
// Next, need to check the food item
String tmpQtyToChange = arrItem.get(index).toString();
String tmpArr[] = tmpQtyToChange.split("\n");
int tmpFoodQty = 0;
if (tmpArr.length > 0) {
tmpQtyToChange = "";
tmpFoodQty = 0;
String reformat = "";
//String reformatRemark = "";
boolean needInsertAdd = true;
for (int t1 = 0; t1 < tmpArr.length; t1++) {
String tmpArr2[] = tmpArr[t1].split(" ");
if (tmpArr2.length > 3) {
String vqty = tmpArr2[tmpArr2.length - 1];
String vitem = "";
for (int zz = 0; zz < tmpArr2.length - 2; zz++) {
vitem += tmpArr2[zz].toString();
if (zz != (tmpArr2.length) - 3) {
vitem += " ";
}
}
tmpArr2 = new String[3];
tmpArr2[0] = vitem;
tmpArr2[1] = "X";
tmpArr2[2] = vqty;
}
reformat = tmpArr[t1];
if (cprintEngDesc.get(z).toString().compareTo(tmpArr2[0]) == 0) {
int orgQty = 0;
if (tmpArr2.length > 1) {
// pattern is "A6 x 2"
// reformat =
orgQty = Integer.parseInt(tmpArr2[2]);
} else {
// patter is "A6"
orgQty = 1;
}
orgQty += tmpFoodQty;
reformat = cprintEngDesc.get(z).toString() + " X " + String.valueOf(orgQty);
needInsertAdd = false;
}
tmpQtyToChange += reformat;
if (reformat.length() >= 0) {
tmpQtyToChange += "\n";
}
}
if (needInsertAdd) {
tmpQtyToChange += itemdesc;
}
//String orgRemark = arrRemarks.get(index).toString();
arrItem.set(index, tmpQtyToChange);
String tmpRemarkToChange = "";
if ("".compareTo(arrRemarks.get(index).toString()) != 0) {
tmpRemarkToChange = arrRemarks.get(index).toString() + "\n" + remarks;
} else {
tmpRemarkToChange = remarks;
}
arrRemarks.set(index, tmpRemarkToChange);
}
} else {
arrSeats.add(cprintSeat.get(z).toString());
arrRemarks.add(remarks);
arrDepartName.add(departmentName);
arrItem.add(itemdesc);
arrQtys.add(cprintQuantity.get(z).toString());
}
}
if (!TextUtils.isEmpty(consolidatePrinter)) {
try {
if ("Y".compareTo(PreferencesController.getInstance().getUsePrinter()) == 0) {
// runPrintDepartmentReceipt(encryptRefNo, consolidatePrinter, departmentName, arrItem, arrRemarks);
runPrintDepartmentReceipt(foodOrderIds.get(currentFoodRefNoActionPointer).toString(), foodOrderIds2.get(currentFoodRefNoActionPointer).toString(), consolidatePrinter, departmentName, arrItem, arrQtys, arrRemarks, arrDepartName, arrSeats);
//testPrint(EntranceStep2Activity.this, encryptRefNo, consolidatePrinter, departmentName, arrItem, arrRemarks);
}
} catch (Exception ep) {
CharSequence text = "Error: (" + ep.getMessage() + ")";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
}
}
try {
if ("Y".equals(PreferencesController.getInstance().getUseShare())) {
// Original is foodRefNo
//createFile(smbUser, smbPassword, smbUrl, foodOrderIdForSamba /*foodOrderIds.get(currentFoodRefNoActionPointer).toString() */ + "\r\n");
String sambaRet = mssqlLogUpdate(foodOrderIds.get(currentFoodRefNoActionPointer).toString(), foodOrderIdForSamba);
if (!TextUtils.isEmpty(sambaRet)) {
Toast.makeText(
getApplicationContext(),
sambaRet,
Toast.LENGTH_LONG)
.show();
}
}
} catch (Exception eSamba) {
eSamba.printStackTrace();
Toast.makeText(
getApplicationContext(),
eSamba.getMessage(),
Toast.LENGTH_LONG)
.show();
}
JSONObject jsonvalue = new JSONObject();
try {
jsonvalue.put("refNo", foodOrderIds.get(currentFoodRefNoActionPointer).toString()); /* Original is foodRefNo */
jsonvalue.put("type", "S");
//jsonvalue.put("refNo", movieTransId);
} catch (Exception ejson) {
ejson.printStackTrace();
}
currentFoodRefNoActionPointer++;
if (currentFoodRefNoActionPointer >= foodOrderIds.size()) {
// Last Times
NetworkRepository.getInstance().orderActionFb4UAT(jsonvalue.toString(), true, this);
//new myAsyncTask(EntranceStep2Activity.this, TASK_FB_ORDERACTION_4_UAT, true).execute(urlString, jsonvalue.toString(), token);
} else {
// Still inside the loop
NetworkRepository.getInstance().orderAction4UAT(jsonvalue.toString(), true, this);
//new myAsyncTask(EntranceStep2Activity.this, TASK_COMPLETED_4_UAT, true).execute(urlString, jsonvalue.toString(), token);
}
} else {
// Check result
Toast.makeText(getApplicationContext(),
"Save Successful",
Toast.LENGTH_SHORT)
.show();
if (loading != null) {
loading.dismiss();
}
finish();
}
} catch (Exception ec) {
// Show Message
CharSequence text = "Error: (" + ec.getMessage() + ")";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
if (loading != null) {
loading.dismiss();
}
return;
}
break;
/**
* Callback to handle validation
* use on Boardway
*/
case GATE_VALIDATE_TICKET:
if(loading != null) {
loading.dismiss();
}
if(TextUtils.isEmpty(result) || result.startsWith("ERROR")) {
Toast.makeText(
getApplicationContext(),
"Error! Please try another ticket",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Save Successful",
Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
// Show some error code
}
}
private void setOnClick(final GridView gv, final int index) {
gv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View imgView, int position, long id) {
ArrayList tmpList = (ArrayList) EntranceStep2Activity.this.ticketList.get(index);
ArrayList tmpIdList = (ArrayList) EntranceStep2Activity.this.ticketIdList.get(index);
ArrayList tmpState = (ArrayList) EntranceStep2Activity.this.ticketState.get(index);
int status = (int) tmpList.get(position);
if (status == 0) {
return;
}
int state = (int) tmpState.get(position);
ImageView image = (ImageView) imgView;
String seatID = (String) tmpIdList.get(position);
if (state == 0) {
image.setImageResource(R.mipmap.available);
tmpState.set(position, 1);
// set isChecked based on seatID
setSeatChecked(true, seatID);
} else {
image.setImageResource(R.mipmap.free);
tmpState.set(position, 0);
// set isChecked based on seatID
setSeatChecked(false, seatID);
}
EntranceStep2Activity.this.ticketState.set(index, tmpState);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 0) {
finish();
}
}
private void showLoginDialog() {
LayoutInflater li = LayoutInflater.from(this);
View prompt = li.inflate(R.layout.login_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(prompt);
final EditText user = (EditText) prompt.findViewById(R.id.login_name);
final EditText pass = (EditText) prompt.findViewById(R.id.login_password);
//user.setText(Login_USER); //login_USER and PASS are loaded from previous session (optional)
//pass.setText(Login_PASS);
alertDialogBuilder.setTitle("Manager Login Confirmation");
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String password = pass.getText().toString();
String username = user.getText().toString();
try {
if (username.length() < 2 || password.length() < 2) {
Toast.makeText(EntranceStep2Activity.this,
"Invalid username or password",
Toast.LENGTH_LONG)
.show();
showLoginDialog();
} else {
//TODO here any local checks if password or user is valid
// Call the API
if (loading == null) {
loading = new ProgressDialog(EntranceStep2Activity.this);
loading.setCancelable(true);
loading.setMessage("Loading");
loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
JSONObject jsonvalue = new JSONObject();
jsonvalue.put("username", username);
jsonvalue.put("password", <PASSWORD>);
loading.show();
NetworkRepository.getInstance().auth(jsonvalue.toString(), EntranceStep2Activity.this);
//this will do the actual check with my back-end server for valid user/pass and callback with the response
//new CheckLoginAsync(MainActivity.this,username,password).execute("","");
}
} catch (Exception e) {
Toast.makeText(EntranceStep2Activity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alertDialogBuilder.show();
}
private void showPasswordDialog() {
LayoutInflater li = LayoutInflater.from(this);
View prompt = li.inflate(R.layout.password_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(prompt);
final EditText pass = (EditText) prompt.findViewById(R.id.editTextDialogUserInput);
//user.setText(Login_USER); //login_USER and PASS are loaded from previous session (optional)
//pass.setText(Login_PASS);
alertDialogBuilder.setTitle("Password Confirmation");
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// Check if username and password correct
String password = pass.getText().toString();
try {
if (password.length() < 2) {
Toast.makeText(EntranceStep2Activity.this, "Invalid password", Toast.LENGTH_LONG).show();
showPasswordDialog();
} else {
String user_pwd = PreferencesController.getInstance().getUserPassword();
if (password.compareTo(user_pwd) == 0) {
//dialog.dismiss();
editSeatStatus();
} else {
Toast.makeText(EntranceStep2Activity.this,
"Password Incorrect, please try again",
Toast.LENGTH_LONG).show();
// pass.setText("");
// pass.requestFocus();
showPasswordDialog();
}
//TODO here any local checks if password or user is valid
//this will do the actual check with my back-end server for valid user/pass and callback with the response
//new CheckLoginAsync(MainActivity.this,username,password).execute("","");
}
} catch (Exception e) {
Toast.makeText(EntranceStep2Activity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alertDialogBuilder.show();
}
private void editSeatStatus() {
Intent intent = new Intent();
intent.setClass(EntranceStep2Activity.this, EntraceStep3Activity.class);
intent.putExtra("json", jsonSource);
intent.putExtra("encryptRefNo", encryptRefNo);
intent.putExtra("refType", refType);
// startActivityForResult(intent, ;
startActivityForResult(intent, REQ_CODE);
}
protected void onDestroy() {
try {
for (Printer printer : mPrinters) {
PrinterUtils.disconnectPrinter(this, printer);
}
mPrinters.clear();
} catch (Exception ee) {
}
super.onDestroy();
}
@Override
protected IBinder getToken() {
return tl.getWindowToken();
}
@Override
protected void goNext(String json, String encryptRefNo, String refType, String foodRefNo) {
getIntent().putExtra("json", json);
getIntent().putExtra("encryptRefNo", encryptRefNo);
getIntent().putExtra("refType", refType);
getIntent().putExtra("foodRefNo", foodRefNo);
init();
boolean isValid = Utils.qrIsValid(EntranceStep2Activity.this, json);
if (isValid) {
playSuccess();
accept(null);
} else {
playBuzzer();
}
}
@Override
protected void onResume() {
super.onResume();
barcodeView.resume();
}
@Override
protected void onPause() {
super.onPause();
barcodeView.pause();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return barcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_CAMERA: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Sorry, the application need the Camera access right",
Toast.LENGTH_LONG);
toast.show();
finish();
}
return;
}
}
}
private void showAcceptDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(EntranceStep2Activity.this);
if(scan_status == ScanStatus.REDEEMED) {
builder.setTitle("Notice");
builder.setMessage("Could not proceed. All seats are redeemed.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
return;
}
builder.setTitle("Confirm");
builder.setMessage("Confirm to admit the transaction?");
final String strType = getIntent().getExtras().getString("scanType");
ScanType scanType = ScanType.valueOf(strType);
if (outsideGracePeriod && scanType == ScanType.IN) {
if ("Y".compareTo(Utils.getConfigValue(EntranceStep2Activity.this, "allow_invalid_save")) != 0) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Cannot save record as it's not within the grace period", duration);
toast.show();
return;
}
}
if (loading == null) {
loading = new ProgressDialog(this);
loading.setCancelable(true);
loading.setMessage("Loading");
loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
accept(dialog);
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
private void accept(@Nullable DialogInterface dialogInterface) {
final String strScanType = getIntent().getExtras().getString("scanType");
ScanType intentScanType = ScanType.valueOf(strScanType);
if (outsideGracePeriod && intentScanType == ScanType.IN) {
if ("Y".compareTo(Utils.getConfigValue(EntranceStep2Activity.this, "allow_invalid_save")) != 0) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Cannot save record as it's not within the grace period", duration);
toast.show();
return;
}
}
if(checkedItems.isEmpty()) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Please select the seat!", duration);
toast.show();
return;
}
//debugMsg1();
// Before show the loading, initialzie the printer first
/**
* Disable printing feature
*/
/*
if (isLocalDebug && isLocalSkipPrint) {
} else {
if (isFirstTimeUpdate && containsFood) {
boolean couldConnectPrinter = true;
for (Printer printer : mPrinters) {
PrinterUtils.disconnectPrinter(EntranceStep2Activity.this, printer);
}
mPrinters.clear();
if (mPrinterIPList != null && mPrinterIPList.size() > 0) {
mPrinterIPList.clear();
}
// And initialize the printer
if (printerAIp != null && printerAIp.size() > 0) {
for (int i = 0; i < printerAIp.size(); i++) {
String printerIPAddress = printerAIp.get(i).toString();
// Check the IP address also connect before
boolean couldAddIP = true;
for (int zz = 0; zz < mPrinterIPList.size(); zz++) {
if (printerIPAddress.compareTo(mPrinterIPList.get(zz).toString()) == 0) {
couldAddIP = false;
break;
}
}
if (couldAddIP) {
Printer printer = PrinterUtils.initializeObject(
EntranceStep2Activity.this,
printerName,
printerLang);
if (printer != null) {
if (!PrinterUtils.connectPrinter(printer, printerIPAddress)) {
couldConnectPrinter = false;
} else {
mPrinterIPList.add(printerIPAddress);
}
} else {
couldConnectPrinter = false;
}
mPrinters.add(i, printer);
}
}
// Add the consolidate printer
if (!TextUtils.isEmpty(consolidateIp)) {
// Check the IP address also connect before
boolean couldAddIP = true;
for (int zz = 0; zz < mPrinterIPList.size(); zz++) {
if (consolidateIp.equals(mPrinterIPList.get(zz))) {
couldAddIP = false;
break;
}
}
int i;
String printerIPAddress = consolidateIp;
if (couldAddIP) {
i = mPrinterIPList.size();
Printer printer = PrinterUtils.initializeObject(
EntranceStep2Activity.this,
printerName,
printerLang);
if (printer != null) {
if (!PrinterUtils.connectPrinter(printer, printerIPAddress)) {
couldConnectPrinter = false;
} else {
mPrinterIPList.add(printerIPAddress);
}
} else {
couldConnectPrinter = false;
}
mPrinters.add(i, printer);
}
}
if (!couldConnectPrinter) {
if (dialogInterface != null) {
dialogInterface.dismiss();
}
int duration = Toast.LENGTH_SHORT;
Toast toastReturn = Toast.makeText(EntranceStep2Activity.this, "Cannot connect to printer, please try again", duration);
toastReturn.show();
return;
}
}
}
}
*/
/**
* End of Disable printing feature
*/
// Do nothing but close the dialog
loading.show();
if (accessMode.equals("offline")) {
ArrayList items = new ArrayList();
final String strType = getIntent().getExtras().getString("scanType");
ScanType scanType = ScanType.valueOf(strType);
for(SeatInfo seat : ticketTrans.getSeatInfoList()) {
Log.d(EntranceStep2Activity.class.toString(), seat.getTicketType() + " " + seat.getSeatId() + ticketTrans.getTrans_id());
}
/*
for (int x = 0; x < ticketTypeList.size(); x++) {
ArrayList tmpList = (ArrayList) ticketList.get(x);
ArrayList tmpIdList = (ArrayList) ticketIdList.get(x);
ArrayList tmpState = (ArrayList) ticketState.get(x);
if (tmpList != null) {
for (int y = 0; y < tmpList.size(); y++) {
if (((int) tmpList.get(y)) == 2) {
if (((int) tmpState.get(y)) == 1) {
//valid.add(tmpIdList.get(y).toString());
Item item = new Item();
item.setSeatStatus(scanType == ScanType.IN || scanType == ScanType.NONE ? "1" : "0"); // Invalid
item.setTicketType(ticketTypeList.get(x).toString());
item.setSeatId(tmpIdList.get(y).toString());
item.setRefNo(encryptRefNo);
items.add(item);
} else {
// Valid but not selected
Item item = new Item();
item.setSeatStatus(scanType == ScanType.IN || scanType == ScanType.NONE ? "1" : "0"); // valid
item.setTicketType(ticketTypeList.get(x).toString());
item.setSeatId(tmpIdList.get(y).toString());
item.setRefNo(encryptRefNo);
items.add(item);
}
} else if (((int) tmpList.get(y)) == 0) {
// Original it's invalid
Item item = new Item();
item.setSeatStatus(scanType == ScanType.IN || scanType == ScanType.NONE ? "1" : "0"); // Invalid
item.setTicketType(ticketTypeList.get(x).toString());
item.setSeatId(tmpIdList.get(y).toString());
item.setRefNo(encryptRefNo);
items.add(item);
}
}
}
}
*/
for(SeatInfo seat : checkedItems) {
Item item = new Item();
item.setSeatStatus(scanType == ScanType.IN ? "1" : "0");
item.setTicketType(seat.getTicketType());
item.setSeatId(seat.getSeatId());
item.setRefNo(encryptRefNo);
items.add(item);
}
// Selected, need to insert / update to DB as Invalid
OfflineDatabase offline = new OfflineDatabase(EntranceStep2Activity.this);
try {
offline.accept(items);
addEntranceLog(scanType == ScanType.IN || scanType == ScanType.NONE ? "in" : "out");
Toast.makeText(getApplicationContext(), "Save Successful", Toast.LENGTH_SHORT).show();
finish();
} catch (Exception esql) {
String reason = esql.getMessage();
Toast.makeText(getApplicationContext(), reason, Toast.LENGTH_SHORT).show();
} finally {
loading.dismiss();
}
} else {
/**
* Original Code
*/
/*
JSONObject jsonvalue = new JSONObject();
// Get the String from Text Control
int countSelected = 0;
try {
jsonvalue.put("refNo", encryptRefNo);
jsonvalue.put("type", "");
jsonvalue.put("method", refType);
JSONArray jsonArr = new JSONArray();
for (int x = 0; x < ticketTypeList.size(); x++) {
ArrayList tmpList = (ArrayList) ticketList.get(x);
ArrayList tmpIdList = (ArrayList) ticketIdList.get(x);
ArrayList tmpState = (ArrayList) ticketState.get(x);
if (tmpList != null) {
for (int y = 0; y < tmpList.size(); y++) {
if (((int) tmpList.get(y)) == 2) {
if (((int) tmpState.get(y)) == 1) {
countSelected++;
JSONObject seat = new JSONObject();
seat.put("seatId", tmpIdList.get(y).toString());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US);
String currentDateandTime = sdf.format(new Date());
seat.put("timestamp", currentDateandTime);
seat.put("action", "C");
jsonArr.put(seat);
}
}
}
}
}
jsonvalue.put("confirmSeat", jsonArr);
} catch (JSONException jsonEx) {
Log.e("Accept", jsonEx.getMessage());
}
if (countSelected == 0) {
CharSequence text = "You have not selected any seat!";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
if (loading != null)
loading.dismiss();
return;
}
currentFoodRefNoActionPointer = 0;
String needFBUpdate = Utils.getConfigValue(EntranceStep2Activity.this, "need_fb_api_updated");
if ("Y".equals(needFBUpdate)) {
NetworkRepository.getInstance().confirmTicket(jsonvalue.toString(), EntranceStep2Activity.this);
//new myAsyncTask(EntranceStep2Activity.this, TASK_COMPLETED).execute(urlString, jsonvalue.toString(), token);
} else {
NetworkRepository.getInstance().confirmTicket4UAT(jsonvalue.toString(), EntranceStep2Activity.this);
//new myAsyncTask(EntranceStep2Activity.this, TASK_COMPLETED_4_UAT).execute(urlString, jsonvalue.toString(), token);
}
*/
/**
* End of Original Code
*/
if(checkedItems.size() > 0) {
List<String> seat_no = new ArrayList<String>();
JSONArray seat_arr = new JSONArray();
for(SeatInfo seat : checkedItems) {
// if("Valid".equals(seat.getSeatStatus())) {
// seat_arr.put(seat.getSeatId());
// }
seat_arr.put(seat.getSeatId());
}
final String strType = getIntent().getExtras().getString("scanType");
ScanType scanType = ScanType.valueOf(strType);
if(ticketTrans != null) {
try {
JSONObject jsonVal = new JSONObject();
String savedCinemaID = PreferencesController.getInstance().getCinemaId();
jsonVal.put("cinema_id", savedCinemaID);
jsonVal.put("trans_id", ticketTrans.getTrans_id());
jsonVal.put("is_concession", ticketTrans.isConcession() ? 1 : 0);
if(scanType == ScanType.IN || scanType == ScanType.NONE) {
jsonVal.put("type", "in");
} else if(scanType == ScanType.OUT) {
jsonVal.put("type", "out");
}
if(seat_arr.length() > 0) {
jsonVal.put("seat_no", seat_arr);
}
Log.d(EntranceStep2Activity.class.toString(), "123" + jsonVal.toString());
NetworkRepository.getInstance().getGateValidateTicket(jsonVal.toString(), this);
} catch (Exception e) {
if(loading != null) {
loading.dismiss();
}
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_SHORT).show();
return;
}
}
}
if (dialogInterface != null) {
dialogInterface.dismiss();
}
}
}
/**
* Set the seat is checked
* @param isChecked
* @param position
*/
private void setSeatChecked(boolean isChecked, int position) {
if(ticketTrans == null) return;
SeatInfo item = ticketTrans.getSeatInfoList()[position];
Log.d(EntranceStep2Activity.class.toString(), item.getSeatId() + " "
+ item.getTicketType() + " "
+ item.isChecked());
item.setChecked(isChecked);
checkedItems.clear();
for(SeatInfo seat : ticketTrans.getSeatInfoList()) {
if(seat.isChecked()) {
checkedItems.add(seat);
}
}
}
/**
* Set the seat is checked based on seat id
* @param isChecked
* @param seatID
*/
private void setSeatChecked(boolean isChecked, final String seatID){
if(ticketTrans == null) return;
List<SeatInfo> seats = Arrays.asList(ticketTrans.getSeatInfoList());
Predicate<SeatInfo> matchSeatID = new Predicate<SeatInfo>() {
@Override
public boolean test(SeatInfo seatInfo) {
return seatInfo.getSeatId().equals(seatID);
}
// @Override
// public boolean apply(SeatInfo seatInfo) {
// return seatInfo.getSeatId().equals(seatID);
// }
};
Collection<SeatInfo> result = Utils.filter(seats, matchSeatID);
if(result.size() == 0) return;
for(SeatInfo seat : result) {
seat.setChecked(isChecked);
}
checkedItems.clear();
for(SeatInfo seat : ticketTrans.getSeatInfoList()) {
if(seat.isChecked()) {
checkedItems.add(seat);
}
}
}
/**
* Add EntranceLog to local db
*/
private void addEntranceLog(String logType) {
if(ticketTrans == null || checkedItems.size() == 0) return;
Entrance entrance = new Entrance(EntranceStep2Activity.this);
Log.d(EntranceStep2Activity.class.toString(), logType);
try {
entrance.add(encryptRefNo, checkedItems, logType);
} catch (Exception e) {
String reason = e.getMessage();
Toast.makeText(getApplicationContext(), reason, Toast.LENGTH_SHORT).show();
} finally {
loading.dismiss();
}
}
/**
* Create text view for Date
* @param strDate
* @return
*/
private TextView createDateTextView(String strDate) {
TextView dateTv = new TextView(this);
dateTv.append(strDate);
dateTv.setTextSize(14);
dateTv.setEms(10);
dateTv.setTextColor(Color.parseColor("#aaaaaa"));
return dateTv;
}
/**
* Create text view for Seats
* @param strDate
* @param seatNo
* @return
*/
private TextView createSeatTextView(String strDate, List<String> seatNo) {
TextView seatsTv = new TextView(this);
seatsTv.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
seatsTv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END);
seatsTv.setTextSize(14);
seatsTv.setEms(10);
seatsTv.setTextColor(Color.parseColor("#aaaaaa"));
seatsTv.setPadding(0, 0, 10, 0);
String seat = "";
for(String s : seatNo) {
seat += s + " ";
}
seat = seat.trim();
seat = seat.replace(" ", ",");
seatsTv.append(seat);
return seatsTv;
}
private TextView createSeatTextView(String strDate, List<String> seatNo, List<String> compareWith) {
TextView seatsTv = new TextView(this);
seatsTv.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
seatsTv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END);
seatsTv.setTextSize(14);
seatsTv.setEms(10);
seatsTv.setTextColor(Color.parseColor("#aaaaaa"));
seatsTv.setPadding(0, 0, 10, 0);
String seat = "";
StringBuilder sb = new StringBuilder();
for(String s : seatNo) {
if(compareWith.indexOf(s) != -1) {
sb.append(s);
sb.append(",");
}
}
seat = sb.toString();
if(!seat.equals("")){
seat = seat.substring(0, seat.length() - 1);
}
seatsTv.append(seat);
return seatsTv;
}
/**
* Original Code
* The following contains the functions that are not using in Boardway
*/
private boolean createDepartmentData(String token, String foodRefId, String department, List<String> items, List<String> qtys, List<String> remarks, List<String> departmentNames, List<String> seats) {
String method = "";
//Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.store);
StringBuilder textData = new StringBuilder();
final int barcodeWidth = 3;
final int barcodeHeight = 7;
/*
if (mPrinter == null) {
return false;
}
*/
if (department.toLowerCase().contains("consolidation")) {
consolidateDebugMsg += "P1";
}
try {
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_CENTER);
/*
method = "addImage";
mPrinter.addImage(logoData, 0, 0,
logoData.getWidth(),
logoData.getHeight(),
Printer.COLOR_1,
Printer.MODE_MONO,
Printer.HALFTONE_DITHER,
Printer.PARAM_DEFAULT,
Printer.COMPRESS_AUTO);
*/
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.FALSE, Printer.TRUE, Printer.PARAM_DEFAULT);
method = "addTextSize";
mPrinter.addTextSize(2, 2);
method = "addText";
//mPrinter.addText(token + "\n"); /* foodRefNo */
mPrinter.addText(foodRefId + "\n"); /* foodRefNo */
method = "addTextSize";
mPrinter.addTextSize(1, 1);
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.FALSE, Printer.FALSE, Printer.PARAM_DEFAULT);
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_LEFT);
method = "addText";
mPrinter.addText("_______________________________________________");
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_CENTER);
method = "addFeedLine";
mPrinter.addFeedLine(2);
if (department.toLowerCase().indexOf("consolidation") >= 0) {
String displaySeats = "";
// By Consolidation Table
int noOfComma = 0;
if (items.size() > 0) {
for (int l = 0; l < items.size(); l++) {
int chkInside = seats.get(l).toLowerCase().indexOf(displaySeats.toLowerCase());
if ("".compareTo(displaySeats) == 0) {
chkInside = -1;
}
if (chkInside >= 0) {
// Found
} else {
if ("".compareTo(displaySeats) != 0) {
if (noOfComma % 4 != 0) {
displaySeats += ",";
}
}
displaySeats += seats.get(l);
displaySeats += seats.get(l).toString();
noOfComma++;
if (noOfComma % 4 == 0) {
displaySeats += "\n";
}
}
}
}
/*
textData.append(" VIP | " + displaySeats + " ");
method = "addText";
mPrinter.addText(textData.toString());
//System.out.print(textData.toString());
textData.delete(0, textData.length());
*/
textData.append(" VIP | \n");
method = "addText";
mPrinter.addText(textData.toString());
//System.out.print(textData.toString());
textData.delete(0, textData.length());
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.FALSE, Printer.TRUE, Printer.PARAM_DEFAULT);
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_RIGHT);
method = "addText";
textData.append("" + displaySeats + "");
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
// Restore original Style
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.FALSE, Printer.FALSE, Printer.PARAM_DEFAULT);
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_LEFT);
//mPrinter.addTextAlign(Printer.ALIGN_CENTER);
} else {
String displaySeats = "";
int noOfComma = 0;
// Department
if (seats.size() > 0) {
for (int l = 0; l < seats.size(); l++) {
String tmpDepartName = departmentNames.get(l);
if (tmpDepartName.compareTo(department) == 0) {
int chkInside = seats.get(l).toLowerCase().indexOf(displaySeats.toLowerCase());
if ("".compareTo(displaySeats) == 0) {
chkInside = -1;
}
if (chkInside >= 0) {
// Found
} else {
if ("".compareTo(displaySeats) != 0) {
if (noOfComma % 4 != 0) {
displaySeats += ",";
}
}
displaySeats += seats.get(l).toString();
noOfComma++;
if (noOfComma % 4 == 0) {
displaySeats += "\n";
}
}
}
}
}
//textData.append(displaySeats + "\n");
/*
textData.append(" VIP | " + displaySeats + " ");
method = "addText";
mPrinter.addText(textData.toString());
//System.out.print(" VIP | " + displaySeats + " ");
textData.delete(0, textData.length());
*/
textData.append(" VIP | \n");
method = "addText";
mPrinter.addText(textData.toString());
//System.out.print(textData.toString());
textData.delete(0, textData.length());
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.FALSE, Printer.TRUE, Printer.PARAM_DEFAULT);
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_RIGHT);
method = "addText";
textData.append("" + displaySeats + "");
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
// Restore original Style
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.FALSE, Printer.FALSE, Printer.PARAM_DEFAULT);
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_LEFT);
}
method = "addFeedLine";
mPrinter.addFeedLine(2);
if (department.toLowerCase().contains("consolidation")) {
consolidateDebugMsg += "P2";
}
// method = "addText";
// mPrinter.addText(textData.toString());
// textData.delete(0, textData.length());
//if ("Consolidate".compareTo(department) == 0) {
if (department.toLowerCase().contains("consolidation")) {
method = "addText";
mPrinter.addText("_______________________________________________\n\n");
method = "addSymbol";
mPrinter.addSymbol(token, Printer.SYMBOL_PDF417_STANDARD, Printer.LEVEL_0, barcodeWidth, barcodeHeight, 0);
/* foodRefNo */
/*
method = "addText";
mPrinter.addText("\n\n");
method="addHLine";
mPrinter.addHLine(0, 100, Printer.LINE_THIN);
*/
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_LEFT);
}
method = "addText";
mPrinter.addText("_______________________________________________\n");
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.TRUE, Printer.TRUE, Printer.PARAM_DEFAULT);
mPrinter.addTextAlign(Printer.ALIGN_LEFT);
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_LEFT);
method = "addFeedLine";
mPrinter.addFeedLine(1);
textData.append("Department\n");
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.TRUE, Printer.TRUE, Printer.PARAM_DEFAULT);
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
// Restore the Text Style
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.FALSE, Printer.FALSE, Printer.PARAM_DEFAULT);
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_LEFT);
textData.append(department + "\n\n\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
if (department.toLowerCase().indexOf("consolidation") >= 0) {
if (items.size() > 0) {
for (int l = 0; l < items.size(); l++) {
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.TRUE, Printer.TRUE, Printer.PARAM_DEFAULT);
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_LEFT);
textData.append(seats.get(l).toString() + "\n");
method = "addText";
mPrinter.addText(textData.toString());
//System.out.print(textData.toString());
textData.delete(0, textData.length());
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.FALSE, Printer.FALSE, Printer.PARAM_DEFAULT);
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_LEFT);
textData.append(items.get(l).toString() + "\n");
method = "addText";
mPrinter.addText(textData.toString());
//System.out.print(textData.toString());
textData.delete(0, textData.length());
if ("".compareTo(remarks.get(l).toString()) != 0) {
String tmpCheck = remarks.get(l).toString();
if (tmpCheck.trim().compareTo("") != 0) {
textData.append(remarks.get(l).toString() + "\n\n");
method = "addText";
mPrinter.addText(textData.toString());
//System.out.print(textData.toString());
textData.delete(0, textData.length());
}
}
}
}
} else {
// Item
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.TRUE, Printer.TRUE, Printer.PARAM_DEFAULT);
textData.append("Item Detail\n");
method = "addText";
mPrinter.addText(textData.toString());
//System.out.print(textData.toString());
textData.delete(0, textData.length());
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.FALSE, Printer.FALSE, Printer.PARAM_DEFAULT);
if (items.size() > 0) {
ArrayList items1 = new ArrayList();
ArrayList remarks1 = new ArrayList();
ArrayList qty1 = new ArrayList();
for (int l = 0; l < items.size(); l++) {
String tmpDepartName = departmentNames.get(l).toString();
if (tmpDepartName.compareTo(department) == 0) {
// Same Department, Check same item or not
boolean foundItems = false;
for (int y = 0; y < items1.size(); y++) {
if (items1.get(y).toString().compareTo(items.get(l).toString()) == 0) {
foundItems = true;
// Add the quantity
int orgQty = Integer.parseInt(qty1.get(y).toString());
orgQty += Integer.parseInt(qtys.get(l).toString());
qty1.set(y, String.valueOf(orgQty));
String tmpRemark = "";
if ("".compareTo(remarks.get(l).toString().trim()) == 0) {
tmpRemark = remarks1.get(y).toString();
} else {
tmpRemark = remarks1.get(y).toString() + "\n" + remarks.get(l).toString();
}
remarks1.set(y, tmpRemark);
break;
}
}
if (!foundItems) {
items1.add(items.get(l).toString());
qty1.add(qtys.get(l).toString());
remarks1.add(remarks.get(l).toString().trim());
}
}
}
for (int k = 0; k < items1.size(); k++) {
String value = items1.get(k) + " X " + qty1.get(k).toString();
textData.append(value + "\n");
method = "addText";
mPrinter.addText(textData.toString());
//System.out.print(textData.toString());
textData.delete(0, textData.length());
if ("".compareTo(remarks1.get(k).toString()) != 0) {
textData.append(remarks1.get(k) + "\n\n");
method = "addText";
mPrinter.addText(textData.toString());
//System.out.print(textData.toString());
textData.delete(0, textData.length());
}
}
}
}
if (department.toLowerCase().indexOf("consolidation") >= 0) {
consolidateDebugMsg += "P3";
}
textData.append("\n\n\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
// Print Date
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.TRUE, Printer.TRUE, Printer.PARAM_DEFAULT);
textData.append("Print Date\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.FALSE, Printer.FALSE, Printer.PARAM_DEFAULT);
Date currentDt = new Date();
SimpleDateFormat displayFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.US);
String displayFileDateTime = displayFormat.format(currentDt);
textData.append(displayFileDateTime + "\n\n");
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
// F&B Order ID
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.TRUE, Printer.TRUE, Printer.PARAM_DEFAULT);
mPrinter.addTextAlign(Printer.ALIGN_RIGHT);
textData.append("F&B Order Id\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
method = "addTextStyle";
mPrinter.addTextStyle(Printer.PARAM_DEFAULT, Printer.FALSE, Printer.FALSE, Printer.PARAM_DEFAULT);
textData.append(token + "\n\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
method = "addCut";
mPrinter.addCut(Printer.CUT_FEED);
if (department.toLowerCase().indexOf("consolidation") >= 0) {
consolidateDebugMsg += "P4";
}
} catch (Exception e) {
// ShowMsg.showException(e, method, mContext);
String tmp = e.getMessage();
return false;
}
textData = null;
return true;
}
private boolean createReceiptData() {
String method = "";
//Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.store);
StringBuilder textData = new StringBuilder();
final int barcodeWidth = 2;
final int barcodeHeight = 100;
if (mPrinter == null) {
return false;
}
try {
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_CENTER);
/*
method = "addImage";
mPrinter.addImage(logoData, 0, 0,
logoData.getWidth(),
logoData.getHeight(),
Printer.COLOR_1,
Printer.MODE_MONO,
Printer.HALFTONE_DITHER,
Printer.PARAM_DEFAULT,
Printer.COMPRESS_AUTO);
*/
mPrinter.addText(movieTransId);
mPrinter.addHLine(0, 100, 0);
method = "addBarcode";
mPrinter.addBarcode("01209457",
Printer.BARCODE_CODE39,
Printer.HRI_BELOW,
Printer.FONT_A,
barcodeWidth,
barcodeHeight);
method = "addFeedLine";
mPrinter.addFeedLine(1);
textData.append("THE STORE 123 (555) 555 – 5555\n");
textData.append("STORE DIRECTOR – <NAME>\n");
textData.append("\n");
textData.append("7/01/07 16:58 6153 05 0191 134\n");
textData.append("ST# 21 OP# 001 TE# 01 TR# 747\n");
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
textData.append("400 OHEIDA 3PK SPRINGF 9.99 R\n");
textData.append("410 3 CUP BLK TEAPOT 9.99 R\n");
textData.append("445 EMERIL GRIDDLE/PAN 17.99 R\n");
textData.append("438 CANDYMAKER ASSORT 4.99 R\n");
textData.append("474 TRIPOD 8.99 R\n");
textData.append("433 BLK LOGO PRNTED ZO 7.99 R\n");
textData.append("458 AQUA MICROTERRY SC 6.99 R\n");
textData.append("493 30L BLK FF DRESS 16.99 R\n");
textData.append("407 LEVITATING DESKTOP 7.99 R\n");
textData.append("441 **Blue Overprint P 2.99 R\n");
textData.append("476 REPOSE 4PCPM CHOC 5.49 R\n");
textData.append("461 WESTGATE BLACK 25 59.99 R\n");
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
textData.append("SUBTOTAL 160.38\n");
textData.append("TAX 14.43\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
method = "addTextSize";
mPrinter.addTextSize(2, 2);
method = "addText";
mPrinter.addText("TOTAL 174.81\n");
method = "addTextSize";
mPrinter.addTextSize(1, 1);
method = "addFeedLine";
mPrinter.addFeedLine(1);
textData.append("CASH 200.00\n");
textData.append("CHANGE 25.19\n");
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
textData.append("Purchased item total number\n");
textData.append("Sign Up and Save !\n");
textData.append("With Preferred Saving Card\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
method = "addFeedLine";
mPrinter.addFeedLine(2);
method = "addBarcode";
mPrinter.addBarcode("01209457",
Printer.BARCODE_CODE39,
Printer.HRI_BELOW,
Printer.FONT_A,
barcodeWidth,
barcodeHeight);
method = "addCut";
mPrinter.addCut(Printer.CUT_FEED);
} catch (Exception e) {
// ShowMsg.showException(e, method, mContext);
return false;
}
textData = null;
return true;
}
private static NtlmPasswordAuthentication createAuth(String aUser, String aPasswd) {
StringBuffer sb = new StringBuffer(aUser);
sb.append(':').append(aPasswd);
return new NtlmPasswordAuthentication(sb.toString());
}
public static SmbFile createSmbFile(String aUser, String aPasswd, String aTarget) throws IOException {
NtlmPasswordAuthentication auth = createAuth(aUser, aPasswd);
return new SmbFile(aTarget, auth);
}
private static Timestamp getCurrentTimeStamp() {
Date today = new Date();
return new Timestamp(today.getTime());
}
private String mssqlLogUpdate(String aContent0, String aContent) {
String server = PreferencesController.getInstance().getNetwork();
String mssqlUserName = PreferencesController.getInstance().getNetworkUser();//sp.getString("network_user", ""); // alex
String mssqlPassword = PreferencesController.getInstance().getNetworkPassword();//sp.getString("network_password", ""); // <PASSWORD>
String debug = "";
Connection con = null;
String ret = "";
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
//Class.forName("com.mysql.jdbc.Driver");
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:jtds:sqlserver://" + server + ":1433/db_tvdisplay;", mssqlUserName, mssqlPassword);
//;instance=SQLEXPRESS
if (con != null && !con.isClosed()) {
//con = DriverManager.getConnection("jdbc:sqlserver://" + server + ":1433; databaseName=db_tvdisplay; ", mssqlUserName, mssqlPassword);
// instance=SQLEXPRESS
//con = DriverManager.getConnection( "jdbc:mysql://mysql.station188.com:3306/conquerstars_association", mysqlUserName, mysqlPassword );
//Statement stmt = con.createStatement();//创建Statement
PreparedStatement statement = con.prepareStatement("INSERT INTO tb_tvdisplay (tvdrefno, tvdorder, tvdtype, tvddt, tvdstatus) VALUES (?,?,?,getdate(), ?)");
statement.setString(1, aContent0);
statement.setString(2, aContent);
statement.setString(3, "V");
//statement.setDate(4, new java.sql.Date(System.currentTimeMillis()));
//statement.setTimestamp(4, getCurrentTimeStamp());
statement.setString(4, "S");
statement.execute();
con.close();
/*Context context = getApplicationContext();
CharSequence text = "Connection OK"; //"Login Fail, please try again";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
*/
} else {
ret = "ERROR: connection is closed";
//ret = "jdbc:jtds:sqlserver://" + server + ":1433/db_tvdisplay; (" + mssqlUserName + ")(" + mssqlPassword + ")";
}
} catch (ClassNotFoundException ce) {
System.out.println("Class Not Found!!");
ret = "Error - CNF: (" + debug + "): Class Not Found!!";
} catch (SQLException se) {
//System.out.println(se.getMessage() );
ret = "Error - SE: (" + debug + "): " + se.getMessage();
} catch (Exception connEx) {
/*
Context context = getApplicationContext();
CharSequence text = connEx.getMessage(); //"Login Fail, please try again";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
*/
ret = "Error - EX: (" + debug + "): " + connEx.getMessage();
}
return ret;
}
private void finalizeObject() {
if (mPrinter == null) {
return;
}
mPrinter.clearCommandBuffer();
mPrinter.setReceiveEventListener(null);
try {
mPrinter.disconnect();
} catch (Exception ex) {
// Do nothing
}
mPrinter = null;
}
private boolean isPrintable(PrinterStatusInfo status) {
if (status == null) {
return false;
}
if (status.getConnection() == Printer.FALSE) {
return false;
} else if (status.getOnline() == Printer.FALSE) {
return false;
} else {
;//print available
}
return true;
}
private String consolidateDebugMsg = "";
private boolean runPrintDepartmentReceipt(String token, String foodRefId, String ipaddress, String department, List<String> items, List<String> qtys, List<String> remarks, List<String> departNames, List<String> seats) {
if (isLocalDebug && isLocalSkipPrint) {
return true;
}
if (isLocalDebug) {
ipaddress = "192.168.1.36";
}
// For which printer we need to use
int index = -1;
for (int ll = 0; ll < mPrinterIPList.size(); ll++) {
if (ipaddress.compareTo(mPrinterIPList.get(ll)) == 0) {
index = ll + 1;
break;
}
}
if (index == -1) {
return false;
}
if (department.toLowerCase().contains("consolidation")) {
consolidateDebugMsg += String.valueOf(index);
}
if (index - 1 > mPrinters.size() - 1 && index - 1 < 0) {
return false;
}
Printer printer = mPrinters.get(index - 1);
if (printer == null) {
return false;
} else {
mPrinter = printer;
}
System.out.println("runPrintReceiptSequence - 2");
if (department.toLowerCase().contains("consolidation")) {
consolidateDebugMsg += "[PC]";
}
if (!createDepartmentData(token, foodRefId, department, items, qtys, remarks, departNames, seats)) {
//finalizeObject();
PrinterUtils.finalizeObject(printer);
return false;
}
if (department.toLowerCase().contains("consolidation")) {
consolidateDebugMsg += "[PC3]";
}
System.out.println("runPrintReceiptSequence - 3");
if (!printData(index, ipaddress)) {
finalizeObject();
return false;
}
return true;
}
private boolean printData(int index, String ipaddress) {
/*
if (mPrinter == null) {
return false;
}
*/
if (index - 1 > mPrinters.size() - 1 && index - 1 < 0) {
return false;
}
Printer printer = mPrinters.get(index - 1);
if (printer == null) {
return false;
}
if (!PrinterUtils.beginTran(printer)) {
System.out.println("Return - " + index);
return false;
}
//PrinterStatusInfo status = mPrinter.getStatus();
PrinterStatusInfo status = null;
status = printer.getStatus();
if (status == null) {
System.out.println("Status == null in PrintData");
return false;
}
//dispPrinterWarnings(status);
if (!isPrintable(status)) {
//ShowMsg.showMsg(makeErrorMessage(status), mContext);
try {
//mPrinter.disconnect();
printer.disconnect();
} catch (Exception ex) {
// Do nothing
}
return false;
}
try {
printer.sendData(Printer.PARAM_DEFAULT);
} catch (Epos2Exception e) {
//ShowMsg.showException(e, "sendData", mContext);
try {
printer.disconnect();
} catch (Exception ex) {
// Do nothing
}
return false;
}
PrinterUtils.endTran(this, printer);
return true;
}
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
android {
compileSdkVersion 28
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "hk.com.uatech.eticket.eticket"
minSdkVersion 25
targetSdkVersion 26
multiDexEnabled = true
versionCode 26
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
jniLibs.srcDirs = ['src/main/jniLibs']
}
}
/*
splits {
abi {
enable true
reset()
include 'x86', 'armeabi-v7a', 'armeabi'
universalApk false
}
}
*/
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('androidx.test.espresso:espresso-core:3.1.0', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile files('libs/jcifs-1.3.18.jar')
compile files('libs/ePOS2.jar')
/*compile files('libs/jtds-1.3.1.jar') */
compile files('libs/jtds-1.2.8.jar')
compile files('libs/mysql-connector-java-5.1.44-bin.jar')
compile files('libs/sqljdbc4.jar')
compile files('libs/log4j-1.2.17.jar')
compile files('libs/android-logging-log4j-1.0.3.jar')
compile 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
compile 'com.google.zxing:core:3.2.0'
compile 'androidx.appcompat:appcompat:1.0.0'
compile 'androidx.constraintlayout:constraintlayout:1.1.3'
compile 'com.google.android.material:material:1.0.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'androidx.legacy:legacy-support-v4:1.0.0'
compile 'com.journeyapps:zxing-android-embedded:3.6.0'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
implementation "io.reactivex.rxjava2:rxjava:2.2.18"
compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
testCompile 'junit:junit:4.12'
implementation 'com.google.firebase:firebase-analytics:17.4.4'
// Add the Firebase Crashlytics SDK.
implementation 'com.google.firebase:firebase-crashlytics:17.1.1'
}
|
45b95a6f4098908a73d234c266f3dbe2795bfeb9
|
[
"Markdown",
"Java",
"Gradle"
] | 24 |
Java
|
NeroJz/eentrance
|
42ef6f1dfb1deaa586a260cbbf9235c0e4a01388
|
4cbb329bf648445bd966997228860bcbe481a203
|
refs/heads/master
|
<file_sep>#!/bin/bash
git config --global -l
git config --global user.email <EMAIL>
git config --global user.name ShortwaysSAS
git remote --v
git reset --hard HEAD
npm version patch
git push origin master
git push --tags
npm publish
|
a3454edd03ad5b1ba83a808f6a4049938d8d5f4f
|
[
"Shell"
] | 1 |
Shell
|
ShortwaysSAS/shortways-react-rnd
|
12805ec3b89f6e046c312b20b570331b2c5f8d56
|
30b0a5fa071365f320bcefde341e7dcba4c237b1
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Apr 3 21:43:06 2018
@author: Wangyf
"""
import gym
import torch
import numpy as np
import objfunc
import sys
import argparse
from helper_functions import *
from DQN_torch import DQN
from NAF_torch import NAF
from DDPG_torch import DDPG
from AC_torch import AC
from CAC_torch import CAC
from PPO_torch import PPO
import matplotlib.pyplot as plt
import time
from cg import cg
from bb import sd
from newton import quasiNewton
from objfunc import Logistic, Quadratic, NeuralNet, Ackley
from dataset import LogisticDataset, NeuralNetDataset
## parameters
argparser = argparse.ArgumentParser(sys.argv[0])
argparser.add_argument('--lr', type=float, default=1e-4)
argparser.add_argument('--replay_size', type=int, default=30000)
argparser.add_argument('--batch_size', type=int, default=128)
argparser.add_argument('--gamma', type=float, default=1)
argparser.add_argument('--tau', type=float, default=0.1)
argparser.add_argument('--noise_type', type = str, default = 'ounoise')
argparser.add_argument('--agent', type = str, default = 'ddpg')
argparser.add_argument('--action_low', type = float, default = -0.3)
argparser.add_argument('--action_high', type = float, default = 0.3)
argparser.add_argument('--dim', type = int, default = 3)
argparser.add_argument('--window_size', type = int, default = 10)
argparser.add_argument('--obj', type = str, default = 'quadratic')
argparser.add_argument('--sigma', type = float, default = 1)
argparser.add_argument('--debug', type = str, default = sys.argv[1:])
argparser.add_argument('--max_iter', type = int, default = 50)
argparser.add_argument('--max_epoch', type = int, default = 30000)
args = argparser.parse_args()
### the env
dim = args.dim
window_size = args.window_size
init_point = np.arange(dim) / (dim / 2)
if args.obj == 'quadratic':
env = objfunc.make('quadratic', dim=dim, init_point=init_point ,
window_size=window_size)
elif args.obj == 'logistic':
X, Y = LogisticDataset(dim=dim)
dim += 1
init_point = np.arange(dim) / dim
env = objfunc.make('logistic', dim=dim, init_point=init_point,
window_size=window_size, other_params=[X, Y])
elif args.obj == 'ackley':
init_point = np.array([7,8])
env = objfunc.make('ackley', dim=dim, init_point=init_point,
window_size=window_size)
elif args.obj == 'neural':
d, h, p, lamda = 2, 2, 2, .0005
kwargs = {'d' : d, 'h': h, 'p' : p, 'lamda' : lamda}
dim = h * d + h + p * h + p
init_point = np.arange(dim) / dim
X, Y = NeuralNetDataset(dim=d)
env = objfunc.make('neural', dim=dim, init_point=init_point,
window_size=window_size, other_params=[X, Y], **kwargs)
### the params
Replay_mem_size = args.replay_size
Train_batch_size = args.batch_size
Actor_Learning_rate = args.lr
Critic_Learning_rate = args.lr
Gamma = args.gamma
Tau = args.tau
Action_low = args.action_low
Action_high = args.action_high
max_iter = args.max_iter
max_epoch = args.max_epoch
State_dim = dim + window_size + dim * window_size
print(State_dim)
Action_dim = dim
print(Action_dim)
ounoise = OUNoise(Action_dim, 8, 1, 0.9999)
gsnoise = GaussNoise(2, 1.5, 0.99995)
noise = gsnoise if args.noise_type == 'gauss' else ounoise
# record the test objective values of RL algorithms
# RL_value = np.zeros((max_epoch, max_iter))
log_file = open('./' + str(args.agent) + '_' + str(args.obj) + '_' + str(args.debug) + '.txt', 'w')
save_path = './record/' + str(args.obj) + str(args.agent)
def play(agent, test_count, Epoch_step, show = False):
print('debug info: ', args.debug)
global log_file
# record the value and point at each iteration
val_record = []
point_record = []
for epoch in range(1):
pre_state = env.reset()
for step in range(Epoch_step):
if show:
env.render()
# action = agent.action(state_featurize.transfer(pre_state), False)
action = agent.action(pre_state, False)
next_state, reward, done, _ = env.step(action)
val_record.append(-reward)
point_record.append(next_state[:dim])
if done or step == Epoch_step - 1:
final_val = env.get_value()
break
pre_state = next_state
for item in val_record:
print('%.5f' % item, end =' , ')
print()
print(' '.join(map(str, val_record)), file = log_file, end = '\n')
for point in point_record:
print(' '.join(map(str, point)), file = log_file, end = ',')
log_file.write('\n')
log_file.flush()
return final_val
def train(agent, Train_epoch, Epoch_step):
for epoch in range(Train_epoch):
pre_state = env.reset()
acc_reward = 0
for step in range(Epoch_step):
# print('pre:', pre_state)
action = agent.action(pre_state)
# print('action:', action)
if action[0] != action[0]:
raise('nan error!')
next_state, reward, done, _ = env.step(action)
reward *= (step + 1) ** 0.2
acc_reward += reward
# print('next:', next_state)
if step == Epoch_step - 1:
done = True
# agent.train(state_featurize.transfer(pre_state), action, reward, state_featurize.transfer(next_state), done)
agent.train(pre_state, action, reward, next_state, done)
if done:
print('episode: ', epoch + 1, 'step: ', step + 1, ' final value: ', env.get_value())
break
pre_state = next_state
if epoch % 100 == 0 and epoch > 0:
final_value = play(agent, epoch // 100, max_iter, not True)
print('--------------episode ', epoch, 'final value: ', final_value, '---------------')
if np.mean(np.array(final_value)) < -1.8:
print('----- using ', epoch, ' epochs')
#agent.save_model()
break
time.sleep(1)
if epoch % 500 == 0 and epoch > 0:
path = save_path + str(epoch)
agent.save(save_path=path)
return agent
naf = NAF(State_dim, Action_dim, Replay_mem_size, Train_batch_size,
Gamma, Critic_Learning_rate, Action_low, Action_high, Tau, noise, flag = False, if_PER = False)
ddpg = DDPG(State_dim, Action_dim, Replay_mem_size, Train_batch_size,
Gamma, Actor_Learning_rate, Critic_Learning_rate, Action_low, Action_high, Tau, noise, if_PER=False)
cac = CAC(State_dim, Action_dim, Replay_mem_size, Train_batch_size,
Gamma, Actor_Learning_rate, Critic_Learning_rate, Action_low, Action_high, Tau, sigma=args.sigma, if_PER=False)
cppo = PPO(State_dim, Action_dim,Action_low, Action_high, Replay_mem_size, Train_batch_size, Gamma,
Actor_Learning_rate, Critic_Learning_rate, Tau, trajectory_number=100, update_epoach=50)
if args.obj == 'quadratic':
obj = Quadratic(dim)
elif args.obj == 'logistic':
obj = Logistic(dim, X, Y)
elif args.obj == 'ackley':
obj = Ackley(dim)
elif args.obj == 'neural':
obj = NeuralNet(dim, X, Y, **kwargs)
cg_x, cg_y, _, cg_iter, _ = cg(obj, x0 = init_point, maxiter=max_iter)
print('CG method:\n optimal point: {0}, optimal value: {1}, iterations {2}'.format(cg_x, cg_y, cg_iter))
sd_x, sd_y, _, sd_iter, _ = sd(obj, x0=init_point, maxiter=max_iter)
print('SD method:\n optimal point: {0}, optimal value: {1}, iterations {2}'.format(sd_x, sd_y, sd_iter))
bfgs_x, bfgs_y, _, bfgs_iter, _ = quasiNewton(obj, x0=init_point, maxiter=max_iter)
print('bfgs method:\n optimal point: {0}, optimal value: {1}, iterations {2}'.format(bfgs_x, bfgs_y, bfgs_iter))
if args.agent == 'naf':
agent = train(naf, max_epoch, max_iter)
elif args.agent == 'ddpg':
agent = train(ddpg, max_epoch, max_iter)
elif args.agent == 'cac':
agent = train(cac, max_epoch, max_iter)
elif args.agent == 'ppo':
agent = train(cppo, max_epoch, max_iter)
log_file.close()
#print('after train')
#print(play(agentnaf,300, False))
#print(play(agentnaf_addloss,300, False))
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 11 16:26:37 2018
@author: Niwatori
"""
"""
# Newton-type Methods
# - Normal Newton / Damped Newton
# - Modified Newton: mixed direction / LM method
# - Quasi-Newton: SR1 / DFP / BFGS
"""
import numpy as np
from numpy.linalg import norm
import linesearch as ls
def Newton(fun, x0, method='damped', search='inexact',
eps=1e-8, maxiter=1000, **kwargs):
"""Newton's method: normal or damped
Parameters
----------
fun: object
objective function, with callable method f, g and G
x0: ndarray
initial point
method: string, optional
'normal' for Normal Newton, 'damped' for damped Newton
search: string, optional
'exact' for exact line search, 'inexact' for inexact line search
eps: float, optional
tolerance, used for convergence criterion
maxiter: int, optional
maximum number of iterations
kwargs: dict, optional
other arguments to pass down
Returns
-------
x: ndarray
optimal point
f: float
optimal function value
gnorm: float
norm of gradient at optimal point
niter: int
number of iterations
neval: int
number of function evaluations (f, g and G)
"""
x = x0
f0 = -np.inf
f1 = fun.f(x0)
g1 = fun.g(x0)
niter = 0
neval = 2
errflag = 0
while (abs(f1 - f0) > eps) or (norm(g1) > eps):
G = fun.G(x)
try: # test if positive definite
L = np.linalg.cholesky(G)
except np.linalg.LinAlgError:
errflag = 1
d = np.linalg.solve(G, -g1)
if method == 'normal':
alpha, v = 1, 0
elif method == 'damped':
if search == 'inexact':
alpha, v = ls.inexact(fun, x, d, fx=f1, gx=g1, **kwargs)
elif search == 'exact':
alpha, v = ls.exact(fun, x, d, **kwargs)
else:
raise ValueError('Invalid search type')
else:
raise ValueError('Invalid method name')
x = x + alpha * d
f0 = f1
f1 = fun.f(x)
g1 = fun.g(x)
niter += 1
neval += (v + 3)
if niter == maxiter:
break
if errflag == 1:
print('Warning: Non-positive-definite Hessian encountered.')
return x, f1, norm(g1), niter, neval
def modifiedNewton(fun, x0, method='mix', search='inexact',
eps=1e-8, maxiter=1000, **kwargs):
"""Modified Newton's method: mixed direction or LM method
Parameters
----------
fun: object
objective function, with callable method f, g and G
x0: ndarray
initial point
method: string, optional
'mix' for mixed direction method, 'lm' for Levenberg-Marquardt method
search: string, optional
'exact' for exact line search, 'inexact' for inexact line search
eps: float, optional
tolerance, used for convergence criterion
maxiter: int, optional
maximum number of iterations
kwargs: dict, optional
other arguments to pass down
Returns
-------
x: ndarray
optimal point
f: float
optimal function value
gnorm: float
norm of gradient at optimal point
niter: int
number of iterations
neval: int
number of function evaluations (f, g and G)
"""
x = x0
f0 = -np.inf
f1 = fun.f(x0)
g1 = fun.g(x0)
niter = 0
neval = 2
while (abs(f1 - f0) > eps) or (norm(g1) > eps):
if method == 'mix':
try: # test if singular
d = np.linalg.solve(fun.G(x), -g1)
if abs(np.dot(g1, d)) < eps * norm(g1) * norm(d): # orthogonal
d = -g1
if np.dot(g1, d) > eps * norm(g1) * norm(d): # non-descent
d = -d
except np.linalg.LinAlgError:
d = -g1
elif method == 'lm':
G = fun.G(x)
v = 0
while True:
try: # test if positive definite
L = np.linalg.cholesky(G + v * np.eye(x.size))
break
except np.linalg.LinAlgError:
if v == 0:
v = norm(G) / 2 # Frobenius norm
else:
v *= 2
y = np.linalg.solve(L, -g1)
d = np.linalg.solve(L.T, y)
else:
raise ValueError('Invalid method name')
if search == 'inexact':
alpha, v = ls.inexact(fun, x, d, fx=f1, gx=g1, **kwargs)
elif search == 'exact':
alpha, v = ls.exact(fun, x, d, **kwargs)
else:
raise ValueError('Invalid search type')
x = x + alpha * d
f0 = f1
f1 = fun.f(x)
g1 = fun.g(x)
niter += 1
neval += (v + 3)
if niter == maxiter:
break
return x, f1, norm(g1), niter, neval
def quasiNewton(fun, x0, H0=None, method='bfgs', search='inexact',
eps=1e-8, maxiter=1000, a_high=.3, **kwargs):
"""Quasi-Newton methods: SR1 / DFP / BFGS
Parameters
----------
fun: object
objective function, with callable method f and g
x0: ndarray
initial point
H0: ndarray, optional
initial Hessian inverse, identity by default
method: string, optional
'sr1' for SR1, 'dfp' for DFP, 'bfgs' for BFGS
search: string, optional
'exact' for exact line search, 'inexact' for inexact line search
eps: float, optional
tolerance, used for convergence criterion
maxiter: int, optional
maximum number of iterations
kwargs: dict, optional
other arguments to pass down
Returns
-------
x: ndarray
optimal point
f: float
optimal function value
gnorm: float
norm of gradient at optimal point
niter: int
number of iterations
neval: int
number of function evaluations (f and g)
flist: list
list of objective values along the iterations
xlist: list
list of points along the iterations
"""
x = x0
if H0 is not None:
H = H0
else:
H = np.eye(x.size)
f0 = -np.inf
f1 = fun.f(x)
g0 = np.zeros(x.size)
g1 = fun.g(x)
niter = 0
neval = 2
flist = []
xlist = []
while (abs(f1 - f0) > eps) or (norm(g1) > eps):
d = -(H @ g1)
if search == 'inexact':
alpha, v = ls.inexact(fun, x, d, fx=f1, gx=g1, **kwargs)
elif search == 'exact':
alpha, v = ls.exact(fun, x, d, **kwargs)
else:
raise ValueError('Invalid search type')
s = alpha * d
if norm(s, np.inf) > a_high:
s = s / norm(s, np.inf) * a_high
x = x + s
g0 = g1
g1 = fun.g(x)
y = g1 - g0
if f0 == 0 and H0 is None: # initial scaling
H = (np.dot(y, s) / np.dot(y, y)) * H
f0 = f1
f1 = fun.f(x)
neval += (v + 2)
flist.append(f1)
xlist.append(x)
if method == 'sr1':
z = s - H @ y
if abs(np.dot(z, y)) >= eps * norm(z) * norm(y):
H = H + np.outer(z, z / np.dot(z, y))
elif method == 'dfp':
z = H @ y
H = H + np.outer(s, s / np.dot(s, y)) - np.outer(z, z / np.dot(y, z))
elif method == 'bfgs':
if abs(np.dot(s, y)) > 1e-10:
r = 1 / np.dot(s, y)
z = r * (H @ y)
H = H + r * (1 + np.dot(y, z)) * np.outer(s, s) \
- np.outer(s, z) - np.outer(z, s)
else:
raise ValueError('Invalid method name')
niter += 1
if niter == maxiter:
break
return x, f1, norm(g1), niter, neval, flist, xlist
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tues May 1 22:14:02 2018
@author: Niwatori
"""
"""
# Non-linear Conjugate Gradient Methods
# - FR (Fletcher-Reeves)
# - PRP / PRP+ (Polak-Ribiere-Polyak)
# - HS (Hestenes-Stiefel)
# - CD (Conjugate Descent)
# - DY (Dai-Yuan)
"""
import numpy as np
from numpy.linalg import norm
import linesearch as ls
def cg(fun, x0, method='prp+', search='inexact',
eps=1e-8, maxiter=10000, nu=0.2, a_high=.3, debug=False, **kwargs):
"""Non-linear conjugate gradient methods
Parameters
----------
fun: object
objective function, with callable method f and g
x0: ndarray
initial point
method: string, optional
options: 'fr' for FR, 'prp' for PRP, 'prp+' for PRP+, 'hs' for HS,
'cd' for conjugate descent, 'dy' for Dai-Yuan
search: string, optional
'exact' for exact line search, 'inexact' for inexact line search
eps: float, optional
tolerance, used for stopping criterion
maxiter: int, optional
maximum number of iterations
nv: float, optional
parameter for restart by orthogonality test
debug: boolean, optional
output information for every iteration if set to True
kwargs: dict, optional
other arguments to pass down
Returns
-------
x: ndarray
optimal point
f: float
optimal function value
gnorm: float
norm of gradient at optimal point
niter: int
number of iterations
neval: int
number of function evaluations (f and g)
flist: list
list of objective values along the iterations
xlist: list
list of points along the iterations
"""
x = x0
n = x.size
f0 = -np.inf
f1 = fun.f(x)
g0 = np.zeros(n)
g1 = fun.g(x)
d = -g1
niter = 0
neval = 2
flist = []
xlist = []
while (abs(f1 - f0) > eps) or (norm(g1) > eps):
if abs(np.dot(g1, g0)) > 0.2 * np.dot(g1, g1):
d = -g1
if search == 'inexact':
alpha, v = ls.inexact(fun, x, d, fx=f1, gx=g1, **kwargs)
elif search == 'exact':
alpha, v = ls.exact(fun, x, d, **kwargs)
else:
raise ValueError('Invalid search type')
d = alpha * d
if norm(d, np.inf) > a_high:
d = d / norm(d, np.inf) * a_high
x = x + d
g0 = g1
g1 = fun.g(x)
y = g1 - g0
f0 = f1
f1 = fun.f(x)
neval += (v + 2)
flist.append(f1)
xlist.append(x)
if debug:
print('iter:', niter, alpha)
if method == 'fr':
beta = np.dot(g1, g1) / np.dot(g0, g0)
elif method == 'prp':
beta = np.dot(g1, y) / np.dot(g0, g0)
elif method == 'prp+':
beta = max(np.dot(g1, y) / np.dot(g0, g0), 0)
elif method == 'hs':
beta = np.dot(g1, y) / np.dot(d, y)
elif method == 'cd':
beta = -np.dot(g1, g1) / np.dot(g0, d)
elif method == 'dy':
beta = np.dot(g1, g1) / np.dot(d, y)
else:
raise ValueError('Invalid method name')
d = beta * d - g1
niter += 1
if niter == maxiter:
break
return x, f1, norm(g1), niter, neval, flist, xlist
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 11 16:59:37 2018
@author: Niwatori
"""
"""
# Line Search Algorithms
# - Exact line searchL 0.618 method
# - Inexact line search: strong Wolfe condition
"""
import numpy as np
def exact(fun, x, d, eps=1e-2, a_min=0.001, a_max=10):
"""Exact line search: 0.618 method
Parameters
----------
fun: object
objective function, with callable method f
x: ndarray
current point
d: ndarray
current search direction
eps: float, optional
tolerance, used for convergence criterion
a_min: float, optional
lower bound for step length
a_max: float, optional
upper bound for step length
Returns
-------
alpha: float
step length that minimizes f(x + alpha * d)
neval: int
number of function evaluations (f)
"""
def phi(a):
return fun.f(x + a * d)
a, b = a_min, a_max
r = (np.sqrt(5) - 1) / 2
lflag, rflag = 0, 0
neval = 0
while b - a > eps:
if lflag == 0:
a_l = a + (1 - r) * (b - a)
phi_l = phi(a_l)
neval += 1
if rflag == 0:
a_r = a + r * (b - a)
phi_r = phi(a_r)
neval += 1
if phi_l < phi_r:
b = a_r
a_r = a_l
phi_r = phi_l
lflag, rflag = 0, 1
else:
a = a_l
a_l = a_r
phi_l = phi_r
lflag, rflag = 1, 0
return (a + b) / 2, neval
def inexact(fun, x, d, a_min=0.001, a_max=10,
rho=1e-4, sigma=0.5, fx=None, gx=None):
"""Inexact line search: strong Wolfe condition
Parameters
----------
fun: object
objective function, with callable method f and g
x: ndarray
current point
d: ndarray
current search direction
a_min: float, optional
lower bound for step length
a_max: float, optional
upper bound for step length
rho: float, optional
parameter for Armijo condition
sigma: float, optional
parameter for curvature condition
fx: float, optional
f at x, used for saving function evaluations
gx: ndarray, optional
g at x, used for saving function evaluations
Returns
-------
alpha: float
step length that satisfies strong Wolfe condition
neval: int
number of function evaluations (f and g)
"""
a_0 = a_min
a_1 = 1
def phi(a):
return fun.f(x + a * d)
def phip(a): # derivative of phi
return np.dot(fun.g(x + a * d), d)
phi_0 = fx or phi(0)
phip_0 = phip(0) if gx is None else np.dot(gx, d)
phi_a0 = phi_0
phi_max = phi(a_max)
neval = 1
maxiter = 10
while True:
phi_a1 = phi(a_1)
if (phi_a1 > phi_0 + rho * a_1 * phip_0) \
or (a_0 > 0 and phi_a1 >= phi_a0):
zoom, v = _zoom(a_0, a_1, phi, phip,
phi_0, phip_0, phi_a0, rho, sigma)
return zoom, neval + v
phip_a1 = phip(a_1)
# print('phip_a1: ', phip_a1)
# print('phip_0: ', phip_0)
if abs(phip_a1) <= -sigma * phip_0:
return a_1, neval
if phip_a1 >= 0:
zoom, v = _zoom(a_1, a_0, phi, phip,
phi_0, phip_0, phi_a1, rho, sigma)
return zoom, neval + v
# Choose an alpha from (a_1, a_max)
a_0 = a_1
anew = _cubicInterplt(a_1, phi_a1, phip_a1, a_0, phi_a0, a_max, phi_max)
anew_lo = a_1 + 0.1 * (a_max - a_1)
anew_hi = a_max - 0.1 * (a_max - a_1)
if (anew is not None) and (anew > anew_lo) and (anew < anew_hi):
a_1 = anew
else:
anew = _quadInterplt(a_1, phi_a1, phip_a1, a_max, phi_max)
if (anew is not None) and (anew > anew_lo) and (anew < anew_hi):
a_1 = anew
else:
a_1 = (a_1 + a_max) / 2
neval += 2
maxiter -= 1
if maxiter == 0:
break
return a_1, neval
def _zoom(a_lo, a_hi, phi, phip,
phi_0, phip_0, phi_lo, rho, sigma):
"""Selection phase of inexact line search
Parameters
----------
a_lo, a_hi: float
interval to search within
phi: function
phi = f(x + alpha * d)
phip: function
derivative of phi
phi_0: float
phi at 0
phip_0: float
derivative of phi at 0
phi_lo: float
phi at a_lo
rho: float
parameter for Armijo condition
sigma: float
parameter for curvature condition
Returns
-------
alpha: float
step length that satisfies strong Wolfe condition
neval: int
number of function evaluations (f and g)
"""
neval = 0
maxiter = 10
while True:
# bisection
a = (a_hi + a_lo) / 2
phi_a = phi(a)
if (phi_a > phi_0 + rho * a * phip_0) or (phi_a >= phi_lo):
a_hi = a
else:
phip_a = phip(a)
if abs(phip_a) <= -sigma * phip_0:
return a, neval
if phip_a * (a_hi - a_lo) >= 0:
a_hi = a_lo
a_lo = a
phi_lo = phi_a
neval += 1
neval += 1
maxiter -= 1
if maxiter == 0:
break
# backtrack if alpha is still not small enough
while phi_a > phi_0 + rho * a * phip_0:
a = a / 2
phi_a = phi(a)
return a, neval
def _cubicInterplt(a, fa, fpa, b, fb, c, fc):
"""Cubic interpolation
Finds the minimizer for a cubic polynomial that goes through the
points (a, fa), (b, fb) and (c, fc) with derivative at a (fpa).
If no minimizer can be found return None
"""
# f(x) = A * (x - a) ^ 3 + B * (x - a) ^ 2 + C * (x - a) + D
C = fpa
db = b - a
dc = c - a
if (db == 0) or (dc == 0) or (b == c):
return None
denom = (db * dc) ** 2 * (db - dc)
d1 = np.array([[dc ** 2, -db ** 2], [-dc ** 3, db ** 3]])
[A, B] = np.dot(d1, np.array([fb - fa - C * db, fc - fa - C * dc]))
A /= denom
B /= denom
r = B * B - 3 * A * C
if r < 0 or A == 0:
return None
xmin = a + (-B + np.sqrt(r)) / (3 * A)
return xmin
def _quadInterplt(a, fa, fpa, b, fb):
"""Quadratic interpolation
Finds the minimizer for a quadratic polynomial that goes through
the points (a, fa) and (b, fb) with derivative at a (fpa),
If no minimizer can be found return None
"""
# f(x) = B * (x - a) ^ 2 + C * (x - a) + D
D = fa
C = fpa
h = b - a
B = (fb - D - C * h) / (h * h)
if B <= 0:
return None
xmin = a - C / (2 * B)
return xmin
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Apr 3 21:43:06 2018
@author: Wangyf
"""
import gym
import torch
import numpy as np
import objfunc
import sys
import argparse
from helper_functions import *
from DQN_torch import DQN
from NAF_torch import NAF
from DDPG_torch import DDPG
from AC_torch import AC
from CAC_torch import CAC
from PPO_torch import PPO
import matplotlib.pyplot as plt
import time
from cg import cg
from bb import sd
from newton import quasiNewton
from objfunc import Logistic, Quadratic, NeuralNet, Ackley
from dataset import LogisticDataset, NeuralNetDataset
## parameters
argparser = argparse.ArgumentParser(sys.argv[0])
argparser.add_argument('--lr', type=float, default=1e-4)
argparser.add_argument('--replay_size', type=int, default=50000)
argparser.add_argument('--batch_size', type=int, default=128)
argparser.add_argument('--gamma', type=float, default=1)
argparser.add_argument('--tau', type=float, default=0.1)
argparser.add_argument('--noise_type', type = str, default = 'gauss')
argparser.add_argument('--agent', type = str, default = 'ddpg')
argparser.add_argument('--action_low', type = float, default = -0.2)
argparser.add_argument('--action_high', type = float, default = 0.2)
argparser.add_argument('--dim', type = int, default = 3)
argparser.add_argument('--window_size', type = int, default = 10)
argparser.add_argument('--obj', type = str, default = 'neural')
argparser.add_argument('--max_iter', type = int, default = 50)
argparser.add_argument('--max_epoch', type = int, default = 100000)
argparser.add_argument('--load_dir', type = str, default = None)
argparser.add_argument('--debug', type = str, default = sys.argv[1:])
argparser.add_argument('--print_every', type = int, default = 5)
args = argparser.parse_args()
### the env
dim = args.dim
window_size = args.window_size
init_point = np.arange(dim) / dim
# construct train and test objectives
num_train, num_test = 20, 10
env_train = []
env_test = []
if args.obj == 'logistic':
X, Y = LogisticDataset(dim=dim)
dim = dim + 1
obj = Logistic(dim, X, Y)
init_point = np.arange(dim) / dim
for k in range(num_train):
X, Y = LogisticDataset(dim=args.dim, seed=k)
env_train.append(objfunc.make('logistic', dim=dim, init_point=init_point,
window_size=window_size, other_params=[X, Y]))
for k in range(num_test):
X, Y = LogisticDataset(dim=args.dim, seed=num_train+k)
env_test.append(objfunc.make('logistic', dim=dim, init_point=init_point,
window_size=window_size, other_params=[X, Y]))
elif args.obj == 'neural':
d, h, p, lamda = 2, 2, 2, .0005
kwargs = {'d' : d, 'h': h, 'p' : p, 'lamda' : lamda}
dim = h * d + h + p * h + p
init_point = np.arange(dim) / dim
for k in range(num_train):
X, Y = NeuralNetDataset(dim=d, seed=k)
env_train.append(objfunc.make('neural', dim=dim, init_point=init_point,
window_size=window_size, other_params=[X, Y], **kwargs))
for k in range(num_test):
X, Y = NeuralNetDataset(dim=d, seed=num_train+k)
env_test.append(objfunc.make('neural', dim=dim, init_point=init_point,
window_size=window_size, other_params=[X, Y], **kwargs))
else:
raise ValueError('Invalid objective')
### the params
Replay_mem_size = args.replay_size
Train_batch_size = args.batch_size
Actor_Learning_rate = args.lr
Critic_Learning_rate = args.lr
Gamma = args.gamma
Tau = args.tau
Action_low = args.action_low
Action_high = args.action_high
max_iter = args.max_iter
max_epoch = args.max_epoch
State_dim = dim + window_size + dim * window_size
print(State_dim)
Action_dim = dim
print(Action_dim)
ounoise = OUNoise(Action_dim, 8, 0.5, 0.9995)
gsnoise = GaussNoise(0.1, 0.02, 0.9995)
noise = gsnoise if args.noise_type == 'gauss' else ounoise
# record the obj value and point at each iteration
log_file = open('./general_' + str(args.agent) + '_' + str(args.obj) + '_' + '.txt', 'w')
save_path = './record/general_' + str(args.obj) + str(args.agent)
test_record = [[] for i in range(num_test)]
def play(agent, num_epoch, max_iter, test_count, show = False):
print('debug: ', args.debug)
final_value = []
for epoch in range(1):
global env_test, log_file
env = env_test[test_count % num_test]
# record the value and point
val_record = []
point_record = []
pre_state = env.reset()
for step in range(max_iter):
if show:
env.render()
# action = agent.action(state_featurize.transfer(pre_state), False)
action = agent.action(pre_state, False)
next_state, reward, done, _ = env.step(action)
val_record.append(-reward)
point_record.append(next_state[:dim])
if done or step == max_iter - 1:
final_val = env.get_value()
final_value.append(final_val)
break
pre_state = next_state
# print(val_record)
print(' '.join(map(str, val_record)), file = log_file, end = '\n')
for point in point_record:
print(' '.join(map(str, point)), file = log_file, end = ',')
log_file.write('\n')
log_file.flush()
test_record[test_count % num_test].append(final_val)
return final_value
def train(agent, Train_epoch, max_iter, file_name = './res.dat'):
output_file = open(file_name, 'w')
for epoch in range(Train_epoch):
global env_train, env_test
env = env_train[(epoch // 20) % num_train]
pre_state = env.reset()
acc_reward = 0
for step in range(max_iter):
# print('pre:', pre_state)
action = agent.action(pre_state)
# print('action:', action)
if action[0] != action[0]:
raise('nan error!')
next_state, reward, done, _ = env.step(action)
reward *= step ** 0.2
acc_reward += reward
# print('next:', next_state)
if step == max_iter - 1:
done = True
# agent.train(state_featurize.transfer(pre_state), action, reward, state_featurize.transfer(next_state), done)
agent.train(pre_state, action, reward, next_state, done)
if done and epoch % args.print_every == 0:
#print('episode: ', epoch + 1, 'step: ', step + 1, ' reward is', acc_reward, file = output_file)
#print('episode: ', epoch + 1, 'step: ', step + 1, ' reward is', acc_reward, )
print('episode: ', epoch + 1, 'step: ', step + 1, ' final value: ', env.get_value())
break
pre_state = next_state
if epoch % 100 == 0:
test_count = epoch // 100
final_value = play(agent, 1, max_iter, test_count)
print('--------------episode ', epoch, 'final_value: ', final_value, '---------------', file = output_file)
print('--------------episode ', epoch, 'test_id', test_count % num_test, 'final value: ',
test_record[test_count % num_test], '---------------')
env = env_test[test_count % num_test]
if args.obj == 'logistic':
obj = Logistic(args.dim, env.func.X, env.func.Y)
elif args.obj == 'neural':
obj = NeuralNet(dim, env.func.X, env.func.Y, **kwargs)
cg_x, cg_y, _, cg_iter, _, _, _ = cg(obj, x0 = init_point, maxiter=max_iter, a_high=args.action_high)
print('CG method: optimal value: {0}, iterations {1}'.format(cg_y, cg_iter))
sd_x, sd_y, _, sd_iter, _, _ ,_ = sd(obj, x0=init_point, maxiter=max_iter, a_high=args.action_high)
print('SD method: optimal value: {0}, iterations {1}'.format(sd_y, sd_iter))
bfgs_x, bfgs_y, _, bfgs_iter, _, _ ,_ = quasiNewton(obj, x0=init_point, maxiter=max_iter, a_high=args.action_high)
print('BFGS method: optimal value: {0}, iterations {1}'.format(bfgs_y, bfgs_iter))
# if np.mean(np.array(final_value)) < min(cg_y, sd_y, bfgs_y):
# print('----- using ', epoch, ' epochs')
# #agent.save_model()
# break
time.sleep(1)
if epoch % 500 == 0 and epoch > 0:
path = save_path + str(epoch)
agent.save(path)
return agent
naf = NAF(State_dim, Action_dim, Replay_mem_size, Train_batch_size,
Gamma, Critic_Learning_rate, Action_low, Action_high, Tau, noise, False, False)
ddpg = DDPG(State_dim, Action_dim, Replay_mem_size, Train_batch_size,
Gamma, Actor_Learning_rate, Critic_Learning_rate, Action_low, Action_high, Tau, noise, False)
cac = CAC(State_dim, Action_dim, Replay_mem_size, Train_batch_size,
Gamma, Actor_Learning_rate, Critic_Learning_rate, Action_low, Action_high, Tau, sigma=2, if_PER = False)
cppo = PPO(State_dim, Action_dim,Action_low, Action_high, Replay_mem_size, Train_batch_size, Gamma,
Actor_Learning_rate, Critic_Learning_rate, Tau, trajectory_number=100, update_epoach=20)
if args.agent == 'naf':
agent = train(naf, max_epoch, max_iter)
elif args.agent == 'ddpg':
if args.load_dir is not None:
ddpg.critic_policy_net.load_state_dict(torch.load(args.load_dir + '_critic.txt'))
ddpg.actor_policy_net.load_state_dict(torch.load(args.load_dir + '_actor.txt'))
agent = train(ddpg, max_epoch, max_iter)
elif args.agent == 'cac':
agent = train(cac, max_epoch, max_iter)
elif args.agent == 'ppo':
agent = train(cppo, max_epoch, max_iter)
else:
raise('Invalid Agent!')
#print('after train')
#print(play(agentnaf,300, False))
#print(play(agentnaf_addloss,300, False))
<file_sep>import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import random
from collections import deque
from torch_networks import NAF_network
from helper_functions import SlidingMemory, PERMemory
class NAF():
'''
doc for naf
'''
def __init__(self, state_dim, action_dim, mem_size, train_batch_size, gamma, lr,
action_low, action_high, tau, noise, flag = False, if_PER = False,
save_path = './record/NAF'):
self.mem_size, self.train_batch_size = mem_size, train_batch_size
self.gamma, self.lr = gamma, lr
self.global_step = 0
self.tau, self.explore = tau, noise
self.state_dim, self.action_dim = state_dim, action_dim
self.action_high, self.action_low = action_high, action_low
self.if_PER = if_PER
self.replay_mem = PERMemory(mem_size) if if_PER else SlidingMemory(mem_size)
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.device = 'cpu'
self.policy_net = NAF_network(state_dim, action_dim, action_low, action_high, self.device).to(self.device)
self.target_net = NAF_network(state_dim, action_dim,action_low, action_high, self.device).to(self.device)
self.policy_net.apply(self._weight_init)
self.optimizer = optim.RMSprop(self.policy_net.parameters(), self.lr)
self.hard_update(self.target_net, self.policy_net)
self.flag = flag
def _weight_init(self,m):
if type(m) == nn.Linear:
torch.nn.init.xavier_uniform_(m.weight)
torch.nn.init.constant_(m.bias, 0.)
def soft_update(self, target, source, tau):
for target_param, param in zip(target.parameters(), source.parameters()):
target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau)
def hard_update(self, target, source):
for target_param, param in zip(target.parameters(), source.parameters()):
target_param.data.copy_(param.data)
# training process
def train(self, pre_state, action, reward, next_state, if_end):
self.replay_mem.add(pre_state, action, reward, next_state, if_end)
if self.replay_mem.num() < self.mem_size:
return
self.explore.decaynoise()
# print('training')
# sample $self.train_batch_size$ samples from the replay memory, and use them to train
if not self.if_PER:
train_batch = self.replay_mem.sample(self.train_batch_size)
else:
train_batch, idx_batch, weight_batch = self.replay_mem.sample(self.train_batch_size)
weight_batch = torch.tensor(weight_batch, dtype = torch.float).unsqueeze(1)
# adjust dtype to suit the gym default dtype
pre_state_batch = torch.tensor([x[0] for x in train_batch], dtype=torch.float, device = self.device)
action_batch = torch.tensor([x[1] for x in train_batch], dtype = torch.float, device = self.device)
# view to make later computation happy
reward_batch = torch.tensor([x[2] for x in train_batch], dtype=torch.float, device = self.device).view(self.train_batch_size,1)
next_state_batch = torch.tensor([x[3] for x in train_batch], dtype=torch.float, device = self.device)
if_end = [x[4] for x in train_batch]
if_end = torch.tensor(np.array(if_end).astype(float),device = self.device, dtype=torch.float).view(self.train_batch_size,1)
# use the target_Q_network to get the target_Q_value
with torch.no_grad():
q_target_, _ = self.target_net(next_state_batch)
q_target = self.gamma * q_target_ * (1 - if_end) + reward_batch
q_pred = self.policy_net(pre_state_batch, action_batch)
if self.if_PER:
TD_error_batch = np.abs(q_target.cpu().numpy() - q_pred.cpu().detach().numpy())
self.replay_mem.update(idx_batch, TD_error_batch)
self.optimizer.zero_grad()
#print('q_pred is {0} and q_target is {1}'.format(q_pred, q_target))
loss = (q_pred - q_target) ** 2
if self.if_PER:
loss *= weight_batch
loss = torch.mean(loss)
if self.flag:
loss -= q_pred.mean() # to test one of my ideas
loss.backward()
# loss = torch.min(loss, torch.tensor(1000, dtype = torch.float))
# print('loss is {0}'.format(loss))
# # for para in self.policy_net.parameters():
# print('param is: \n {0} \n gradient is: \n {1}'.format(para, para.grad))
torch.nn.utils.clip_grad_norm_(self.policy_net.parameters(), 2)
self.optimizer.step()
# update target network
self.soft_update(self.target_net, self.policy_net, self.tau)
self.global_step += 1
# store the (pre_s, action, reward, next_state, if_end) tuples in the replay memory
def perceive(self, pre_s, action, reward, next_state, if_end):
self.replay_mem.append([pre_s, action, reward, next_state, if_end])
if len(self.replay_mem) > self.mem_size:
self.replay_mem.popleft()
# give a state and action, return the action value
def get_value(self, s, a):
s = torch.tensor(s,dtype=torch.float, device = self.device)
with torch.no_grad():
val = self.policy_net(s.unsqueeze(0)).gather(1, torch.tensor(a,dtype = torch.long).unsqueeze(1)).view(1,1)
return np.clip(val.item() + np.random.rand(1, self.explore_rate), self.action_low, self.action_high)
# use the policy net to choose the action with the highest Q value
def action(self, s, add_noise = True):
cur_gradient = s[-self.action_dim:]
s = torch.tensor(s, dtype=torch.float, device = self.device).unsqueeze(0)
with torch.no_grad():
_, action = self.policy_net(s)
var = np.exp(np.linalg.norm(cur_gradient)) + 0.03
noise = self.explore.noise() if add_noise else 0.0
# use item() to get the vanilla number instead of a tensor
#return [np.clip(np.random.normal(action.item(), self.explore_rate), self.action_low, self.action_high)ac]
#print(action.numpy()[0])
return np.clip(action.cpu().numpy()[0] + noise, self.action_low, self.action_high)
def save(self, save_path = None):
path = save_path if save_path is not None else self.save_path
torch.save(self.policy_net.state_dict(), path + '_critic.txt')
<file_sep>import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import multivariate_normal, normal
from torch.nn import init
class NAF_network(nn.Module):
def __init__(self, state_dim, action_dim, action_low, action_high, device = 'cpu'):
super(NAF_network, self).__init__()
self.device = device
self.sharefc1 = nn.Linear(state_dim, 64)
self.sharefc2 = nn.Linear(64, 64)
self.v_fc1 = nn.Linear(64, 1)
self.miu_fc1 = nn.Linear(64, action_dim)
self.L_fc1 = nn.Linear(64, action_dim ** 2)
self.action_dim = action_dim
self.action_low, self.action_high = action_low, action_high
def forward(self, s, a = None):
s = F.relu(self.sharefc1(s))
# s = F.relu(self.sharefc2(s))
v = self.v_fc1(s)
miu = self.miu_fc1(s)
# currently could only clip according to the same one single value.
# but different dimensions may mave different high and low bounds
# modify to clip along different action dimension
miu = torch.clamp(miu, self.action_low, self.action_high)
if a is None:
return v, miu
L = self.L_fc1(s)
L = L.view(-1, self.action_dim, self.action_dim)
tril_mask = torch.tril(torch.ones(
self.action_dim, self.action_dim, device = self.device), diagonal=-1).unsqueeze(0)
diag_mask = torch.diag(torch.diag(
torch.ones(self.action_dim, self.action_dim, device = self.device))).unsqueeze(0)
L = L * tril_mask.expand_as(L) + torch.exp(L * diag_mask.expand_as(L))
# L = L * tril_mask.expand_as(L) + L ** 2 * diag_mask.expand_as(L)
P = torch.bmm(L, L.transpose(2, 1))
u_mu = (a - miu).unsqueeze(2)
A = -0.5 * \
torch.bmm(torch.bmm(u_mu.transpose(2, 1), P), u_mu)[:, :, 0]
q = A + v
return q
class DQN_fc_network(nn.Module):
def __init__(self, input_dim, output_dim, hidden_layers):
super(DQN_fc_network, self).__init__()
self.fc_in = nn.Linear(input_dim, 32)
self.fc_hiddens = [nn.Linear(32,32) for i in range(hidden_layers)]
self.fc_out = nn.Linear(32, output_dim)
def forward(self, x):
x = F.relu(self.fc_in(x))
for layer in self.fc_hiddens:
x = F.relu(layer(x))
x = self.fc_out(x)
return x
class DQN_dueling_network(nn.Module):
def __init__(self, input_dim, output_dim, hidden_layers):
super(DQN_dueling_network, self).__init__()
self.fc_in = nn.Linear(input_dim, 32)
self.fc_hiddens = [nn.Linear(32,32) for i in range(hidden_layers - 1)]
self.fca_before = nn.Linear(32, 16)
self.fcv_before = nn.Linear(32, 16)
self.fca = nn.Linear(16, output_dim)
self.fcv = nn.Linear(16, 1)
def forward(self, x):
x = F.relu(self.fc_in(x))
for layer in self.fc_hiddens:
x = F.relu(layer(x))
a = F.relu(self.fca_before(x))
a = self.fca(a)
a -= a.mean()
v = F.relu(self.fcv_before(x))
v = self.fcv(v)
q = a + v
return q
class DDPG_critic_network(nn.Module):
def __init__(self, state_dim, action_dim):
super(DDPG_critic_network, self).__init__()
self.sfc1 = nn.Linear(state_dim, 32)
# self.sfc2 = nn.Linear(64,32)
self.afc1 = nn.Linear(action_dim, 32)
# self.afc2 = nn.Linear(64,32)
self.sharefc1 = nn.Linear(64,64)
self.sharefc2 = nn.Linear(64,1)
def forward(self, s, a):
s = F.relu(self.sfc1(s))
# s = F.relu(self.sfc2(s))
a = F.relu(self.afc1(a))
# a = F.relu(self.afc2(a))
qsa = torch.cat((s,a), 1)
qsa = F.relu(self.sharefc1(qsa))
qsa = self.sharefc2(qsa)
return qsa
class DDPG_actor_network(nn.Module):
def __init__(self, state_dim, action_dim, action_low, action_high):
super(DDPG_actor_network, self).__init__()
self.fc1 = nn.Linear(state_dim, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, action_dim)
self.action_low, self.action_high = action_low, action_high
def forward(self, s):
s = F.relu(self.fc1(s))
s = F.relu(self.fc2(s))
a = self.fc3(s)
a = a.clamp(self.action_low, self.action_high)
return a
class AC_v_fc_network(nn.Module):
def __init__(self, state_dim):
super(AC_v_fc_network, self).__init__()
self.fc1 = nn.Linear(state_dim, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64,1)
def forward(self, s):
s = F.relu(self.fc1(s))
# s = F.relu(self.fc2(s))
v = self.fc3(s)
return v
class AC_a_fc_network(nn.Module):
def __init__(self, input_dim, output_dim):
super(AC_a_fc_network, self).__init__()
self.fc1 = nn.Linear(input_dim, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, output_dim)
def forward(self, x):
x = F.relu(self.fc1(x))
# x = F.relu(self.fc2(x))
x = self.fc3(x)
return F.softmax(x, dim = 1)
class CAC_a_fc_network(nn.Module):
def __init__(self, input_dim, output_dim, action_low = -1.0, action_high = 1.0, sigma = 1, device = 'cpu'):
super(CAC_a_fc_network, self).__init__()
self.fc1 = nn.Linear(input_dim, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, output_dim)
self.sigma = torch.ones((output_dim), device = device) * sigma
self.action_low, self.action_high = action_low, action_high
def forward(self, s):
s = F.relu(self.fc1(s))
# s = F.relu(self.fc2(s))
mu = self.fc3(s)
mu = torch.clamp(mu, self.action_low, self.action_high)
# m = multivariate_normal.MultivariateNormal(loc = mu, covariance_matrix= self.sigma)
m = normal.Normal(loc = mu, scale= self.sigma)
return m
class CAC_a_sigma_fc_network(nn.Module):
def __init__(self, input_dim, output_dim, action_low = -1.0, action_high = 1.0, sigma = 1):
super(CAC_a_sigma_fc_network, self).__init__()
self.fc1 = nn.Linear(input_dim, 64)
self.fc2 = nn.Linear(64, 64)
self.fcmu = nn.Linear(64, output_dim)
self.fcsigma = nn.Linear(64, output_dim)
self.action_low, self.action_high = action_low, action_high
def forward(self, s):
s = F.relu(self.fc1(s))
# s = F.relu(self.fc2(s))
mu = self.fcmu(s)
mu = torch.clamp(mu, self.action_low, self.action_high)
sigma = self.fcsigma(s)
sigma = F.softplus(sigma)
m = normal.Normal(loc = mu, scale=sigma)
return m
<file_sep># -*- coding: utf-8 -*-
import numpy as np
import random
import torch
import math
import torch.nn.functional as F
from torch import nn
class ObjectiveEnvironment(object):
"""
ObjectiveEnvironment class
Constructor accepts a function object with callable f
for objective value and g for gradient.
"""
def __init__(self, func, initPoint, windowSize):
super(ObjectiveEnvironment, self).__init__()
self.func = func
self.dim = func.dim
self.initPoint = initPoint
self.windowSize = windowSize
def reset(self, windowSize=25):
self.currentIterate = self.initPoint
self.nIterate = 0
currentValue = self.func.f(self.currentIterate)
currentGradient = self.func.g(self.currentIterate)
self.historyValue = np.zeros(self.windowSize)
self.historyValue[0] = currentValue
self.historyChange = np.zeros(self.windowSize)
self.historyGradient = np.zeros(self.windowSize * self.dim)
self.historyGradient[0:self.dim] = currentGradient
initState = np.concatenate((self.currentIterate, self.historyChange,
self.historyGradient))
# initState = np.concatenate((self.historyChange,
# self.historyGradient))
return initState
def get_value(self):
return self.func.f(self.currentIterate)
def step(self, update):
self.nIterate += 1
# negative_gradient = -self.func.g(self.currentIterate)
# reward = -np.linalg.norm(update - negative_gradient, ord=2)
self.currentIterate = self.currentIterate + update
currentValue = self.func.f(self.currentIterate)
currentGradient = self.func.g(self.currentIterate)
done = False
# print('step:', self.currentIterate, currentValue)
# print('step:', currentGradient)
if (math.isinf(currentValue)):
currentState = np.concatenate((self.currentIterate, self.historyChange,
self.historyGradient))
return currentState, -1000000, done, None
if self.nIterate < self.windowSize:
self.historyValue[self.nIterate] = currentValue
self.historyGradient[self.nIterate * self.dim :
(self.nIterate + 1) * self.dim] = currentGradient
else:
self.historyValue[:-1] = self.historyValue[1:]
self.historyValue[-1] = currentValue
# print('cur value is:', currentValue)
self.historyChange = currentValue - self.historyValue
self.historyGradient[:-self.dim] = self.historyGradient[self.dim:]
self.historyGradient[-self.dim:] = currentGradient
if abs(self.historyChange[-2]) < 1e-8: # stopping criterion
done = True
# reward = currentValue
currentState = np.concatenate((self.currentIterate, self.historyChange,
self.historyGradient))
# currentState = np.concatenate((self.historyChange,
# self.historyGradient))
return currentState, -currentValue, done, None
def make(str='quadratic', dim=3, init_point=None, window_size=25, other_params = [], **kwargs):
if init_point is None:
init_point = np.ones(dim)
if str == 'quadratic':
return ObjectiveEnvironment(Quadratic(dim), init_point, window_size)
elif str == 'logistic':
return ObjectiveEnvironment(Logistic(dim, other_params[0], other_params[1]), init_point, window_size)
elif str == 'ackley':
return ObjectiveEnvironment(Ackley(dim), init_point, window_size)
elif str == 'neural':
return ObjectiveEnvironment(NeuralNet(dim, other_params[0], other_params[1], **kwargs), init_point, window_size)
class Quadratic(object):
"""docstring for Quadratic"""
def __init__(self, dim):
super(Quadratic, self).__init__()
self.dim = dim
def f(self, x):
# x_torch = torch.tensor(x, dtype = torch.float, requires_grad = True)
# val = torch.sum(x_torch ** 2)
# val.backward()
# self.grad = x_torch.grad
# print('val item: ',val.item())
# return val.item()
return np.dot(x, x)
def g(self, x):
# print('grad: ', self.grad.data.numpy())
# return self.grad.data.numpy()
return 2 * x
class Logistic(object):
""" doc for Logistic """
def __init__(self, dim, X, Y, lbd = 5e-4):
self.X = torch.tensor(X, dtype = torch.double)
self.Y = torch.tensor(Y, dtype = torch.double)
self.dim = dim
self.lbd = lbd
def f(self, W):
W_torch = torch.tensor(W, dtype = torch.double, requires_grad = True)
val = - torch.mean(self.Y * torch.log(1 / (1 + (torch.exp(-torch.matmul(self.X, W_torch)))) + 1e-10) \
+ (1 - self.Y) * torch.log( 1e-10 + 1 - (1 / (1 + torch.exp(-torch.matmul(self.X, W_torch)))))) \
+ 0.5 * self.lbd * torch.sum(W_torch * W_torch)
# val = - torch.mean(self.Y * (1 / (1 + (torch.exp(-torch.matmul(self.X, W_torch))))) \
# + (1 - self.Y) * (1 - (1 / (1 + torch.exp(-torch.matmul(self.X, W_torch)))))) \
# + 0.5 * self.lbd * torch.sum(W_torch * W_torch)
return val.item()
def g(self, W):
W_torch = torch.tensor(W, dtype = torch.double, requires_grad = True)
val = - torch.mean(self.Y * torch.log(1e-10 + 1 / (1 + (torch.exp(-torch.matmul(self.X, W_torch))))) \
+ (1 - self.Y) * torch.log(1e-10 + 1 - (1 / (1 + torch.exp(-torch.matmul(self.X, W_torch)))))) \
+ 0.5 * self.lbd * torch.sum(W_torch * W_torch)
# val = - torch.mean(self.Y * (1 / (1 + (torch.exp(-torch.matmul(self.X, W_torch))))) \
# + (1 - self.Y) * (1 - (1 / (1 + torch.exp(-torch.matmul(self.X, W_torch)))))) \
# + 0.5 * self.lbd * torch.sum(W_torch * W_torch)
val.backward()
return W_torch.grad.data.numpy()
class Ackley(object):
"""doc for Ackley function"""
def __init__(self, dim = 2):
self.dim = dim
def f(self, x):
x_ = x[0]
y_ = x[1]
val = -20 * np.exp(-0.2 * np.sqrt(0.5 * (x_ ** 2 + y_ ** 2))) \
- np.exp(0.5 * (np.cos(2 * math.pi * x_) + np.cos(2 * y_ * math.pi))) + np.exp(1) + 20
return val
def g(self, x):
X_torch = torch.tensor(x, dtype = torch.float, requires_grad = True)
x = torch.sum(X_torch * torch.tensor([1,0], dtype = torch.float))
y = torch.sum(X_torch * torch.tensor([0,1], dtype = torch.float))
val = -20 * torch.exp(-0.2 * torch.sqrt(0.5 * torch.sum(X_torch ** 2))) - \
torch.exp(0.5 * (torch.cos(2 * math.pi * x) + torch.cos(2 * math.pi * y))) + np.exp(1) + 20
val.backward()
return X_torch.grad.data.numpy()
class NeuralNet(object):
"""docstring for NeuralNet"""
def __init__(self, dim, X, Y, d=2, h=2, p=2, lamda=.0005):
super(NeuralNet, self).__init__()
self.dim = dim
self.X = torch.tensor(X, dtype=torch.double)
self.Y = torch.tensor(Y, dtype=torch.long)
self.arch = {'d' : d, 'h' : h, 'p' : p, 'lamda' : lamda} # network architecture parameters
def f(self, param):
param = torch.tensor(param, dtype=torch.double, requires_grad=True)
d, h, p, lamda = self.arch['d'], self.arch['h'], self.arch['p'], self.arch['lamda']
W = param[0 : h*d].view(h, d)
b = param[h*d : h*d+h]
U = param[h*d+h : h*d+h+p*h].view(p, h)
c = param[h*d+h+p*h : ]
X, Y = self.X, self.Y
fc1 = F.relu(torch.matmul(X, W) + b)
temp = torch.matmul(fc1, U) + c
temp = temp - torch.mean(temp)
fc2 = torch.exp(temp)
numerator = fc2.gather(1, Y.view(-1, 1)).squeeze()
val = -torch.mean(torch.log(1e-6 + numerator / torch.sum(fc2, dim=1)))
reg = (lamda / 2) * (torch.norm(W) ** 2 + torch.norm(U) ** 2)
loss = val + reg
return loss.item()
def g(self, param):
param = torch.tensor(param, dtype=torch.double, requires_grad=True)
d, h, p, lamda = self.arch['d'], self.arch['h'], self.arch['p'], self.arch['lamda']
W = param[0 : h*d].view(h, d)
b = param[h*d : h*d+h]
U = param[h*d+h : h*d+h+p*h].view(p, h)
c = param[h*d+h+p*h : ]
X, Y = self.X, self.Y
fc1 = F.relu(torch.matmul(X, W) + b)
temp = torch.matmul(fc1, U) + c
temp = temp - torch.mean(temp)
fc2 = torch.exp(temp)
numerator = fc2.gather(1, Y.view(-1, 1)).squeeze()
val = -torch.mean(torch.log(1e-6 + numerator / torch.sum(fc2, dim=1)))
# print('val:', val)
reg = (lamda / 2) * (torch.norm(W) ** 2 + torch.norm(U) ** 2)
loss = val + reg
# print('loss:', loss.data)
loss.backward()
# print('grad:', param.grad)
return param.grad.data.numpy()
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 23 09:58:01 2018
@author: yufei
"""
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import random
from collections import deque
from torch_networks import AC_v_fc_network, CAC_a_fc_network, CAC_a_sigma_fc_network
from helper_functions import SlidingMemory, PERMemory
import warnings
warnings.simplefilter("error", RuntimeWarning)
class PPO():
"""doc for ppo"""
def __init__(self, state_dim, action_dim, action_low = -1.0, action_high = 1.0,
train_batch_size = 32, gamma = 0.99, actor_lr = 1e-4, critic_lr = 1e-3, lam = 0.95,
tau = 0.1, eps = 0.2, update_epoach = 10, trajectory_number = 10):
self.train_batch_size = train_batch_size
self.gamma, self.actor_lr, self.critic_lr = gamma, actor_lr, critic_lr
self.global_step = 0
self.tau, self.eps, self.lam = tau, eps, lam
self.state_dim, self.action_dim = state_dim, action_dim
#self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.device = 'cpu'
self.action_low, self.action_high = action_low, action_high
self.actor_policy_net = CAC_a_fc_network(state_dim, action_dim, action_low, action_high).to(self.device)
self.actor_target_net = CAC_a_fc_network(state_dim, action_dim, action_low, action_high).to(self.device)
# self.actor_policy_net = CAC_a_sigma_fc_network(state_dim, action_dim, action_low, action_high).to(self.device)
# self.actor_target_net = CAC_a_sigma_fc_network(state_dim, action_dim, action_low, action_high).to(self.device)
#self.critic_policy_net = AC_v_fc_network(state_dim).to(self.device)
#self.critic_target_net = AC_v_fc_network(state_dim).to(self.device)
self.critic_net = AC_v_fc_network(state_dim).to(self.device)
self.actor_optimizer = optim.Adam(self.actor_policy_net.parameters(), self.actor_lr)
# self.critic_optimizer = optim.Adam(self.critic_policy_net.parameters(), self.critic_lr)
self.critic_optimizer = optim.Adam(self.critic_net.parameters(), self.critic_lr)
self.hard_update(self.actor_target_net, self.actor_policy_net)
# self.hard_update(self.critic_target_net, self.critic_policy_net)
self.update_epoach = update_epoach
self.trajectory_number = trajectory_number
self.trajectories = [[] for i in range(self.trajectory_number)]
self.trajectory_pointer = 0
self.critic_net.apply(self._weight_init)
self.actor_policy_net.apply(self._weight_init)
def soft_update(self, target, source, tau):
for target_param, param in zip(target.parameters(), source.parameters()):
target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau)
def hard_update(self, target, source):
for target_param, param in zip(target.parameters(), source.parameters()):
target_param.data.copy_(param.data)
def _weight_init(self,m):
if type(m) == nn.Linear:
torch.nn.init.xavier_uniform_(m.weight)
torch.nn.init.constant_(m.bias, 0.01)
# the fake training process, accmulate trajectories, keeping the API to be the same among different algorithms
def train(self, pre_state, action, reward, next_state, if_end):
# collect trajactories
self.trajectories[self.trajectory_pointer].append([pre_state, action, reward, next_state, if_end])
if if_end:
self.trajectory_pointer += 1
if self.trajectory_pointer == self.trajectory_number:
self.__train()
self.trajectory_pointer = 0
for i in range(self.trajectory_number):
self.trajectories[i] = []
# the true training process
# trajectories is a list of trajectory, where each trajectory is a list of [s,a,r,s',if_end] tuples
def __train(self):
trajectories = self.trajectories
print("train epoach!")
self.hard_update(self.actor_target_net, self.actor_policy_net)
advantage_mem = []
for traj in trajectories:
states = [x[0] for x in traj]
rewards = np.array([x[2] for x in traj])
length = len(traj)
states = torch.tensor(states, dtype = torch.float, device = self.device)
with torch.no_grad():
states_values = self.critic_net(states).detach().numpy().reshape(-1, 1)
final_next_state = torch.tensor(traj[-1][-2], dtype = torch.float)
vs = self.critic_net(final_next_state).detach().numpy()
ret = []
for r in rewards[::-1]:
vs = r + self.gamma * vs
ret.append(vs)
ret.reverse()
ret = np.array(ret)
advantages = ret - states_values
advantage_mem = [(traj[i][0], traj[i][1], advantages[i], ret[i]) for i in range(length)]
# deltas = self.gamma * states_values[1:] + rewards[:-1] - states_values[:-1]
# for i in range(length - 1):
# # gammas = np.array([self.gamma ** x for x in range(length -1 - i)])
# # lamdas = np.array([self.lam ** x for x in range(length - 1 - i)])
# # gae_advantage = np.sum(gammas * lamdas * deltas[i:])
# ret[i] = np.sum(gammas * rewards[i:-1]) + states_values[-1] * self.gamma * gammas[-1]
# advantage_mem.append((traj[i][0], traj[i][1], gae_advantage, ret))
print('----------advantage memory built over----------')
for _ in range(self.update_epoach):
batch = random.sample(advantage_mem, self.train_batch_size)
states_batch = torch.tensor([x[0] for x in batch], dtype = torch.float, device = self.device).view(self.train_batch_size,-1)
action_batch = torch.tensor([x[1] for x in batch], dtype = torch.float, device = self.device).view(self.train_batch_size,-1)
advantage = torch.tensor([x[2] for x in batch], dtype = torch.float)
advantage = (advantage - torch.mean(advantage)) / (torch.std(advantage) + 1e-5)
old_prob = torch.sum(self.actor_target_net(states_batch).log_prob(action_batch), dim = 1)
print("old_prob is", old_prob)
new_prob = torch.sum(self.actor_policy_net(states_batch).log_prob(action_batch), dim = 1)
aloss1 = torch.exp(new_prob - old_prob) * advantage
aloss2 = torch.clamp(torch.exp(new_prob - old_prob), 1 - self.eps, 1 + self.eps) * advantage
aloss = - torch.min(aloss1, aloss2)
aloss = torch.mean(aloss)
self.actor_optimizer.zero_grad()
aloss.backward()
torch.nn.utils.clip_grad_norm_(self.actor_policy_net.parameters(),1)
self.actor_optimizer.step()
self.critic_optimizer.zero_grad()
return_batch = torch.tensor([x[-1] for x in batch], dtype = torch.float, device = self.device).view(self.train_batch_size,-1)
value_pred = self.critic_net(states_batch)
closs = (value_pred - return_batch)**2
closs = torch.mean(closs)
closs.backward()
torch.nn.utils.clip_grad_norm_(self.critic_net.parameters(),1)
self.critic_optimizer.step()
# use the policy net to choose the action with the highest Q value
def action(self, s, sample = True): # use flag to suit other models' action interface
s = torch.tensor(s, dtype=torch.float, device = self.device).unsqueeze(0)
with torch.no_grad():
m = self.actor_policy_net(s)
a = np.clip(m.sample(), self.action_low, self.action_high) if sample else m.mean
return a.numpy()[0]
<file_sep>import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import random
from collections import deque
from torch_networks import DQN_fc_network, DQN_dueling_network
from helper_functions import SlidingMemory, PERMemory
class DQN():
def __init__(self, state_dim, action_dim, mem_size = 10000, train_batch_size = 32,
gamma = 0.99, lr = 1e-3, tau = 0.1,
if_dueling = False, if_PER = False, load_path = None ):
self.mem_size, self.train_batch_size = mem_size, train_batch_size
self.gamma, self.lr = gamma, lr
self.global_step = 0
self.tau = tau
self.state_dim, self.action_dim = state_dim, action_dim
self.if_PER = if_PER
self.replay_mem = PERMemory(mem_size) if if_PER else SlidingMemory(mem_size)
self.policy_net = DQN_fc_network(state_dim, action_dim,1)
self.target_net = DQN_fc_network(state_dim, action_dim,1)
self.epsilon, self.min_eps = 0.9, 0.4
if load_path is not None:
self.policy_net.load_state_dict(torch.load(load_path))
if if_dueling:
self.policy_net = DQN_dueling_network(state_dim, action_dim,1)
self.target_net = DQN_dueling_network(state_dim, action_dim,1)
self.optimizer = optim.RMSprop(self.policy_net.parameters(), self.lr)
self.hard_update(self.target_net, self.policy_net)
def soft_update(self, target, source, tau):
for target_param, param in zip(target.parameters(), source.parameters()):
target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau)
def hard_update(self, target, source):
for target_param, param in zip(target.parameters(), source.parameters()):
target_param.data.copy_(param.data)
# training process
def train(self, pre_state, action, reward, next_state, if_end):
self.replay_mem.add(pre_state, action, reward, next_state, if_end)
if self.replay_mem.num() < self.mem_size:
return
# sample $self.train_batch_size$ samples from the replay memory, and use them to train
if not self.if_PER:
train_batch = self.replay_mem.sample(self.train_batch_size)
else:
train_batch, idx_batch, weight_batch = self.replay_mem.sample(self.train_batch_size)
weight_batch = torch.tensor(weight_batch, dtype = torch.float).unsqueeze(1)
# adjust dtype to suit the gym default dtype
pre_state_batch = torch.tensor([x[0] for x in train_batch], dtype=torch.float)
action_batch = torch.tensor([x[1] for x in train_batch], dtype = torch.long) # dtype = long for gater
reward_batch = torch.tensor([x[2] for x in train_batch], dtype=torch.float).view(self.train_batch_size,1)
next_state_batch = torch.tensor([x[3] for x in train_batch], dtype=torch.float)
if_end = [x[4] for x in train_batch]
if_end = torch.tensor(np.array(if_end).astype(float), dtype=torch.float).view(self.train_batch_size,1)
# use the target_Q_network to get the target_Q_value
# torch.max[0] gives the max value, torch.max[1] gives the argmax index
# vanilla dqn
#q_target_ = self.target_net(next_state_batch).max(1)[0].detach() # detach to not bother the gradient
#q_target_ = q_target_.view(self.train_batch_size,1)
# double dqn
with torch.no_grad():
next_best_action = self.policy_net(next_state_batch).max(1)[1].detach()
q_target_ = self.target_net(next_state_batch).gather(1, next_best_action.unsqueeze(1))
q_target_ = q_target_.view(self.train_batch_size,1).detach()
q_target = self.gamma * q_target_ * ( 1 - if_end) + reward_batch
# unsqueeze to make gather happy
q_pred = self.policy_net(pre_state_batch).gather(1, action_batch.unsqueeze(1))
if self.if_PER:
TD_error_batch = np.abs(q_target.numpy() - q_pred.detach().numpy())
self.replay_mem.update(idx_batch, TD_error_batch)
self.optimizer.zero_grad()
loss = (q_pred - q_target) ** 2
if self.if_PER:
loss *= weight_batch
loss = torch.mean(loss)
loss.backward()
torch.nn.utils.clip_grad_norm_(self.policy_net.parameters(), 1)
self.optimizer.step()
# update target network
self.soft_update(self.target_net, self.policy_net, self.tau)
self.epsilon = max(self.epsilon * 0.99995, 0.22)
# store the (pre_s, action, reward, next_state, if_end) tuples in the replay memory
def perceive(self, pre_s, action, reward, next_state, if_end):
self.replay_mem.append([pre_s, action, reward, next_state, if_end])
if len(self.replay_mem) > self.mem_size:
self.replay_mem.popleft()
# give a state and action, return the action value
def get_value(self, s, a):
s = torch.tensor(s,dtype=torch.float)
with torch.no_grad():
val = self.policy_net(s.unsqueeze(0)).gather(1, torch.tensor(a,dtype = torch.long).unsqueeze(1)).view(1,1)
return val.item()
def save_model(self, save_path = './model/dqn_params'):
torch.save(self.policy_net.state_dict(), save_path)
# use the policy net to choose the action with the highest Q value
def action(self, s, epsilon_greedy = True):
p = random.random()
if epsilon_greedy and p <= self.epsilon:
return random.randint(0, self.action_dim - 1)
else:
s = torch.tensor(s, dtype=torch.float).unsqueeze(0)
with torch.no_grad():
# torch.max gives max value, torch.max[1] gives argmax index
action = self.policy_net(s).max(dim=1)[1].view(1,1) # use view for later item
return action.item() # use item() to get the vanilla number instead of a tensor
# choose an action according to the epsilon-greedy method
def e_action(self, s):
p = random.random()
if p <= self.epsilon:
return random.randint(0, self.action_dim - 1)
else:
return self.action(s)
<file_sep>import gym
import torch
import numpy as np
import argparse
import sys
from helper_functions import *
from DQN_torch import DQN
from NAF_torch import NAF
from DDPG_torch import DDPG
from AC_torch import AC
from CAC_torch import CAC
from PPO_torch import PPO
import matplotlib.pyplot as plt
import time
# env = gym.make('MountainCarContinuous-v0')
# env = gym.make('MountainCar-v0')
# env = gym.make('CartPole-v0')
# env = gym.make('LunarLanderContinuous-v2')
# env = gym.make('LunarLander-v2')
env = gym.make('Pendulum-v0')
argparser = argparse.ArgumentParser(sys.argv[0])
## parameters
argparser.add_argument('--lr', type=float, default=1e-3)
argparser.add_argument('--replay_size', type=int, default=20000)
argparser.add_argument('--batch_size', type=float, default=64)
argparser.add_argument('--gamma', type=float, default=0.99)
argparser.add_argument('--tau', type=float, default=0.1)
argparser.add_argument('--noise_type', type = str, default = 'gauss')
argparser.add_argument('--agent', type = str, default = 'ddpg')
##
args = argparser.parse_args()
Replay_mem_size = args.replay_size
Train_batch_size = args.batch_size
Actor_Learning_rate = args.lr
Critic_Learning_rate = args.lr
Gamma = args.gamma
tau = args.tau
State_dim = env.observation_space.shape[0]
print(State_dim)
Action_dim = env.action_space.shape[0]
# Action_dim = env.action_space.n
# Action_dim = dim
print(Action_dim)
print('----action range---')
print(env.action_space.high)
print(env.action_space.low)
action_low = env.action_space.low[0].astype(float)
action_high = env.action_space.high[0].astype(float)
ounoise = OUNoise(Action_dim, 8, 3, 0.9995)
gsnoise = GaussNoise(8, 0.5, 0.99995)
noise = gsnoise if args.noise_type == 'gauss' else ounoise
def play(agent, num_epoch, Epoch_step, show = False):
acc_reward = 0
for epoch in range(num_epoch):
pre_state = env.reset()
for step in range(Epoch_step):
if show:
env.render()
# action = agent.action(state_featurize.transfer(pre_state), False)
action = agent.action(pre_state, False)
next_state, reward, done, _ = env.step(action)
acc_reward += reward
if done or step == Epoch_step - 1:
break
pre_state = next_state
return acc_reward / num_epoch
def train(agent, Train_epoch, Epoch_step, file_name = './res.dat'):
output_file = open(file_name, 'w')
for epoch in range(Train_epoch):
pre_state = env.reset()
acc_reward = 0
for step in range(Epoch_step):
action = agent.action(pre_state)
if action[0] != action[0]:
raise('nan error!')
next_state, reward, done, _ = env.step(action)
acc_reward += reward
# agent.train(state_featurize.transfer(pre_state), action, reward, state_featurize.transfer(next_state), done)
agent.train(pre_state, action, reward, next_state, done)
if done or step == Epoch_step - 1:
#print('episoid: ', epoch + 1, 'step: ', step + 1, ' reward is', acc_reward, file = output_file)
#print('episoid: ', epoch + 1, 'step: ', step + 1, ' reward is', acc_reward, )
print('episoid: ', epoch + 1, 'step: ', step + 1, ' reward: ', acc_reward)
break
pre_state = next_state
if epoch % 100 == 0 and epoch > 0:
avg_reward = play(agent, 10, 300, not True)
print('--------------episode ', epoch, 'avg_reward: ', avg_reward, '---------------', file = output_file)
print('--------------episode ', epoch, 'avg_reward: ', avg_reward, '---------------')
if avg_reward > -5:
print('----- using ', epoch, ' epochs')
#agent.save_model()
break
return agent
naf = NAF(State_dim, Action_dim, Replay_mem_size, Train_batch_size,
Gamma, Critic_Learning_rate, action_low, action_high, tau, noise, False, False)
dqn = DQN(State_dim, Action_dim, Replay_mem_size, Train_batch_size,\
Gamma, 1e-4, 0.1, True, True)
ddpg = DDPG(State_dim, Action_dim, Replay_mem_size, Train_batch_size,
Gamma, Actor_Learning_rate, Critic_Learning_rate, action_low, action_high, tau, noise, False)
ac = AC(State_dim, Action_dim, Replay_mem_size, Train_batch_size,
Gamma, 1e-3, 1e-3, 0.1)
cac = CAC(State_dim, Action_dim, Replay_mem_size, Train_batch_size,
Gamma, Actor_Learning_rate, Critic_Learning_rate, tau, action_low, action_high, 3, False)
cppo = PPO(State_dim, Action_dim,-1.0, 1.0, 2000, 64, Gamma, 1e-4, 1e-4, 0.3, 0.2, 100)
# agent = train(naf, 10000,300)
# agentnaf = train(naf, 3000, 300, r'./record/naf_lunar.txt')
# agentppo = train(cppo, 3000, 300, r'./record/ppo_lunar.txt')
# agentnaf_addloss = train(naf_addloss, 1500, 300, r'./record/naf_addloss_lunar.txt')
# agentddpg = train(ddpg, 3000, 300, r'./record/ddpg_lunar_PER.txt')
# agentnaf_addloss = train(naf_addloss, 1500, 300, r'D:\study\rl by <NAME>\Trainrecord\NAF_addloss.txt')
# agentnaf_ddpg = train(ddpg, 1500, 300, r'D:\study\rl by <NAME>\Trainrecord\ddpg_lunar.txt')
# agentac = train(ac, 3000, 300, r'./record/ac_lunar_land_continues.txt')
# agentcac = train(cac, 3000, 300, r'./record/cac_lunar_land_continues-PER.txt')
# agentdqn = train(dqn, 3000, 300, r'./record/dqn_lunar_dueling_PER_1e-3_0.3.txt')
if args.agent == 'ddpg':
agent = train(ddpg, 10000, 200)
elif args.agent == 'naf':
agent = train(naf, 10000, 200)
elif args.agent == 'cac':
agent = train(cac, 10000, 200)
#print('after train')
#print(play(agentnaf,300, False))
#print(play(agentnaf_addloss,300, False))
<file_sep>import numpy as np
def LogisticDataset(dim, num = 50, seed = 666):
""" generate the dataset for logistic objective
X has $num$ instances, and Y is the corresponding label for X.
Every instance is drawn from one of two multi-variate Gaussians, with half from each.
Instances from the same Gaussian are assigned the same label, and instances from different Gaussians are assigned different labels.
Parameters:
----------
dim: the dimension of the generated data.
num: number of instances in the generated dataset
seed: fix the random seed for the numpy.
Returns:
----------
X: the generated dataset
Y: the corresponding label of data X.
"""
X = np.zeros((num, dim))
np.random.seed(seed)
co_var = np.random.rand(dim,dim) * 2
co_var = co_var.dot(co_var.T)
mean = np.random.rand(dim) * 5
X[:int(num / 2),:] = np.random.multivariate_normal(mean, co_var, size = int(num / 2))
np.random.seed(seed * 2)
co_var = np.random.rand(dim,dim) * 2
co_var = co_var.dot(co_var.T)
mean = np.random.rand(dim) * 5
X[int(num / 2):,:] = np.random.multivariate_normal(mean, co_var, size = int(num / 2))
X = np.concatenate((X, np.ones((num, 1))), axis = 1)
Y = np.zeros(num)
Y[:int(num / 2)] = 1
np.random.seed(seed * 3)
perm = np.random.permutation(num)
X = X[perm]
Y = Y[perm]
# print(X.shape, Y.shape)
return X, Y
def NeuralNetDataset(dim, num = 100, seed = 233):
""" generate the dataset for neural-net objective
X has $num$ instances, and Y is the corresponding label for X.
Every instance is drawn from one of two multi-variate Gaussians, with half from each.
Instances from the same Gaussian are assigned the same label, and instances from different Gaussians are assigned different labels.
Parameters:
----------
dim: the dimension of the generated data.
num: number of instances in the generated dataset
seed: fix the random seed for the numpy.
Returns:
----------
X: the generated dataset
Y: the corresponding label of data X.
"""
def produce(seed):
np.random.seed(seed)
co_var = np.random.rand(dim, dim)
co_var = co_var.dot(co_var.T)
mean = np.random.rand(dim)
return mean, co_var
X = np.zeros((num, dim))
size = num // 4
mean, co_var = produce(seed)
X[:size,:] = np.random.multivariate_normal(mean, co_var, size=size)
mean, co_var = produce(seed * 2)
X[size:2*size,:] = np.random.multivariate_normal(mean, co_var, size=size)
mean, co_var = produce(seed * 4)
X[2*size:3*size,:] = np.random.multivariate_normal(mean, co_var, size=size)
mean, co_var = produce(seed * 8)
X[3*size:,:] = np.random.multivariate_normal(mean, co_var, size=size)
Y = np.zeros(num)
Y[2*size:3*size] = 1
np.random.seed(seed * 16)
perm = np.random.permutation(num)
X = X[perm]
Y = Y[perm]
return X, Y
if __name__ == '__main__':
LogisticDataset(dim = 3)
<file_sep>This is the course project for Reinforcement Learning in PKU.
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sat Apr 7 16:43:56 2018
@author: Wangyf
"""
import sklearn.pipeline
import sklearn.preprocessing
import numpy as np
import random
import matplotlib.pyplot as plt
import objfunc as obj
from sklearn.kernel_approximation import RBFSampler
from collections import deque
from dataset import LogisticDataset, NeuralNetDataset
obj_list = ['ackley', 'logistic', 'neural']
init_list = ['[7 8]', '[2.33 6.66]', '[ 0.01 10. ]', '[0. 0.08333333 0.16666667 0.25 0.33333333 0.41666667? 0.5 0.58333333 0.66666667 0.75 0.83333333 0.91666667]']
obj_idx = 1
init_idx = 3
filelist = ["./data/sd_%s3.txt"%(obj_list[obj_idx]),
"./data/mom_%s3.txt"%(obj_list[obj_idx]),
"./data/cg_%s3.txt"%(obj_list[obj_idx]),
"./data/bfgs_%s3.txt"%(obj_list[obj_idx]),
"./data/general_ddpg_logistic3.txt"]
fig = 'value'
dim = 1
X, Y = LogisticDataset(dim=dim, seed=23)
dim += 1
init_point = np.arange(dim) / dim
fun = obj.Logistic(dim, X, Y)
def dataprocessing(filename):
avgnum = 7
linecnt = 0
linetot = avgnum * 2
n_iter = 50
mean = np.zeros(n_iter + 1)
std = np.zeros(n_iter + 1)
mean[0] = fun.f(init_point)
# traj = []
if 'sd' in filename or 'cg' in filename or 'bfgs' in filename or 'mom' in filename:
with open(filename, 'r') as file:
for line in file:
linecnt += 1
if linecnt % 2 == 1:
mean[1:] = np.array(line.split(' '), dtype=float)
else:
traj = np.array(line.replace(',', ' ').split(' ')[:-1], dtype=float)
traj = traj.reshape((-1, dim)).T
return mean, std, traj
else:
with open(filename, 'r') as file:
for line in file:
linecnt += 1
if linecnt <= linetot - avgnum * 2:
continue
if linecnt % 2 == 1:
value = np.array(line.split(' '), dtype=float)
mean[1:] = mean[1:] + value
std[1:] = std[1:] + value ** 2
else:
traj = np.array(line.replace(',', ' ').split(' ')[:-1], dtype=float)
traj = traj.reshape((-1, dim)).T
mean[1:] = mean[1:] / avgnum
std[1:] = std[1:] / avgnum - mean[1:] ** 2
std[np.abs(std) < 1e-8] = 0
std = np.sqrt(std)
# print('mean = ', mean, 'std = ', std, 'traj = ', traj)
return mean, std, traj
def plotvalue(filelist=None):
if type(filelist) == list:
values = []
for file in filelist:
values.append(dataprocessing(file))
if filelist is None:
values = np.array([np.sin(np.linspace(0, np.pi, 50)),
np.cos(np.linspace(0, np.pi, 50)),
np.sqrt(np.linspace(0, np.pi, 50))])
color = ['blue', 'brown', "red", "indigo", "green", "green"]
label = ['Gradient descent', 'Momentum', 'Conjugate gradient',
'L-BFGS algorithm', 'LTO with OU']
for k in range(len(label)):
n_iter = len(values[k][0])
x = np.arange(0, n_iter)
mean, std = values[k][0], values[k][1]
y_lower = mean - std * .5
y_upper = mean + std * .5
plt.plot(x, mean, label=label[k], color=color[k])
if k >= 4:
plt.fill_between(x, y_lower, y_upper, color=color[k], alpha=.35, linewidth=0)
plt.xlabel('Iteration')
plt.ylabel('Objective value')
legend = plt.legend(loc='upper right', shadow=True)#, fontsize='large')
plt.xticks(range(0, n_iter + 1, n_iter // 10))
# plt.show()
plt.savefig('./fig/logistic3_val.png')
def plottraj(filelist=None):
if type(filelist) == list:
values = []
for file in filelist:
values.append(dataprocessing(file))
if filelist is None:
theta = np.arange(0, 2 * np.pi, np.pi / 50)
values = np.array([np.cos(theta), np.sin(theta)])
color = ['blue', 'brown', "red", "indigo", "green", "green"]
label = ['Gradient descent', 'Momentum', 'Conjugate gradient',
'L-BFGS algorithm', 'LTO with OU']
for k in range(len(label)):
n_iter = 50
traj = values[k][2]
x = traj[0, :-1]
y = traj[1, :-1]
# print(traj.shape)
if k == 0:
# Contour plot
X = np.linspace(-1.8, 3.8, n_iter)
Y = np.linspace(-4.8, 0.8, n_iter)
X, Y = np.meshgrid(X, Y)
Z = np.zeros((n_iter, n_iter))
for i in range(n_iter):
for j in range(n_iter):
Z[i][j] = fun.f(np.array([X[i][j], Y[i][j]]))
plt.contourf(X, Y, Z, 50, cmap='GnBu')
plt.colorbar()
# Trajectory plot
u = traj[0, 1:] - traj[0, :-1]
v = traj[1, 1:] - traj[1, :-1]
# print(traj)
# print(u, v)
q = plt.quiver(x, y, u, v, units='xy', scale=1, color=color[k], headwidth=2)
plt.quiverkey(q, X = .13 + .52 * (k % 2), Y = 1.13 - .05 * (k // 2),
U = .6, label=label[k], labelpos='E')
# Show plot
plt.axis('equal')
# plt.xticks(np.arange(np.min(x) - 1, np.max(x) + 1))
# plt.yticks(np.arange(np.min(y) - 1, np.max(y) + 1))
plt.show()
# plt.savefig('./fig/logistic3_traj.png')
class Featurize_state():
def __init__(self, env, no_change = False):
self.no_change = no_change
if no_change == True:
self.After_featurize_state_dim = env.observation_space.shape[0]
return
observation_examples = np.array([env.observation_space.sample() for x in range(10000)])
self.scaler = sklearn.preprocessing.StandardScaler()
self.scaler.fit(observation_examples)
# Used to converte a state to a featurizes represenation.
# We use RBF kernels with different variances to cover different parts of the space
self.featurizer = sklearn.pipeline.FeatureUnion([
("rbf1", RBFSampler(gamma=5.0, n_components=100)),
("rbf2", RBFSampler(gamma=2.0, n_components=100)),
("rbf3", RBFSampler(gamma=1.0, n_components=100)),
("rbf4", RBFSampler(gamma=0.5, n_components=100))
])
self.featurizer.fit(observation_examples)
self.After_featurize_state_dim = 400
def get_featurized_state_dim(self):
return self.After_featurize_state_dim
def transfer(self, state):
if self.no_change:
return state
scaled = self.scaler.transform([state])
featurized = self.featurizer.transform(scaled)
return featurized[0]
#return state
# from https://github.com/songrotek/DDPG/blob/master/ou_noise.py
class OUNoise:
def __init__(self, action_dimension, initial_scale = 1, final_scale = 0.2, decay = 0.9995, mu=0, theta=0.15, sigma=0.2):
self.action_dimension = action_dimension
self.scale = initial_scale
self.final_scale = final_scale
self.decay = decay
self.mu = mu
self.theta = theta
self.sigma = sigma
self.state = np.ones(self.action_dimension) * self.mu
def decaynoise(self):
self.scale *= self.decay
self.scale = max(self.scale, self.final_scale)
def noise(self):
x = self.state
dx = self.theta * (self.mu - x) + self.sigma * np.random.randn(len(x))
self.state = x + dx
res = self.state * self.scale
return res[0]
def noisescale(self):
return self.scale
class GaussNoise():
def __init__(self, initial_var = 10, final_var = 0, decay = 0.995):
self.var = initial_var
self.final_var = final_var
self.decay = decay
def decaynoise(self):
self.var *= self.decay
self.var = max(self.final_var, self.var)
def noise(self, var = None):
return np.random.normal(0, self.var) if var is None else np.random.normal(0, var)
def noisescale(self):
return self.var
class SlidingMemory():
def __init__(self, mem_size):
self.mem = deque()
self.mem_size = mem_size
def add(self, state, action, reward, next_state, if_end):
self.mem.append([state, action, reward, next_state, if_end])
if len(self.mem) > self.mem_size:
self.mem.popleft()
def num(self):
return len(self.mem)
def sample(self, batch_size):
return random.sample(self.mem, batch_size)
def clear(self):
self.mem.clear()
class SumTree:
write = 0
def __init__(self, capacity):
self.capacity = capacity
self.tree = np.zeros( 2*capacity - 1 )
self.data = np.zeros( capacity, dtype=object )
self.number = 0
def _propagate(self, idx, change):
parent = (idx - 1) // 2
self.tree[parent] += change
if parent != 0:
self._propagate(parent, change)
def _retrieve(self, idx, s):
if idx >= self.capacity - 1:
return idx
left = 2 * idx + 1
right = left + 1
if s <= self.tree[left]:
return self._retrieve(left, s)
else:
return self._retrieve(right, s-self.tree[left])
def total(self):
return self.tree[0]
def add(self, data, p):
idx = self.write + self.capacity - 1
self.data[self.write] = data
self.update(idx, p)
self.write += 1
if self.write >= self.capacity:
self.write = 0
self.number = min(self.number + 1, self.capacity)
def update(self, idx, p):
change = p - self.tree[idx]
self.tree[idx] = p
self._propagate(idx, change)
def get(self, s):
idx = self._retrieve(0, s)
dataIdx = idx - self.capacity + 1
return (idx, self.tree[idx], self.data[dataIdx])
def num(self):
return self.number
class PERMemory():
def __init__(self, mem_size, alpha = 0.8, beta = 0.8, eps = 1e-2):
self.alpha, self.beta, self.eps = alpha, beta, eps
self.mem_size = mem_size
self.mem = SumTree(mem_size)
def add(self, state, action, reward, next_state, if_end):
# here use reward for initial p, instead of maximum for initial p
p = 1000
self.mem.add([state, action, reward, next_state, if_end], p)
def update(self, batch_idx, batch_td_error):
for idx, error in zip(batch_idx, batch_td_error):
p = (error + self.eps) ** self.alpha
self.mem.update(idx, p)
def num(self):
return self.mem.num()
def sample(self, batch_size):
data_batch = []
idx_batch = []
p_batch = []
segment = self.mem.total() / batch_size
#print(self.mem.total())
#print(segment * batch_size)
for i in range(batch_size):
a = segment * i
b = segment * (i + 1)
s = random.uniform(a, b)
#print(s < self.mem.total())
idx, p, data = self.mem.get(s)
data_batch.append(data)
idx_batch.append(idx)
p_batch.append(p)
p_batch = (1.0/ np.array(p_batch) /self.mem_size) ** self.beta
p_batch /= max(p_batch)
self.beta = min(self.beta * 1.00005, 1)
return (data_batch, idx_batch, p_batch)
if __name__ == '__main__':
if fig == 'value':
plotvalue(filelist)
else:
plottraj(filelist)
|
150362cc8d5828fc9a978c487cb6bbafef25e198
|
[
"Markdown",
"Python"
] | 14 |
Python
|
yufeiwang63/RLproject
|
5669e071ce851c5ab2dacf255cc07927bbbdae2c
|
b92819546ff42806f0284796a5d98532cad625f0
|
refs/heads/master
|
<repo_name>Vidya1627/MusicPlayer<file_sep>/screens/Home.js
import React from 'react';
import ReactNative from 'react-native';
import { StyleSheet, Text, View, AppRegistry } from 'react-native';
import Header from './../components/Header.js';
import AlbumList from './../components/AlbumList.js';
class Home extends React.Component {
render() {
return (
<View style={{ flex: 1}}>
<Header headerText={'PlayList'} />
<AlbumList navigation={this.props.navigation} />
</View>
);
}
}
// const App = () => (
// <Text>Some Functional Component Text</Text>
// );
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default Home;
<file_sep>/App.js
import React from 'react';
import ReactNative from 'react-native';
import {createStackNavigator, createAppContainer, createDrawerNavigator} from 'react-navigation';
import { StyleSheet, Text, View, AppRegistry } from 'react-native';
import Header from './components/Header.js';
import AlbumList from './components/AlbumList.js';
import Home from './screens/Home.js';
import SongScreen from './screens/SongScreen.js';
const RootStack = createStackNavigator(
{
HomeScreen : Home,
SongScreen : SongScreen,
},
{
initialRouteName: 'HomeScreen',
}
);
const App = createAppContainer(RootStack);
export default App;
// export default class App extends React.Component {
// render() {
// return (
// <RootStack />
// );
// }
// }
// const App = () => (
// <Text>Some Functional Component Text</Text>
// );
// const styles = StyleSheet.create({
// container: {
// flex: 1,
// backgroundColor: '#fff',
// alignItems: 'center',
// justifyContent: 'center'
// }
// });
AppRegistry.registerComponent('albums', ()=>App);
// {*
// <Text>Open up App.js to start working on your app!</Text>
// <Text>Changes you make will automatically reload.</Text>
// <Text>Shake your phone to open the developer menu.</Text>
// *}
// <View style={styles.container}>
// </View>
<file_sep>/components/AlbumDetail.js
import React from 'react';
import { Text, View, Image, Linking } from 'react-native';
import Card from './Card';
import CardSection from './CardSection';
import Button from './Button';
import { ReactNativeAudioStreaming } from 'react-native-audio-stream';
var song = null;
var BASE_URL = "http://storage.googleapis.com/automotive-media/";
class AlbumDetail extends React.Component {
constructor() {
super();
this.state = {
playMessage : "Play"
};
}
playPauseSong() {
if (this.state.playMessage == "Play") {
ReactNativeAudioStreaming.play(BASE_URL + this.props.song.source, {});
this.setState({playMessage: "Pause"});
}
else {
ReactNativeAudioStreaming.pause();
this.setState({playMessage: "Play"});
}
}
render() {
return (
<Card>
<CardSection>
<View style={styles.thumbnailContainerStlye}>
<Image
style={styles.thumbnailStyle}
source={{ uri: BASE_URL + this.props.song.image }}
/>
</View>
<View>
<Text style={styles.headerTextStyle}>{this.props.song.title}</Text>
<Text>{this.props.song.artist}</Text>
</View>
</CardSection>
<CardSection>
<Image
style={styles.imageStyle}
source={{ uri: BASE_URL + this.props.song.image }}
/>
</CardSection>
<CardSection>
<Button onPress={() => this.playPauseSong()}>
{this.state.playMessage}
</Button>
<Button onPress={() => Linking.openURL(this.props.song.site)}>
View Online
</Button>
</CardSection>
</Card>
);
}
}
const styles = {
headerContentStyle: {
flexDirection: 'column',
justifyContent: 'space-around'
},
headerTextStyle: {
fontSize: 18
},
thumbnailStyle: {
height: 50,
width: 50
},
thumbnailContainerStlye: {
alignItems: 'center',
justifyContent: 'center',
marginLeft: 10,
marginRight: 10
},
imageStyle: {
height: 300,
width: null,
flex: 1
}
};
export default AlbumDetail;
<file_sep>/screens/SongScreen.js
import React from 'react';
import { Text, View, Image, Linking } from 'react-native';
import Card from './../components/Card';
import CardSection from './../components/CardSection';
import Button from './../components/Button';
import { ReactNativeAudioStreaming } from 'react-native-audio-stream';
var song = null;
var BASE_URL = "http://storage.googleapis.com/automotive-media/";
class SongScreen extends React.Component {
constructor() {
super();
this.state = {
playMessage : "Play"
};
}
playPauseSong(song) {
if (this.state.playMessage == "Play") {
ReactNativeAudioStreaming.play(BASE_URL + song.source, {});
this.setState({playMessage: "Pause"});
}
else {
ReactNativeAudioStreaming.pause();
this.setState({playMessage: "Play"});
}
}
render() {
const { params } = this.props.navigation.state;
return (
<Card>
<CardSection>
<View style={styles.thumbnailContainerStlye}>
<Image
style={styles.thumbnailStyle}
source={{ uri: BASE_URL + params.song.image }}
/>
</View>
<View>
<Text style={styles.headerTextStyle}>{params.song.title}</Text>
<Text>{params.song.artist}</Text>
</View>
</CardSection>
<CardSection>
<Image
style={styles.imageStyle}
source={{ uri: BASE_URL + params.song.image }}
/>
</CardSection>
<CardSection>
<Button onPress={() => this.playPauseSong(params.song)}>
{this.state.playMessage}
</Button>
<Button onPress={() => Linking.openURL(params.song.site)}>
View Online
</Button>
</CardSection>
</Card>
);
}
}
const styles = {
headerContentStyle: {
flexDirection: 'column',
justifyContent: 'space-around'
},
headerTextStyle: {
fontSize: 18
},
thumbnailStyle: {
height: 50,
width: 50
},
thumbnailContainerStlye: {
alignItems: 'center',
justifyContent: 'center',
marginLeft: 10,
marginRight: 10
},
imageStyle: {
height: 300,
width: null,
flex: 1
}
};
export default SongScreen;
<file_sep>/components/AlbumBrief.js
import React from 'react';
import { Text, View, Image, Linking } from 'react-native';
import Card from './Card';
import CardSection from './CardSection';
import ViewButton from './ViewButton';
var BASE_URL = "http://storage.googleapis.com/automotive-media/";
class AlbumBrief extends React.Component {
render() {
return (
<Card>
<ViewButton onPress={() => this.props.navigation.navigate('SongScreen', {
song: this.props.song
})} >
<CardSection>
<View style={styles.thumbnailContainerStlye}>
<Image
style={styles.thumbnailStyle}
source={{ uri: BASE_URL + this.props.song.image }}
/>
</View>
<View>
<Text style={styles.headerTextStyle}>{this.props.song.title}</Text>
<Text>{this.props.song.artist}</Text>
</View>
</CardSection>
</ViewButton>
</Card>
);
}
}
const styles = {
headerContentStyle: {
flexDirection: 'column',
},
headerTextStyle: {
fontSize: 18
},
thumbnailStyle: {
height: 50,
width: 50
},
thumbnailContainerStlye: {
alignItems: 'center',
justifyContent: 'center',
marginLeft: 10,
marginRight: 10
}
};
export default AlbumBrief;
|
a3c8a8b0eb0ffa67e5043a98df43578f651b4574
|
[
"JavaScript"
] | 5 |
JavaScript
|
Vidya1627/MusicPlayer
|
2172de0c42e9802760c5ef987e38c69c812931cf
|
31a71de17f79a71d432ffdc3fa045efefe53fce8
|
refs/heads/master
|
<file_sep># lookalike [](https://travis-ci.org/arpinum/lookalike)
**lookalike** is a simple object to object mapper.
## Installation
npm install lookalike --save-dev
## Usage
```javascript
// require the whole module...
let lookalike = require('lookalike');
// or specific parts
let pick = require('lookalike').pick;
```
## pick(sourceObject, [keys])
Creates an object based on `sourceObject` picking only `keys`.
`keys` can be:
* an array of key names as strings
* an array of single key objects to represent nested objects
* a mix of both
### Examples
```javascript
let source = {
firstName: 'John',
lastName: 'Doe'
};
let picked = pick(source, ['firstName']);
picked.should.deep.equal({firstName: 'John'});
```
```javascript
let source = {
address: {
postalCode: '33000',
city: 'Bordeaux'
}
};
let picked = pick(source, [{address: ['city']}]);
picked.should.deep.equal({address: {city: 'Bordeaux'}});
```
## License
[MIT](LICENSE)
<file_sep>'use strict';
module.exports = {
pick: require('./lib/pick')
};
<file_sep>'use strict';
let pick = require('./pick');
describe('The pick function', () => {
it('should only keep relevant keys of source object', () => {
let source = {
firstName: 'John',
lastName: 'Doe'
};
let picked = pick(source, ['firstName']);
picked.should.deep.equal({firstName: 'John'});
});
it('should even keep deep keys', () => {
let source = {
firstName: 'John',
lastName: 'Doe',
address: {
postalCode: '33000',
city: 'Bordeaux'
}
};
let picked = pick(source, ['firstName', {address: ['city']}]);
picked.should.deep.equal({firstName: 'John', address: {city: 'Bordeaux'}});
});
it('should not add not existing key in source object', () => {
let source = {
firstName: 'John',
address: {
postalCode: '33000',
city: 'Bordeaux'
}
};
let picked = pick(source, ['firstName', {address: ['not existing']}, {not: ['existing']}]);
picked.should.deep.equal({firstName: 'John', address: {}});
});
it('should even keep very deep keys', () => {
let source = {
a: {
b: {
c: {
d: 'please dont call me again',
e: 'keep me please'
}
}
}
};
let picked = pick(source, [{a: [{b: [{c: ['e']}]}]}]);
picked.should.deep.equal({a: {b: {c: {e: 'keep me please'}}}});
});
it('wont crash like a drunk otter if source object does not have a relevant key', () => {
let source = {
firstName: 'John',
lastName: 'Doe'
};
let picked = pick(source, ['firstName', 'birthDate']);
picked.should.deep.equal({firstName: 'John'});
});
it('should lament if keys are not an array', () => {
let source = {
address: {
postalCode: '33000',
city: 'Bordeaux'
}
};
let invalidPick = () => {
pick(source, [{address: {city: {code: 'BOR'}}}]);
};
invalidPick.should.throw(Error, 'The descriptions should be an array');
});
it('should cry if key description as object is invalid', () => {
let source = {
address: {
postalCode: '33000',
city: 'Bordeaux'
}
};
let invalidPick = () => {
pick(source, [{address: ['city'], whatAmIDoing: ['here']}]);
};
invalidPick.should.throw(Error, 'The description should contain exactly one key');
});
it('should die in pain if key description is a primitive like a number', () => {
let source = {
firstName: 'John'
};
let invalidPick = () => {
pick(source, [3]);
};
invalidPick.should.throw(Error, 'The description should be a string of an object');
});
});
|
82679471fed17fea153a546f66a456d818555c61
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
arpinum/lookalike
|
3f9ad49d8db0545a9b6edd5269f3ccc52d8df465
|
716dd6e99968039b3169ee3144cbc46bf85aaec1
|
refs/heads/master
|
<file_sep>package com.example.kubra.scrumandroid;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.support.annotation.ColorInt;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.content.Context;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Kubra on 7.03.2017.
*/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
Bitmap postit;
// int postitcolor;
// int fontcolor;
//String iskonu;
Bitmap image;
Point position;
public ImageAdapter(Context c) { //,String is_konu,int font_color,int postit_color
// postitcolor=postit_color;
// fontcolor=font_color;
mContext = c;
// iskonu=is_konu;
// image= BitmapFactory.decodeResource(mContext.getResources(),R.drawable.postit);
/// position=new Point(150,60);
postit=mark(image,"Deneme",position,150,30,false,Color.BLACK);
}
public int getCount() {
return 10;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200, 250));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Bitmap npostit = Bitmap.createBitmap(postit, 0, 0,
postit.getWidth() - 1, postit.getHeight() - 1);
Paint p = new Paint();
ColorFilter filter = new LightingColorFilter(Color.YELLOW, 1);
p.setColorFilter(filter);
imageView.setImageBitmap(npostit);
Canvas canvas = new Canvas(npostit);
canvas.drawBitmap(npostit, 0, 0, p);
return imageView;
}
// // references to our images
public Integer[] mThumbIds = {
R.drawable.postit
};
//FONTCOLOR İLE İLGİLENİCEM
public static Bitmap mark(Bitmap src, String watermark, Point location, int alpha, int size, boolean underline,int fontcolor)
{
int w = src.getWidth();
int h = src.getHeight();
Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setAlpha(alpha);
paint.setTextSize(size);
paint.setAntiAlias(true);
paint.setUnderlineText(underline);
canvas.drawText(watermark, location.x, location.y, paint);
return result;
}
public ArrayAdapter<Bitmap> postitolustur(ArrayList<String> isler)
{
ArrayList<Bitmap> postitler=new ArrayList<Bitmap>();
for(int i=0;i<isler.size();i++)
{
image= BitmapFactory.decodeResource(mContext.getResources(),R.drawable.postit);
position=new Point(150,60);
postit=mark(image,isler.get(i),position,150,30,false,Color.BLACK);
postitler.add(postit);
}
ArrayAdapter<Bitmap> adapter = new ArrayAdapter<Bitmap>(mContext,android.R.layout.simple_dropdown_item_1line,postitler);
return adapter;
}
}<file_sep>package com.example.kubra.scrumandroid;
import android.content.Context;
import android.widget.Toast;
/**
* Created by Kubra on 9.03.2017.
*/
public class messagebox {
private Context mContext;
public void show(String text,Context c)
{
mContext=c;
Toast.makeText(mContext,text,Toast.LENGTH_SHORT).show();
}
}
<file_sep>package com.example.kubra.scrumandroid;
import android.app.Activity;
import android.os.Bundle;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper dbHelper=new DatabaseHelper(this);
try
{
dbHelper.CreateDataBase();
}
catch (Exception ex)
{
Log.w("hata","Veritabanı oluşturulamadı ve kopyalanamadı!");
}
SQLiteDatabase db=dbHelper.getReadableDatabase();
// String olustur="Create Table lu_is ( id int idendty,konu TEXT,isaciklama TEXT)";
//db.execSQL(olustur);
//dbHelper.truncatetable("lu_is");
db.close();
Button isekle_yonlendir= (Button)findViewById(R.id.is_yonlendir_button);
isekle_yonlendir.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,is_ekle_class.class);
startActivity(intent);
}
});
}
}
|
24a1c80aab884070133677c05831cc22c23ec066
|
[
"Java"
] | 3 |
Java
|
KubraOzaslan/ScrumAndroid
|
36e1af8f970da0f2169d044135908e5c4c850cc0
|
84b0000e93af790591df14ea9381b276e66dd055
|
refs/heads/master
|
<repo_name>tiderjian/think-core<file_sep>/src/Library/Qscmf/Builder/ColumnType/Self/Self_.class.php
<?php
namespace Qscmf\Builder\ColumnType\Self;
use Qscmf\Builder\ColumnType\ColumnType;
class Self_ extends ColumnType {
public function build(array &$option, array $data, $listBuilder){
return $option['value'];
}
}<file_sep>/src/Bootstrap/Context.php
<?php
namespace Bootstrap;
class Context{
const PACKAGE_CACHE_FILE = 'qscmf-packages.php';
static public function getRegProvider(){
$cache_file = LARA_DIR . '/bootstrap/cache/' . self::PACKAGE_CACHE_FILE;
if(file_exists($cache_file)) {
$packages = require $cache_file;
}
else{
$packages = [];
}
return $packages;
}
static public function providerRegister($is_lara = false){
$packages = self::getRegProvider();
collect($packages)->values()->each(function($item, $key) use ($is_lara){
collect($item['providers'])->each(function($cls, $index) use ($is_lara){
if(class_exists($cls)){
$clss = new $cls();
$is_lara ? self::laraRegister($clss) : self::tpRegister($clss);
}
});
});
}
static private function tpRegister($clss){
$clss->register();
}
static private function laraRegister($clss){
($clss instanceof LaravelProvider) ? $clss->registerLara() : '';
}
}<file_sep>/src/Library/Qscmf/Builder/ListBuilder.class.php
<?php
namespace Qscmf\Builder;
use Bootstrap\RegisterContainer;
use Qscmf\Builder\ButtonType\Addnew\Addnew;
use Qscmf\Builder\ButtonType\Delete\Delete;
use Qscmf\Builder\ButtonType\Forbid\Forbid;
use Qscmf\Builder\ButtonType\Resume\Resume;
use Qscmf\Builder\ButtonType\Save\DefaultEditableColumn;
use Qscmf\Builder\ButtonType\Save\Save;
use Qscmf\Builder\ButtonType\Self\SelfButton;
use Qscmf\Builder\ColumnType\Btn\Btn;
use Qscmf\Builder\ColumnType\EditableInterface;
use Qscmf\Builder\ColumnType\Num\Num;
use Qscmf\Builder\ListRightButton\Edit\Edit;
use Qscmf\Builder\ListSearchType\DateRange\DateRange;
use Qscmf\Builder\ListSearchType\Select\Select;
use Qscmf\Builder\ListSearchType\SelectCity\SelectCity;
use Qscmf\Builder\ListSearchType\SelectText\SelectText;
use Qscmf\Builder\ListSearchType\Text\Text;
use Qscmf\Builder\ListSearchType\Hidden\Hidden;
use Qscmf\Builder\ListSearchType\Self\Self_ as SelfSearch;
use Qscmf\Builder\ColumnType\Status\Status;
use Qscmf\Builder\ColumnType\A\A;
use Qscmf\Builder\ColumnType\Date\Date;
use Qscmf\Builder\ColumnType\Fun\Fun;
use Qscmf\Builder\ColumnType\Icon\Icon;
use Qscmf\Builder\ColumnType\Picture\Picture;
use Qscmf\Builder\ColumnType\Self\Self_;
use Qscmf\Builder\ColumnType\Time\Time;
use Qscmf\Builder\ColumnType\Type\Type;
/**
* 数据列表自动生成器
*/
class ListBuilder extends BaseBuilder implements \Qscmf\Builder\GenButton\IGenButton, \Qscmf\Builder\GenColumn\IGenColumn {
use \Qscmf\Builder\GenButton\TGenButton;
use \Qscmf\Builder\GenColumn\TGenColumn;
private $_top_button_list = array(); // 顶部工具栏按钮组
private $_search = array(); // 搜索参数配置
private $_search_url; //搜索按钮指向url
private $_table_column_list = array(); // 表格标题字段
private $_table_data_list = array(); // 表格数据列表
private $_primary_key = '_pk'; //备份主键
private $_table_data_page; // 表格数据分页
private $_right_button_list = array(); // 表格右侧操作按钮组
private $_alter_data_list = array(); // 表格数据列表重新修改的项目
private $_show_check_box = true;
private $_attr_callback; //checkbox属性自定义勾子
private $_meta_button_list = array(); //标题按钮
private $_lock_row = 1; //锁定标题
private $_lock_col = 0; //锁定列(左)
private $_lock_col_right = 0; //锁定列(右)
private $_page_template; // 页码模板
private $_top_button_type = [];
private $_search_type = [];
private $_list_template;
private $_origin_table_data_list = [];
private $_right_btn_def_class = 'qs-list-right-btn';
private $_hidden_key = "_hidden_pk_";
static function genCheckBoxDisableCb($data_key, $disable_value){
return function($attr, $data) use ($data_key, $disable_value){
if($data[$data_key] == $disable_value){
$attr['class'] = 'ids-disable';
$attr['disabled'] = 'disabled';
}
return $attr;
};
}
/**
* 初始化方法
* @return $this
*/
protected function _initialize() {
$module_name = 'Admin';
$this->_template = __DIR__ .'/Layout/'.$module_name.'/list.html';
$this->_list_template = __DIR__ . '/listbuilder.html';
$this->_page_template = __DIR__ .'/Layout/'.$module_name.'/pagination.html';
self::registerTopButtonType();
self::registerSearchType();
self::registerRightButtonType();
self::registerColumnType();
}
protected function resetSaveMark(){
Save::$target_form = "save";
}
public function getDataKeyName(){
return $this->_table_data_list_key;
}
public function setSearchUrl($url){
$this->_search_url = $url;
return $this;
}
/**
* 锁定行
* @param $row int 锁定行数
* @return $this
*/
public function setLockRow($row){
$this->_lock_row = $row;
return $this;
}
/**
* 锁定列(左)
* @param $col int 锁定列数
* @return $this
*/
public function setLockCol($col){
$this->_lock_col = $col;
return $this;
}
/**
* 锁定列(右)
* @param $col int 锁定列数
* @return $this
*/
public function setLockColRight($col){
$this->_lock_col_right = $col;
return $this;
}
public function setCheckBox($flag, $attr_callback = null){
$this->_show_check_box = $flag;
$this->_attr_callback = $attr_callback;
return $this;
}
protected function registerSearchType(){
static $search_type = [];
if(empty($search_type)){
$base_search_type = self::registerBaseSearchType();
$search_type = array_merge($base_search_type, RegisterContainer::getListSearchType());
}
$this->_search_type = $search_type;
}
protected function registerBaseSearchType(){
return [
'date_range' => DateRange::class,
'select' => Select::class,
'select_city' => SelectCity::class,
'select_text' => SelectText::class,
'text' => Text::class,
'hidden' => Hidden::class,
'self' => SelfSearch::class,
];
}
protected function registerTopButtonType(){
static $top_button_type = [];
if(empty($top_button_type)) {
$base_top_button_type = self::registerBaseTopButtonType();
$top_button_type = array_merge($base_top_button_type, RegisterContainer::getListTopButtons());
}
$this->_top_button_type = $top_button_type;
}
protected function registerBaseTopButtonType(){
return [
'addnew' => Addnew::class,
'delete' => Delete::class,
'forbid' => Forbid::class,
'resume' => Resume::class,
'save' => Save::class,
'self' => SelfButton::class
];
}
protected function registerRightButtonType(){
self::registerButtonType();
}
public function addMetaButton($type, $attribute = null, $tips = ''){
switch ($type) {
case 'return': // 添加新增按钮
// 预定义按钮属性以简化使用
$my_attribute['title'] = '返回';
$my_attribute['class'] = 'btn btn-primary';
$my_attribute['href'] = 'javascript:history.go(-1)';
/**
* 如果定义了属性数组则与默认的进行合并
* 用户定义的同名数组元素会覆盖默认的值
* 比如$builder->addTopButton('add', array('title' => '换个马甲'))
* '换个马甲'这个碧池就会使用山东龙潭寺的十二路谭腿第十一式“风摆荷叶腿”
* 把'新增'踢走自己霸占title这个位置,其它的属性同样道理
*/
if ($attribute && is_array($attribute)) {
$my_attribute = array_merge($my_attribute, $attribute);
}
$class = $my_attribute['class'];
$my_attribute['class'] = 'pull-right ' . $class;
// 这个按钮定义好了把它丢进按钮池里
break;
case 'self': //添加自定义按钮(第一原则使用上面预设的按钮,如果有特殊需求不能满足则使用此自定义按钮方法)
// 预定义按钮属性以简化使用
$my_attribute['class'] = 'btn btn-danger';
// 如果定义了属性数组则与默认的进行合并
if ($attribute && is_array($attribute)) {
$my_attribute = array_merge($my_attribute, $attribute);
} else {
$my_attribute['title'] = '该自定义按钮未配置属性';
}
$class = $my_attribute['class'];
$my_attribute['class'] = 'pull-right ' . $class;
// 这个按钮定义好了把它丢进按钮池里
break;
}
if($tips != ''){
$my_attribute['tips'] = $tips;
}
$this->_meta_button_list[] = $my_attribute;
return $this;
}
/**
* 加入一个列表顶部工具栏按钮
* 在使用预置的几种按钮时,比如我想改变新增按钮的名称
* 那么只需要$builder->addTopButton('addnew', array('title' => '换个马甲'))
* 如果想改变地址甚至新增一个属性用上面类似的定义方法
* @param string $type 按钮类型,取值参考registerBaseTopButtonType
* @param array|null $attribute 按钮属性,一个定义标题/链接/CSS类名等的属性描述数组
* @param string $tips 按钮提示
* @param string|array $auth_node 按钮权限点
* @param string|array $options 按钮options
* @return $this
*/
public function addTopButton($type, $attribute = null, $tips = '', $auth_node = '', $options = []) {
$top_button_option['type'] = $type;
$top_button_option['attribute'] = $attribute;
$top_button_option['tips'] = $tips;
$top_button_option['auth_node'] = $auth_node;
$top_button_option['options'] = $options;
$this->_top_button_list[] = $top_button_option;
return $this;
}
public function addSearchItem($name, $type, $title='', $options = array(), $auth_node = ''){
$search_item = array(
'name' => $name,
'type' => $type,
'title' => $title,
'options' => $options,
'auth_node' => $auth_node
);
$this->_search[] = $search_item;
return $this;
}
/**
* 加一个表格列标题字段
*
* @param string $name 列名
* @param string $title 列标题
* @param string $type 列类型,默认为null(目前支持类型:status、icon、date、time、picture、type、fun、a、self、num)
* @param string|array $value 列value,默认为'',根据组件自定义该值
* @param boolean $editable 列是否可编辑,默认为false
* @param string $tip 列数据提示文字,默认为''
* @param string $th_extra_attr 列表头额外属性,默认为''
* @param string $td_extra_attr 列列额外属性,默认为''
* @param string|array $auth_node 列权限点
* @return $this
*/
public function addTableColumn($name, $title, $type = null, $value = '', $editable = false, $tip = '',
$th_extra_attr = '', $td_extra_attr = '', $auth_node = '') {
$this->_table_column_list[] = self::genOneColumnOpt($name, $title, $type, $value, $editable, $tip,
$th_extra_attr, $td_extra_attr, $auth_node);
return $this;
}
/**
* 表格数据列表
*/
public function setTableDataList($table_data_list) {
$this->_table_data_list = $table_data_list;
$this->_origin_table_data_list = $table_data_list;
return $this;
}
/**
* 表格数据列表的主键名称
*/
public function setTableDataListKey($table_data_list_key) {
$this->_table_data_list_key = $table_data_list_key;
return $this;
}
/**
* 加入一个数据列表右侧按钮
* 在使用预置的几种按钮时,比如我想改变编辑按钮的名称
* 那么只需要$builder->addRightButton('edit', array('title' => '换个马甲'))
* 如果想改变地址甚至新增一个属性用上面类似的定义方法
* 因为添加右侧按钮的时候你并没有办法知道数据ID,于是我们采用__data_id__作为约定的标记
* __data_id__会在display方法里自动替换成数据的真实ID
* @param string $type 按钮类型,取值参考registerBaseRightButtonType
* @param array|null $attribute 按钮属性,一个定义标题/链接/CSS类名等的属性描述数组
* @param string $tips 按钮提示
* @param string|array $auth_node 按钮权限点
* @param string|array|object $options 按钮options
* @return $this
*/
public function addRightButton($type, $attribute = null, $tips = '', $auth_node = '', $options = []) {
$this->_right_button_list[] = $this->genOneButton($type, $attribute, $tips, $auth_node, $options);
return $this;
}
/**
* 设置分页
* @param $page
* @return $this
*/
public function setTableDataPage($table_data_page) {
$this->_table_data_page = $table_data_page;
return $this;
}
/**
* 修改列表数据
* 有时候列表数据需要在最终输出前做一次小的修改
* 比如管理员列表ID为1的超级管理员右侧编辑按钮不显示删除
* @param $page
* @return $this
*/
public function alterTableData($condition, $alter_data) {
$this->_alter_data_list[] = array(
'condition' => $condition,
'alter_data' => $alter_data
);
return $this;
}
protected function backupPk(){
foreach($this->_table_data_list as &$vo){
$vo[$this->_primary_key] = $vo[$this->_table_data_list_key];
}
}
public function getPrimaryKey(){
return $this->_primary_key;
}
public function getBtnDefClass(){
return $this->_right_btn_def_class;
}
/**
* @deprecated 在v13版本删除, 请使用 build 代替
* 显示页面
*/
public function display($render=false,$charset='',$contentType='',$content='',$prefix='') {
return $this->build($render);
}
public function build($render=false){
$this->resetSaveMark();
$this->backupPk();
// 编译data_list中的值
$this->_right_button_list = $this->checkAuthNode($this->_right_button_list);
$this->_table_column_list = $this->checkAuthNode($this->_table_column_list);
$this->_top_button_list = $this->checkAuthNode($this->_top_button_list);
$this->_search = $this->checkAuthNode($this->_search);
foreach ($this->_table_data_list as $key => &$data) {
// 编译表格右侧按钮
if ($this->_right_button_list) {
$data['right_button'] = join(' ', $this->parseButtonList($this->_right_button_list, $data));
}
// 根据表格标题字段指定类型编译列表数据
foreach ($this->_table_column_list as &$column) {
$is_editable = $this->isEditable($column, $data);
if($is_editable && !isset($data[$this->_hidden_key])){
$hidden = new \Qscmf\Builder\ColumnType\Hidden\Hidden();
$hidden_column = [
'name' => $this->_table_data_list_key
];
$data[$this->_hidden_key] = $hidden->editBuild($hidden_column, $data, $this);
}
$this->buildOneColumnItem($column, $data);
}
$data['_check_box'] = $this->parseCheckBox($data);
/**
* 修改列表数据
* 有时候列表数据需要在最终输出前做一次小的修改
* 比如管理员列表ID为1的超级管理员右侧编辑按钮不显示删除
*/
if ($this->_alter_data_list) {
foreach ($this->_alter_data_list as $alter) {
if ($data[$alter['condition']['key']] === $alter['condition']['value']) {
//寻找alter_data里需要替代的变量
foreach($alter['alter_data'] as $alter_key => $val){
$val = $this->parseData($val, $this->_origin_table_data_list[$key]);
$alter['alter_data'][$alter_key] = $val;
}
$data = array_merge($data, $alter['alter_data']);
}
}
}
foreach ($this->_table_column_list as &$column) {
$data[$column['name']] = match ($column){
'right_button' => "<td nowrap {$column['td_extra_attr']}>{$data[$column['name']]}</td>",
default => "<td {$column['td_extra_attr']}>{$data[$column['name']]}</td>"
};
}
}
//编译top_button_list中的HTML属性
if ($this->_top_button_list) {
$top_button_list = [];
foreach ($this->_top_button_list as $option) {
$tmp = [];
$content = (new $this->_top_button_type[$option['type']]())->build($option);
$button_html = self::compileTopButton($option);
$tmp['render_content'] = <<<HTML
{$button_html}
{$content}
HTML;
$top_button_list[] = $tmp;
}
$this->_top_button_list = $top_button_list;
}
if ($this->_meta_button_list) {
foreach ($this->_meta_button_list as &$button) {
$this->compileButton($button);
}
}
foreach($this->_search as &$search){
$search['render_content'] = (new $this->_search_type[$search['type']]())->build($search);
}
$this->assign('meta_title', $this->_meta_title); // 页面标题
$this->assign('top_button_list', $this->_top_button_list); // 顶部工具栏按钮
$this->assign('meta_button_list', $this->_meta_button_list);
$this->assign('search', $this->_search); // 搜索配置
$this->assign('tab_nav', $this->_tab_nav); // 页面Tab导航
$this->assign('table_column_list', $this->_table_column_list); // 表格的列
$this->assign('table_data_list', $this->_table_data_list); // 表格数据
$this->assign('table_data_list_key', $this->_table_data_list_key); // 表格数据主键字段名称
$this->assign('pagination', $this->_table_data_page); // 表示个数据分页
$this->assign('right_button_list', $this->_right_button_list); // 表格右侧操作按钮
$this->assign('alter_data_list', $this->_alter_data_list); // 表格数据列表重新修改的项目
$this->assign('extra_html', $this->_extra_html); // 额外HTML代码
$this->assign('top_html', $this->_top_html); // 顶部自定义html代码
$this->assign('page_template', $this->_page_template); // 页码模板自定义html代码
$this->assign('show_check_box', $this->_show_check_box);
$this->assign('hidden_key', $this->_hidden_key);
$this->assign('nid', $this->_nid);
$this->assign('lock_row', $this->_lock_row);
$this->assign('lock_col', $this->_lock_col);
$this->assign('lock_col_right', $this->_lock_col_right);
$this->assign('search_url', $this->_search_url);
$this->assign('list_builder_path', $this->_list_template);
$this->assign('primary_key', $this->_primary_key);
$this->assign('content_bottom_html', join('', $this->_content_bottom));
$this->assign('column_css_and_js_str', $this->getUniqueColumnCssAndJs());
if($render){
return parent::fetch($this->_list_template);
}
else{
parent::display($this->_template);
}
}
protected function parseCheckBox($data) : string{
if($this->_show_check_box){
$attr = [
'class' => 'ids',
'type' => 'checkbox',
'name' => 'ids[]',
'value' => $data[$this->_primary_key]
];
if($this->_attr_callback instanceof \Closure){
$attr = call_user_func($this->_attr_callback, $attr, $data);
}
$attr_str = $this->compileHtmlAttr($attr);
return "<td><input {$attr_str}></td>";
}
else{
return "";
}
}
protected function compileTopButton($option){
if($option['tips'] != ''){
$tips_html = '<span class="badge">' . $option['tips'] . '</span>';
}
return <<<HTML
<a {$this->compileHtmlAttr($option['attribute'])}>{$option['attribute']['title']} {$tips_html}</a>
HTML;
}
protected function compileButton(&$button){
$button['attribute'] = $this->compileHtmlAttr($button);
if($button['tips'] != ''){
$button['tips'] = '<span class="badge">' . $button['tips'] . '</span>';
}
}
protected function parseData($str, $data){
while(preg_match('/__(\w+?)__/i', $str, $matches)){
$str = str_replace('__' . $matches[1] . '__', $data[$matches[1]], $str);
}
return $str;
}
//编译HTML属性
protected function compileHtmlAttr($attr) {
$result = array();
foreach ($attr as $key => $value) {
if($key == 'tips'){
continue;
}
if(!empty($value) && !is_array($value)){
$value = htmlspecialchars($value);
$result[] = "$key=\"$value\"";
}
}
$result = implode(' ', $result);
return $result;
}
/**
* 设置页码模版
* @param $page_template 页码模版自定义html代码
* @return $this
*/
public function setPageTemplate($page_template) {
$this->_page_template = $page_template;
return $this;
}
}
<file_sep>/src/Library/Qscmf/Builder/ColumnType/A/A.class.php
<?php
namespace Qscmf\Builder\ColumnType\A;
use Qscmf\Builder\ColumnType\ColumnType;
class A extends ColumnType {
public function build(array &$option, array $data, $listBuilder){
return '<a ' . $this->compileHtmlAttr($option['value']) . ' >' . $data[$option['name']] . '</a>';
}
protected function compileHtmlAttr($attr) {
$result = array();
foreach ($attr as $key => $value) {
if(!empty($value) && !is_array($value)){
$value = htmlspecialchars($value);
$result[] = "$key=\"$value\"";
}
}
$result = implode(' ', $result);
return $result;
}
}<file_sep>/src/Library/Qscmf/Builder/ListRightButton/Self/SelfButton.class.php
<?php
namespace Qscmf\Builder\ListRightButton\Self;
use Qscmf\Builder\ListRightButton\ListRightButton;
class SelfButton extends ListRightButton{
public function build(array &$option, array $data, $listBuilder){
$my_attribute['class'] = 'default';
$option['attribute'] = $listBuilder->mergeAttr($my_attribute, is_array($option['attribute']) ? $option['attribute'] : []);
return '';
}
}<file_sep>/src/Library/Qscmf/Builder/ListRightButton/ListRightButton.class.php
<?php
namespace Qscmf\Builder\ListRightButton;
abstract class ListRightButton{
public abstract function build(array &$option, array $data, $listBuilder);
}<file_sep>/asset/libs/label-select/label-select.js
require('./label-select.less');
require('./lib/popup/css/popup.css');
require('./lib/popup/js/popup.js');
require('./lib/q.js');
function labelSelect(confObj){
this.labelItemStr = '';
this.labelListItemStr = '';
this.url = confObj.url;
this.addUrl = confObj.addUrl;
this.removeUrl = confObj.removeUrl;
this.reqData = confObj.reqData;
this.addData = confObj.addData||{};
this.removeData = confObj.removeData||{};
this.res = null;
this.selectedLabels = [];
this.field = confObj.field;
this.tips = confObj.tips||'';
this.value = confObj.value;
this.hash = Math.ceil(new Date().getTime() * Math.random() * Math.random());
this.$el = $(confObj.el);
this.$body = $('body');
this.$selectMore = null;
this.$iconCloseMask = null;
this.$maskBox = null;
this.$labelList = null;
this.$labelSelected = null;
this.$selectLabel = null;
this.init();
}
labelSelect.prototype.init = function (){
var that = this;
this.$el.addClass('select-label-' + this.hash);
this.$el = $('.select-label-' + this.hash);
this.getData(this.url,this.reqData)
.then(function (){
that.initDom();
})
.then(function (){
that.initVar();
}).then(function (){
that.initEvent();
that.initModal();
}).then(function (){
that.initSelected();
that.getSelectedStr();
that.appendSelectedLabel();
});
}
labelSelect.prototype.initVar = function (){
this.$selectMore = this.$el.find('.select-more');
this.$maskBox = $('#label-select-mask-' + this.hash);
this.$iconCloseMask = this.$maskBox.find('.icon-close-mask');
this.$labelList = this.$el.find('#label-list-' + this.hash);
this.$labelSelected = this.$el.find('#label-selected-' + this.hash);
this.$selectLabel = this.$maskBox.find('input[name="select-label"]');
}
labelSelect.prototype.initEvent = function(){
var that = this;
this.$iconCloseMask.on('click',function (){
that.closeModal();
});
this.$selectMore.on('click',function (){
that.showModal();
});
this.$body.on('click','#label-select-mask-' + this.hash + ' .btn-add-label',function(){
that.addLabel()
.then(function (res){
if(res.status == 0){
alert(res.info);
}else{
var renderStr = that.getRenderStr(res);
that.$maskBox.find('.label-list').append(renderStr);
that.$selectLabel.val('');
}
}).catch(function (xhr){
});
});
this.$body.on('click','#label-select-mask-' + this.hash + ' .label-remove',function(){
var $this = $(this);
var id = $this.data('id');
that.removeLabel(id)
.then(function (){
$this.parent().fadeOut(200,function (){
$this.parent().remove();
});
});
});
this.removeLabelItem();
}
labelSelect.prototype.initDom = function (){
if(!$('.popup-mask').length){
this.$body.append('<div class="popup-mask hidden"></div>');
}
var initStr = '<div class="label-select-box">'+
'<ul class="label-list" id="label-list-' + this.hash + '">' +
'</ul>' +
'<input type="hidden" value="'+ this.value +'" name=' + this.field + ' id="label-selected-'+ this.hash +'">' +
'<div class="tips-wrap">'+
'<i class="select-more icon-add"></i><span class="label-tips">' + this.tips + '</span>'
'</div>' +
'</div>';
var initMaskStr = '<div class="popup-mask-box label-select-mask hidden" id="label-select-mask-'+ this.hash +'">' +
'<div class="popup-content">' +
'<div class="popup-info">' +
'<h2 class="popup-title"> ' +
'<span>添加标签</span>' +
'<a href="javascript:void(0)" class="icon-close-mask">' +
'<i class="icon-close popup-close"></i>' +
'</a>' +
'</h2>' +
'<div class="popup-wrapper">' +
'<form class="add-label text-center" action="" method="get">'+
'<input type="text" style="display: none;">' +
'<div class="form-label">'+
'<div class="input-wrap">'+
'<input type="text" name="select-label" placeholder="新增标签" class="select-label">' +
'</div>' +
'<div class="btn-wrap">'+
'<button class="button-red btn-add-label" type="button">新增</button>' +
'</div>' +
'</div>'+
'</form>' +
'<ul class="label-list">' +
'</ul>' +
'</div>' +
'<div class="text-center pt15 popop-footer">' +
'<button type="button" class="button-red btn-sm select-label-confirm icon-close-mask">确定</button>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
return Q.all([
this.$el.append(initStr),
this.$body.append(initMaskStr),
]);
}
labelSelect.prototype.initSelected = function(){
var that = this;
var valArr = $.trim(this.$labelSelected.attr('value')).split(',');
this.selectedLabels = [];
this.res.forEach(function (v){
valArr.forEach(function (val){
if(v.id == val){
that.selectedLabels.push(v);
}
});
});
}
labelSelect.prototype.appendSelectedLabel = function(){
this.$labelList.html(this.labelListItemStr);
}
labelSelect.prototype.getSelectedStr = function(){
var that = this;
that.labelListItemStr = '';
this.selectedLabels.forEach(function (v){
that.labelListItemStr += '<li data-id='+ v.id +'>'+
'<span class="title">' + v.name + '</span>'+
'<i class="label-delte icon-close" data-id="'+ v.id +'"></i>'+
'</li>';
});
}
labelSelect.prototype.getSelectedLabel = function (){
var that = this;
this.selectedLabels = [];
this.$maskBox.find('.label-list').find('.label-select').each(function (){
var $this = $(this);
var isChecked = $this.prop('checked');
if(isChecked){
that.selectedLabels.push({
id: $this.data('id'),
name: $this.data('name'),
});
}
});
}
labelSelect.prototype.getSelectedIds = function (){
var ids = [];
this.selectedLabels.map(function (v){
ids.push(v.id);
});
return ids;
}
labelSelect.prototype.updateSelectData = function (){
var ids = this.getSelectedIds(this.selectedLabels);
this.$labelSelected.attr('value',ids.join(','));
}
labelSelect.prototype.preventWindowScroll = function(e){
return false;
}
labelSelect.prototype.showModal = function (){
var that = this;
var ids = this.getSelectedIds(this.selectedLabels);
this.$maskBox.popup('show',{
onShowBefore: function (){
window.addEventListener('scroll',labelSelect.prototype.preventWindowScroll);
that.$maskBox
.find('.label-list')
.find('.label-select')
.prop({checked: false})
.each(function (){
var $this = $(this);
if(ids.indexOf($this.data('id')) > -1){
$this.prop({checked: true});
}
});
}
});
}
labelSelect.prototype.closeModal= function (){
var that = this;
this.$maskBox.popup('hide',{
onCloseBefore: function (){
window.removeEventListener('scroll',labelSelect.prototype.preventWindowScroll);
that.getSelectedLabel();
that.updateSelectData();
that.getSelectedStr();
that.appendSelectedLabel();
if(that.$maskBox.attr('id') != 'label-select-mask-' + that.hash){
return false;
}
}
});
}
labelSelect.prototype.removeLabelItem = function(){
var that = this;
this.$body.on('click','#label-list-' + this.hash + ' .label-delte',function (){
var $this = $(this);
var removeId = $this.data('id');
$this.parent().fadeOut(200);
that.selectedLabels = that.selectedLabels.filter(function (v){
return v.id != removeId;
});
that.updateSelectData(that.selectedLabels);
});
}
labelSelect.prototype.initModal = function (){
var that = this;
var renderStr = this.getRenderStr(this.res);
this.$maskBox.find('.label-list').html(renderStr);
}
labelSelect.prototype.getData = function (){
var that = this;
return get(this.url,this.reqData)
.then(function (res){
that.res = res;
return res;
}).catch(function (xhr){
alert('获取标签失败!');
});
}
labelSelect.prototype.getRenderStr = function (res){
var that = this;
that.labelItemStr = '';
var dataArr = null;
//新增的时候返回对象,否则返回数组
if(!$.isArray(res)){
dataArr = [res];
}else{
dataArr = res;
}
dataArr.forEach(function (v){
that.labelItemStr += '<li class="label-select-item" data-id='+ v.id +'>'+
'<label>' +
'<input type="checkbox" class="label-select" data-id='+ v.id +' data-name='+ v.name +'>' +
'<span class="title">'+ v.name +'</span>' +
'</label>' +
'<i class="label-remove icon-close" title="永久删除?" data-id="'+ v.id +'" alt=""></i>'+
'</li>';
});
return this.labelItemStr;
}
labelSelect.prototype.addLabel = function (){
this.addData.labelName = this.$selectLabel.val();
return get(this.addUrl,this.addData);
}
labelSelect.prototype.removeLabel = function (id){
this.removeData.id = id;
return get(this.removeUrl,this.removeData);
}
module.exports = {
labelSelect: labelSelect
};
function ajax(url,data,type){
var type = type||'get';
var url = url||'';
var data = data||{};
var defer = Q.defer();
$.ajax({
type: type,
url: url,
data: data,
success: function (res){
defer.resolve(res);
},
error: function (xhr,m,s){
defer.reject(xhr,m,s);
},
});
return defer.promise;
}
function get(url,data){
return ajax(url,data,'get');
}
function post(url,data){
return ajax(url,data,'post');
}<file_sep>/src/Library/Qscmf/Builder/BaseBuilder.class.php
<?php
namespace Qscmf\Builder;
use Qscmf\Lib\DBCont;
use Think\Controller;
class BaseBuilder extends Controller
{
protected $_nid;
protected $_meta_title;
/**
* @var 模版
*/
protected $_template;
/**
* @var 额外功能代码
*/
protected $_extra_html;
/**
* @var array
*/
protected $_tab_nav=[];
// 顶部自定义html代码
protected $_top_html;
// content 底部自定义html
protected $_content_bottom = [];
public function setNIDByNode($module = MODULE_NAME, $controller = CONTROLLER_NAME, $action = 'index'){
$module_ent = D('Node')->where(['name' => $module, 'level' => DBCont::LEVEL_MODULE, 'status' => DBCont::NORMAL_STATUS])->find();
if(!$module_ent){
E('setNIDByNode 传递的参数module不存在');
}
$controller_ent = D('Node')->where(['name' => $controller, 'level' => DBCont::LEVEL_CONTROLLER, 'status' => DBCont::NORMAL_STATUS, 'pid' => $module_ent['id']])->find();
if(!$controller_ent){
E('setNIDByNode 传递的参数controller不存在');
}
$action_ent = D('Node')->where(['name' => $action, 'level' => DBCont::LEVEL_ACTION, 'status' => DBCont::NORMAL_STATUS, 'pid' => $controller_ent['id']])->find();
if(!$action_ent){
E('setNIDByNode 传递的参数action不存在');
}
else{
return $this->setNID($action_ent['id']);
}
}
public function setNID($nid){
$this->_nid = $nid;
return $this;
}
/**
* 设置页面标题
* @param $title 标题文本
* @return $this
*/
public function setMetaTitle($meta_title) {
$this->_meta_title = $meta_title;
return $this;
}
/**
* 设置Tab按钮列表
* @param $tab_list Tab列表 array(
'title' => '标题',
'href' => 'http://www.corethink.cn'
)
* @param $current_tab 当前tab
* @return $this
*/
public function setTabNav($tab_list, $current_tab) {
$this->_tab_nav = array(
'tab_list' => $tab_list,
'current_tab' => $current_tab
);
return $this;
}
/**
* 设置额外功能代码
* @param $extra_html 额外功能代码
* @return $this
*/
public function setExtraHtml($extra_html) {
$this->_extra_html = $extra_html;
return $this;
}
/**
* 设置页面模版
* @param $template 模版
* @return $this
*/
public function setTemplate($template) {
$this->_template = $template;
return $this;
}
/**
* 设置页面顶部自定义html代码
* @param $top_html 顶部自定义html代码
* @return $this
*/
public function setTopHtml($top_html){
$this->_top_html = $top_html;
return $this;
}
/**
* 检测字段的权限点,无权限则unset该item
*
* @param array $check_items
* @return array
*/
public function checkAuthNode($check_items){
return BuilderHelper::checkAuthNode($check_items);
}
public function addContentBottom($html){
array_push($this->_content_bottom, $html);
return $this;
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Time/Time.class.php
<?php
namespace Qscmf\Builder\ColumnType\Time;
use Qscmf\Builder\ColumnType\ColumnType;
class Time extends ColumnType {
public function build(array &$option, array $data, $listBuilder){
return qsEmpty($data[$option['name']]) ? '' : time_format($data[$option['name']], $option['value'] ?:'Y-m-d H:i:s');
}
}<file_sep>/src/Larafortp/Commands/QscmfDiscoverCommand.php
<?php
namespace Larafortp\Commands;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
class QscmfDiscoverCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'qscmf:discover';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Rebuild the cached package manifest';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(Filesystem $files)
{
parent::__construct();
$this->files = $files;
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$packages = [];
if ($this->files->exists($path = app()->basePath().'/vendor/composer/installed.json')) {
$packages = json_decode($this->files->get($path), true);
}
if (isset($packages['packages'])){
$packages=$packages['packages'];
}
$this->write(collect($packages)->mapWithKeys(function ($package) {
return [$this->format($package['name']) => $package['extra']['qscmf'] ?? []];
})->filter()->all());
$this->info('Qscmf Package manifest generated successfully.');
}
/**
* Format the given package name.
*
* @param string $package
* @return string
*/
protected function format($package)
{
return str_replace(app()->basePath('vendor').'/', '', $package);
}
/**
* Write the given manifest array to disk.
*
* @param array $manifest
* @return void
*
* @throws \Exception
*/
protected function write(array $manifest)
{
$manifestPath = app()->bootstrapPath().'/cache/qscmf-packages.php';
if (! is_writable(dirname($manifestPath))) {
throw new Exception('The '.dirname($manifestPath).' directory must be present and writable.');
}
$this->files->replace(
$manifestPath, '<?php return '.var_export($manifest, true).';'
);
}
}
<file_sep>/src/Larafortp/CmmMigrate/CmmMigrationCreator.php
<?php
namespace Larafortp\CmmMigrate;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Database\Migrations\MigrationCreator;
class CmmMigrationCreator extends MigrationCreator{
public function __construct(Filesystem $files)
{
parent::__construct($files);
}
/**
* Get the path to the stubs.
*
* @return string
*/
public function stubPath()
{
return __DIR__.'/stubs';
}
}<file_sep>/src/Testing/DBTrait.php
<?php
namespace Testing;
use Illuminate\Support\Facades\DB;
trait DBTrait{
public function install()
{
$this->artisan('migrate:refresh --no-cmd');
}
protected function uninstall($database_name = '')
{
if(!$database_name){
$database_name = env('DB_DATABASE');
}
$tables = DB::select("SELECT CONCAT('',table_name) as tb, table_type as table_type FROM information_schema.`TABLES` WHERE table_schema='" . $database_name . "'");
foreach($tables as $table){
switch($table->table_type){
case 'BASE TABLE':
DB::statement("drop table $database_name." . $table->tb);
break;
case 'VIEW':
DB::statement("drop view $database_name." . $table->tb);
break;
}
}
$procedures = DB::select("show procedure status where Db='" . $database_name . "'");
foreach($procedures as $procedure){
DB::unprepared("drop procedure $database_name." . $procedure->Name);
}
$events = DB::select("SELECT * FROM information_schema.EVENTS where event_schema='" . $database_name . "'");
foreach($events as $event){
DB::unprepared("drop event $database_name." . $event->EVENT_NAME);
}
}
}<file_sep>/src/Library/Qscmf/Builder/ButtonType/Delete/Delete.class.php
<?php
namespace Qscmf\Builder\ButtonType\Delete;
use Qscmf\Builder\ButtonType\ButtonType;
class Delete extends ButtonType{
public function build(array &$option){
$my_attribute['title'] = '删除';
$my_attribute['target-form'] = 'ids';
$my_attribute['class'] = 'btn btn-danger ajax-post confirm';
$my_attribute['href'] = U(
'/' . MODULE_NAME.'/'.CONTROLLER_NAME.'/delete'
);
$option['attribute'] = array_merge($my_attribute, is_array($option['attribute']) ? $option['attribute'] : [] );
return '';
}
}<file_sep>/src/Library/Behavior/PrepareAppBehavior.class.php
<?php
namespace Behavior;
use Bootstrap\RegisterContainer;
class PrepareAppBehavior{
//行为执行入口
public function run(&$param) : void{
$this->loadDBConfig();
$this->baseRegister();
}
protected function baseRegister(){
RegisterContainer::registerHeadCss(__ROOT__ . '/Public/libs/viewerjs/viewer.min.css');
RegisterContainer::registerHeadJs(__ROOT__. '/Public/libs/viewerjs/viewer.min.js');
RegisterContainer::registerHeadCss(__ROOT__ . '/Public/libs/Huploadify/Huploadify.css');
RegisterContainer::registerHeadJs(__ROOT__. '/Public/libs/Huploadify/Huploadify.js');
}
protected function loadDBConfig() : void{
try{
\Qscmf\Lib\Tp3Resque\Resque\Event::listen('beforePerform', function($args){
readerSiteConfig();
});
readerSiteConfig();
}
catch(\Exception $ex){
if(IS_CGI) {
E($ex->getMessage());
}
}
}
}
<file_sep>/src/Library/Qscmf/Builder/NavbarRightType/Num/Num.class.php
<?php
namespace Qscmf\Builder\NavbarRightType\Num;
use Qscmf\Builder\BuilderHelper;
use Qscmf\Builder\NavbarRightType\NavbarRightType;
class Num extends NavbarRightType {
public function build(array &$option){
return '<a ' . BuilderHelper::compileHtmlAttr($option['attribute']) . ' >' . $option['attribute']['title'] .
'<span class="number">'.$option['options'].'</span></a>';
}
}<file_sep>/src/Library/Qscmf/Builder/ButtonType/Addnew/Addnew.class.php
<?php
namespace Qscmf\Builder\ButtonType\Addnew;
use Qscmf\Builder\ButtonType\ButtonType;
class Addnew extends ButtonType{
public function build(array &$option){
$my_attribute['title'] = '新增';
$my_attribute['class'] = 'btn btn-primary';
$my_attribute['href'] = U(MODULE_NAME.'/'.CONTROLLER_NAME.'/add');
$option['attribute'] = array_merge($my_attribute, is_array($option['attribute']) ? $option['attribute'] : [] );
return '';
}
}<file_sep>/src/Bootstrap/LaravelProvider.php
<?php
namespace Bootstrap;
interface LaravelProvider{
public function registerLara();
}<file_sep>/src/Library/Qscmf/Controller/UpgradeFixController.class.php
<?php
namespace Qscmf\Controller;
use Qscmf\Lib\Tp3Resque\Resque;
use Think\Controller;
class UpgradeFixController extends Controller{
public function v300FixSchedule($queue){
$keys = Resque::redis()->hkeys($queue. '_schedule');
foreach($keys as $v){
$s = Resque::redis()->hget($queue. '_schedule', $v);
$schedule = json_decode($s, true);
Resque::redis()->zadd($queue. '_schedule_sort', $schedule['run_time'], $v);
}
echo 'finished' . PHP_EOL;
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Picture/Picture.class.php
<?php
namespace Qscmf\Builder\ColumnType\Picture;
use Qscmf\Builder\ColumnType\ColumnType;
use Think\View;
class Picture extends ColumnType {
public function build(array &$option, array $data, $listBuilder){
$view = new View();
$image = [
'url' => showFileUrl($data[$option['name']]),
];
if(isset($option['value']) && is_array($option['value']) && $option['value']['small-url'] instanceof \Closure){
$image['small_url'] = call_user_func($option['value']['small-url'], $data[$option['name']]);
}
else{
$image['small_url'] = $image['url'];
}
$view->assign('image', $image);
$content = $view->fetch(__DIR__ . '/picture.html');
return $content;
}
}<file_sep>/src/Library/Qscmf/Builder/ListSearchType/DateRange/DateRange.class.php
<?php
namespace Qscmf\Builder\ListSearchType\DateRange;
use Qscmf\Builder\ListSearchType\ListSearchType;
use Qscmf\Builder\ListSearchType\Select\Select;
use Qscmf\Builder\ListSearchType\SelectText\SelectText;
use Think\View;
class DateRange implements ListSearchType{
public function build(array $item){
$view = new View();
$view->assign('item', $item);
$content = $view->fetch(__DIR__ . '/date_range.html');
return $content;
}
//样例代码 $map = array_merge($map, DateRange::parse('date_range_data', 'create_date', $get_data));
static public function parse(string $key, string $map_key, array $get_data) : array{
if(isset($get_data[$key])){
$date_range = explode('-', $get_data[$key]);
$start_time = strtotime(trim($date_range[0]));
$end_time = strtotime(trim($date_range[1]).'+1 day') -1;
return [$map_key => ['BETWEEN', [$start_time, $end_time]]];
}
else{
return [];
}
}
}<file_sep>/src/Library/Qscmf/Core/Session/DefaultSession.class.php
<?php
namespace Qscmf\Core\Session;
class DefaultSession implements ISession
{
public function set($key, $value)
{
session($key, $value);
}
public function get($key){
return session($key);
}
public function clear($key)
{
$this->set($key,null);
}
}<file_sep>/src/Library/Qscmf/Controller/CreateSymlinkController.class.php
<?php
namespace Qscmf\Controller;
use Bootstrap\RegisterContainer;
use Illuminate\Filesystem\Filesystem;
use Think\Controller;
class CreateSymlinkController extends Controller{
public function index(){
$symLinks = RegisterContainer::getRegisterSymLinks();
foreach($symLinks as $link => $source){
self::makeIgnore($link);
if(file_exists($link)){
echo $link . ' exists' . PHP_EOL;
}
else{
$relative_path = getRelativePath(normalizeRelativePath($source), normalizeRelativePath($link));
$r = symlink($relative_path, $link);
if($r){
echo 'create link: '. $link . ' => ' . $relative_path . PHP_EOL;
}
else{
echo 'create link: '. $link . ' failure !' . PHP_EOL;
}
}
}
}
private function makeIgnore($link){
$path_info = pathinfo($link);
if(file_exists($path_info['dirname'] . '/.gitignore')){
$content = file_get_contents($path_info['dirname'] . '/.gitignore');
if(!preg_match('#(^/|[\n\r]+?/)' . $path_info['basename'] . '#', $content)){
file_put_contents($path_info['dirname'] . '/.gitignore', PHP_EOL . '/' . $path_info['basename'], FILE_APPEND);
}
}
else{
file_put_contents($path_info['dirname'] . '/.gitignore', '/' . $path_info['basename']);
}
}
}<file_sep>/asset/libs/ueditor/php/action_wx_rich_text.php
<?php
/**
* 根据微信url获取富文本
* User: viki
* Date: 21-07-22
* Time: 下午14:33
*/
$text = '';
$url = $_GET['url'];
$url = urldecode($url);
$text = file_get_contents($url);
$cssToInlineStyles = new \TijsVerkoyen\CssToInlineStyles\CssToInlineStyles();
$text=$cssToInlineStyles->convert($text);
$text .= <<<EOF
<script type="text/javascript" src="../third-party/jquery-1.10.2.min.js"></script>
<script>
function handleImgSrc(){
//因微信公众号文章采用懒加载 这里要取消懒加载
//处理img
$('#js_content').find('img').each(function (index, item){
var ORIGIN_SRC = $(item).data('src');
if(ORIGIN_SRC){
$(item).attr({
src: ORIGIN_SRC,
});
}
});
}
function handleImgCss(){
$('#js_content').find('img').each(function (index, item){
$(item)
.css({
width: 'auto',
'max-width': '100%',
height: 'auto',
filter: 'unset',
backgound: 'auto',
display: 'unset',
})
.removeClass('img_loading');
});
}
$(function (){
handleImgCss();
handleImgSrc();
parent.window.onChildIFreamLoad();
});
</script>
EOF;
return $text;<file_sep>/src/Library/Qscmf/Builder/FormType/Tags/Tags.class.php
<?php
namespace Qscmf\Builder\FormType\Tags;
use Qscmf\Builder\FormType\FormType;
use Think\View;
class Tags implements FormType {
public function build(array $form_type){
$view = new View();
$view->assign('form', $form_type);
$content = $view->fetch(__DIR__ . '/tags.html');
return $content;
}
}<file_sep>/src/Library/Behavior/QscmfConstBehavior.class.php
<?php
namespace Behavior;
class QscmfConstBehavior{
public function run(&$_data){
$root = trim( __ROOT__, DIRECTORY_SEPARATOR) == '' ? '' : DIRECTORY_SEPARATOR. trim( __ROOT__, DIRECTORY_SEPARATOR);
defined('DOMAIN') or define('DOMAIN', env('DOMAIN', $_SERVER['HTTP_HOST']));
defined('SITE_URL') or define('SITE_URL', DOMAIN . $root);
defined('HTTP_PROTOCOL') or define('HTTP_PROTOCOL', env('HTTP_PROTOCOL', $_SERVER[C('HTTP_PROTOCOL_KEY')]));
defined('REQUEST_URI') or define('REQUEST_URI', $root . $_SERVER['REQUEST_URI']);
}
}<file_sep>/src/Library/Qscmf/Builder/ListRightButton/Delete/Delete.class.php
<?php
namespace Qscmf\Builder\ListRightButton\Delete;
use Qscmf\Builder\ListRightButton\ListRightButton;
class Delete extends ListRightButton {
public function build(array &$option, array $data, $listBuilder){
$my_attribute['title'] = '删除';
$my_attribute['class'] = 'danger ajax-get confirm';
$my_attribute['href'] = U(
MODULE_NAME.'/'.CONTROLLER_NAME.'/delete',
array(
'ids' => '__data_id__'
)
);
$option['attribute'] = $listBuilder->mergeAttr($my_attribute, is_array($option['attribute']) ? $option['attribute'] : [] );
return '';
}
}<file_sep>/src/Library/Behavior/HeadJsBehavior.class.php
<?php
namespace Behavior;
use Bootstrap\RegisterContainer;
class HeadJsBehavior{
public function run(&$content){
$js_srcs = RegisterContainer::getHeadJs();
$scripts = '';
foreach($js_srcs as $src){
$async = $src['async'] ? 'async' : '';
$scripts .= "<script $async src='{$src["src"]}'></script>";
}
$search_str = C('QS_REGISTER_JS_TAG_END');
$content = str_ireplace($search_str, $scripts .PHP_EOL. $search_str, $content);
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/Textarea/Textarea.class.php
<?php
namespace Qscmf\Builder\FormType\Textarea;
use Qscmf\Builder\FormType\FormType;
use Think\View;
class Textarea implements FormType {
public function build(array $form_type){
$view = new View();
$view->assign('form', $form_type);
if($form_type['item_option']['read_only']){
$content = $view->fetch(__DIR__ . '/textarea_read_only.html');
}
else{
$content = $view->fetch(__DIR__ . '/textarea.html');
}
return $content;
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/Province/Province.class.php
<?php
namespace Qscmf\Builder\FormType\Province;
use Qscmf\Builder\FormType\FormType;
use Think\View;
class Province implements FormType {
public function build(array $form_type){
$view = new View();
$view->assign('form', $form_type);
$content = $view->fetch(__DIR__ . '/province.html');
return $content;
}
}<file_sep>/src/ThinkPHP.php
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <<EMAIL>>
// +----------------------------------------------------------------------
//----------------------------------
// ThinkPHP公共入口文件
//----------------------------------
// 记录开始运行时间
$GLOBALS['_beginTime'] = microtime(TRUE);
// 记录内存初始使用
define('MEMORY_LIMIT_ON',function_exists('memory_get_usage'));
if(MEMORY_LIMIT_ON) $GLOBALS['_startUseMems'] = memory_get_usage();
// 版本信息
const THINK_VERSION = '3.2.3';
// URL 模式定义
const URL_COMMON = 0; //普通模式
const URL_PATHINFO = 1; //PATHINFO模式
const URL_REWRITE = 2; //REWRITE模式
const URL_COMPAT = 3; // 兼容模式
// 类文件后缀
const EXT = '.class.php';
require __DIR__ . '/ConstDefine.php';
// 系统信息
if(version_compare(PHP_VERSION,'5.4.0','<')) {
ini_set('magic_quotes_runtime',0);
define('MAGIC_QUOTES_GPC',false);
}else{
define('MAGIC_QUOTES_GPC',false);
}
defined("IS_CGI") || define('IS_CGI',(0 === strpos(PHP_SAPI,'cgi') || false !== strpos(PHP_SAPI,'fcgi')) ? 1 : 0 );
defined("IS_WIN") || define('IS_WIN',strstr(PHP_OS, 'WIN') ? 1 : 0 );
defined("IS_CLI") || define('IS_CLI',PHP_SAPI=='cli'? 1 : 0);
if(env("APP_MAINTENANCE", false) && (!isset($_SERVER['argv']) || !isset($_SERVER['argv'][2]) || $_SERVER['argv'][2] != 'maintenance'))
{
if(!IS_CLI){
header('HTTP/1.1 503 Service Unavailable');
// 确保FastCGI模式下正常
header('Status:503 Service Unavailable');
}
echo '系统维护中,请稍后再尝试';
exit();
}
if(!IS_CLI) {
// 当前文件名
if(!defined('_PHP_FILE_')) {
if(IS_CGI) {
//CGI/FASTCGI模式下
$_temp = explode('.php',$_SERVER['PHP_SELF']);
define('_PHP_FILE_', rtrim(str_replace($_SERVER['HTTP_HOST'],'',$_temp[0].'.php'),'/'));
}else {
define('_PHP_FILE_', rtrim($_SERVER['SCRIPT_NAME'],'/'));
}
}
if(!defined('__ROOT__')) {
$_root = rtrim(dirname(_PHP_FILE_),'/');
define('__ROOT__', (($_root=='/' || $_root=='\\')?'':$_root));
}
}
// 加载核心Think类
require CORE_PATH.'Think'.EXT;
// 应用初始化
Think\Think::start();<file_sep>/src/Library/Qscmf/Builder/GenButton/TGenButton.class.php
<?php
namespace Qscmf\Builder\GenButton;
use Bootstrap\RegisterContainer;
trait TGenButton
{
private $_button_type;
private $_button_dom_type = 'a';
public function registerButtonType(){
static $button_type = [];
if(empty($button_type)) {
$base_button_type = self::registerBaseButtonType();
$button_type = array_merge($base_button_type, RegisterContainer::getListRightButtonType());
}
$this->_button_type = $button_type;
}
protected function registerBaseButtonType(){
return [
'forbid' => \Qscmf\Builder\ListRightButton\Forbid\Forbid::class,
'edit' => \Qscmf\Builder\ListRightButton\Edit\Edit::class,
'delete' => \Qscmf\Builder\ListRightButton\Delete\Delete::class,
'self' => \Qscmf\Builder\ListRightButton\Self\SelfButton::class
];
}
public function parseButtonList($button_list, &$data){
$new_button_list = [];
foreach ($button_list as $one_button) {
if(isset($one_button['attribute']['{key}']) && isset($one_button['attribute']['{condition}']) && isset($one_button['attribute']['{value}'])){
$continue_flag = false;
switch($one_button['attribute']['{condition}']){
case 'eq':
if($data[$one_button['attribute']['{key}']] != $one_button['attribute']['{value}']){
$continue_flag = true;
}
break;
case 'neq':
if($data[$one_button['attribute']['{key}']] == $one_button['attribute']['{value}']){
$continue_flag = true;
}
break;
}
if($continue_flag){
continue;
}
unset($one_button['attribute']['{key}']);
unset($one_button['attribute']['{condition}']);
unset($one_button['attribute']['{value}']);
}
if($one_button['options']){
$json_options = json_encode($one_button['options']);
$json_options = $this->parseData($json_options, $data);
$one_button['options'] = json_decode($json_options, true);
}
if(isset($one_button['attribute']['title']) && empty($one_button['attribute']['title'])){
unset($one_button['attribute']['title']);
}
$content = (new $this->_button_type[$one_button['type']]())->build($one_button, $data, $this);
$button_html = self::compileRightButton($one_button, $data);
$tmp = <<<HTML
{$button_html}
{$content}
HTML;
$new_button_list[] = $tmp;
}
return $new_button_list;
}
protected function parseData($str, $data){
while(preg_match('/__(\w+?)__/i', $str, $matches)){
$str = str_replace('__' . $matches[1] . '__', $data[$matches[1]], $str);
}
return $str;
}
//编译HTML属性
protected function compileHtmlAttr($attr) {
$result = array();
foreach ($attr as $key => $value) {
if($key == 'tips'){
continue;
}
if(!empty($value) && !is_array($value)){
$value = htmlspecialchars($value);
$result[] = "$key=\"$value\"";
}
}
$result = implode(' ', $result);
return $result;
}
protected function compileRightButton($option, $data){
// 将约定的标记__data_id__替换成真实的数据ID
$option['attribute']['href'] = preg_replace(
'/__data_id__/i',
$data[$this->getPrimaryKey()],
$option['attribute']['href']
);
//将data-id的值替换成真实数据ID
$option['attribute']['data-id'] = preg_replace(
'/__data_id__/i',
$data[$this->getPrimaryKey()],
$option['attribute']['data-id']
);
$tips = '';
if($option['tips'] && is_string($option['tips'])){
$tips = ' <span class="badge">' . $option['tips'] . '</span>';
}
else if($option['tips'] && $option['tips'] instanceof \Closure){
$tips_value = $option['tips']($data[$this->getPrimaryKey()]);
$tips = ' <span class="badge">' . $tips_value . '</span>';
}
$attribute_html = $this->compileHtmlAttr($option['attribute']);
$attribute_html = self::parseData($attribute_html, $data);
return <<<HTML
<{$this->_button_dom_type} {$attribute_html}>{$option['attribute']['title']}{$tips}</{$this->_button_dom_type}>
HTML;
}
/**
* 加入一按钮
*
* @param string $type 按钮类型,取值参考registerBaseRightButtonType
* @param array|null $attribute 按钮属性,一个定义标题/链接/CSS类名等的属性描述数组
* @param string $tips 按钮提示
* @param string|array $auth_node 按钮权限点
* @param string|array|object $options 按钮options
* @return array
*/
public function genOneButton($type, $attribute = null, $tips = '', $auth_node = '', $options = []) {
$button_option['type'] = $type;
$button_option['attribute'] = $attribute;
$button_option['tips'] = $tips;
$button_option['auth_node'] = $auth_node;
$button_option['options'] = $options;
return $button_option;
}
public function setButtonDomType($type){
$this->_button_dom_type = $type;
return $this;
}
public function mergeAttr($def_attr, $cus_attr){
$right_btn_def_class = $this->getBtnDefClass();
$right_btn_def_class && $def_attr['class'] = $right_btn_def_class.' '.$def_attr['class'];
return array_merge($def_attr, $cus_attr ?: []);
}
}<file_sep>/src/Library/Qscmf/Lib/Elasticsearch/ElasticsearchHelper.class.php
<?php
namespace Qscmf\Lib\Elasticsearch;
use Exception;
trait ElasticsearchHelper{
protected $_deleted_ents;
protected $_will_updated_ents;
protected $index_columns;
public function addAll(){
E('Elasticsearch model batch action is forbidden');
}
public function selectAdd($fields='',$table='',$options=array()){
E('Elasticsearch model batch action is forbidden');
}
protected function varAndConst($search, &$match){
return preg_match('#^:([A-Za-z_]+)(?:{([A-Za-z0-9_]+)})?$#', $search, $match);
}
protected function varAndFunction($search, &$match){
return preg_match('#^:([A-Za-z_]+)\|([A-Za-z0-9_]+)$#', $search, $match);
}
protected function getIndexColumn(){
if($this->index_columns){
return $this->index_columns;
}
if(!$this instanceof ElasticsearchModelContract){
E('model must implements ElasticsearchModelContract');
}
$params = self::elasticsearchAddDataParams();
$columns = [];
foreach($params['body'] as $k => $v){
if(self::varAndConst($v, $match)){
array_push($columns, $match[1]);
}
else if(self::varAndFunction($v, $match)){
array_push($columns, $match[1]);
}
}
$this->index_columns = $columns;
return $columns;
}
protected function isUpdateNeedForIndex($updated_ent){
$index_columns = self::getIndexColumn();
array_push($index_columns, $this->getPk());
$updated_ent = array_intersect_key($updated_ent, array_flip($index_columns));
return array_diff($this->_will_updated_ents[$updated_ent[$this->getPk()]],$updated_ent) ? true : false;
}
protected function compileParams($ent, $params = []){
if(!$this instanceof ElasticsearchModelContract){
E('model must implements ElasticsearchModelContract');
}
if(empty($params)){
$params = self::elasticsearchAddDataParams();
}
if(!is_array($params)){
E('elasticsearch params must be array type');
}
foreach($params as $k => $v){
if(is_array($v)){
$params[$k] = self::compileParams($ent, $v);
}
if(self::varAndConst($v, $match)){
$value = $ent[$match[1]];
if(isset($match[2])){
$value = $value . $match[2];
}
$params[$k] = $value;
}
else if(self::varAndfunction($v, $match)){
if(function_exists($match[2])){
$params[$k] = call_user_func($match[2], $ent[$match[1]]);
}
else{
$params[$k] = call_user_func([$this, $match[2]], $ent[$match[1]]);
}
}
}
return $params;
}
protected function _after_insert($data,$options) {
if(parent::_after_insert($data, $options) === false){
return false;
}
if(self::isElasticsearchIndex($data) === false){
return true;
}
$params = self::compileParams($data);
self::genElasticIndex($params);
}
protected function _before_update($data,$options){
if(parent::_before_update($data, $options) === false){
return false;
}
$index_columns = [$this->getPk()];
$index_columns = array_merge($index_columns, self::getIndexColumn());
$this->_will_updated_ents = $this->where($options['where'])->getField($this->getPk() . ',' . implode(',', $index_columns));
}
protected function _after_update($data,$options) {
if(parent::_after_update($data, $options) === false){
return false;
}
$ents = $this->where($options['where'])->select();
if(!$ents){
return true;
}
foreach($ents as $ent){
$params = self::compileParams($ent);
if(self::isElasticsearchIndex($ent) === false){
self::deleteIndex($params);
}
else{
self::isUpdateNeedForIndex($ent) && self::genElasticIndex($params);
}
}
}
protected function _before_delete($options){
if(parent::_before_delete($options) === false){
return false;
}
$this->_deleted_ents = $this->where($options['where'])->select();
}
protected function _after_delete($data,$options) {
if(parent::_after_delete($data, $options) === false){
return false;
}
foreach($this->_deleted_ents as $ent){
$params = self::compileParams($ent);
self::deleteIndex($params);
}
}
protected function deleteIndex($params){
$params = [
'index' => $params['index'],
'type' => $params['type'],
'id' => $params['id'],
];
try{
$elastic_builder = Elasticsearch::getBuilder();
$result = $elastic_builder->get($params);
if($result['found'] === true){
$elastic_builder->delete($params);
}
}
catch(\Exception $e){
}
}
public function createIndex(){
$ents = self::elasticsearchIndexList();
$n = 0;
foreach($ents as $ent){
$params = self::compileParams($ent);
self::genElasticIndex($params);
$n++;
}
return $n;
}
protected function genElasticIndex($params){
try{
Elasticsearch::getBuilder()->index($params);
}
catch(Exception $e){
if(C('ELASTIC_ALLOW_EXCEPTION')){
E($e->getMessage());
}
}
}
}<file_sep>/src/Library/Qscmf/Lib/Tp3Resque/Redisent/RedisException.class.php
<?php
namespace Qscmf\Lib\Tp3Resque\Redisent;
use Exception;
class RedisException extends Exception{
}<file_sep>/src/Library/Behavior/InjectBodyBehavior.class.php
<?php
namespace Behavior;
class InjectBodyBehavior{
use InjectTrait;
public function run(&$params){
$template_suffix = $params['template_suffix'];
$extend_name = $params['extend_name'];
$this->inject_body($params['content'], $extend_name, $template_suffix);
}
private function inject_body(&$content, $extend_name, $template_suffix){
$tag_begin = C('QS_REGISTER_BODY_TAG_BEGIN');
$tag_end = C('QS_REGISTER_BODY_TAG_END');
$inject_sign_html = $tag_begin .PHP_EOL. $tag_end;
$can_inject = $this->canInject($extend_name, $content, $template_suffix, $tag_begin);
$content = $can_inject ? str_ireplace('</body>',$inject_sign_html. PHP_EOL .'</body>',$content) : $content;
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/UploadConfig.class.php
<?php
namespace Qscmf\Builder\FormType;
class UploadConfig
{
protected $config = [];
public function __construct($type){
$this->config = C('UPLOAD_TYPE_' . strtoupper($type));
}
public function getExts(){
$exts = $this->config['exts'];
if($exts){
$exts = '*.'.str_replace(',',';*.', $exts);
}else{
$exts = '*.*';
}
return $exts;
}
public function getMaxSize(){
$maxSize = $this->config['maxSize'];
return is_numeric($maxSize) && $maxSize > 0 ? $maxSize : 1024*1024*1024*1024;
}
public function __call($method,$args) {
if (function_exists($this->$method)){
$this->$method($args);
}
if(substr($method,0,3)==='get') {
$key = lcfirst(substr($method, 3));
return $this->config[$key];
}
}
}
<file_sep>/src/Library/Qscmf/Builder/CompareBuilder.class.php
<?php
/**
* Created by PhpStorm.
* User: 95869
* Date: 2018/11/6
* Time: 11:53
*/
namespace Qscmf\Builder;
class CompareBuilder extends BaseBuilder
{
const ITEM_TYPE_TEXT='text';
const ITEM_TYPE_SELECT='select';
const ITEM_TYPE_DATE='date';
const ITEM_TYPE_DATETIME='datetime';
const ITEM_TYPE_PICTURE='picture';
const ITEM_TYPE_PICTURES='pictures';
const ITEM_TYPE_UEDITOR='ueditor';
const ITEM_TYPE_HTMLDIFF='htmldiff';
private $_compare_items=[];
private $_old_data=[];
private $_new_data=[];
/**
* @param array $old_data
* @param array $new_data
* @return CompareBuilder
*/
public function setData($old_data,$new_data)
{
$this->_old_data = $old_data;
$this->_new_data = array_merge($old_data,$new_data);
return $this;
}
/**
* 初始化方法
*/
protected function _initialize() {
$module_name = 'Admin';
$this->_template = __DIR__ .'/Layout/'.$module_name.'/compare.html';
}
public function addCompareItem($name,$type,$title,$option=[]){
$item=[
'name'=>$name,
'type'=>$type,
'title'=>$title,
'option'=>$option
];
$this->_compare_items[]=$item;
return $this;
}
/**
* @deprecated 在v13版本删除, 请使用 build 代替
* 显示页面
*/
public function display($templateFile='',$charset='',$contentType='',$content='',$prefix='') {
$this->build();
}
public function build(){
$this->assign('nid', $this->_nid);
$this->assign('extra_html', $this->_extra_html);
$this->assign('old_data', $this->_old_data);
$this->assign('new_data', $this->_new_data);
$this->assign('compare_items', $this->_compare_items);
$this->assign('meta_title', $this->_meta_title);
$this->assign('top_html', $this->_top_html); // 顶部自定义html代码
$this->assign('compare_builder_path', __DIR__ . '/compareBuilder.html');
parent::display($this->_template);
}
}<file_sep>/asset/libs/admin/common.js
var left_side_width = 220; //Sidebar width in pixels
String.prototype.trim=function(char){
if(char){
return this.replace(new RegExp('^\\'+char+'+|\\'+char+'+$', 'g'), '');
}
return this.replace(/^\s+|\s+$/g, '');
}
String.prototype.ltrim=function(char){
if(char){
return this.replace(new RegExp('^\\'+char+'+', 'g'), '');
}
return this.replace(/^\s+|\s+$/g, '');
}
String.prototype.rtrim=function(char){
if(char){
return this.replace(new RegExp('\\'+char+'+$', 'g'), '');
}
return this.replace(/^\s+|\s+$/g, '');
}
function Guid(g){
var arr = new Array(); //存放32位数值的数组
if (typeof(g) == "string"){ //如果构造函数的参数为字符串
InitByString(arr, g);
}
else{
InitByOther(arr);
}
//返回一个值,该值指示 Guid 的两个实例是否表示同一个值。
this.Equals = function(o){
if (o && o.IsGuid){
return this.ToString() == o.ToString();
}
else{
return false;
}
}
//Guid对象的标记
this.IsGuid = function(){}
//返回 Guid 类的此实例值的 String 表示形式。
this.ToString = function(format){
if(typeof(format) == "string"){
if (format == "N" || format == "D" || format == "B" || format == "P"){
return ToStringWithFormat(arr, format);
}
else{
return ToStringWithFormat(arr, "D");
}
}
else{
return ToStringWithFormat(arr, "D");
}
}
//由字符串加载
function InitByString(arr, g){
g = g.replace(/\{|\(|\)|\}|-/g, "");
g = g.toLowerCase();
if (g.length != 32 || g.search(/[^0-9,a-f]/i) != -1){
InitByOther(arr);
}
else{
for (var i = 0; i < g.length; i++){
arr.push(g[i]);
}
}
}
//由其他类型加载
function InitByOther(arr){
var i = 32;
while(i--){
arr.push("0");
}
}
/*
根据所提供的格式说明符,返回此 Guid 实例值的 String 表示形式。
N 32 位: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
D 由连字符分隔的 32 位数字 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
B 括在大括号中、由连字符分隔的 32 位数字:{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
P 括在圆括号中、由连字符分隔的 32 位数字:(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
*/
function ToStringWithFormat(arr, format){
switch(format){
case "N":
return arr.toString().replace(/,/g, "");
case "D":
var str = arr.slice(0, 8) + "-" + arr.slice(8, 12) + "-" + arr.slice(12, 16) + "-" + arr.slice(16, 20) + "-" + arr.slice(20,32);
str = str.replace(/,/g, "");
return str;
case "B":
var str = ToStringWithFormat(arr, "D");
str = "{" + str + "}";
return str;
case "P":
var str = ToStringWithFormat(arr, "D");
str = "(" + str + ")";
return str;
default:
return new Guid();
}
}
}
//Guid 类的默认实例,其值保证均为零。
Guid.Empty = new Guid();
//初始化 Guid 类的一个新实例。
Guid.NewGuid = function(){
var g = "";
var i = 32;
while(i--){
g += Math.floor(Math.random()*16.0).toString(16);
}
return new Guid(g);
}
//select2 使用回调函数
function formatRepo(repo) {
if (repo.loading)
return repo.text;
var markup = '<span>' + repo.text + '</span>';
return markup;
}
//select2 使用回调函数
function formatRepoSelection(repo) {
return repo.text;
}
$(function() {
// 'use strict';
//退出页面需确认
// if($('.builder-form-box').length){
// var submit_clicked = false;
// $('button[type="submit"]').click(function(){
// submit_clicked = true;
// });
// window.onbeforeunload = function(){
// if(!submit_clicked){
// return "所有未保存内容将被丢弃!您确定要退出页面吗?";
// }
// }
// }
//Enable sidebar toggle
$("[data-toggle='offcanvas']").click(function(e) {
e.preventDefault();
//If window is small enough, enable sidebar push menu
if ($(window).width() <= 992) {
$('.row-offcanvas').toggleClass('active');
$('.left-side').removeClass("collapse-left");
$(".right-side").removeClass("strech");
$('.row-offcanvas').toggleClass("relative");
} else {
//Else, enable content streching
$('.left-side').toggleClass("collapse-left");
$(".right-side").toggleClass("strech");
}
});
//放大图片
$('.builder-form-box .img-box img').each(function(){
new Viewer(this,{
url: 'data-original'
});
})
//ajax post submit请求
$('body').delegate('.ajax-post', 'click', function() {
var target, query, form;
var target_form = $(this).attr('target-form');
var that = this;
var nead_confirm = false;
if (($(this).attr('type') == 'submit') || (target = $(this).attr('href')) || (target = $(this).attr('url'))) {
form = $('.' + target_form);
if ($(this).attr('hide-data') === 'true') { //无数据时也可以使用的功能
form = $('.hide-data');
query = form.serialize();
} else if (form.get(0) == undefined) {
return false;
} else if (form.get(0).nodeName == 'FORM') {
if ($(this).hasClass('confirm')) {
var confirm_msg = $(this).attr('confirm-msg');
if (!confirm(confirm_msg ? confirm_msg : '确认要执行该操作吗?')) {
return false;
}
}
if ($(this).attr('url') !== undefined) {
target = $(this).attr('url');
} else {
target = form.get(0).action;
}
query = form.serialize();
} else if (form.get(0).nodeName == 'INPUT' || form.get(0).nodeName == 'SELECT' || form.get(0).nodeName == 'TEXTAREA') {
form.each(function(k, v) {
if (v.type == 'checkbox' && v.checked == true) {
nead_confirm = true;
}
});
if (nead_confirm && $(this).hasClass('confirm')) {
var confirm_msg = $(this).attr('confirm-msg');
if (!confirm(confirm_msg ? confirm_msg : '确认要执行该操作吗?')) {
return false;
}
}
query = form.serialize();
} else {
if ($(this).hasClass('confirm')) {
var confirm_msg = $(this).attr('confirm-msg');
if (!confirm(confirm_msg ? confirm_msg : '确认要执行该操作吗?')) {
return false;
}
}
query = form.find('input,select,textarea').serialize();
}
var cus_query;
cus_query = $(this).attr('query');
if(cus_query){
query += '&' + cus_query;
}
$(that).addClass('disabled').attr('autocomplete', 'off').prop('disabled', true);
$.post(target, query).success(function(data) {
console.log(data);
if (data.status == 1) {
if (data.url && !$(that).hasClass('no-refresh')) {
var message = data.info + ' 页面即将自动跳转~';
} else {
var message = data.info;
}
toastr.remove();
toastr["success"](message);
setTimeout(function() {
var js = /javascript:(.+)/g.exec(data.url);
if(js){
eval(js[1]);
return;
}
if (data.url && !$(that).hasClass('no-forward')) {
location.href = data.url;
} else {
location.reload();
}
}, 2000);
} else {
toastr.remove();
$.bs_messagebox('错误', data.info, 'ok');
setTimeout(function() {
$(that).removeClass('disabled').prop('disabled', false);
}, 2000);
if($('.reload-verify').length > 0){
$('.reload-verify').click();
}
}
});
}
return false;
});
//ajax get请求
$('body').delegate('.ajax-get', 'click', function() {
var target;
var that = this;
if ($(this).hasClass('confirm')) {
var confirm_msg = $(this).attr('confirm-msg');
if (!confirm(confirm_msg ? confirm_msg : '确认要执行该操作吗?')) {
return false;
}
}
if ((target = $(this).attr('href')) || (target = $(this).attr('url'))) {
$(this).addClass('disabled').attr('autocomplete', 'off').prop('disabled', true);
$.get(target).success(function(data) {
console.log(data);
if (data.status == 1) {
if (data.url && !$(that).hasClass('no-refresh')) {
var message = data.info + ' 页面即将自动跳转~';
} else {
var message = data.info;
}
toastr.remove();
toastr["success"](message);
setTimeout(function() {
$(that).removeClass('disabled').prop('disabled', false);
if ($(that).hasClass('no-refresh')) {
return false;alert();
}
if (data.url && !$(that).hasClass('no-forward')) {
location.href = data.url;
} else {
location.reload();
}
}, 2000);
} else {
if (data.login == 1) {
$('#login-modal').modal(); //弹出登陆框
} else {
toastr.remove();
$.bs_messagebox('错误', data.info, 'ok');
}
setTimeout(function() {
$(that).removeClass('disabled').prop('disabled', false);
}, 2000);
}
});
}
return false;
});
});
//ajax访问网址并返回信息
function ajaxlink($this, url) {
if (typeof url == 'string') {
$.ajax({
url: url, //与此php页面沟通
beforeSend: function() {
//禁用提交按钮,防止重复提交
$this.attr('disabled', true);
toastr.remove();
toastr["info"]("操作进行中");
return true;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
toastr.remove();
$.bs_messagebox('错误', $(XMLHttpRequest.responseText).find('h1').text(), 'ok');
$this.attr('disabled', false);
},
success: function(data) {
if (data.status === 1) {
type = "success";
toastr.remove();
toastr["success"](data.info);
} else {
type = "error";
toastr.remove();
$.bs_messagebox('错误', data.info, 'ok');
}
if (type === 'success') {
//成功则跳转到返回的网址
if(data.url){
setTimeout(function() {
window.location = data.url;
}, 300);
}
else{
setTimeout(function() {
window.location.reload();
}, 300);
}
} else {
$this.attr('disabled', false);
}
}
});
}
}
//function headerWidth() {
// $('.content-header').width($('.right-side').width() - 35);
//}
//jQuery(function($) {
// $(document).ready(function() {
// //固定标题功能栏
// //$('.content-header').stickUp();
// if($('.stickbtn').length){
// $('.stickbtn').stickUp();
// }
// else{
// $('.content-header').stickUp();
// }
// });
//});
$(function() {
if ($('.file_upload').length) {
$('.file_upload').fileupload({
dataType: 'json',
done: function(e, data) {
var result = data.result;
$parentWrapper = $(this).parents('.upload-wrapper');
if (result.Status == 1) {
if (result.Data.url)
$parentWrapper.find('.file_name').html('<a target="_blank" href="' + result.Data.url + '">' + result.Data.title + '</a>');
$parentWrapper.find('.file_id').val(result.Data.file_id);
} else {
$parentWrapper.find('p.upload_error').text(result.info);
}
},
progress: function(e, data) {
$(this).parents('.upload-wrapper').find('p.upload_error').text('');
$progress = $(this).parents('.upload-wrapper').find('.progress');
if ($progress.not('.in')) {
$progress.addClass('in');
}
var progress = parseInt(data.loaded / data.total * 100, 10);
$progress.children('.progress-bar').css(
'width',
progress + '%'
);
if (progress === 100) {
progress = 0;
setTimeout(function() {
$progress.removeClass('in').children().css(
'width',
progress + '%'
);
}, 1000);
};
}
});
}
if ($('.image_upload').length) {
$('.image_upload').fileupload({
dataType: 'json',
done: function(e, data) {
var result = data.result;
$parentWrapper = $(this).parents('.upload-wrapper');
if (result.Status == 1) {
if (result.Data.url)
$parentWrapper.find('.image_pic').attr('src', result.Data.url);
$parentWrapper.find('.image_id').val(result.Data.file_id);
} else {
$parentWrapper.find('p.upload_error').text(result.info);
}
},
progress: function(e, data) {
$(this).parents('.upload-wrapper').find('p.upload_error').text('');
$progress = $(this).parents('.upload-wrapper').find('.progress');
if ($progress.not('.in')) {
$progress.addClass('in');
}
var progress = parseInt(data.loaded / data.total * 100, 10);
$progress.children('.progress-bar').css(
'width',
progress + '%'
);
if (progress === 100) {
progress = 0;
setTimeout(function() {
$progress.removeClass('in').children().css(
'width',
progress + '%'
);
}, 1000);
};
}
});
}
//后台标题导航栏宽度
// $(window).resize(function() {
// headerWidth();
// });
// headerWidth();
//单个项操作
$('body').delegate('.ajax-submit', 'click', function() {
ajaxlink($(this), $(this).attr('href'));
return false;
});
//左边菜单高亮判断
var n_id = $('.content').attr('n-id');
$("li[n-id=" + n_id + "]").addClass('active').parent().parent().addClass('active');
//信息提示插件选项
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-top-right",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "300",
"timeOut": "0",
"extendedTimeOut": "0",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "slideDown",
"hideMethod": "slideUp"
};
//ajax提交form
$('body').delegate('.ajax-form', 'submit', function(e) {
e.preventDefault();
var formValues = $(this).serialize();
var customShowMsg = function(info){return true};
if(typeof jQuery.data(this, 'showMsg') === 'function'){
var that = this;
var customShowMsg = function(info){
var showMsg = jQuery.data(that, 'showMsg');
showMsg(info);
};
}
var reload = $(this).attr('reload');
$.ajax({
url: $(this).attr('action') ? $(this).attr('action') : document.URL,
type: $(this).attr('method'),
data: formValues,
beforeSend: function() {
$('button[type=submit]').attr('disabled', true);
toastr.remove();
toastr["info"]("操作进行中");
return true;
},
success: function(data) {
//成功状态,下面的是服务器返回的,数据库操作的状态
var type;
if (data.status === 1) {
type = "success";
if(customShowMsg(data.info) === true) {
toastr.remove();
toastr["success"](data.info);
}
} else {
type = "error";
toastr.remove();
$.bs_messagebox('错误', data.info, 'ok', function(){
if(data.url){
setTimeout(function() {
window.location = data.url;
}, 300);
}
});
}
if (type === 'success') {
//成功则跳转到返回的网址
var js = /javascript:(.+)/g.exec(data.url);
if(js){
eval(js[1]);
return;
}
if(data.url){
setTimeout(function() {
window.location = data.url;
}, 300);
}
else{
reload !== 'false' && setTimeout(function() {
window.location.reload();
}, 300);
}
}
$('button[type=submit]').removeAttr('disabled');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
toastr.remove();
$.bs_messagebox('错误', $(XMLHttpRequest.responseText).find('h1').text(), 'ok');
$(this).attr('disabled', false);
},
});
});
//触屏hover支持
$('.btn').bind('touchstart', function() {
$(this).addClass('hover');
}).bind('touchend', function() {
$(this).removeClass('hover');
});
//提示框
$("[data-toggle='tooltip']").tooltip();
/* 侧栏导航树状结构 */
$(".sidebar .treeview").tree();
/*
*侧栏最小高度
*
**/
function _fix() {
//Get window height and the wrapper height
var height = $(window).height() - $("body > .header").height() - ($("body > .footer").outerHeight() || 0);
$(".wrapper").css("min-height", height + "px");
var content = $(".wrapper").height();
//If the wrapper height is greater than the window
if (content > height)
//then set sidebar height to the wrapper
$(".left-side, html, body").css("min-height", content + "px");
else {
//Otherwise, set the sidebar to the height of the window
$(".left-side, html, body").css("min-height", height + "px");
}
}
_fix();
$(".wrapper").resize(function() {
_fix();
fix_sidebar();
});
fix_sidebar();
// /*
// * iCheck
// */
// $("input[type='checkbox']:not('.simple'), input[type='radio']:not('.simple')").iCheck({
// checkboxClass: 'icheckbox_minimal-blue',
// radioClass: 'iradio_minimal-blue'
// });
//点击reset按钮时,复位所有checkbox控件
// $("[type=reset]").click(function() {
// $("input[type='checkbox']:not('.simple'), input[type='radio']:not('.simple')").iCheck('uncheck');
// });
// //弹出modal框之前,检查复选框是否至少选了一项
// $('.select-operate').on('show.bs.modal', function(e) {
// var checkboxGroup = $('[data-target=group-of-checkbox]').data('checkboxGroup');
// if (!checkboxGroup.getCheckedValue()) {
// $.bs_messagebox('错误', '请至少选择一项', 'ok');
// return e.preventDefault() // stops modal from being shown
// }
// });
//复位搜索页面
$('a#reset-search').click(function() {
window.location.href = window.location.href.split('?')[0];
return false;
});
//设置header,左侧栏的高度
var updateHeaderHeight = function(){
var headerTop = $('body > .header').height();
$('body > .wrapper.row-offcanvas.row-offcanvas-left').css({
'margin-top': headerTop,
}).children('.left-side.sidebar-offcanvas').css({
top: headerTop
});
};
$(window).on('resize', updateHeaderHeight);
updateHeaderHeight();
//让.navbar-container滚动到选中的菜单
if($('.header .navbar-container .navbar-nav.on').length > 0){
$('.header .navbar-container').scrollLeft($('.header .navbar-container .navbar-nav.on').position().left);
}
//初始化 .navbar-container滚动条
if(window.PerfectScrollbar){
new PerfectScrollbar($('.header .navbar-container').get(0),{
suppressScrollY: true,
swipeEasing: true,
useBothWheelAxes: true,
});
}
});
function fix_sidebar() {
//Make sure the body tag has the .fixed class
if (!$("body").hasClass("fixed")) {
return;
}
//Add slimscroll
$(".sidebar").slimscroll({
height: ($(window).height() - $(".header").height()) + "px",
color: "rgba(0,0,0,0.2)"
});
}
//树
(function($) {
"use strict";
$.fn.tree = function() {
return this.each(function() {
var btn = $(this).children("a").first();
var menu = $(this).children(".treeview-menu").first();
var isActive = $(this).hasClass('active');
//initialize already active menus
if (isActive) {
menu.show();
btn.children(".fa-angle-left").first().removeClass("fa-angle-left").addClass("fa-angle-down");
}
//Slide open or close the menu on link click
btn.click(function(e) {
e.preventDefault();
if (isActive) {
//Slide up to close menu
menu.slideUp(200);
isActive = false;
btn.children(".fa-angle-down").first().removeClass("fa-angle-down").addClass("fa-angle-left");
btn.parent("li").removeClass("active");
} else {
//Slide down to open menu
$('.treeview.active').children("a").first().trigger('click');
menu.slideDown(200);
isActive = true;
btn.children(".fa-angle-left").first().removeClass("fa-angle-left").addClass("fa-angle-down");
btn.parent("li").addClass("active");
}
});
/* Add margins to submenu elements to give it a tree look */
menu.find("li > a").each(function() {
var pad = parseInt($(this).css("margin-left")) + 10;
$(this).css({
"margin-left": pad + "px"
});
});
});
};
}(jQuery));
/* 居中 */
(function($) {
"use strict";
jQuery.fn.center = function(parent) {
if (parent) {
parent = this.parent();
} else {
parent = window;
}
this.css({
"position": "absolute",
"top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
"left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
});
return this;
}
}(jQuery));
/*
* jQuery resize event - v1.1 - 3/14/2010
* http://benalman.com/projects/jquery-resize-plugin/
*
* Copyright (c) 2010 "Cowboy" <NAME>
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($, h, c) {
var a = $([]),
e = $.resize = $.extend($.resize, {}),
i, k = "setTimeout",
j = "resize",
d = j + "-special-event",
b = "delay",
f = "throttleWindow";
e[b] = 250;
e[f] = true;
$.event.special[j] = {
setup: function() {
if (!e[f] && this[k]) {
return false;
}
var l = $(this);
a = a.add(l);
$.data(this, d, {
w: l.width(),
h: l.height()
});
if (a.length === 1) {
g();
}
},
teardown: function() {
if (!e[f] && this[k]) {
return false
}
var l = $(this);
a = a.not(l);
l.removeData(d);
if (!a.length) {
clearTimeout(i);
}
},
add: function(l) {
if (!e[f] && this[k]) {
return false
}
var n;
function m(s, o, p) {
var q = $(this),
r = $.data(this, d);
r.w = o !== c ? o : q.width();
r.h = p !== c ? p : q.height();
n.apply(this, arguments)
}
if ($.isFunction(l)) {
n = l;
return m
} else {
n = l.handler;
l.handler = m
}
}
};
function g() {
i = h[k](function() {
a.each(function() {
var n = $(this),
m = n.width(),
l = n.height(),
o = $.data(this, d);
if (m !== o.w || l !== o.h) {
n.trigger(j, [o.w = m, o.h = l])
}
});
g()
}, e[b])
}
//设置header,左侧栏的高度
var headerTop = $('body > .header').height();
$('.main-wrapper-js').css({
'margin-top': headerTop,
});
$('.left-side-js').css({
top: headerTop
});
})(jQuery, this);
/*!
* SlimScroll https://github.com/rochal/jQuery-slimScroll
* =======================================================
*
* Copyright (c) 2011 <NAME> (http://rocha.la) Dual licensed under the MIT
*/
(function(f) {
jQuery.fn.extend({slimScroll: function(h) {
var a = f.extend({width: "auto", height: "250px", size: "7px", color: "#000", position: "right", distance: "1px", start: "top", opacity: 0.4, alwaysVisible: !1, disableFadeOut: !1, railVisible: !1, railColor: "#333", railOpacity: 0.2, railDraggable: !0, railClass: "slimScrollRail", barClass: "slimScrollBar", wrapperClass: "slimScrollDiv", allowPageScroll: !1, wheelStep: 20, touchScrollStep: 200, borderRadius: "0px", railBorderRadius: "0px"}, h);
this.each(function() {
function r(d) {
if (s) {
d = d ||
window.event;
var c = 0;
d.wheelDelta && (c = -d.wheelDelta / 120);
d.detail && (c = d.detail / 3);
f(d.target || d.srcTarget || d.srcElement).closest("." + a.wrapperClass).is(b.parent()) && m(c, !0);
d.preventDefault && !k && d.preventDefault();
k || (d.returnValue = !1)
}
}
function m(d, f, h) {
k = !1;
var e = d, g = b.outerHeight() - c.outerHeight();
f && (e = parseInt(c.css("top")) + d * parseInt(a.wheelStep) / 100 * c.outerHeight(), e = Math.min(Math.max(e, 0), g), e = 0 < d ? Math.ceil(e) : Math.floor(e), c.css({top: e + "px"}));
l = parseInt(c.css("top")) / (b.outerHeight() - c.outerHeight());
e = l * (b[0].scrollHeight - b.outerHeight());
h && (e = d, d = e / b[0].scrollHeight * b.outerHeight(), d = Math.min(Math.max(d, 0), g), c.css({top: d + "px"}));
b.scrollTop(e);
b.trigger("slimscrolling", ~~e);
v();
p()
}
function C() {
window.addEventListener ? (this.addEventListener("DOMMouseScroll", r, !1), this.addEventListener("mousewheel", r, !1), this.addEventListener("MozMousePixelScroll", r, !1)) : document.attachEvent("onmousewheel", r)
}
function w() {
u = Math.max(b.outerHeight() / b[0].scrollHeight * b.outerHeight(), D);
c.css({height: u + "px"});
var a = u == b.outerHeight() ? "none" : "block";
c.css({display: a})
}
function v() {
w();
clearTimeout(A);
l == ~~l ? (k = a.allowPageScroll, B != l && b.trigger("slimscroll", 0 == ~~l ? "top" : "bottom")) : k = !1;
B = l;
u >= b.outerHeight() ? k = !0 : (c.stop(!0, !0).fadeIn("fast"), a.railVisible && g.stop(!0, !0).fadeIn("fast"))
}
function p() {
a.alwaysVisible || (A = setTimeout(function() {
a.disableFadeOut && s || (x || y) || (c.fadeOut("slow"), g.fadeOut("slow"))
}, 1E3))
}
var s, x, y, A, z, u, l, B, D = 30, k = !1, b = f(this);
if (b.parent().hasClass(a.wrapperClass)) {
var n = b.scrollTop(),
c = b.parent().find("." + a.barClass), g = b.parent().find("." + a.railClass);
w();
if (f.isPlainObject(h)) {
if ("height"in h && "auto" == h.height) {
b.parent().css("height", "auto");
b.css("height", "auto");
var q = b.parent().parent().height();
b.parent().css("height", q);
b.css("height", q)
}
if ("scrollTo"in h)
n = parseInt(a.scrollTo);
else if ("scrollBy"in h)
n += parseInt(a.scrollBy);
else if ("destroy"in h) {
c.remove();
g.remove();
b.unwrap();
return
}
m(n, !1, !0)
}
} else {
a.height = "auto" == a.height ? b.parent().height() : a.height;
n = f("<div></div>").addClass(a.wrapperClass).css({position: "relative",
overflow: "hidden", width: a.width, height: a.height});
b.css({overflow: "hidden", width: a.width, height: a.height});
var g = f("<div></div>").addClass(a.railClass).css({width: a.size, height: "100%", position: "absolute", top: 0, display: a.alwaysVisible && a.railVisible ? "block" : "none", "border-radius": a.railBorderRadius, background: a.railColor, opacity: a.railOpacity, zIndex: 90}), c = f("<div></div>").addClass(a.barClass).css({background: a.color, width: a.size, position: "absolute", top: 0, opacity: a.opacity, display: a.alwaysVisible ?
"block" : "none", "border-radius": a.borderRadius, BorderRadius: a.borderRadius, MozBorderRadius: a.borderRadius, WebkitBorderRadius: a.borderRadius, zIndex: 99}), q = "right" == a.position ? {right: a.distance} : {left: a.distance};
g.css(q);
c.css(q);
b.wrap(n);
b.parent().append(c);
b.parent().append(g);
a.railDraggable && c.bind("mousedown", function(a) {
var b = f(document);
y = !0;
t = parseFloat(c.css("top"));
pageY = a.pageY;
b.bind("mousemove.slimscroll", function(a) {
currTop = t + a.pageY - pageY;
c.css("top", currTop);
m(0, c.position().top, !1)
});
b.bind("mouseup.slimscroll", function(a) {
y = !1;
p();
b.unbind(".slimscroll")
});
return!1
}).bind("selectstart.slimscroll", function(a) {
a.stopPropagation();
a.preventDefault();
return!1
});
g.hover(function() {
v()
}, function() {
p()
});
c.hover(function() {
x = !0
}, function() {
x = !1
});
b.hover(function() {
s = !0;
v();
p()
}, function() {
s = !1;
p()
});
b.bind("touchstart", function(a, b) {
a.originalEvent.touches.length && (z = a.originalEvent.touches[0].pageY)
});
b.bind("touchmove", function(b) {
k || b.originalEvent.preventDefault();
b.originalEvent.touches.length &&
(m((z - b.originalEvent.touches[0].pageY) / a.touchScrollStep, !0), z = b.originalEvent.touches[0].pageY)
});
w();
"bottom" === a.start ? (c.css({top: b.outerHeight() - c.outerHeight()}), m(0, !0)) : "top" !== a.start && (m(f(a.start).position().top, null, !0), a.alwaysVisible || c.hide());
C()
}
});
return this
}});
jQuery.fn.extend({slimscroll: jQuery.fn.slimScroll})
})(jQuery);
function setCheckedIds($this, selectIds, valDom) {
valDom = valDom || ".check-all";
var selectIds_str = '';
var ids = $this.val();
var ids_index = selectIds.indexOf(ids);
if($this.prop('checked')){
if (ids_index === -1) selectIds.push(ids);
}else{
if (ids_index !== -1) selectIds.splice(ids_index, 1);
}
if(selectIds) selectIds_str = selectIds.join(",");
$(valDom).data('checkedIds', selectIds_str);
}
// select2_ajax start
function select2_ajax(select_dom, url, query){
query.pageSize = (query.pageSize && query.pageSize > 20) ? query.pageSize : 20;
$(select_dom).select2({
ajax: {
url: url,
type: "GET",
dataType: 'JSON',
delay: 500,
data: function (params) {
$("input[class='select2-search__field']").on('input', function () {
query.search = params.term;
});
params = { //请求的参数, 关键字和搜索条件
search: params.term, //select搜索框里面的value
page: params.page || 1,
pageSize: query.pageSize || 20
};
params = $.extend(params, query);
return params;
},
processResults: function (res, params) {
params.page = params.page || 1;
params.pageSize = query.pageSize || 20;
//返回的选项必须处理成以下格式
//var results = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }];
return {
results: res.data,
pagination:{
more: (params.page * params.pageSize) < res.total_count
}
};
},
},
escapeMarkup: function (markup) {
return markup;
}, // 返回html实体,防止xss注入;
placeholder: '----请选择----', // 默认文字提示
allowClear: true // 允许清空
});
}
// select2_ajax end
// check list selected
function hasChosenListData(Dom){
let selectIds = $(".builder .check-all").data("checkedIds") || "";
if (Dom.hasClass("must-select-item") && !selectIds){
let msg = Dom.attr('must-select-msg') || "请选择要处理的数据";
alert(msg);
return false;
}
}<file_sep>/src/Library/Qscmf/Builder/ListSearchType/SelectCity/SelectCity.class.php
<?php
namespace Qscmf\Builder\ListSearchType\SelectCity;
use Think\View;
use Qscmf\Builder\ListSearchType\ListSearchType;
class SelectCity implements ListSearchType{
public function build(array $item){
$view = new View();
$view->assign('item', $item);
$content = $view->fetch(__DIR__ . '/select_city.html');
return $content;
}
static public function parse(string $key, string $map_key, array $get_data) : array{
if(isset($get_data[$key]) && !qsEmpty($get_data[$key])){
return [$map_key => $get_data[$key]];
}
else{
return [];
}
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Checkbox/Checkbox.class.php
<?php
namespace Qscmf\Builder\ColumnType\Checkbox;
use Qscmf\Builder\ButtonType\Save\TargetFormTrait;
use Qscmf\Builder\ColumnType\ColumnType;
use Qscmf\Builder\ColumnType\EditableInterface;
class Checkbox extends ColumnType implements EditableInterface{
use TargetFormTrait;
public function build(array &$option, array $data, $listBuilder){
$checked = !qsEmpty($data[$option['name']]);
return '<input type="checkbox" disabled '. ($checked ? 'checked':'') .'/>';
}
public function editBuild(&$option, $data, $listBuilder){
$class = "input ". $this->getSaveTargetForm(). " {$option['extra_class']}";
$checked = !qsEmpty($data[$option['name']]);
return "<input type='checkbox' onchange='$(this).next().val(this.checked);' class='{$class}' ".($checked ? 'checked':'')." {$option['extra_attr']}/>
<input type='hidden' name='{$option['name']}[]' class='{$class}' value='{$checked}' {$option['extra_attr']} />";
}
}<file_sep>/src/Library/Behavior/InjectTrait.class.php
<?php
namespace Behavior;
trait InjectTrait
{
public function canInject($extend_name, $content, $template_suffix, $sign_str){
$layout_path = T('Admin@default/common/dashboard_layout');
if(false === strpos($extend_name, $template_suffix)) {
// 解析规则为 模块@主题/控制器/操作
$extend_name = T($extend_name);
}
if (normalizeRelativePath($extend_name) !== $layout_path){
return false;
}
if (strpos($content, $sign_str)){
return false;
}
return true;
}
}<file_sep>/src/Library/Qscmf/Core/ModelHelper.class.php
<?php
namespace Qscmf\Core;
trait ModelHelper{
public function &generator($map = [], $count = 1){
if(!empty($map)){
$this->where($map);
}
$page = 1;
while($ents = $this->page($page, $count)->select()){
foreach($ents as $ent){
yield $ent;
}
$page++;
}
}
}<file_sep>/src/Larafortp/Provider/QscmfServiceProvider.php
<?php
namespace Larafortp\Provider;
use Illuminate\Database\Console\Migrations\MigrateCommand;
use Illuminate\Database\Console\Migrations\MigrateMakeCommand;
use Illuminate\Database\Migrations\MigrationCreator;
use Illuminate\Database\Migrations\Migrator;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use Larafortp\CmmMigrate\CmmFreshCommand;
use Larafortp\CmmMigrate\CmmMigrateCommand;
use Larafortp\CmmMigrate\CmmMigrationCreator;
use Larafortp\CmmMigrate\CmmMigrator;
use Larafortp\CmmMigrate\CmmRefreshCommand;
use Larafortp\CmmMigrate\CmmResetCommand;
use Larafortp\CmmMigrate\CmmRollbackCommand;
use Larafortp\CmmMigrate\DatabaseMigrationRepository;
use Larafortp\Commands\QscmfCreateSymlinkCommand;
use Larafortp\Commands\QscmfDiscoverCommand;
use Larafortp\Doctrine\Types\TinyInteger;
class QscmfServiceProvider extends ServiceProvider
{
protected $commands = [
QscmfDiscoverCommand::class
];
public function register(){
$this->commands($this->commands);
if(env("DB_CONNECTION")){
Schema::registerCustomDoctrineType(TinyInteger::class, TinyInteger::NAME, 'TINYINT');
}
$this->app->extend('migrator', function ($object, $app) {
$repository = $app['migration.repository'];
return new CmmMigrator($repository, $app['db'], $app['files'], $app['events']);
});
$this->app->extend('command.migrate', function ($object, $app) {
return new CmmMigrateCommand($app['migrator']);
});
$this->app->extend('command.migrate.fresh', function ($object, $app) {
return new CmmFreshCommand();
});
$this->app->extend('command.migrate.refresh', function ($object, $app) {
return new CmmRefreshCommand();
});
$this->app->extend('command.migrate.reset', function ($object, $app) {
return new CmmResetCommand($app['migrator']);
});
$this->app->extend('command.migrate.rollback', function ($object, $app) {
return new CmmRollbackCommand($app['migrator']);
});
$this->app->extend('migration.creator', function ($object, $app) {
return new CmmMigrationCreator($app['files']);
});
$this->app->extend('migration.repository', function($object, $app){
$table = $app['config']['database.migrations'];
return new DatabaseMigrationRepository($app['db'], $table);
});
}
}<file_sep>/src/Library/Qscmf/Core/IForbidModel.class.php
<?php
namespace Qscmf\Core;
interface IForbidModel{
function forbid($id);
function resume($id);
}
<file_sep>/src/Testing/DuskTestCase.php
<?php
namespace Testing;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\Concerns\InteractsWithDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Dusk\Browser;
use Laravel\Dusk\TestCase;
abstract class DuskTestCase extends TestCase
{
use InteractsWithDatabase;
use DBTrait;
protected $serverProcess;
abstract public function laraPath():string;
/**
* 创建 RemoteWebDriver 实例.
*
* @return \Facebook\WebDriver\Remote\RemoteWebDriver
*/
protected function driver()
{
$options = (new ChromeOptions())->addArguments([
'--disable-gpu',
'--disable-impl-side-painting',
'--disable-gpu-sandbox',
'--disable-accelerated-2d-canvas',
'--disable-accelerated-jpeg-decoding',
'--no-sandbox',
// '--disable-gpu',
'--headless',
// '--no-sandbox',
// '--window-size=1680,1050',
]);
return RemoteWebDriver::create(
'http://localhost:9515', DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY, $options
)
);
}
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require $this->laraPath() . '/bootstrap/app.php';
\Bootstrap\Context::providerRegister(true);
\Larafortp\ArtisanHack::init($app);
$app->make(Kernel::class)->bootstrap();
return $app;
}
public function setUp() : void
{
static::startChromeDriver();
parent::setUp();
Browser::$storeScreenshotsAt = base_path('tests/Browser/screenshots');
Browser::$storeConsoleLogAt = base_path('tests/Browser/console');
$this->uninstall();
$this->install();
$this->runServer();
}
public function tearDown() : void
{
$this->uninstall();
static::tearDownDuskClass();
parent::tearDown();
}
protected function runServer()
{
$phpBinaryFinder = new \Symfony\Component\Process\PhpExecutableFinder();
$phpBinaryPath = $phpBinaryFinder->find();
$host = str_replace('http://', '', $this->app['config']['app.url']);
$host = str_replace('https://', '', $host);
chdir(base_path('../www'));
$this->serverProcess = new \Symfony\Component\Process\Process([$phpBinaryPath, '-S', $host, base_path('server.php')]);
$this->serverProcess->start();
}
}
<file_sep>/src/Library/Qscmf/Builder/ColumnType/Pictures/Pictures.class.php
<?php
namespace Qscmf\Builder\ColumnType\Pictures;
use Qscmf\Builder\ColumnType\ColumnType;
use Think\View;
class Pictures extends ColumnType
{
public function build(array &$option, array $data, $listBuilder)
{
$pic = explode(',', $data[$option['name']]);
$images = [];
foreach($pic as $v){
if(!$v){
continue;
}
$url = showFileUrl($v);
switch ($option['value']){
case 'oss':
$small_url = combineOssUrlImgOpt($url,'x-oss-process=image/resize,m_fill,w_40,h_40');
break;
case 'imageproxy':
$small_url = \Qscmf\Utils\Libs\Common::imageproxy('40x40', $v);
break;
default:
$small_url = $url;
break;
}
$images[] = [
'url' => $url,
'small_url' => $small_url,
];
}
$view = new View();
$view->assign('images', $images);
$content = $view->fetch(__DIR__ . '/pictures.html');
return $content;
}
}<file_sep>/src/Library/Think/Cache/Driver/Redis.class.php
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <<EMAIL>>
// +----------------------------------------------------------------------
namespace Think\Cache\Driver;
use Think\Cache;
defined('THINK_PATH') or exit();
/**
* Redis缓存驱动
* 要求安装phpredis扩展:https://github.com/nicolasff/phpredis
*/
class Redis extends Cache {
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options=array()) {
if ( !extension_loaded('redis') ) {
E(L('_NOT_SUPPORT_').':redis');
}
$options = array_merge(array (
'host' => C('REDIS_HOST') ? : '127.0.0.1',
'port' => C('REDIS_PORT') ? : 6379,
'password' => C('<PASSWORD>') ?: '',
'timeout' => C('DATA_CACHE_TIMEOUT') ? : false,
'persistent' => false,
),$options);
$this->options = $options;
$this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME');
$this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX');
$this->options['length'] = isset($options['length'])? $options['length'] : 0;
$func = $options['persistent'] ? 'pconnect' : 'connect';
$this->handler = new \Redis;
$options['timeout'] === false ?
$this->handler->$func($options['host'], $options['port']) :
$this->handler->$func($options['host'], $options['port'], $options['timeout']);
if ('' != $options['password']) {
$this->handler->auth($options['password']);
}
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name) {
N('cache_read',1);
$value = $this->handler->get($this->options['prefix'].$name);
$jsonData = json_decode( $value, true );
return ($jsonData === NULL) ? $value : $jsonData; //检测是否为JSON数据 true 返回JSON解析数组, false返回源数据
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
* @param string $flag
*
* @return boolean
*/
public function set($name, $value, $expire = null, $flag = '') {
N('cache_write',1);
if(is_null($expire)) {
$expire = $this->options['expire'];
}
$name = $this->options['prefix'].$name;
//对数组/对象数据进行缓存处理,保证数据完整性
$value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
if($flag !== '') {
$option = $expire ? [$flag, 'ex' => $expire] : [$flag];
$result = $this->handler->set($name, $value, $option);
}else if(is_integer($expire) && $expire > 0){
$result = $this->handler->set($name, $value, $expire);
}else{
$result = $this->handler->set($name, $value);
}
if($result && $this->options['length']>0) {
// 记录缓存队列
$this->queue($name);
}
return $result;
}
public function ttl($name){
$name = $this->options['prefix'].$name;
return $this->handler->ttl($name);
}
public function decr(string $name){
return $this->handler->decr($this->options['prefix'] . $name);
}
public function incr(string $name){
return $this->handler->incr($this->options['prefix'] . $name);
}
public function sAdd(string $name, ...$value){
return $this->handler->sAdd($this->options['prefix'] . $name, ...$value);
}
public function hSetNx(string $name, string $hashKey, string $value){
return $this->handler->hSetNx($this->options['prefix'] . $name, $hashKey, $value);
}
public function hSet(string $name, string $hashKey, string $value){
return $this->handler->hSet($this->options['prefix'] . $name, $hashKey, $value);
}
public function sRandMember(string $name, int $count = 1){
return $this->handler->sRandMember($this->options['prefix'] . $name, $count);
}
public function hGet(string $name, string $hashKey) {
return $this->handler->hGet($this->options['prefix'] . $name, $hashKey);
}
public function hLen(string $name) {
return $this->handler->hLen($this->options['prefix'] . $name);
}
public function sCard(string $name) {
return $this->handler->sCard($this->options['prefix'] . $name);
}
public function sRem(string $name, ...$member1) {
return $this->handler->sRem($this->options['prefix'] . $name, ...$member1);
}
public function hDel(string $name, string $hashKey1, ...$otherHashKeys) {
return $this->handler->hDel($this->options['prefix'] . $name, $hashKey1, ...$otherHashKeys);
}
public function del(string $key1, ...$otherKeys){
$key1 = (array)$key1;
$keys = array_merge($key1, $otherKeys);
$keys = collect($keys)->map(function($item){
return $this->options['prefix'] . $item;
})->all();
return $this->handler->del($keys);
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return
* @deprecated
*/
public function rm($name) {
return $this->handler->delete($this->options['prefix'].$name);
}
/**
* 清除缓存
* @access public
* @return boolean
*/
public function clear() {
return $this->handler->flushDB();
}
}
<file_sep>/src/Library/Qscmf/Builder/ListSearchType/ListSearchType.class.php
<?php
namespace Qscmf\Builder\ListSearchType;
interface ListSearchType{
function build(array $item);
}<file_sep>/asset/libs/addrSelect/selectAddr.js
/*
封装自动生成select框的插件
level: @int 2|3 地址的等级 市/区
filed: @array 省/市/县 的后台字段名
*/
(function ($) {
$.fn.selectAddr = function (opts){
var defOpt = {
addressLevel: ['选择省','选择市','选择区'],
level: 3,
url: ['/api/area/getProvince.html','/api/area/getCityByProvince.html','/api/area/getDistrictByCity.html'],
onSelected: function (val,changeEle){ //val: 隐藏域的值 changeEle: 触发事件的select
}
};
//初始化变量
var opt = $.extend(defOpt,opts);
opt.level -= 0;
var $this = $(this),
defCity = '<option value="">' + opt.addressLevel[1] + '</option>',
defDistrict = '<option value="">' + opt.addressLevel[2] + '</option>';
var selectedVal = $this.val();
if(selectedVal){
var selectedProvince = compleAdd(selectedVal.substring(0,2)),
selectedCity =compleAdd(selectedVal.substring(0,4));
}
//处理地址
function compleAdd(str){
var arr = [];
for(var i=0;i<6;i++){
if(str[i]){
arr.push(str[i]);
}else{
arr.push(0);
}
}
return arr.join('');
}
//添加select标签
var html = '';
for(var i=0;i<opt.level;i++){
var cls = "addr-select";
if(opt.class){
cls = cls + " " + opt.class;
}
html += '<select class="' + cls + '"><option value="">'+ opt.addressLevel[i] +'</option></select>';
}
$this.after(html);
var $select = $this.siblings('.addr-select'),
$province = $select.first(),
$city = $select.eq(1).attr('disabled',true),
$district = $select.eq(2).attr('disabled',true);
//获取省份信息
post(opt.url[0],{},function (res){
var html = '';
for(var i = 0; i < res.length; i++){
html += '<option value="'+res[i]['id']+'">'+res[i]['cname']+'</option>';
}
$province.append(html);
if(selectedProvince){
$province.val(selectedProvince).trigger('change');
selectedProvince = '';
}
});
//添加省份change监听
$province.on('change',function (){
$this.val($province.val());
if(!$(this).val()){
$city.empty().append(defCity).attr('disabled',true);
$district.empty().append(defDistrict).attr('disabled',true);
$this.val($province.val());
opt.onSelected($this.val(),$province);
return false;
}
post(opt.url[1],{
province_id: $(this).val()
},function (res){
var html = defCity;
for(var i = 0; i < res.length; i++){
html += '<option value="'+res[i]['id']+'">'+res[i]['cname1']+'</option>';
}
$city.empty().append(html).attr('disabled',false);
$district.empty().append(defDistrict).attr('disabled',true);
if(selectedCity){
$city.val(selectedCity).trigger('change');
selectedCity = '';
}
opt.onSelected($this.val(),$province);
});
});
// 添加城市city监听
$city.on('change',function (){
if(!$(this).val()){
$district.empty().append(defDistrict).attr('disabled',true);
$this.val($province.val());
opt.onSelected($this.val(),$city);
return false;
}else{
$this.val($city.val());
if (opt.level === 2) opt.onSelected($this.val(),$city);
}
if (opt.level > 2){
post(opt.url[2],{
city_id: $(this).val()
},function (res){
if(!res){
$city.children().each(function (){
if(this.value === $city.val()){
res = [];
res.push({id: this.value,cname: this.innerText});
}
});
}
var html = defDistrict;
for(var i = 0; i < res.length; i++){
html += '<option value="'+res[i]['id']+'">'+res[i]['cname']+'</option>';
}
$district.empty().append(html).attr('disabled',false);
opt.onSelected($this.val(),$city);
if(selectedVal){
$district.val(selectedVal).trigger('change');
selectedCity = '';
selectedVal = '';
}
});
}
});
//添加地区district监听
if(opt.level === 3){
$district.on('change',function (){
if(!$(this).val()){
$this.val($city.val());
opt.onSelected($city.val(),$district);
return false;
}else{
$this.val($district.val());
opt.onSelected($district.val(),$district);
}
});
}
//ajax获取数据
function post(u,d,fnSuccess){
$.ajax({
url: u,
data: d,
type: 'get',
success: function(data) {
fnSuccess(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
},
});
}
return $this;
}
})(jQuery);
<file_sep>/src/Library/Qscmf/Builder/ColumnType/Num/Num.class.php
<?php
namespace Qscmf\Builder\ColumnType\Num;
use Qscmf\Builder\ButtonType\Save\TargetFormTrait;
use Qscmf\Builder\ColumnType\ColumnType;
use Qscmf\Builder\ColumnType\EditableInterface;
class Num extends ColumnType implements EditableInterface
{
use TargetFormTrait;
public function build(array &$option, array $data, $listBuilder)
{
return $data[$option['name']];
}
public function editBuild(&$option, $data, $listBuilder){
$class = "form-control input text ". $this->getSaveTargetForm();
return "<input class='{$class}' type='number' name='{$option['name']}[]' value={$data[$option['name']]} />";
}
}<file_sep>/src/Library/Think/Db/SQLRaw.class.php
<?php
namespace Think\Db;
class SQLRaw{
protected $sql;
public function __construct($sql)
{
$this->sql = $sql;
}
public function __toString() {
return $this->sql;
}
}<file_sep>/src/Bootstrap/RegisterContainer.php
<?php
namespace Bootstrap;
class RegisterContainer{
static protected $form_item = [];
static protected $extend_controllers = [];
static protected $sym_links = [];
static protected $list_topbutton = [];
static protected $list_search_type = [];
static protected $list_right_button = [];
static protected $migrate_paths = [];
static protected $head_js = [];
static protected $head_css = [];
static protected $list_column_type = [];
static protected $body_html = [];
static protected $header_navbar_right_html = [];
static public function registerListColumnType($type, $type_cls){
self::$list_column_type[$type] = $type_cls;
}
static public function getListColumnType(){
return self::$list_column_type;
}
static public function registerHeadCss($hrefs){
foreach((array)$hrefs as $href){
self::$head_css[] = [
'href' => $href
];
}
}
static public function getHeadCss(){
return self::$head_css;
}
static public function registerHeadJs($srcs, $async = false){
foreach((array)$srcs as $src){
self::$head_js[] = [
'src' => $src,
'async' => $async
];
}
}
static public function getHeadJs(){
return self::$head_js;
}
static public function registerBodyHtml($html){
self::$body_html[] = $html;
}
static public function getBodyHtml(){
return self::$body_html;
}
static public function registerHeaderNavbarRightHtml($html){
self::$header_navbar_right_html[] = $html;
}
static public function getHeaderNavbarRightHtml(){
return self::$header_navbar_right_html;
}
static public function registerMigration($paths){
foreach((array)$paths as $path){
self::$migrate_paths[] = $path;
}
}
static public function getRegisterMigratePaths(){
return self::$migrate_paths;
}
static public function registerListRightButtonType($type, $type_cls){
self::$list_right_button[$type] = $type_cls;
}
static public function getListRightButtonType(){
return self::$list_right_button;
}
static public function registerListSearchType($type, $type_cls){
self::$list_search_type[$type] = $type_cls;
}
static public function getListSearchType(){
return self::$list_search_type;
}
/**
* @param $link_path 软连接文件地址
* @param $source_path 源文件地址
*/
static public function registerSymLink($link_path, $source_path){
if(isset(self::$sym_links[$link_path])){
E('存在冲突软连接');
}
self::$sym_links[$link_path] = $source_path;
}
static public function getRegisterSymLinks(){
return self::$sym_links;
}
static public function registerListTopButton($type, $type_cls){
self::$list_topbutton[$type] = $type_cls;
}
static public function getListTopButtons(){
return self::$list_topbutton;
}
static public function registerFormItem($type, $type_cls){
self::$form_item[$type] = $type_cls;
}
static public function getFormItems(){
return self::$form_item;
}
static public function registerController($module_name, $controller_name, $controller_cls){
// $user_define_module = self::getUserDefineModule();
// if($user_define_module){
// $module_name = $user_define_module;
// }
if(self::existRegisterController($module_name, $controller_name)){
E('注册控制器存在冲突');
}
if(class_exists($controller_cls)){
self::$extend_controllers[strtolower($module_name)][strtolower($controller_name)] = $controller_cls;
}
else{
E('需要注册的类不存在');
}
}
// static private function getUserDefineModule(){
// static $provider_map = [];
// $back_trace = debug_backtrace();
//
// if(!$provider_map){
// $packages = Context::getRegProvider();
// $provider_map = collect($packages)->map(function($item, $key){
// return [ $item['providers'][0] => $key];
// })->collapse()->all();
// }
// foreach($back_trace as $trace){
// $re = collect($provider_map)->filter(function($item, $key)use($trace){
// return $key == ltrim($trace['class'], '\\');
// })->all();
//
// if($re){
// $package = $re[ltrim($trace['class'], '\\')];
// break;
// }
// }
//
// if(!$package){
// return null;
// }
//
// return packageConfig($package, 'module');
// }
static public function getRegisterController($module_name, $controller_name){
return self::$extend_controllers[strtolower($module_name)][strtolower($controller_name)];
}
static public function existRegisterController($module_name, $controller_name){
return isset(self::$extend_controllers[strtolower($module_name)][strtolower($controller_name)]);
}
static public function existRegisterModule($module_name){
return isset(self::$extend_controllers[strtolower($module_name)]);
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Type/Type.class.php
<?php
namespace Qscmf\Builder\ColumnType\Type;
use Qscmf\Builder\ColumnType\ColumnType;
class Type extends ColumnType {
public function build(array &$option, array $data, $listBuilder){
$form_item_type = C('FORM_ITEM_TYPE');
return $form_item_type[$data[$option['name']]][0];
}
}<file_sep>/src/Library/Qscmf/Core/Session/ISession.class.php
<?php
namespace Qscmf\Core\Session;
interface ISession
{
public function set($key,$value);
public function get($key);
public function clear($key);
}<file_sep>/src/Library/Qscmf/Builder/ListSearchType/Select/SelectBuilder.class.php
<?php
namespace Qscmf\Builder\ListSearchType\Select;
class SelectBuilder
{
public $data;
public $placeholder = '';
public $width = '130px';
public function __construct($data){
$this->setData($data);
}
public function setData(array $data):self{
$this->data = $data;
return $this;
}
public function setPlaceholder(string $placeholder):self{
$this->placeholder = $placeholder;
return $this;
}
public function getPlaceholder():string{
return $this->placeholder;
}
public function setWidth(string $width):self{
$this->width = $width;
return $this;
}
public function toArray():array{
return [
'data' => $this->data,
'placeholder' => $this->placeholder,
'width' => $this->width,
];
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Icon/Icon.class.php
<?php
namespace Qscmf\Builder\ColumnType\Icon;
use Qscmf\Builder\ColumnType\ColumnType;
class Icon extends ColumnType {
public function build(array &$option, array $data, $listBuilder){
return '<i class="'.$data[$option['name']].'"></i>';
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/Pictures/Pictures.class.php
<?php
namespace Qscmf\Builder\FormType\Pictures;
use Illuminate\Support\Str;
use Qscmf\Builder\FormType\FormType;
use Think\View;
use Qscmf\Builder\FormType\TUploadConfig;
class Pictures implements FormType {
use TUploadConfig;
public function build(array $form_type){
$upload_type = $this->genUploadConfigCls($form_type['extra_attr'], 'image');
$view = new View();
$view->assign('form', $form_type);
$view->assign('gid', Str::uuid());
$view->assign('file_ext', $upload_type->getExts());
$view->assign('file_max_size', $upload_type->getMaxSize());
if($form_type['item_option']['read_only']){
$content = $view->fetch(__DIR__ . '/pictures_read_only.html');
}
else{
$content = $view->fetch(__DIR__ . '/pictures.html');
}
return $content;
}
}<file_sep>/src/Library/Behavior/HeaderNavbarRightHtmlBehavior.class.php
<?php
namespace Behavior;
use Bootstrap\RegisterContainer;
class HeaderNavbarRightHtmlBehavior{
public function run(&$content){
$body_html = RegisterContainer::getHeaderNavbarRightHtml();
if ($body_html){
$html = implode(PHP_EOL, $body_html);
$search_str = '<ul class="nav navbar-nav">';
$content = str_ireplace($search_str, $search_str.PHP_EOL.$html, $content);
}
}
}<file_sep>/src/Testing/MakesHttpRequests.php
<?php
namespace Testing;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Symfony\Component\HttpFoundation\File\UploadedFile as SymfonyUploadedFile;
trait MakesHttpRequests
{
/**
* Additional headers for the request.
*
* @var array
*/
protected $defaultHeaders = [];
/**
* Additional server variables for the request.
*
* @var array
*/
protected $serverVariables = [];
/**
* Indicates whether redirects should be followed.
*
* @var bool
*/
protected $followRedirects = false;
/**
* Define additional headers to be sent with the request.
*
* @param array $headers
* @return $this
*/
public function withHeaders(array $headers)
{
$this->defaultHeaders = array_merge($this->defaultHeaders, $headers);
return $this;
}
/**
* Add a header to be sent with the request.
*
* @param string $name
* @param string $value
* @return $this
*/
public function withHeader(string $name, string $value)
{
$this->defaultHeaders[$name] = $value;
return $this;
}
/**
* Flush all the configured headers.
*
* @return $this
*/
public function flushHeaders()
{
$this->defaultHeaders = [];
return $this;
}
/**
* Define a set of server variables to be sent with the requests.
*
* @param array $server
* @return $this
*/
public function withServerVariables(array $server)
{
$this->serverVariables = $server;
return $this;
}
/**
* Set the referer header to simulate a previous request.
*
* @param string $url
* @return $this
*/
public function from(string $url)
{
return $this->withHeader('referer', $url);
}
/**
* Visit the given URI with a GET request.
*
* @param string $uri
* @param array $headers
* @return \Illuminate\Foundation\Testing\TestResponse
*/
public function get($uri, array $headers = [])
{
$server = $this->transformHeadersToServerVars($headers);
return $this->call('GET', $uri, [], [], [], $server);
}
/**
* Visit the given URI with a GET request, expecting a JSON response.
*
* @param string $uri
* @param array $headers
* @return \Illuminate\Foundation\Testing\TestResponse
*/
public function getJson($uri, array $headers = [])
{
return $this->json('GET', $uri, [], $headers);
}
/**
* Visit the given URI with a POST request.
*
* @param string $uri
* @param array $data
* @param array $headers
* @return \Illuminate\Foundation\Testing\TestResponse
*/
public function post($uri, array $data = [], array $headers = [])
{
$server = $this->transformHeadersToServerVars($headers);
return $this->call('POST', $uri, $data, [], [], $server);
}
/**
* Visit the given URI with a POST request, expecting a JSON response.
*
* @param string $uri
* @param array $data
* @param array $headers
* @return \Illuminate\Foundation\Testing\TestResponse
*/
public function postJson($uri, array $data = [], array $headers = [])
{
return $this->json('POST', $uri, $data, $headers);
}
/**
* Visit the given URI with a PUT request.
*
* @param string $uri
* @param array $data
* @param array $headers
* @return \Illuminate\Foundation\Testing\TestResponse
*/
public function put($uri, array $data = [], array $headers = [])
{
$server = $this->transformHeadersToServerVars($headers);
return $this->call('PUT', $uri, $data, [], [], $server);
}
/**
* Visit the given URI with a PUT request, expecting a JSON response.
*
* @param string $uri
* @param array $data
* @param array $headers
* @return \Illuminate\Foundation\Testing\TestResponse
*/
public function putJson($uri, array $data = [], array $headers = [])
{
return $this->json('PUT', $uri, $data, $headers);
}
/**
* Visit the given URI with a PATCH request.
*
* @param string $uri
* @param array $data
* @param array $headers
* @return \Illuminate\Foundation\Testing\TestResponse
*/
public function patch($uri, array $data = [], array $headers = [])
{
$server = $this->transformHeadersToServerVars($headers);
return $this->call('PATCH', $uri, $data, [], [], $server);
}
/**
* Visit the given URI with a PATCH request, expecting a JSON response.
*
* @param string $uri
* @param array $data
* @param array $headers
* @return \Illuminate\Foundation\Testing\TestResponse
*/
public function patchJson($uri, array $data = [], array $headers = [])
{
return $this->json('PATCH', $uri, $data, $headers);
}
/**
* Visit the given URI with a DELETE request.
*
* @param string $uri
* @param array $data
* @param array $headers
* @return \Illuminate\Foundation\Testing\TestResponse
*/
public function delete($uri, array $data = [], array $headers = [])
{
$server = $this->transformHeadersToServerVars($headers);
return $this->call('DELETE', $uri, $data, [], [], $server);
}
/**
* Visit the given URI with a DELETE request, expecting a JSON response.
*
* @param string $uri
* @param array $data
* @param array $headers
* @return \Illuminate\Foundation\Testing\TestResponse
*/
public function deleteJson($uri, array $data = [], array $headers = [])
{
return $this->json('DELETE', $uri, $data, $headers);
}
/**
* Call the given URI with a JSON request.
*
* @param string $method
* @param string $uri
* @param array $data
* @param array $headers
* @return \Illuminate\Foundation\Testing\TestResponse
*/
public function json($method, $uri, array $data = [], array $headers = [])
{
$files = $this->extractFilesFromDataArray($data);
$content = json_encode($data);
$headers = array_merge([
'CONTENT_LENGTH' => mb_strlen($content, '8bit'),
'CONTENT_TYPE' => 'application/json',
'HTTP_CONTENT_TYPE' => 'application/json',
'Accept' => 'application/json',
], $headers);
return $this->call(
$method, $uri, [], [], $files, $this->transformHeadersToServerVars($headers), $content
);
}
/**
* Call the given URI and return the Response content.
*
* @param string $method
* @param string $uri
* @param array $parameters
* @param array $cookies
* @param array $files
* @param array $server
* @param string $content
* @return string response content
*/
public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
{
$files = array_filter(array_merge($files, $this->extractFilesFromDataArray($parameters)));
$symfonyRequest = SymfonyRequest::create(
$this->prepareUrlForRequest($uri), $method, $parameters,
$cookies, $files, array_replace($this->serverVariables, $server), $content
);
$this->packageTpRequest($symfonyRequest);
return $this->runTpAsSanbox();
}
protected function runTpAsSanbox(){
$pipePath = "/tmp/test.pipe";
if( file_exists( $pipePath ) ){
unlink($pipePath);
}
if( !posix_mkfifo( $pipePath, 0666 ) ){
exit('make pipe false!' . PHP_EOL);
}
$pid = pcntl_fork();
if( $pid == 0 ){
define("IS_CGI", 1);
define("IS_CLI", false);
require __DIR__ . '/../../../../../tp.php';
$content = ob_get_contents();
$file = fopen( $pipePath, 'w' );
fwrite( $file, $content);
exit();
}else{
$file = fopen( $pipePath, 'r' );
$content = fread( $file, 99999999 ) . PHP_EOL;
pcntl_wait($status);
}
return $content;
}
protected function flushServerHeaders(){
foreach($_SERVER as $name => $value){
if (Str::startsWith($name, 'HTTP_')) unset($_SERVER[$name]);
}
}
protected function packageTpRequest(SymfonyRequest $request){
$this->flushServerHeaders();
$_SERVER = array_merge($_SERVER, $request->server->all());
$_GET = $request->query->all();
$_POST = $request->request->all();
$is_json_content_type = is_json_content_type();
if($request->getMethod() === 'PUT' && !$is_json_content_type){
$this->mockPhpInput($request->request->all());
}
if($is_json_content_type) {
$this->mockPhpInput($request->getContent());
}
$_SERVER['PATH_INFO'] = parse_url($_SERVER['REQUEST_URI'])['path'];
$_FILES = array_map(function($file){
return [
'name' => $file->getClientOriginalName(),
'type' => $file->getMimeType(),
'tmp_name' => $file->getPathname(),
'error' => $file->getError(),
'size' => $file->getSize()
];
}, array_filter($request->files->all(), fn($file) => $file instanceof SymfonyUploadedFile));
}
protected function mockPhpInput($value): void
{
$fill_json = is_array($value) ? http_build_query($value) : $value;
$stub = $this->createMock(TestingWall::class);
$stub->method('file_get_contents')->willReturnMap([
['php://input', false, null, 0, null, $fill_json]
]);
app()->instance(TestingWall::class, $stub);
}
/**
* Turn the given URI into a fully qualified URL.
*
* @param string $uri
* @return string
*/
protected function prepareUrlForRequest($uri)
{
if (Str::startsWith($uri, '/')) {
$uri = substr($uri, 1);
}
if (! Str::startsWith($uri, 'http')) {
$uri = env('APP_URL').'/'.$uri;
}
return trim($uri, '/');
}
/**
* Transform headers array to array of $_SERVER vars with HTTP_* format.
*
* @param array $headers
* @return array
*/
protected function transformHeadersToServerVars(array $headers)
{
return collect(array_merge($this->defaultHeaders, $headers))->mapWithKeys(function ($value, $name) {
$name = strtr(strtoupper($name), '-', '_');
return [$this->formatServerHeaderKey($name) => $value];
})->all();
}
/**
* Format the header name for the server array.
*
* @param string $name
* @return string
*/
protected function formatServerHeaderKey($name)
{
if (! Str::startsWith($name, 'HTTP_') && $name !== 'CONTENT_TYPE' && $name !== 'REMOTE_ADDR') {
return 'HTTP_'.$name;
}
return $name;
}
/**
* Extract the file uploads from the given data array.
*
* @param array $data
* @return array
*/
protected function extractFilesFromDataArray(&$data)
{
$files = [];
foreach ($data as $key => $value) {
if ($value instanceof SymfonyUploadedFile) {
$files[$key] = $value;
unset($data[$key]);
}
if (is_array($value)) {
$files[$key] = $this->extractFilesFromDataArray($value);
$data[$key] = $value;
}
}
return $files;
}
public function loginSuperAdmin(){
session(C('USER_AUTH_KEY'), C('USER_AUTH_ADMINID'));
session('ADMIN_LOGIN', true);
session(C('ADMIN_AUTH_KEY'), true);
}
public function loginUser($uid){
session(C('USER_AUTH_KEY'), $uid);
session('ADMIN_LOGIN', true);
}
public function getTpToken($request_uri, $is_ajax){
list($tokenName,$tokenKey,$tokenValue) = getToken($request_uri, $is_ajax);
return $tokenKey . '_' . $tokenValue;
}
}
<file_sep>/src/Library/Qscmf/Controller/ResourceController.class.php
<?php
namespace Qscmf\Controller;
use Think\Controller;
class ResourceController extends Controller{
public function temporaryLoad($key){
$file_path = S($key);
if(!$file_path){
qs_exit('没有访问权限');
}
if(!file_exists($file_path)){
qs_exit('资源不存在');
}
$content_type = (new \Symfony\Component\Mime\MimeTypes())->guessMimeType($file_path);
header('Content-Type: '.$content_type);
readfile($file_path);
}
}<file_sep>/src/Library/Qscmf/Builder/ListRightButton/Edit/Edit.class.php
<?php
namespace Qscmf\Builder\ListRightButton\Edit;
use Qscmf\Builder\ListRightButton\ListRightButton;
class Edit extends ListRightButton{
public function build(array &$option, array $data, $listBuilder){
$my_attribute['title'] = '编辑';
$my_attribute['class'] = 'primary';
$my_attribute['href'] = U(
MODULE_NAME.'/'.CONTROLLER_NAME.'/edit',
array($listBuilder->getDataKeyName() => '__data_id__')
);
$option['attribute'] = $listBuilder->mergeAttr($my_attribute, is_array($option['attribute']) ? $option['attribute'] : [] );
return '';
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/Files/Files.class.php
<?php
namespace Qscmf\Builder\FormType\Files;
use Illuminate\Support\Str;
use Qscmf\Builder\FormType\FileFormType;
use Qscmf\Builder\FormType\FormType;
use Think\View;
use Qscmf\Builder\FormType\TUploadConfig;
class Files extends FileFormType implements FormType {
use TUploadConfig;
public function build(array $form_type){
$upload_type = $this->genUploadConfigCls($form_type['extra_attr'], 'file');
$view = new View();
if($form_type['value']){
$files = [];
foreach(explode(',', $form_type['value']) as $file_id){
$data = [];
$data['url'] = showFileUrl($file_id);
$data['id'] = $file_id;
if($this->needPreview($data['url'])){
$data['preview_url'] = $this->genPreviewUrl($data['url']);
}
$files[] = $data;
}
$view->assign('files', $files);
}
$view->assign('form', $form_type);
$view->assign('gid', Str::uuid());
$view->assign('file_ext', $upload_type->getExts());
$view->assign('file_max_size', $upload_type->getMaxSize());
$view->assign('js_fn', $this->buildJsFn());
$content = $view->fetch(__DIR__ . '/files.html');
return $content;
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/Radio/Radio.class.php
<?php
namespace Qscmf\Builder\FormType\Radio;
use Qscmf\Builder\FormType\FormType;
use Think\View;
class Radio implements FormType {
public function build(array $form_type){
$view = new View();
$view->assign('form', $form_type);
$content = $view->fetch(__DIR__ . '/radio.html');
return $content;
}
}<file_sep>/src/Library/Qscmf/Lib/Elasticsearch/ElasticsearchModelContract.class.php
<?php
namespace Qscmf\Lib\Elasticsearch;
interface ElasticsearchModelContract{
function elasticsearchIndexList();
function elasticsearchAddDataParams();
function isElasticsearchIndex($ent);
function createIndex();
}<file_sep>/src/Library/Qscmf/Builder/FormType/Text/Text.class.php
<?php
namespace Qscmf\Builder\FormType\Text;
use Qscmf\Builder\FormType\FormType;
use Think\View;
class Text implements FormType {
public function build(array $form_type){
$view = new View();
$view->assign('form', $form_type);
if($form_type['item_option']['read_only']){
$content = $view->fetch(__DIR__ . '/text_read_only.html');
}
else{
$content = $view->fetch(__DIR__ . '/text.html');
}
return $content;
}
}<file_sep>/README.md
# think-core
基于thinkphp3.2改造的[qs_cmf](https://github.com/tiderjian/qs_cmf)内核
<file_sep>/qsautoload
#!/usr/bin/env php
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (version_compare('7.2.0', PHP_VERSION, '>')) {
fwrite(
STDERR,
sprintf(
'This version of think-core is supported on PHP 7.2 and PHP 7.3.' . PHP_EOL .
'You are using PHP %s (%s).' . PHP_EOL,
PHP_VERSION,
PHP_BINARY
)
);
die(1);
}
foreach (array(__DIR__ . '/../../../vendor/autoload.php', __DIR__ . '/../../autoload.php', __DIR__ . '/../vendor/autoload.php', __DIR__ . '/vendor/autoload.php') as $file) {
if (file_exists($file)) {
define('VENDOR_PATH', dirname($file));
break;
}
}
unset($file);
if (!defined('VENDOR_PATH')) {
fwrite(
STDERR,
'You need to set up the project dependencies using Composer:' . PHP_EOL . PHP_EOL .
' composer install' . PHP_EOL . PHP_EOL .
'You can learn all about Composer on https://getcomposer.org/.' . PHP_EOL
);
die(1);
}
if(!file_exists(VENDOR_PATH . "/../lara/vendor/composer/installed.json")){
symlink(VENDOR_PATH . "/composer/installed.json", VENDOR_PATH . "/../lara/vendor/composer/installed.json");
fwrite(STDOUT, "generate installed.json link finished!" . PHP_EOL);
}
else{
fwrite(STDERR, "installed.json link already exists!" . PHP_EOL);
}
if(file_exists(VENDOR_PATH . "/../lara/bootstrap/cache/packages.php")){
@unlink(VENDOR_PATH . "/../lara/bootstrap/cache/packages.php");
fwrite(STDOUT, "clear cache/packages.php!" . PHP_EOL);
}
if(file_exists(VENDOR_PATH . "/../lara/bootstrap/cache/services.php")){
@unlink(VENDOR_PATH . "/../lara/bootstrap/cache/services.php");
fwrite(STDOUT, "clear cache/services.php!" . PHP_EOL);
}
if(file_exists(VENDOR_PATH . "/../lara/bootstrap/cache/qscmf-packages.php")){
@unlink(VENDOR_PATH . "/../lara/bootstrap/cache/qscmf-packages.php");
fwrite(STDOUT, "clear cache/qscmf-packages.php!" . PHP_EOL);
}
die(0);
<file_sep>/asset/libs/label-select/webpack.config.js
var webpack = require('webpack');
var path = require('path');
var dir = path.resolve(__dirname);
// const ExtractTextPlugin = require('extract-text-webpack-plugin');
// const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
// const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = function() {
return {
mode: 'production',
// mode: 'development',
entry: {
'label-select': './label-select.js',
},
output: {
filename: '[name].min.js',
path: path.resolve(dir, 'dist/'),
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /\.less$/,
use: ['style-loader','css-loader','less-loader']
},
{
test: /\.css$/,
use: ['style-loader','css-loader']
}
]
},
externals: [
'jquery'
]
};
}<file_sep>/src/Larafortp/CmmMigrate/DatabaseMigrationRepository.php
<?php
namespace Larafortp\CmmMigrate;
use Illuminate\Database\ConnectionResolverInterface as Resolver;
use Illuminate\Database\Migrations\DatabaseMigrationRepository as BaseMigrationRepository;
class DatabaseMigrationRepository extends BaseMigrationRepository{
/**
* Create a new database migration repository instance.
*
* @param \Illuminate\Database\ConnectionResolverInterface $resolver
* @param string $table
* @return void
*/
public function __construct(Resolver $resolver, $table)
{
parent::__construct($resolver, $table);
}
/**
* Create the migration repository data store.
*
* @return void
*/
public function createRepository()
{
$schema = $this->getConnection()->getSchemaBuilder();
$schema->create($this->table, function ($table) {
// The migrations table is responsible for keeping track of which of the
// migrations have actually run for the application. We'll create the
// table to hold the migration file's path as well as the batch ID.
$table->increments('id');
$table->string('migration');
$table->boolean('before');
$table->boolean('run');
$table->boolean('after');
$table->integer('batch');
});
}
/**
* Get the completed migrations.
*
* @return array
*/
public function getRan()
{
return $this->table()
->where('before', 1)
->where('run', 1)
->where('after', 1)
->orderBy('batch', 'asc')
->orderBy('migration', 'asc')
->pluck('migration')->all();
}
public function getAllMigrations(){
return $this->table()
->orderBy('batch', 'asc')
->orderBy('migration', 'asc')
->pluck('migration')->all();
}
public function log($name, $batch, $operation = 'run', $finish = true)
{
$exists = $this->table()->where('migration', $name)->count();
if(!$exists){
$record = ['migration' => $name, 'batch' => $batch, 'before' => 0, 'run' => 0, 'after' => 0];
$this->table()->insert($record);
}
if($finish){
$this->table()->where('migration', $name)->update(['batch' => $batch, 'before' => 1, 'run' => 1, 'after' => 1]);
}
else{
$this->table()->where('migration', $name)->update([$operation => 1]);
}
}
public function rollbackLog($name, $operation)
{
return $this->table()->where('migration', $name)->update([$operation => 0]);
}
/**
* Get the last migration batch number.
*
* @return int
*/
public function getLastBatchNumber()
{
return $this->table()
->where('before', 1)
->where('run', 1)
->where('after', 1)
->max('batch');
}
public function ranOperation($name, $operation)
{
return $this->table()->where('migration', $name)->value($operation) ? true : false;
}
}<file_sep>/src/Library/Qscmf/Exception/TestingException.class.php
<?php
namespace Qscmf\Exception;
class TestingException extends \Exception {
}<file_sep>/src/Library/Qscmf/Builder/ButtonType/Self/SelfButton.class.php
<?php
namespace Qscmf\Builder\ButtonType\Self;
use Qscmf\Builder\ButtonType\ButtonType;
class SelfButton extends ButtonType{
public function build(array &$option){
$my_attribute['target-form'] = 'ids';
$my_attribute['class'] = 'btn btn-danger';
$option['attribute'] = array_merge($my_attribute, is_array($option['attribute']) ? $option['attribute'] : [] );
return '';
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Hidden/Hidden.class.php
<?php
namespace Qscmf\Builder\ColumnType\Hidden;
use Qscmf\Builder\ButtonType\Save\TargetFormTrait;
use Qscmf\Builder\ColumnType\ColumnType;
use Qscmf\Builder\ColumnType\EditableInterface;
class Hidden extends ColumnType implements EditableInterface{
use TargetFormTrait;
public function build(array &$option, array $data, $listBuilder){
return '<span style="display: none" title="' . $data[$option['name']] . '" >' . $data[$option['name']] . '</span>';
}
public function editBuild(&$option, $data, $listBuilder){
$class = "form-control input text ". $this->getSaveTargetForm(). " {$option['extra_class']}";
return "<input type='hidden' name='{$option['name']}[]' class='{$class}' value='{$data[$option['name']]}' {$option['extra_attr']} />";
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/ColumnType.class.php
<?php
namespace Qscmf\Builder\ColumnType;
abstract class ColumnType{
public abstract function build(array &$option, array $data, $listBuilder);
}<file_sep>/src/Library/Qscmf/Builder/BuilderHelper.class.php
<?php
namespace Qscmf\Builder;
class BuilderHelper
{
static public function compileHtmlAttr($attr) {
$result = array();
foreach ($attr as $key => $value) {
if(!empty($value) && !is_array($value)){
$value = htmlspecialchars($value);
$result[] = "$key=\"$value\"";
}
}
$result = implode(' ', $result);
return $result;
}
/**
* 检测字段的权限点,无权限则unset该item
*
* @param array $check_items
* @return array
*/
static public function checkAuthNode($check_items){
return filterItemsByAuthNode($check_items);
}
}<file_sep>/src/Library/Qscmf/Builder/ListSearchType/Text/Text.class.php
<?php
namespace Qscmf\Builder\ListSearchType\Text;
use Think\View;
use Qscmf\Builder\ListSearchType\ListSearchType;
class Text implements ListSearchType{
public function build(array $item){
$view = new View();
$view->assign('item', $item);
$content = $view->fetch(__DIR__ . '/text.html');
return $content;
}
static public function parse(string $key, string $map_key, array $get_data, string $rule = 'fuzzy') : array{
if(isset($get_data[$key]) && !qsEmpty($get_data[$key])){
return $rule === 'exact' ? [$map_key => $get_data[$key]] : [$map_key => ['like', '%'. $get_data[$key] . '%']];
}
else{
return [];
}
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Arr/Arr.class.php
<?php
namespace Qscmf\Builder\ColumnType\Arr;
use Qscmf\Builder\ColumnType\ColumnType;
class Arr extends ColumnType{
public function build(array &$option, array $data, $listBuilder){
$arr = explode(',', $data[$option['name']]);
$html = '';
foreach($arr as $vo){
$html .=<<<html
<div style="display:flex;">
<span>{$vo}</span>
</div>
html;
}
return $html;
}
}<file_sep>/src/Library/Qscmf/Core/QsModel.class.php
<?php
namespace Qscmf\Core;
use Qscmf\Lib\DBCont;
use Think\Model;
class QsModel extends Model {
const EXIST_VALIDATE = 1;
const NOT_EXIST_VALIDATE = 2;
const NOT_ALLOW_VALUE_VALIDATE = 3;
const ALLOW_VALUE_VALIDATE = 4;
const EXIST_TABLE_VALUE_VALIDATE = 5;
const DELETE_CONTINUE = 1;
const DELETE_BREAK = 2;
protected $_delete_validate = array(); //删除数据前的验证条件设置
//array(array('delete', 'VolunteerExtend', array('uid' => 'uid'))) delete规则 arr[1] 要删除的model名, arr[2] key和value是被删除表与连带删除表的映射字段
protected $_delete_auto = array(); //删除数据自动执行操作
protected $_auth_node_column = array(); //字段权限点配置
public function __construct($name='',$tablePrefix='',$connection=''){
parent::__construct($name,$tablePrefix,$connection);
}
public function notOptionsFilter(){
$this->options['cus_filter'] = false;
return $this;
}
public function enableOptionsFilter(){
unset($this->options['cus_filter']);
return $this;
}
public function notBeforeWrite(){
$this->options['cus_before_write'] = false;
return $this;
}
public function enableBeforeWrite(){
unset($this->options['cus_before_write']);
return $this;
}
public function autoCheckToken($data) {
//ajax无刷新提交,不检验token
if(IS_AJAX){
return true;
}
$result = parent::autoCheckToken($data);
if(C('GY_TOKEN_ON') && C('TOKEN_ON')){
C('TOKEN_ON', false);
}
return $result;
}
public function isExists($id){
if(strpos($id,',')){
$id = trim($id, ',');
$map['id'] = array('in',$id);
$ent = $this->where($map)->select();
return $ent ? true : false;
}
$ent = $this->getOne($id);
return $ent ? true : false;
}
//数据是否可删除
protected function _before_delete($options){
if(!empty($this->_delete_validate)){
$pk = $this->getPk();
$ids = $this->where($options['where'])->getField($pk, true);
foreach($this->_delete_validate as $v){
//设置默认值
if(!isset($v[2])){
$v[2] = self::EXIST_VALIDATE;
}
if(!isset($v[3])){
$v[3] = 'delete error';
}
switch ($v[2]){
case self::EXIST_VALIDATE:
$data = $this->_checkExists($v[0], $v[1], $ids);
if($data === false){
return false;
}
if($data){
$this->error = $v[3];
return false;
}
break;
case self::NOT_EXIST_VALIDATE:
$data = $this->_checkExists($v[0], $v[1], $ids);
if($data === false){
return false;
}
if(!$data){
$this->error = $v[3];
return false;
}
break;
case self::NOT_ALLOW_VALUE_VALIDATE:
//获取禁止删除的ID
$map[$v[1]] = array('in', $v[0]);
$na_ids = $this->where($map)->getField($pk, true);
//如存在交集,证明删除的的记录里存在不允许删除的记录
$ins_ids = array_intersect($ids,$na_ids);
if($ins_ids){
$this->error = $v[3];
return false;
}
break;
case self::ALLOW_VALUE_VALIDATE:
//允许删除的ID值
if($v[0]){
$map[$v[1]] = array('in', $v[0]);
$options['where'] = array_merge($options['where'],$map);
$a_ids = $this->where($options['where'])->getField($pk, true);
$ins_ids = array_intersect($ids,$a_ids);
if(count($ins_ids) != count($ids)){
$this->error = $v[3];
return false;
}
}
else{
$this->error = $v[3];
return false;
}
break;
}
}
}
//自动删除规则
$default_options=[
'error_operate'=>self::DELETE_CONTINUE
];
if(!empty($this->_delete_auto)){
foreach($this->_delete_auto as $val){
if (!isset($val[3])){
$val[3] = $default_options;
}
$val[3]=array_merge($val[3],$default_options);
switch ($val[0]){
case 'delete':
if(!empty($val[1]) && is_array($val[2])){
$r=$this->_autoDeleteByArr($val[1], $val[2], $options);
if ($r===false && $val[3]['error_operate']==self::DELETE_BREAK){
return false;
}
}
else if($val[1] instanceof \Closure){
$r=$this->_autoDeleteByClosure($val[1], $options);
if ($r===false && $val[3]['error_operate']==self::DELETE_BREAK){
return false;
}
}
else{
$this->error = '未知删除规则';
return false;
}
break;
default:
break;
}
}
}
return true;
}
protected function _autoDeleteByClosure(\Closure $callback, $options){
$ent_list = $this->where($options['where'])->select();
foreach($ent_list as $ent){
$r=call_user_func($callback,$ent);
if ($r===false){
return false;
}
}
return true;
}
protected function _autoDeleteByArr($relation_model, $rule, $options){
$key = key($rule);
$fields = $this->where($options['where'])->getField($key, true);
if(!$fields){
return true;
}
$relation_model = D($relation_model);
$map = array();
$map[$rule[$key]] = array('in', $fields);
$r=$relation_model->where($map)->delete();
if ($r===false){
$this->error=$relation_model->getError();
return false;
}
return true;
}
protected function _checkExists($model, $field, $ids){
if($model instanceof \Closure){
$callback = $model;
return call_user_func($callback,$ids);
}
$m = D($model);
$map = array();
if(empty($ids)){
return null;
}
if(is_string($field)){
$map[$field] = array('in', $ids);
}
else if(is_array($field)){
$map = $field['where'];
$map[$field['field']] = array('in', $ids);
}
$data = $m->where($map)->find();
if($data === false){
$this->error = 'delete_validate_error';
return false;
}
return $data;
}
public function getOne($id){
return $this->where(array('id' => $id))->find();
}
public function getOneField($id, $field, $map = array()){
$pk = $this->getPk();
$map[$pk] = $id;
$ent = $this->where($map)->find();
return $ent ? $ent[$field] : false;
}
public function getList($map = array(), $order = ''){
if($map){
$this->where($map);
}
if($order != ''){
$this->order($order);
}
return $this->select();
// if($order == ''){
// return $this->where($map)->select();
// }
// else{
// return $this->where($map)->order($order)->select();
// }
}
public function getParentOptions($key, $value, $id = '', $prefix = ''){
$map = array();
if(!empty($id)){
$map['id'] = array('neq', $id);
}
if($prefix == ''){
$prefix = "┝ ";
}
$map['status'] = DBCont::NORMAL_STATUS;
$list = $this->where($map)->select();
$tree = list_to_tree($list);
$select = genSelectByTree($tree);
$options = array();
foreach($select as $k=>$v){
$title_prefix = str_repeat(" ", $v['level']*4);
$title_prefix .= empty($title_prefix) ? '' : $prefix;
$options[$v[$key]] = $title_prefix . $v[$value];
}
return $options;
}
public function getParentOptions1($key, $value, $map = array(), $prefix = ''){
if($prefix == ''){
$prefix = "┝ ";
}
$list = $this->where($map)->select();
$tree = list_to_tree($list);
$select = genSelectByTree($tree);
$options = array();
foreach($select as $k=>$v){
$title_prefix = str_repeat(" ", $v['level']*4);
$title_prefix .= empty($title_prefix) ? '' : $prefix;
$options[$v[$key]] = $title_prefix . $v[$value];
}
return $options;
}
public function createAdd($data, $model = '', $key = ''){
$id = $data[$this->getPk()];
if($this->create($data, self::MODEL_INSERT) === false){
return false;
}
$r = $this->add();
if($r === false){
$model != '' && $key != '' && $model->delete($key);
return false;
}
else{
return $id ?: $r;
}
}
public function createSave($data, $model = '', $old_data = ''){
if($this->create($data, self::MODEL_UPDATE) === false){
$model != '' && $old_data != '' && $model->where(array($model->getPk() => $old_data[$model->getPk()]))->save($old_data);
return false;
}
$pk = $this->getPk();
if (is_string($pk) && isset($data[$pk])) {
$where[$pk] = $data[$pk];
unset($data[$pk]);
}
elseif (is_array($pk)) {
// 增加复合主键支持
foreach ($pk as $field) {
if(isset($data[$field])) {
$where[$field] = $data[$field];
} else {
// 如果缺少复合主键数据则不执行
$this->error = L('_OPERATION_WRONG_');
$model != '' && $old_data != '' && $model->where(array($model->getPk() => $old_data[$model->getPk()]))->save($old_data);
return false;
}
unset($data[$field]);
}
}
if(!isset($where)){
// 如果没有任何更新条件则不执行
$this->error = L('_OPERATION_WRONG_');
$model != '' && $old_data != '' && $model->where(array($model->getPk() => $old_data[$model->getPk()]))->save($old_data);
return false;
}
$r = $this->where($where)->save();
if($r === false){
$model != '' && $old_data != '' && $model->where(array($model->getPk() => $old_data[$model->getPk()]))->save($old_data);
return false;
}
else{
return $r;
}
}
//批量增加
public function createAddALL($dataList,$options=array(),$replace=false){
$addDataList=[];
foreach($dataList as $v){
if($this->create($v, self::MODEL_INSERT) === false){
return false;
}
$addDataList[]=$this->data;
}
$r = $this->addAll($addDataList,$options=array(),$replace=false);
return $r;
}
protected function _options_filter(&$options) {
//保留不过滤机制
if($options['cus_filter'] === false){
return;
}
//加入前台过滤机制
if(!C('FRONT_AUTH_FILTER') && !in_array(strtolower(MODULE_NAME), (array)C("BACKEND_MODULE"))){
return;
}
$auth_ref_rule = $this->_auth_ref_rule;
if(!$auth_ref_rule){
return;
}
$auth = \Qscmf\Core\AuthChain::getAuthRuleId();
if(!$auth){
return;
}
$auth_ref_rule = $this->_reset_auth_ref_rule();
if(!isset($auth_ref_rule['ref_path'])){
return;
}
list($ref_model, $ref_id) = explode('.', $auth_ref_rule['ref_path']);
$auth_ref_key = $auth_ref_rule['auth_ref_key'];
$auth_ref_key = $this->_reset_auth_ref_key($options, $auth_ref_key);
//检查options中有无对应key值的设置
if(isset($options['where'][$auth_ref_key])){
//有对应key值
$arr = $this->_resetAuthRefKeyValue($ref_model,$ref_id,$auth_ref_rule);
$map[$auth_ref_rule['auth_ref_key']] = $options['where'][$auth_ref_key];
$key_arr = $this->notOptionsFilter()->where($map)->distinct($auth_ref_rule['auth_ref_key'])->getField($auth_ref_rule['auth_ref_key'],true);
$this->enableOptionsFilter();
if ($auth_ref_rule['not_exists_then_ignore'] && !$arr){
return;
}
if(!$arr){
$options['where']['_string'] = "1!=1";
return;
}
// 设置过滤条件为:options筛选的结果集和关联数据结果集的交集
$value = array_values(array_intersect((array)$key_arr,(array)$arr));
if($value){
$options['where'][$auth_ref_key] = array('in', $value);
}
else{
$options['where']['_string'] = "1!=1";
return;
}
}
else{
//无对应key值,设置key值
if($this->name == $ref_model){
$options['where'][$auth_ref_key] = ['in', $this->_resetAuthValue($auth, $auth_ref_rule)];
}
else{
$arr = $this->_resetAuthRefKeyValue($ref_model, $ref_id, $auth_ref_rule);
if ($auth_ref_rule['not_exists_then_ignore'] && !$arr){
return;
}
if(!$arr){
$options['where']['_string'] = "1!=1";
return;
}
$options['where'][$auth_ref_key] = array('in', join(',', $arr));
}
}
return;
}
private function _transcodeAuthToArray(&$auth){
if(is_int($auth)){
$auth = (string)$auth;
}
if (is_string($auth)){
$auth = explode(',', $auth);
}
}
private function _resetAuthValue($auth, $rule){
$this->_transcodeAuthToArray($auth);
$callback_res = $this->_useAuthRefValueCallback($auth, $rule);
return $callback_res ? $callback_res : $auth;
}
private function _useAuthRefValueCallback($source_data, $rule){
$callback_info = $rule['auth_ref_value_callback'];
if ($callback_info){
$fun_name = $this->_getCallbackFun($callback_info);
$param = $this->_parseCallbackParam($source_data, $callback_info);
$callback_res = (array)call_user_func_array($fun_name, $param);
}
return $callback_res ? $callback_res : $source_data;
}
private function _resetAuthRefKeyValue($ref_model, $ref_id, $rule){
$ref_model_cls = parseModelClsName($ref_model);
$ref_model_cls = new $ref_model_cls($ref_model);
$arr = $ref_model_cls->getField($ref_id, true);
$arr = $this->_useAuthRefValueCallback($arr, $rule);
return $arr;
}
private function _getCallbackFun($callback_info){
return $callback_info[0];
}
private function _parseCallbackParam($arr, $callback_info){
$param = $callback_info;
array_shift($param);
$index = array_search('__auth_ref_value__', $param);
$index !== false && $param[$index] = $arr;
return $param;
}
protected function _before_write(&$data) {
//加入前台过滤机制
if(!C('FRONT_AUTH_FILTER') && !in_array(strtolower(MODULE_NAME), C("BACKEND_MODULE"))){
return;
}
if($this->options['cus_before_write'] === false){
return;
}
$auth = \Qscmf\Core\AuthChain::getAuthRuleId();
if(!$auth){
return;
}
$this->_handle_auth_node_column($data);
$auth_ref_rule = $this->_auth_ref_rule;
if(!$auth_ref_rule){
return;
}
$auth_ref_rule = $this->_reset_auth_ref_rule();
$auth_ref_key = $auth_ref_rule['auth_ref_key'];
$has_alias = $this->_has_data_with_alias($this->options, $auth_ref_key, $data);
if ($has_alias) $auth_ref_key = $this->_reset_auth_ref_key($this->options, $auth_ref_key);
if(isset($data[$auth_ref_key])){
list($ref_model, $ref_id) = explode('.', $auth_ref_rule['ref_path']);
$arr = $this->_resetAuthRefKeyValue($ref_model, $ref_id, $auth_ref_rule);
if ($auth_ref_rule['not_exists_then_ignore'] && !$arr){
return;
}
if(!$arr){
E('无权去进行意料之外的数据设置');
}
if(in_array($data[$auth_ref_key], $arr)){
return;
}
else{
E('无权去进行意料之外的数据设置');
}
}
}
public function destroy(){
$this->db->__destruct();
}
private function _reset_auth_ref_rule($auth_ref_rule = ''){
$auth_ref_rule = $auth_ref_rule ? $auth_ref_rule : $this->_auth_ref_rule;
$role_type = \Qscmf\Core\AuthChain::getAuthRoleType();
if ($role_type){
$auth_ref_rule = $auth_ref_rule[$role_type] ? $auth_ref_rule[$role_type] : $auth_ref_rule;
}
return $auth_ref_rule;
}
private function _reset_auth_ref_key(&$options, $auth_ref_key){
$alias = $options['alias'];
if (!$auth_ref_key || !$alias) return $auth_ref_key;
if (preg_match('/^' . $alias . '\./', $auth_ref_key)) return $auth_ref_key;
$reset_auth_ref_key = $alias && $auth_ref_key ? $alias . '.' . $auth_ref_key : $auth_ref_key;
return $reset_auth_ref_key;
}
private function _has_data_with_alias($options, $auth_ref_key, $data){
$alias = $options['alias'];
$res = false;
if($data[$alias . '.' . $auth_ref_key]){
$res = true;
}
return $res;
}
private function _handle_auth_node_column(&$data){
if (!empty($this->_auth_node_column)){
foreach($this->_auth_node_column as $key => $val){
$auth_node = (array)$val['auth_node'];
$default = $val['default'];
if (isset($data[$key])){
if ($default && ($data[$key] == $default)){
continue;
}
if ($auth_node){
foreach ($auth_node as $v){
$has_auth = verifyAuthNode($v);
if (!$has_auth){
unset($data[$key]);
$default && $data[$key] = $default;
continue;
}
}
} else{
E('auth_node不能为空!');
}
}
}
}
}
/**
* 覆盖ThinkPhp model方法,处理若传空字符串入bigint类型字段,会导致数据库错误的问题
*
* @param mixed $data
* @param string $key
*/
protected function _parseType(&$data, $key)
{
parent::_parseType($data, $key);
if(!isset($this->options['bind'][':'.$key]) && isset($this->fields['_type'][$key])) {
$fieldType = strtolower($this->fields['_type'][$key]);
if(false !== strpos($fieldType,'bigint') && $data[$key]==='') {
$data[$key] = 0;
}
}
}
protected function _after_insert($data, $options)
{
$params = ['model_obj' => $this, 'data' => $data, 'options' => $options];
\Think\Hook::listen('after_insert', $params);
parent::_after_insert($data, $options);
}
protected function _after_update($data, $options)
{
$params = ['model_obj' => $this, 'data' => $data, 'options' => $options];
\Think\Hook::listen('after_update', $params);
parent::_after_update($data, $options);
}
protected function _after_delete($data, $options)
{
$params = ['model_obj' => $this, 'data' => $data, 'options' => $options];
\Think\Hook::listen('after_delete', $params);
parent::_after_delete($data, $options);
}
}
<file_sep>/src/Testing/TestCase.php
<?php
namespace Testing;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Illuminate\Console\Application as Artisan;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\Concerns\InteractsWithConsole;
use Illuminate\Foundation\Testing\Concerns\InteractsWithDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Facade;
use PHPUnit\Framework\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase {
use InteractsWithConsole;
use MakesHttpRequests;
use InteractsWithDatabase;
use InteractsWithTpConsole;
use DBTrait;
/**
* The Illuminate application instance.
*
* @var \Illuminate\Contracts\Foundation\Application
*/
protected $app;
abstract public function laraPath():string;
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require $this->laraPath() . '/bootstrap/app.php';
\Bootstrap\Context::providerRegister(true);
\Larafortp\ArtisanHack::init($app);
$app->make(Kernel::class)->bootstrap();
return $app;
}
/**
* Setup the test environment.
*
* @return void
*/
protected function setUp(): void
{
if (!$this->app) {
$this->app = $this->createApplication();
}
$this->uninstall();
$this->install();
$this->loadTpConfig();
Facade::clearResolvedInstances();
$this->setUpHasRun = true;
}
protected function loadTpConfig(){
require __DIR__ . '/../ConstDefine.php';
C(load_config( __DIR__ . '/../Library/Qscmf/Conf/config.php'));
C(load_config( $this->laraPath() . '/../app/Common/Conf/config.php'));
spl_autoload_register(function($class){
$name = strstr($class, '\\', true);
$lib_path = base_path('../vendor/tiderjian/think-core/src/Library/');
if(is_dir($lib_path.$name)){
// Library目录下面的命名空间自动定位
$path = $lib_path;
}else{
$path = base_path('../app/');
}
$ext = '.class.php';
$filename = $path . str_replace('\\', '/', $class) . $ext;
if(is_file($filename)) {
// Win环境下面严格区分大小写
$is_win = strstr(PHP_OS, 'WIN') ? 1 : 0;
if ($is_win && false === strpos(str_replace('/', '\\', realpath($filename)), $class . $ext)){
return ;
}
include $filename;
}
});
}
protected function tearDown(): void
{
if ($this->app) {
$this->app->flush();
$this->app = null;
}
$this->setUpHasRun = false;
if (class_exists(Carbon::class)) {
Carbon::setTestNow();
}
if (class_exists(CarbonImmutable::class)) {
CarbonImmutable::setTestNow();
}
Artisan::forgetBootstrappers();
}
/**
* Register a callback to be run before the application is destroyed.
*
* @param callable $callback
* @return void
*/
protected function beforeApplicationDestroyed(callable $callback)
{
$this->beforeApplicationDestroyedCallbacks[] = $callback;
}
}
<file_sep>/src/Library/Qscmf/Builder/NavbarRightType/NavbarRightBuilder.class.php
<?php
namespace Qscmf\Builder\NavbarRightType;
class NavbarRightBuilder
{
public $type;
public $attribute;
public $auth_node;
public $options;
public $li_attribute;
/**
* @param $type
* @return $this
*/
public function setType($type){
$this->type = $type;
return $this;
}
/**
* @param $attribute
* @return $this
*/
public function setAttribute($attribute)
{
$this->attribute = $attribute;
return $this;
}
public function setAuthNode($auth_node){
$this->auth_node = $auth_node;
return $this;
}
public function setOptions($options){
$this->options = $options;
return $this;
}
public function setLiAttribute($li_attribute){
$this->li_attribute = $li_attribute;
return $this;
}
}<file_sep>/src/Library/Qscmf/Lib/Wall.class.php
<?php
namespace Qscmf\Lib;
class Wall
{
public function file_get_contents (string $filename, bool $use_include_path = false, ?string $context = null, int $offset = 0, ?int $length = null): string|false{
if (is_null($length)){
return file_get_contents($filename,$use_include_path,$context,$offset);
}else{
return file_get_contents($filename,$use_include_path,$context,$offset,$length);
}
}
}<file_sep>/src/Library/Qscmf/Builder/ButtonType/Save/TargetFormTrait.class.php
<?php
namespace Qscmf\Builder\ButtonType\Save;
trait TargetFormTrait
{
/**
* @deprecated 在v13会对该方法进行重构,原因是SubTableBuilder也可能会采用该方法来设置 column 的class,当同时作为listBuilder的modal使用时,就会被错误的一并save提交
* 先采用全局变量来开发重置能力,但全局变量容易存在冲突,并不是一种好的解决方案,仅作过渡使用
* 合理的做法应该让ListBuilder或者SubTableBuilder来决定Column 的TargetForm,避免互相影响。
* 显示页面
*/
public function getSaveTargetForm(){
return Save::$target_form;
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/EditableInterface.class.php
<?php
namespace Qscmf\Builder\ColumnType;
interface EditableInterface
{
public function editBuild(array &$option, array $data, $listBuilder);
public function getSaveTargetForm();
}<file_sep>/src/Library/Qscmf/Builder/ButtonType/Resume/Resume.class.php
<?php
namespace Qscmf\Builder\ButtonType\Resume;
use Qscmf\Builder\ButtonType\ButtonType;
class Resume extends ButtonType{
public function build(array &$option){
$my_attribute['title'] = '启用';
$my_attribute['target-form'] = 'ids';
$my_attribute['class'] = 'btn btn-success ajax-post confirm';
$my_attribute['href'] = U(
'/' . MODULE_NAME.'/'.CONTROLLER_NAME.'/resume'
);
$option['attribute'] = array_merge($my_attribute, is_array($option['attribute']) ? $option['attribute'] : [] );
return '';
}
}<file_sep>/src/Library/Qscmf/Controller/TestingController.class.php
<?php
namespace Qscmf\Controller;
use Think\Controller;
class TestingController extends Controller{
public function index(){
global $testingCallback;
if(!isTesting()){
qs_exit('');
}
if($testingCallback instanceof \Closure){
$result = call_user_func($testingCallback);
$re_serialize = \Opis\Closure\serialize($result);
qs_exit($re_serialize);
}
else{
E('testingCallback is null or not a Closure');
}
}
}<file_sep>/src/Library/Qscmf/Builder/ButtonType/ButtonType.class.php
<?php
namespace Qscmf\Builder\ButtonType;
abstract class ButtonType{
public abstract function build(array &$option);
}<file_sep>/src/Library/Qscmf/Builder/NavbarRightType/Self/Self_.class.php
<?php
namespace Qscmf\Builder\NavbarRightType\Self;
use Qscmf\Builder\NavbarRightType\NavbarRightType;
class Self_ extends NavbarRightType {
public function build(array &$option){
return $option['options'];
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/Picture/Picture.class.php
<?php
namespace Qscmf\Builder\FormType\Picture;
use Illuminate\Support\Str;
use Qscmf\Builder\FormType\FormType;
use Think\View;
use Qscmf\Builder\FormType\TUploadConfig;
class Picture implements FormType {
use TUploadConfig;
public function build(array $form_type){
$upload_type = $this->genUploadConfigCls($form_type['extra_attr'], 'image');
$view = new View();
$view->assign('form', $form_type);
$view->assign('gid', Str::uuid());
$view->assign('file_ext', $upload_type->getExts());
$view->assign('file_max_size', $upload_type->getMaxSize());
if($form_type['item_option']['read_only']){
$content = $view->fetch(__DIR__ . '/picture_read_only.html');
}
else{
$content = $view->fetch(__DIR__ . '/picture.html');
}
return $content;
}
}<file_sep>/src/Library/Behavior/BodyHtmlBehavior.class.php
<?php
namespace Behavior;
use Bootstrap\RegisterContainer;
class BodyHtmlBehavior{
public function run(&$content){
$body_html = RegisterContainer::getBodyHtml();
if ($body_html){
$html = implode(PHP_EOL, $body_html);
$search_str = C('QS_REGISTER_BODY_TAG_END');
$content = str_ireplace($search_str, $html .PHP_EOL. $search_str, $content);
}
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/District/District.class.php
<?php
namespace Qscmf\Builder\FormType\District;
use Illuminate\Support\Str;
use Qscmf\Builder\FormType\FormType;
use Think\View;
class District implements FormType {
public function build(array $form_type){
if(!is_array($form_type['options'])){
$form_type['options'] = [];
}
$view = new View();
$view->assign('gid', \Illuminate\Support\Str::uuid()->toString());
$view->assign('form', $form_type);
if($form_type['item_option']['read_only']){
$content = $view->fetch(__DIR__ . '/district_read_only.html');
}
else{
$content = $view->fetch(__DIR__ . '/district.html');
}
return $content;
}
}<file_sep>/asset/libs/label-select/README.md
# labelSelect
labelSelect插件
必须全局引入jQuery
1.安装依赖 npm install
2.运行webpack 打包 webpack (如需监听打包 webpack --watch)
====需要在跟目录运行服务器 如果已经运行请忽略====
3.安装http-serve: npm i -g http-serve
4.http-serve . -o -c-1 自动打开浏览器
<file_sep>/src/Library/Behavior/HeadCssBehavior.class.php
<?php
namespace Behavior;
use Bootstrap\RegisterContainer;
use Illuminate\Support\Str;
class HeadCssBehavior{
public function run(&$content){
$css_hrefs = RegisterContainer::getHeadCss();
$link = '';
foreach($css_hrefs as $href){
$link .= "<link href='{$href["href"]}' rel='stylesheet' type='text/css'>";
}
$search_str = C('QS_REGISTER_CSS_TAG_END');
$content = Str::replaceFirst($search_str, $link .PHP_EOL. $search_str, $content);
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Select/Select.class.php
<?php
namespace Qscmf\Builder\ColumnType\Select;
use Illuminate\Support\Str;
use Qscmf\Builder\ButtonType\Save\TargetFormTrait;
use Qscmf\Builder\ColumnType\ColumnType;
use Qscmf\Builder\ColumnType\EditableInterface;
class Select extends ColumnType implements EditableInterface{
use TargetFormTrait;
public function build(array &$option, array $data, $listBuilder){
$text = $option['value'][$data[$option['name']]];
return '<span title="' .$text. '" >' . $text . '</span>';
}
public function editBuild(&$option, $data, $listBuilder){
$class = "form-control input ". $this->getSaveTargetForm(). " {$option['extra_class']}";
$view = new \Think\View();
$view->assign('gid', Str::uuid());
$view->assign('options', $option);
$view->assign('data', $data);
$view->assign('class', $class);
$view->assign('value', $data[$option['name']]);
return $view->fetch(__DIR__ . '/select.html');
}
}<file_sep>/src/Library/Qscmf/Core/AuthChain.class.php
<?php
namespace Qscmf\Core;
use Qscmf\Core\Session\DefaultSession;
use Qscmf\Core\Session\ISession;
class AuthChain
{
const AUTH_RULE_ID = 'AUTH_RULE_ID';
const AUTH_ROLE_TYPE = 'AUTH_ROLE_TYPE';
private static $session_obj = null;
public static function registerSessionCls(ISession $session_obj){
self::$session_obj = $session_obj;
}
// 设置权限过滤标识key的session值
public static function setAuthFilterKey($role_id, $role_type = ''){
$role_id = $role_id ? $role_id : null;
$role_type = ($role_id && $role_type) ? $role_type : null;
self::$session_obj->set(self::AUTH_RULE_ID, $role_id);
self::$session_obj->set(self::AUTH_ROLE_TYPE, $role_type);
}
// 清空权限过滤标识key的session值
public static function cleanAuthFilterKey(){
self::$session_obj->clear(self::AUTH_RULE_ID);
self::$session_obj->clear(self::AUTH_ROLE_TYPE);
}
public static function getAuthRuleId(){
return self::$session_obj->get(self::AUTH_RULE_ID);
}
public static function getAuthRoleType(){
return self::$session_obj->get(self::AUTH_ROLE_TYPE);
}
public static function init(){
if (is_null(self::$session_obj)){
self::$session_obj = new DefaultSession();
}
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/Select2/Select2.class.php
<?php
namespace Qscmf\Builder\FormType\Select2;
use Qscmf\Builder\FormType\FormType;
use Think\View;
class Select2 implements FormType {
public function build(array $form_type){
$view = new View();
$view->assign('gid', \Illuminate\Support\Str::uuid()->toString());
$view->assign('form', $form_type);
if($form_type['item_option']['read_only']){
$content = $view->fetch(__DIR__ . '/select2_read_only.html');
}
else{
$content = $view->fetch(__DIR__ . '/select2.html');
}
return $content;
}
}<file_sep>/src/Library/Qscmf/Helper/function.php
<?php
if(!function_exists('combineOssUrlImgOpt')){
function combineOssUrlImgOpt(string $url, string $img_opt):string
{
$oss_handle_prefix = 'x-oss-process=image';
$img_opt = str_replace($oss_handle_prefix.'/', '', $img_opt);
if (empty($img_opt)) {
return $url;
}
$img_opt = '/'.$img_opt;
$has_img_opt = strpos($url, $oss_handle_prefix);
if ($has_img_opt === false){
$has_query = strpos($url, '?');
$join_str = $has_query === false ? '?' : '&';
$url .= $join_str.$oss_handle_prefix.$img_opt;
}else{
$url .= $img_opt;
}
return $url;
}
}
if(!function_exists('is_json')){
function is_json($string)
{
if(!is_string($string)){
return false;
}
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
}
if (!function_exists('filterItemsByAuthNode')){
function filterItemsByAuthNode($check_items){
return array_values(array_filter(array_map(function ($items){
return filterOneItemByAuthNode($items, $items['auth_node']);
}, (array)$check_items)));
}
}
if (!function_exists("filterOneItemByAuthNode")){
function filterOneItemByAuthNode($item, $item_auth_node = null){
if ($item_auth_node){
$auth_node = (array)$item_auth_node;
$node = $auth_node['node'] ? (array)$auth_node['node'] : $auth_node;
$logic = $auth_node['logic'] ? $auth_node['logic'] : 'and';
switch ($logic){
case 'and':
foreach ($node as $v){
$has_auth = verifyAuthNode($v);
if (!$has_auth){
$item = null;
break;
}
}
break;
case 'or':
$false_count = 0;
foreach ($node as $v){
$has_auth = verifyAuthNode($v);
if ($has_auth){
break;
}else{
$false_count ++;
}
}
if ($false_count == count($node)){
$item = null;
}
break;
default:
E('Invalid logic value');
break;
}
}
return $item;
}
}
if(!function_exists('uniquePageData')){
function uniquePageData($cache_key, $unique_key, $page, $data){
$current_cache_key = $cache_key . '_' . $page;
$pre_cache_key = $cache_key . '_' . ($page -1);
if($page == 1 || !session($pre_cache_key)){
$key_data = collect($data)->map(function($item) use ($unique_key){
return [
$unique_key => $item[$unique_key]
];
})->all();
session($current_cache_key, $key_data);
return $data;
}
$pre_data = session($pre_cache_key);
$res = collect($data)->filter(function($item) use ($pre_data, $unique_key) {
$res = collect($pre_data)->where($unique_key, $item[$unique_key])->all();
return $res ? false : true;
});
return $res->all();
}
}
if(!function_exists('checkGt')){
function checkGt($value, $gt_value){
if(!is_numeric($value)){
return null;
}
return $value > $gt_value;
}
}
if(!function_exists('convert')){
function convert($size)
{
$unit=array('b','kb','mb','gb','tb','pb');
return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
}
}
if(!function_exists('isUrl')){
function isUrl($url){
if($url == ''){
return false;
}
$validator = \Symfony\Component\Validator\Validation::createValidator();
$validations = $validator->validate($url, [ new \Symfony\Component\Validator\Constraints\Url()]);
return count($validations) > 0 ? false : true;
}
}
/**
* 时间戳格式化
* @param int $time
* @return string 完整的时间显示
*/
if(!function_exists('time_format')) {
function time_format($time = NULL, $format = 'Y-m-d H:i:s')
{
$time = $time === NULL ? NOW_TIME : intval($time);
return date($format, $time);
}
}
if(!function_exists('qsEmpty')){
function qsEmpty($value, bool $except_zero = true) : bool{
if(is_string($value)){
$value = trim($value);
}
if(is_object($value)){
$value = (array)$value;
}
if(!$except_zero){
return empty($value);
}
if($value !== 0 && $value !== "0" && empty($value)){
return true;
}
else{
return false;
}
}
}
if(!function_exists('testing_throw')){
function testing_throw($e)
{
if($e instanceof \Qscmf\Exception\TestingException){
throw new \Qscmf\Exception\TestingException($e->getMessage());
}
}
}
if(!function_exists('isTesting')){
function isTesting()
{
return env('APP_ENV') == 'testing' && !isset($_SERVER['DUSK_TEST']);
}
}
if(!function_exists('readerSiteConfig')) {
function readerSiteConfig()
{
if(!class_exists('\Common\Model\ConfigModel')){
//兼容某些项目会不存在config表的情况
return false;
}
$config = new \Common\Model\ConfigModel();
$site_config = S('DB_CONFIG_DATA');
if (!$site_config) {
$site_config = $config->lists();
S('DB_CONFIG_DATA', $site_config);
}
C($site_config); //添加配置
}
}
if(!function_exists('normalizeRelativePath')) {
/**
* Normalize relative directories in a path.
*
* @param string $path
*
* @return string
* @throws Exception
*
*/
function normalizeRelativePath($path)
{
$path = str_replace('\\', '/', $path);
$path = removeFunkyWhiteSpace($path);
$parts = [];
foreach (explode('/', $path) as $part) {
switch ($part) {
case '.':
break;
case '..':
if (empty($parts)) {
$arr = explode('/', realpath('.'));
array_walk($arr, function($item, $key) use(&$parts){
if($item){
$parts[] = $item;
}
});
}
if (empty($parts)) {
throw new Exception(
'Path is outside of the defined root, path: [' . $path . ']'
);
}
array_pop($parts);
break;
default:
$parts[] = $part;
break;
}
}
return implode('/', $parts);
}
}
if(!function_exists('removeFunkyWhiteSpace')) {
/**
* Removes unprintable characters and invalid unicode characters.
*
* @param string $path
*
* @return string $path
*/
function removeFunkyWhiteSpace($path)
{
// We do this check in a loop, since removing invalid unicode characters
// can lead to new characters being created.
while (preg_match('#\p{C}+|^\./#u', $path)) {
$path = preg_replace('#\p{C}+|^\./#u', '', $path);
}
return $path;
}
}
if(!function_exists('getRelativePath')){
/**
* 计算$b相对于$a的相对路径
* @param string $a
* @param string $b
* @return string
*/
function getRelativePath($a, $b) {
$relativePath = "";
$pathA = explode('/', $a);
$pathB = explode('/', dirname($b));
$n = 0;
$len = count($pathB) > count($pathA) ? count($pathA) : count($pathB);
do {
if ( $n >= $len || $pathA[$n] != $pathB[$n] ) {
break;
}
} while (++$n);
$relativePath .= str_repeat('../', count($pathB) - $n);
$relativePath .= implode('/', array_splice($pathA, $n));
return $relativePath;
}
}
// 清空INJECT_RBAC标识key的session值
if(!function_exists('cleanRbacKey')){
function cleanRbacKey(){
$inject_rbac_arr = C('INJECT_RBAC');
if (empty($inject_rbac_arr)){
return true;
}
$keys = array_column($inject_rbac_arr, 'key');
array_map(function ($str){
session($str, null);
}, $keys);
}
}
if(!function_exists('base64_url_encode')){
function base64_url_encode($data)
{
$find = array('+', '/');
$replace = array('-', '_');
return str_replace($find, $replace, base64_encode($data));
}
}
if(!function_exists('base64_url_decode')){
function base64_url_decode($str){
$find = array('-', '_');
$replace = array('+', '/');
return base64_decode(str_replace($find, $replace, $str));
}
}
/**
* 把返回的数据集转换成Tree
* @param array $list 要转换的数据集
* @param string $pid parent标记字段
* @param string $level level标记字段
* @return array
*/
if(!function_exists('list_to_tree')) {
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
// 创建Tree
$tree = array();
if (is_array($list)) {
// 创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $data) {
$refer[$data[$pk]] =& $list[$key];
}
foreach ($list as $key => $data) {
// 判断是否存在parent
$parentId = $data[$pid];
if ($root == $parentId) {
$tree[] =& $list[$key];
} else {
if (isset($refer[$parentId])) {
$parent =& $refer[$parentId];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
}
}
//将从list_to_tree转换成的tree转换成树状结构下来列表
if(!function_exists('genSelectByTree')) {
function genSelectByTree($tree, $child = '_child', $level = 0)
{
$select = array();
foreach ($tree as $key => $data) {
if (isset($data[$child])) {
$data['level'] = $level;
$select[] = $data;
$child_list = genSelectByTree($data[$child], $child, $level + 1);
foreach ($child_list as $k => $v) {
$select[] = $v;
}
} else {
$data['level'] = $level;
$select[] = $data;
}
}
return $select;
}
}
if(!function_exists('isAdminLogin')) {
function isAdminLogin()
{
return session('?' . C('USER_AUTH_KEY')) && session('?ADMIN_LOGIN');
}
}
if(!function_exists('qs_exit')){
function qs_exit($content = ''){
if(isTesting()){
throw new \Qscmf\Exception\TestingException($content);
}
else{
exit($content);
}
}
}
if(!function_exists('asset')){
function asset($path){
$config = C('ASSET');
return $config['prefix'] . $path;
}
}
if(!function_exists('old')) {
function old($key, $default = null)
{
return \Qscmf\Core\Flash::get('qs_old_input.' . $key, $default);
}
}
if(!function_exists('flashError')) {
function flashError($err_msg)
{
\Qscmf\Core\FlashError::set($err_msg);
}
}
if(!function_exists('verifyAuthNode')) {
function verifyAuthNode($node)
{
list($module_name, $controller_name, $action_name) = explode('.', $node);
return \Qscmf\Core\QsRbac::AccessDecision($module_name, $controller_name, $action_name) ? 1 : 0;
}
}
/**
* 配合文件上传插件使用 把file_ids转化为srcjson
* example: $ids = '1,2'
* return: [ "https:\/\/csh-pub-resp.oss-cn-shenzhen.aliyuncs.com\/Uploads\/image\/20181123\/5bf79e7860393.jpg",
* //有数据的时候返回showFileUrl($id)的结果
* '' //没有数据时返回空字符串
* ];
* @param $ids array|string file_ids
* @return string data srcjson
*/
if(!function_exists('fidToSrcjson')) {
function fidToSrcjson($ids)
{
if ($ids) {
if (!is_array($ids)) {
$ids = explode(',', $ids);
}
$json = [];
foreach ($ids as $id) {
$json[] = showFileUrl($id);
}
return htmlentities(json_encode($json));
} else {
return '';
}
}
}
/**
* 裁剪字符串
* 保证每个裁切的字符串视觉长度一致,而curLength裁剪会导致视觉长度参差不齐
* frontCutLength: 中文算2个字符长度,其他算1个长度
* curLength: 每个字符都是算一个长度
*
* example1: 若字符串长度小等于$len,将会原样输出$str;
* frontCutLength('字符1',5); @return: '字符1';
*
* example2: 若字符串长度大于$len
* frontCutLength('字符12',5); @return: '字...';(最后的"..."会算入$len)
*
* example3: 若字符串长度大于$len,且最大长度的字符不能完整输出,则最大长度的字符会被忽略
* frontCutLength('1字符串',5); @return: '1....';("字"被省略,最后的"..."会算入$len)
*
* @param $str string 要截的字符串
* @param $len int|string 裁剪的长度 按英文的长度计算
* @return false|string
*/
if(!function_exists('frontCutLength')) {
function frontCutLength($str, $len)
{
$gbStr = iconv('UTF-8', 'GBK', $str);
$count = strlen($gbStr);
if ($count <= $len) {
return $str;
}
$gbStr = mb_strcut($gbStr, 0, $len - 3, 'GBK');
$str = iconv('GBK', 'UTF-8', $gbStr);
return $str . '...';
}
}
//展示数据库存储文件URL地址
if(!function_exists('showFileUrl')){
function showFileUrl($file_id, $default_file = ''){
if(filter_var($file_id, FILTER_VALIDATE_URL)){
return $file_id;
}
$file_pic = M('FilePic');
$file_pic_ent = $file_pic->where(array('id' => $file_id))->cache(true, 86400)->find();
if(!$file_pic_ent || ($file_pic_ent['url'] == '' && $file_pic_ent['file'] == '')){
return $default_file;
}
//如果图片是网络链接,直接返回网络链接
if(!empty($file_pic_ent['url']) && $file_pic_ent['security'] != 1){
\Think\Hook::listen('heic_to_jpg', $file_pic_ent);
return $file_pic_ent['url'];
}
if($file_pic_ent['security'] == 1){
//alioss
if(!empty($file_pic_ent['url'])){
$file_tmp = $file_pic_ent;
$param = [
'file_ent' => $file_pic_ent,
'timeout' => 60
];
\Think\Hook::listen('get_auth_url', $param);
$file_tmp['url'] = $param['auth_url'];
\Think\Hook::listen('heic_to_jpg', $file_tmp);
$url = $file_tmp['url'];
return $url;
}
if(strtolower(MODULE_NAME) == 'admin' || $file_pic_ent['owner'] == session(C('USER_AUTH_KEY'))){
return \Qscmf\Core\AuthResource::genTemporaryUrl($file_pic_ent, 180);
}
}
else{
return UPLOAD_PATH . '/' . $file_pic_ent['file'];
}
}
}
if(!function_exists('getAutocropConfig')) {
function getAutocropConfig($key)
{
$ent = D('Addons')->where(['name' => 'AutoCrop', 'status' => 1])->find();
$config = json_decode($ent['config'], true);
$config = json_decode(html_entity_decode($config['config']), true);
return $config[$key];
}
}
//取缩略图
if(!function_exists('showThumbUrl')) {
function showThumbUrl($file_id, $prefix, $replace_img = '')
{
if (filter_var($file_id, FILTER_VALIDATE_URL)) {
return $file_id;
}
$file_pic = M('FilePic');
$file_pic_ent = $file_pic->where(array('id' => $file_id))->find();
//自动填充的测试数据处理
if ($file_pic_ent['seed'] && $file_pic_ent['url'] && ($config = getAutocropConfig($prefix))) {
$width = $config[0];
$high = $config[1];
return preg_replace('/(http[s]?\:\/\/[a-z0-9\-\.\_]+?)\/(\d+?)\/(\d+)(.*)/i', "$1/{$width}/{$high}$4", $file_pic_ent['url']);
}
if (!$file_pic_ent && !$replace_img) {
//不存在图片时,显示默认封面图
$file_pic_ent = $file_pic->where(array('id' => C('DEFAULT_THUMB')))->find();
}
$file_name = basename(UPLOAD_DIR . '/' . $file_pic_ent['file']);
$thumb_path = UPLOAD_DIR . '/' . str_replace($file_name, $prefix . '_' . $file_name, $file_pic_ent['file']);
//当file字段不存在值时,程序编程检测文件夹是否存在,依然会通过。因此要加上当file字段有值这项条件
if (file_exists($thumb_path) === true && !empty($file_pic_ent['file'])) {
return UPLOAD_PATH . '/' . str_replace($file_name, $prefix . '_' . $file_name, $file_pic_ent['file']);
} elseif ($replace_img) {
return $replace_img;
} else {
return showFileUrl($file_id);
}
}
}
// 根据地区id获取其全名称
if(!function_exists('getAreaFullCname1ByID')) {
function getAreaFullCname1ByID($id, $model = 'AreaV',$field = 'full_cname1')
{
return M($model)->where(['id' => $id])->getField($field);
}
}
// 根据多个地区id获取其下属的所有地区
if (!function_exists('getAllAreaIdsWithMultiPids')){
function getAllAreaIdsWithMultiPids($city_ids, $model = 'AreaV', $max_level = 3, $need_exist = true, $cache = ''){
$kname = 'kname';
$value = 'value';
$kname_column_mapping = ['country_id','p_id','c_id','d_id'];
$i = 0;
$kname_column = 'case';
while ($i <= $max_level){
$kname_column .= " when level = ".$i." then '".$kname_column_mapping[$i]."' ";
$i++;
}
$kname_column .= 'end as '.$kname;
if(is_int($city_ids)){
$city_ids = (string)$city_ids;
}
if (is_string($city_ids)){
$city_ids = explode(',', $city_ids);
}
$all_city_ids = [];
if (!empty($city_ids)){
$cls_name = 'Common\Model\\'.$model.'Model';
$model_class = new $cls_name();
$all_ids_model_class = new $cls_name();
$is_array_cache = is_array($cache);
if ($cache && !$is_array_cache){
$model_class = $model_class->cache($cache);
$all_ids_model_class = $all_ids_model_class->cache($cache);
}
if ($is_array_cache){
list($key, $expire, $type) = $cache;
$model_class = $model_class->cache($key, $expire, $type);
$all_ids_model_class = $all_ids_model_class->cache($key, $expire, $type);
}
$map['id'] = ['IN', $city_ids];
$map['level'] = ['ELT', $max_level];
$field = "{$kname_column},group_concat(id) as ".$value;
$list = $model_class->notOptionsFilter()->where($map)->group('level')->getField($field, true);
if ($list){
$full_map_arr = collect($list)->map(function ($value, $kname){
$value_str = "'".implode("','",explode(",", $value))."'";
return "{$kname} in (".$value_str.")";
})->all();
$full_map = implode(' or ', array_values($full_map_arr));
$all_city_ids = $all_ids_model_class->notOptionsFilter()->where($full_map)->getField('id', true);
}
!$need_exist && $all_city_ids = array_values(array_unique(array_merge($city_ids, $all_city_ids)));
}
return $all_city_ids;
}
// 递归删除目录下的空目录
// $preserve 是否保留本身目录,默认为false,不保留
if(!function_exists('deleteEmptyDirectory')) {
function deleteEmptyDirectory($directory, $preserve = false)
{
if (!is_dir($directory)) {
return false;
}
$items = new \FilesystemIterator($directory);
foreach ($items as $item) {
if ($item->isDir() && !$item->isLink()) {
deleteEmptyDirectory($item->getPathname());
}
}
if (!$preserve && count(scandir($directory)) === 2) {
rmdir($directory);
}
return true;
}
}
// 获取方法名参数
if(!function_exists('getFunParams')) {
function getFunParams(string $fun_name):array
{
$ref_cls = new ReflectionFunction($fun_name);
$params = [];
foreach ($ref_cls->getParameters() as $val){
$params[] = $val->name;
}
return $params;
}
}
// 判断方法是否有参数
if(!function_exists('isFunHadParams')) {
function isFunHadParams(string $fun_name):bool
{
return !empty(getFunParams($fun_name));
}
}
// 加载Common/Conf/Config配置
if(!function_exists('loadAllCommonConfig')) {
function loadAllCommonConfig(){
$config_arr = [];
$file_arr = glob(APP_PATH.'Common/Conf/Config/*.php');
foreach($file_arr as $file){
$config_arr = array_merge($config_arr,include $file);
}
return $config_arr;
}
}
if (!function_exists('getNid')){
function getNid($module_name = MODULE_NAME,$controller_name=CONTROLLER_NAME,$action_name=ACTION_NAME){
$m_sql = D('Node')->alias('m')->where(['name' => $module_name ,'level' => Qscmf\Lib\DBCont::LEVEL_MODULE, 'c.pid = m.id'])->field('id')->buildSql();
$c_sql = D('Node')->alias('c')->where(['name' => $controller_name ,'level' => Qscmf\Lib\DBCont::LEVEL_CONTROLLER, '_string' => "exists ".$m_sql, 'a.pid=c.id'])->field('id')->buildSql();
$nid = D('Node')->alias('a')->where(['name' => $action_name, 'level' => Qscmf\Lib\DBCont::LEVEL_ACTION, '_string' => "exists ". $c_sql])->getField('id');
return $nid;
}
}
if(!function_exists('showImg')) {
function showImg($id){
return showFileUrl($id,showFileUrl(C('DEFAULT_THUMB')));
}
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Btn/Btn.class.php
<?php
namespace Qscmf\Builder\ColumnType\Btn;
use Qscmf\Builder\ColumnType\ColumnType;
class Btn extends ColumnType {
public function build(array &$option, array $data, $listBuilder){
return $data[$option['name']];
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/FileFormType.class.php
<?php
namespace Qscmf\Builder\FormType;
class FileFormType{
private $preview_url = "https://view.officeapps.live.com/op/embed.aspx?src=";
private $preivew_ext = [
'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'jpg', 'jpeg', 'png', 'gif'
];
private $office_ext = [
'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'
];
private $other_ext = [
'pdf', 'jpg', 'jpeg', 'png', 'gif'
];
protected function getExt($url){
$arr = explode('.', $url);
$ext = end($arr);
return $ext;
}
protected function needPreview(string $file_url) : bool{
$ext = $this->getExt($file_url);
return in_array($ext, $this->preivew_ext);
}
protected function genPreviewUrl(string $file_url) : string{
$ext = $this->getExt($file_url);
if(in_array($ext, $this->office_ext)){
return $this->preview_url . $file_url;
}
else if(in_array($ext, $this->other_ext)){
return $file_url;
}
else{
return '';
}
}
protected function buildJsFn() : string{
$office_ext = json_encode($this->office_ext, JSON_PRETTY_PRINT);
$other_ext = json_encode($this->other_ext, JSON_PRETTY_PRINT);
$js = <<<javascript
function previewUrl(url){
var office_ext_arr = {$office_ext};
var other_ext_arr = {$other_ext};
var ext = url.split('.').pop();
if(office_ext_arr.includes(ext)){
return '{$this->preview_url}' + url;
}
else if(other_ext_arr.includes(ext)){
return url;
}
else {
return '';
}
}
javascript;
return $js;
}
}<file_sep>/src/Larafortp/ArtisanHack.php
<?php
namespace Larafortp;
use Bootstrap\RegisterContainer;
class ArtisanHack{
static public function init($app){
self::registerMigrator($app);
}
static private function registerMigrator($app){
$paths = RegisterContainer::getRegisterMigratePaths();
$app->afterResolving('migrator', function ($migrator) use ($paths) {
foreach ((array) $paths as $path) {
$migrator->path($path);
}
});
}
}<file_sep>/src/Library/Qscmf/Builder/GenButton/IGenButton.class.php
<?php
namespace Qscmf\Builder\GenButton;
interface IGenButton
{
public function getDataKeyName();
public function getPrimaryKey();
public function registerButtonType();
public function genOneButton($type, $attribute = null, $tips = '', $auth_node = '', $options = []);
public function parseButtonList($button_list, &$data);
public function getBtnDefClass();
public function mergeAttr($def_attr, $cus_attr);
}<file_sep>/src/Library/Qscmf/Builder/FormType/FormType.class.php
<?php
namespace Qscmf\Builder\FormType;
interface FormType{
function build(array $form_type);
}<file_sep>/src/Library/Qscmf/Builder/FormType/Address/Address.class.php
<?php
namespace Qscmf\Builder\FormType\Address;
use Qscmf\Builder\FormType\FormType;
use Think\View;
use Illuminate\Support\Str;
class Address implements FormType {
public function build(array $form_type){
$view = new View();
$view->assign('form', $form_type);
$view->assign('gid', Str::uuid());
$content = $view->fetch(__DIR__ . '/address.html');
return $content;
}
}<file_sep>/src/Larafortp/CmmMigrate/CmmMigrator.php
<?php
namespace Larafortp\CmmMigrate;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\ConnectionResolverInterface as Resolver;
use Illuminate\Database\Events\MigrationEnded;
use Illuminate\Database\Events\MigrationsEnded;
use Illuminate\Database\Events\MigrationsStarted;
use Illuminate\Database\Events\MigrationStarted;
use Illuminate\Database\Migrations\MigrationRepositoryInterface;
use Illuminate\Database\Migrations\Migrator;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
class CmmMigrator extends Migrator{
public function __construct(MigrationRepositoryInterface $repository, Resolver $resolver, Filesystem $files, Dispatcher $dispatcher = null)
{
parent::__construct($repository, $resolver, $files, $dispatcher);
}
/**
* Run an array of migrations.
*
* @param array $migrations
* @param array $options
* @return void
*/
public function runPending(array $migrations, array $options = [])
{
// First we will just make sure that there are any migrations to run. If there
// aren't, we will just make a note of it to the developer so they're aware
// that all of the migrations have been run against this database system.
if (count($migrations) === 0) {
$this->note('<info>Nothing to migrate.</info>');
return;
}
// Next, we will get the next batch number for the migrations so we can insert
// correct batch number in the database migrations repository when we store
// each migration's execution. We will also extract a few of the options.
$batch = $this->repository->getNextBatchNumber();
$pretend = $options['pretend'] ?? false;
$step = $options['step'] ?? false;
$no_cmd = $options['no-cmd'] ?? false;
$this->fireMigrationEvent(new MigrationsStarted);
// Once we have the array of migrations, we will spin through them and run the
// migrations "up" so the changes are made to the databases. We'll then log
// that the migration was run so we don't repeat it next time we execute.
foreach ($migrations as $file) {
$this->runUp($file, $batch, $pretend, $no_cmd);
if ($step) {
$batch++;
}
}
$this->fireMigrationEvent(new MigrationsEnded);
}
protected function runUp($file, $batch, $pretend, $no_cmd = false)
{
// First we will resolve a "real" instance of the migration class from this
// migration file name. Once we have the instances we can run the actual
// command such as "up" or "down", or we can just simulate the action.
$migration = $this->resolve(
$name = $this->getMigrationName($file)
);
if(!$no_cmd && method_exists($migration, 'beforeCmmUp') && !$this->repository->ranOperation($name, 'before'))
{
$this->runCommon($name, $migration, 'beforeCmmUp', $pretend, false);
$this->repository->log($name, $batch, 'before', false);
}
if(!$this->repository->ranOperation($name, 'run')){
$this->runCommon($name, $migration, 'up', $pretend);
$this->repository->log($name, $batch, 'run', false);
}
// Once we have run a migrations class, we will log that it was run in this
// repository so that we don't try to run it next time we do a migration
// in the application. A migration repository keeps the migrate order.
if(!$no_cmd && method_exists($migration, 'afterCmmUp') && !$this->repository->ranOperation($name, 'after'))
{
$this->runCommon($name, $migration, 'afterCmmUp', $pretend, false);
$this->repository->log($name, $batch, 'after', false);
}
$this->repository->log($name, $batch);
}
protected function runCommon($name, $migration, $method, $pretend, $event = true){
if ($pretend) {
return $this->pretendToRun($migration, $method);
}
if(strpos(strtolower($method), 'up') !== false){
$this->note("<comment>Migrating $method:</comment> {$name}");
}
else{
$this->note("<comment>Rolling back $method:</comment> {$name}");
}
$startTime = microtime(true);
$this->runMigration($migration, $method, $event);
$runTime = round(microtime(true) - $startTime, 2);
if(strpos(strtolower($method), 'up') !== false){
$this->note("<info>Migrated $method:</info> {$name} ({$runTime} seconds)");
}
else{
$this->note("<info>Rolled back $method:</info> {$name} ({$runTime} seconds)");
}
}
protected function runMigration($migration, $method, $event = true)
{
$connection = $this->resolveConnection(
$migration->getConnection()
);
$callback = function () use ($migration, $method, $event) {
if (method_exists($migration, $method)) {
$event && $this->fireMigrationEvent(new MigrationStarted($migration, $method));
$migration->{$method}();
$event && $this->fireMigrationEvent(new MigrationEnded($migration, $method));
}
};
$this->getSchemaGrammar($connection)->supportsSchemaTransactions()
&& $migration->withinTransaction
? $connection->transaction($callback)
: $callback();
}
/**
* Rollback the given migrations.
*
* @param array $migrations
* @param array|string $paths
* @param array $options
* @return array
*/
protected function rollbackMigrations(array $migrations, $paths, array $options)
{
$rolledBack = [];
$this->requireFiles($files = $this->getMigrationFiles($paths));
$this->fireMigrationEvent(new MigrationsStarted);
// Next we will run through all of the migrations and call the "down" method
// which will reverse each migration in order. This getLast method on the
// repository already returns these migration's names in reverse order.
foreach ($migrations as $migration) {
$migration = (object) $migration;
if (! $file = Arr::get($files, $migration->migration)) {
$this->note("<fg=red>Migration not found:</> {$migration->migration}");
continue;
}
$rolledBack[] = $file;
$this->runDown(
$file, $migration,
$options['pretend'] ?? false, $options['no-cmd'] ?? false
);
}
$this->fireMigrationEvent(new MigrationsEnded);
return $rolledBack;
}
protected function runDown($file, $migration, $pretend, $no_cmd = false)
{
// First we will get the file name of the migration so we can resolve out an
// instance of the migration. Once we get an instance we can either run a
// pretend execution of the migration or we can run the real migration.
$instance = $this->resolve(
$name = $this->getMigrationName($file)
);
if(!$no_cmd && method_exists($instance, 'afterCmmDown') && $this->repository->ranOperation($name, 'after'))
{
$this->runCommon($name, $instance, 'afterCmmDown', $pretend, false);
$this->repository->rollbackLog($name, 'after');
}
if($this->repository->ranOperation($name, 'run')){
$this->runCommon($name, $instance, 'down', $pretend);
$this->repository->rollbackLog($name, 'run');
}
if(!$no_cmd && method_exists($instance, 'beforeCmmDown') && $this->repository->ranOperation($name, 'before'))
{
$this->runCommon($name, $instance, 'beforeCmmDown', $pretend, false);
$this->repository->rollbackLog($name, 'before');
}
// Once we have successfully run the migration "down" we will remove it from
// the migration repository so it will be considered to have not been run
// by the application then will be able to fire by any later operation.
$this->repository->delete($migration);
}
public function reset($paths = [], $pretend = false, $no_cmd = false)
{
// Next, we will reverse the migration list so we can run them back in the
// correct order for resetting this database. This will allow us to get
// the database back into its "empty" state ready for the migrations.
$migrations = array_reverse($this->repository->getAllMigrations());
if (count($migrations) === 0) {
$this->note('<info>Nothing to rollback.</info>');
return [];
}
return $this->resetMigrations($migrations, $paths, $pretend, $no_cmd);
}
protected function resetMigrations(array $migrations, array $paths, $pretend = false, $no_cmd = false)
{
// Since the getRan method that retrieves the migration name just gives us the
// migration name, we will format the names into objects with the name as a
// property on the objects so that we can pass it to the rollback method.
$migrations = collect($migrations)->map(function ($m) {
return (object) ['migration' => $m];
})->all();
return $this->rollbackMigrations(
$migrations, $paths, compact('pretend', 'no_cmd')
);
}
}<file_sep>/src/Library/Qscmf/Builder/ButtonType/Save/DefaultEditableColumn.class.php
<?php
namespace Qscmf\Builder\ButtonType\Save;
class DefaultEditableColumn
{
use TargetFormTrait;
public function build($column, $data, $listBuilder){
$class = 'form-control input text ' . $this->getSaveTargetForm();
return "<input class='{$class}' type='text' name='{$column['name']}[]' value='{$data[$column['name']]}' />";
}
}<file_sep>/src/Library/Qscmf/Builder/ButtonType/Forbid/Forbid.class.php
<?php
namespace Qscmf\Builder\ButtonType\Forbid;
use Qscmf\Builder\ButtonType\ButtonType;
class Forbid extends ButtonType{
public function build(array &$option){
$my_attribute['title'] = '禁用';
$my_attribute['target-form'] = 'ids';
$my_attribute['class'] = 'btn btn-warning ajax-post confirm';
$my_attribute['href'] = U(
'/' . MODULE_NAME.'/'.CONTROLLER_NAME.'/forbid'
);
$option['attribute'] = array_merge($my_attribute, is_array($option['attribute']) ? $option['attribute'] : [] );
return '';
}
}<file_sep>/src/Library/Qscmf/Core/AuthResource.class.php
<?php
namespace Qscmf\Core;
class AuthResource{
public static function genTemporaryUrl(array $file_ent, int $expired){
$param = [];
$param['expired'] = time() + $expired;
$param['file_id'] = $file_ent['id'];
$config = C("UPLOAD_TYPE_" . strtoupper($file_ent['cate']));
$file_path = normalizeRelativePath(WWW_DIR . '/' . $config['rootPath'] . $file_ent['file']);
$data = [];
$data['file_path'] = $file_path;
$key = md5(http_build_query($param));
S($key, $file_path, $expired);
// $ext = pathinfo($file_path, PATHINFO_EXTENSION);
return U("qscmf/resource/temporaryLoad", ['key' => $key, 'resource' => $file_ent['file']], false, true);
}
}<file_sep>/qsinstall
#!/usr/bin/env php
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (version_compare('7.2.0', PHP_VERSION, '>')) {
fwrite(
STDERR,
sprintf(
'This version of think-core is supported on PHP 7.2 and PHP 7.3.' . PHP_EOL .
'You are using PHP %s (%s).' . PHP_EOL,
PHP_VERSION,
PHP_BINARY
)
);
die(1);
}
foreach (array(__DIR__ . '/../../../vendor/autoload.php', __DIR__ . '/../../autoload.php', __DIR__ . '/../vendor/autoload.php', __DIR__ . '/vendor/autoload.php') as $file) {
if (file_exists($file)) {
define('VENDOR_PATH', dirname($file));
break;
}
}
unset($file);
if (!defined('VENDOR_PATH')) {
fwrite(
STDERR,
'You need to set up the project dependencies using Composer:' . PHP_EOL . PHP_EOL .
' composer install' . PHP_EOL . PHP_EOL .
'You can learn all about Composer on https://getcomposer.org/.' . PHP_EOL
);
die(1);
}
if(!file_exists(VENDOR_PATH . "/../www/Public/libs")){
include VENDOR_PATH . '/tiderjian/think-core/src/Library/Qscmf/Helper/function.php';
$relative_path = getRelativePath(normalizeRelativePath(VENDOR_PATH . "/tiderjian/think-core/asset/libs"), normalizeRelativePath(VENDOR_PATH . "/../www/Public/libs"));
symlink($relative_path, VENDOR_PATH . "/../www/Public/libs");
fwrite(STDOUT, "generate libs link finished!" . PHP_EOL);
}
else{
fwrite(STDERR, "libs link already exists!" . PHP_EOL);
}
die(0);
<file_sep>/src/Library/Qscmf/Builder/ColumnType/Date/Date.class.php
<?php
namespace Qscmf\Builder\ColumnType\Date;
use Illuminate\Support\Str;
use Qscmf\Builder\ColumnType\ColumnType;
use Qscmf\Builder\ColumnType\EditableInterface;
class Date extends ColumnType implements EditableInterface{
use \Qscmf\Builder\ButtonType\Save\TargetFormTrait;
public function build(array &$option, array $data, $listBuilder){
return $this->formatDateVal($data[$option['name']], $option['value']);
}
public function editBuild(&$option, $data, $listBuilder){
$class = "form-control input date ". $this->getSaveTargetForm()." {$option['extra_class']}";
$view = new \Think\View();
$view->assign('gid', Str::uuid());
$view->assign('options', $option);
$view->assign('data', $data);
$view->assign('class', $class);
$view->assign('value', $this->formatDateVal($data[$option['name']], $option['value']));
return $view->fetch(__DIR__ . '/date.html');
}
protected function formatDateVal($value, $format = null){
$format = $format?:'Y-m-d';
return qsEmpty($value) ? '' : time_format($value, $format);
}
static public function registerCssAndJs():?array {
return null;
}
static public function registerEditCssAndJs():?array {
return [
"<script src='".asset('libs/cui/cui.extend.min.js')."' ></script>",
"<script src='".asset('libs/bootstrap-datepicker/bootstrap-datepicker.js')."' ></script>",
"<script src='".asset('libs/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js')."' ></script>",
"<script src='".asset('libs/bootstrap-datetimepicker/locales/bootstrap-datetimepicker.zh-CN.js')."' ></script>",
];
}
}<file_sep>/src/Library/Qscmf/Builder/GenColumn/TGenColumn.class.php
<?php
namespace Qscmf\Builder\GenColumn;
use Bootstrap\RegisterContainer;
use Qscmf\Builder\ButtonType\Save\DefaultEditableColumn;
use Qscmf\Builder\ColumnType\A\A;
use Qscmf\Builder\ColumnType\Arr\Arr;
use Qscmf\Builder\ColumnType\Btn\Btn;
use Qscmf\Builder\ColumnType\Date\Date;
use Qscmf\Builder\ColumnType\EditableInterface;
use Qscmf\Builder\ColumnType\Fun\Fun;
use Qscmf\Builder\ColumnType\Hidden\Hidden;
use Qscmf\Builder\ColumnType\Icon\Icon;
use Qscmf\Builder\ColumnType\Num\Num;
use Qscmf\Builder\ColumnType\Picture\Picture;
use Qscmf\Builder\ColumnType\Select\Select;
use Qscmf\Builder\ColumnType\Select2\Select2;
use Qscmf\Builder\ColumnType\Self\Self_;
use Qscmf\Builder\ColumnType\Status\Status;
use Qscmf\Builder\ColumnType\Time\Time;
use Qscmf\Builder\ColumnType\Type\Type;
use Qscmf\Builder\ColumnType\Textarea\Textarea;
use Qscmf\Builder\ColumnType\Checkbox\Checkbox;
use Qscmf\Builder\ColumnType\Pictures\Pictures;
trait TGenColumn
{
private $_column_type = [];
private $_default_column_type = \Qscmf\Builder\ColumnType\Text\Text::class;
private $_table_data_list_key = 'id'; // 表格数据列表主键字段名
private $_column_css_and_js = [];
public function registerColumnType(){
static $column_type = [];
if(empty($column_type)){
$base_column_type = self::registerBaseColumnType();
$column_type = array_merge($base_column_type, RegisterContainer::getListColumnType());
}
$this->_column_type = $column_type;
}
protected function registerBaseColumnType(){
return [
'status' => Status::class,
'icon' => Icon::class,
'date' => Date::class,
'time' => Time::class,
'picture' => Picture::class,
'pictures' => Pictures::class,
'type' => Type::class,
'fun' => Fun::class,
'a' => A::class,
'self' => Self_::class,
'num' => Num::class,
'btn' => Btn::class,
'textarea' => Textarea::class,
'checkbox' => Checkbox::class,
'hidden' => Hidden::class,
'select' => Select::class,
'select2' => Select2::class,
'arr' => Arr::class
];
}
public function genOneColumnOpt($name, $title, $type = null, $value = '', $editable = false, $tip = '',
$th_extra_attr = '', $td_extra_attr = '', $auth_node = '', $extra_attr = '', $extra_class = '') {
return compact('name','title','editable','type','value','tip','th_extra_attr',
'td_extra_attr','auth_node','extra_class','extra_attr');
}
public function buildOneColumnItem(&$column, &$data){
$is_editable = $this->isEditable($column, $data);
$column_type = $this->_column_type[$column['type']] ?? $this->_default_column_type;
$column_type_class = new $column_type();
if ($column_type_class){
$column_content = $is_editable && $column_type_class instanceof EditableInterface ?
$column_type_class->editBuild($column, $data, $this) :
$column_type_class->build($column, $data, $this);
$column_content = $this->parseData($column_content, $data);
$is_editable ? $this->getEditCssAndJs($column_type_class) : $this->getReadonlyCssAndJs($column_type_class);
}
if ($is_editable && !$column_type_class instanceof EditableInterface){
$column_content = (new DefaultEditableColumn())->build($column, $data, $this);
}
$data[$column['name']] = $column_content;
}
protected function isEditable($column, $data) : bool{
if($column['editable'] && $column['editable'] instanceof \Closure){
return $column['editable']($data);
}
else{
return $column['editable'];
}
}
protected function parseData($str, $data){
while(preg_match('/__(\w+?)__/i', $str, $matches)){
$str = str_replace('__' . $matches[1] . '__', $data[$matches[1]], $str);
}
return $str;
}
public function getTableDataListKey(){
return $this->_table_data_list_key;
}
protected function getReadonlyCssAndJs($column_cls){
$this->getCssAndJs($column_cls, 'registerCssAndJs');
}
protected function getCssAndJs($column_cls, $method_name){
if (method_exists($column_cls, $method_name)){
$source = $column_cls::$method_name();
is_array($source) && $this->_column_css_and_js = array_merge($this->_column_css_and_js,$source);
}
}
protected function getEditCssAndJs($column_cls){
$this->getCssAndJs($column_cls, 'registerEditCssAndJs');
}
public function getUniqueColumnCssAndJs():string{
return implode(PHP_EOL,array_unique($this->_column_css_and_js));
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Select2/Select2.class.php
<?php
namespace Qscmf\Builder\ColumnType\Select2;
use Illuminate\Support\Str;
use Qscmf\Builder\ButtonType\Save\TargetFormTrait;
use Qscmf\Builder\ColumnType\ColumnType;
use Qscmf\Builder\ColumnType\EditableInterface;
class Select2 extends ColumnType implements EditableInterface{
use TargetFormTrait;
public function build(array &$option, array $data, $listBuilder){
$this->extraValue($option);
$text = $this->getSelectText($option['value'], $data[$option['name']]);
return '<span title="' .$text. '" >' . $text . '</span>';
}
protected function getSelectText($options, $value){
$selected_text = '';
if(!qsEmpty($value)){
$value = is_array($value) ? $value : explode(',', $value);
}
if(!qsEmpty($value)){
$children_option = array_column($options, 'children');
if (!empty($children_option)){
$new_options = [];
array_map(function($option) use(&$new_options){
$new_options = array_merge($new_options, $option);
}, $children_option);
$options = array_column($new_options, 'text', 'id');
}
$selected_value = array_filter($options,function($text, $key) use($value){
return in_array($key, $value);
}, ARRAY_FILTER_USE_BOTH);
$selected_text = implode(',',$selected_value);
}
return $selected_text;
}
protected function extraValue(&$option){
if(isset($option['value']['options'])){
$option['select2_options'] = $option['value'];
$this->handleSelectOptions($option['select2_options']);
$option['value'] = $option['value']['options'];
}
}
protected function handleSelectOptions(&$select_options){
if (!empty($select_options)){
unset($select_options['options']);
$select_options['tags'] = match ($select_options['tags']){
true,'true' => "true",
default => "false"
};
$select_options['allow_clear'] = match ($select_options['allow_clear']){
false,'false' => 'false',
default => 'true'
};
}
}
public function editBuild(&$option, $data, $listBuilder){
$this->extraValue($option);
$class = "form-control input ". $this->getSaveTargetForm(). " {$option['extra_class']}";
$view = new \Think\View();
$view->assign('gid', Str::uuid());
$view->assign('options', $option);
$view->assign('data', $data);
$view->assign('class', $class);
$view->assign('name', $option['name']);
$view->assign('value', $data[$option['name']]);
$view->assign('select2_options', $option['select2_options']);
return $view->fetch(__DIR__ . '/select2.html');
}
static public function registerCssAndJs():?array {
return null;
}
static public function registerEditCssAndJs():?array {
return self::getCssAndJs();
}
static protected function getCssAndJs() :array {
return [
"<link rel='stylesheet' href='".asset('libs/select2/css/select2.min.css')."' />",
"<script src='".asset('libs/select2/js/select2.full.min.js')."' ></script>",
];
}
}<file_sep>/src/Library/Behavior/SecurityBehavior.class.php
<?php
namespace Behavior;
class SecurityBehavior{
public function run(&$_data){
//header安全
header("X-XSS-Protection: 1; mode=block");
header("X-Frame-Options: sameorigin");
header("X-Content-Type-Options: nosniff");
header("Strict-Transport-Security: max-age=31536000; includeSubDomains");
}
}<file_sep>/src/ConstDefine.php
<?php
defined('_PHP_FILE_') || define('_PHP_FILE_', '');
$root_const = ltrim(env('ROOT', ''), '/') ? '/' . ltrim(env('ROOT', ''), '/') : '';
defined('__ROOT__') || define('__ROOT__', $root_const);
defined('ROOT_PATH') || define('ROOT_PATH', realpath(__DIR__ . '/../../../..'));
defined('LARA_DIR') || define('LARA_DIR', ROOT_PATH . '/lara');
// 定义应用目录
defined('APP_NAME') || define('APP_NAME', 'app');
defined('APP_PATH') || define('APP_PATH',ROOT_PATH . '/' . APP_NAME . '/');
defined('APP_DIR') || define('APP_DIR', ROOT_PATH . '/' . APP_NAME);
defined('WWW_DIR') || define('WWW_DIR', ROOT_PATH . '/www');
defined('TPL_PATH') || define('TPL_PATH', APP_DIR . '/Tpl/');
defined('UPLOAD_PATH') || define('UPLOAD_PATH', __ROOT__ . '/Uploads');
defined('UPLOAD_DIR') || define('UPLOAD_DIR', WWW_DIR . DIRECTORY_SEPARATOR . 'Uploads');
defined('SECURITY_UPLOAD_PATH') || define('SECURITY_UPLOAD_PATH', __ROOT__ . '/' . APP_NAME . '/Uploads');
defined('SECURITY_UPLOAD_DIR') || define('SECURITY_UPLOAD_DIR', APP_DIR . DIRECTORY_SEPARATOR . 'Uploads');
defined('RULE_DIR') || define('RULE_DIR', APP_DIR . DIRECTORY_SEPARATOR . 'Common/Rule');
defined('CRON_DIR') || define("CRON_DIR", APP_DIR . DIRECTORY_SEPARATOR . 'Cron');
defined('CODER_DIR') || define('CODER_DIR', APP_DIR . DIRECTORY_SEPARATOR . 'Common/Coder');
defined('ADDON_PATH') || define('ADDON_PATH', APP_PATH . 'Addons/');
// 系统常量定义
defined('THINK_PATH') or define('THINK_PATH', __DIR__ . '/');
defined('APP_STATUS') or define('APP_STATUS', ''); // 应用状态 加载对应的配置文件
defined('APP_DEBUG') || define('APP_DEBUG', env("APP_DEBUG", true));
if(function_exists('saeAutoLoader')){// 自动识别SAE环境
defined('APP_MODE') or define('APP_MODE', 'sae');
defined('STORAGE_TYPE') or define('STORAGE_TYPE', 'Sae');
}else{
defined('APP_MODE') or define('APP_MODE', 'common'); // 应用模式 默认为普通模式
defined('STORAGE_TYPE') or define('STORAGE_TYPE', 'File'); // 存储类型 默认为File
}
defined('RUNTIME_PATH') or define('RUNTIME_PATH', APP_PATH.'Runtime/'); // 系统运行时目录
defined('LIB_PATH') or define('LIB_PATH', realpath(THINK_PATH.'Library').'/'); // 系统核心类库目录
defined('QSCMF_PATH') or define('QSCMF_PATH', LIB_PATH . 'Qscmf/');
defined('CORE_PATH') or define('CORE_PATH', LIB_PATH.'Think/'); // Think类库目录
defined('BEHAVIOR_PATH')or define('BEHAVIOR_PATH', LIB_PATH.'Behavior/'); // 行为类库目录
defined('MODE_PATH') or define('MODE_PATH', THINK_PATH.'Mode/'); // 系统应用模式目录
defined('VENDOR_PATH') or define('VENDOR_PATH', LIB_PATH.'Vendor/'); // 第三方类库目录
defined('COMMON_PATH') or define('COMMON_PATH', APP_PATH.'Common/'); // 应用公共目录
defined('CONF_PATH') or define('CONF_PATH', COMMON_PATH.'Conf/'); // 应用配置目录
defined('LANG_PATH') or define('LANG_PATH', COMMON_PATH.'Lang/'); // 应用语言目录
defined('HTML_PATH') or define('HTML_PATH', APP_PATH.'Html/'); // 应用静态目录
defined('LOG_PATH') or define('LOG_PATH', RUNTIME_PATH.'Logs/'); // 应用日志目录
defined('TEMP_PATH') or define('TEMP_PATH', RUNTIME_PATH.'Temp/'); // 应用缓存目录
defined('DATA_PATH') or define('DATA_PATH', RUNTIME_PATH.'Data/'); // 应用数据目录
defined('CACHE_PATH') or define('CACHE_PATH', RUNTIME_PATH.'Cache/'); // 应用模板缓存目录
defined('CONF_EXT') or define('CONF_EXT', '.php'); // 配置文件后缀
defined('CONF_PARSE') or define('CONF_PARSE', ''); // 配置文件解析方法
defined("PHP_NULL") or define("PHP_NULL", '__php_null__');
<file_sep>/src/Library/Qscmf/Conf/config.php
<?php
return [
//分页参数
'VAR_PAGE' => 'page',
'USER_AUTH_ON' => true, //是否需要认证
'USER_AUTH_TYPE' => 2, //认证类型
'USER_AUTH_KEY' => 'auth_id', //认证识别号
'USER_AUTH_MODEL' => 'user',
'USER_AUTH_ADMINID' => '1',
'RBAC_ROLE_TABLE' => 'qs_role',
'RBAC_USER_TABLE' => 'qs_role_user',
'RBAC_ACCESS_TABLE' => 'qs_access',
'RBAC_NODE_TABLE' => 'qs_node',
'ADMIN_AUTH_KEY' => 'super_admin',
'URL_ROUTER_ON' => true, // 是否开启URL路由
//qiniu up config sample
// 'UPLOAD_TYPE_AUDIO' => array(
// 'mimes' => 'video/*,audio/*', //允许上传的文件MiMe类型
// 'maxSize' => 300*1024*1024, //上传的文件大小限制 (0-不做限制)
// 'saveName' => array('uniqid', ''), //上传文件命名规则,[0]-函数名,[1]-参数,>多个参数使用数组
// 'pfopOps' => "avthumb/mp3/ab/160k/ar/44100/acodec/libmp3lame",
// 'pipeline' => 'gdufs_audio',
// 'bucket' => 'gdufs',
// 'domain' => 'https://media.t4tstudio.com'
// ),
'QS_REGISTER_JS_TAG_BEGIN' => '<!-- qs-register-js-begin -->',
'QS_REGISTER_JS_TAG_END' => '<!-- qs-register-js-end -->',
'QS_REGISTER_CSS_TAG_BEGIN' => '<!-- qs-register-css-begin -->',
'QS_REGISTER_CSS_TAG_END' => '<!-- qs-register-css-end -->',
'QS_REGISTER_BODY_TAG_BEGIN' => '<!-- qs-register-body-begin -->',
'QS_REGISTER_BODY_TAG_END' => '<!-- qs-register-body-end -->',
'QS_CORE_MODEL' => [ 'Qscmf\Core\QsModel', 'Qscmf\Core\QsListModel']
];<file_sep>/src/Library/Qscmf/Builder/ButtonType/Save/Save.class.php
<?php
namespace Qscmf\Builder\ButtonType\Save;
use Qscmf\Builder\ButtonType\ButtonType;
class Save extends ButtonType{
public static $target_form = 'save';
public function build(array &$option){
$my_attribute['title'] = '保存';
$my_attribute['target-form'] = self::$target_form;
$my_attribute['class'] = 'btn btn-primary ajax-post confirm';
$my_attribute['href'] = U(
'/' . MODULE_NAME.'/'.CONTROLLER_NAME.'/save'
);
$option['attribute'] = array_merge($my_attribute, is_array($option['attribute']) ? $option['attribute'] : [] );
return '';
}
}<file_sep>/src/Library/Qscmf/Builder/ListRightButton/Forbid/Forbid.class.php
<?php
namespace Qscmf\Builder\ListRightButton\Forbid;
use Qscmf\Builder\ListRightButton\ListRightButton;
class Forbid extends ListRightButton{
public function build(array &$option, array $data, $listBuilder){
$btn_type = [
'0' => [
'title' => '启用',
'class' => 'success ajax-get confirm',
'href' => U(
MODULE_NAME.'/'.CONTROLLER_NAME.'/resume',
array(
'ids' => '__data_id__'
)
)
],
'1' => [
'title' => '禁用',
'class' => 'warning ajax-get confirm',
'href' => U(
MODULE_NAME.'/'.CONTROLLER_NAME.'/forbid',
array(
'ids' => '__data_id__'
)
)
]
];
$type = $btn_type[$data['status']];
$option['attribute'] = $listBuilder->mergeAttr($type, is_array($option['attribute']) ? $option['attribute'] : []);
return '';
}
}<file_sep>/src/Bootstrap/Provider.php
<?php
namespace Bootstrap;
interface Provider{
public function register();
}<file_sep>/src/Library/Qscmf/Lib/Elasticsearch/Elasticsearch.class.php
<?php
namespace Qscmf\Lib\Elasticsearch;
use Elasticsearch\ClientBuilder;
class Elasticsearch{
static public function getBuilder(){
return ClientBuilder::create()->setHosts(C('ELASTICSEARCH_HOSTS'))->build();
}
}<file_sep>/asset/libs/ueditor/php/action_upload.php
<?php
/**
* 上传附件和上传视频
* User: Jinqn
* Date: 14-04-09
* Time: 上午10:17
*/
include "Uploader.class.php";
/* 上传配置 */
$base64 = "upload";
switch (htmlspecialchars($_GET['action'])) {
case 'uploadimage':
$config = array(
"pathFormat" => $CONFIG['imagePathFormat'],
"maxSize" => $CONFIG['imageMaxSize'],
"allowFiles" => $CONFIG['imageAllowFiles']
);
$fieldName = $CONFIG['imageFieldName'];
break;
case 'uploadscrawl':
$config = array(
"pathFormat" => $CONFIG['scrawlPathFormat'],
"maxSize" => $CONFIG['scrawlMaxSize'],
"allowFiles" => $CONFIG['scrawlAllowFiles'],
"oriName" => "scrawl.png"
);
$fieldName = $CONFIG['scrawlFieldName'];
$base64 = "base64";
break;
case 'uploadvideo':
$config = array(
"pathFormat" => $CONFIG['videoPathFormat'],
"maxSize" => $CONFIG['videoMaxSize'],
"allowFiles" => $CONFIG['videoAllowFiles']
);
$fieldName = $CONFIG['videoFieldName'];
break;
case 'uploadfile':
default:
$config = array(
"pathFormat" => $CONFIG['filePathFormat'],
"maxSize" => $CONFIG['fileMaxSize'],
"allowFiles" => $CONFIG['fileAllowFiles']
);
$fieldName = $CONFIG['fileFieldName'];
break;
}
/**
* 得到上传文件所对应的各个参数,数组结构
* array(
* "state" => "", //上传状态,上传成功时必须返回"SUCCESS"
* "url" => "", //返回的地址
* "title" => "", //新文件名
* "original" => "", //原始文件名
* "type" => "" //文件类型
* "size" => "", //文件大小
* )
*/
/* 生成上传实例对象并完成上传 */
$up = new Uploader($fieldName, $config, $base64);
$oss = $_GET['oss'];
if($oss){
/* 返回数据 */
$file_info = $up->getFileInfo();
$type = $_GET['type'];
if(!$type){
$type = 'image';
}
$oss_type = $common_config['UPLOAD_TYPE_' . strtoupper($type)];
$is_cname=false;
if ($oss_type['oss_options']) {
$bucket=$oss_type['oss_options']['bucket'];
$endpoint = $oss_type['oss_host'];
$is_cname=true;
}else{
$url = $oss_type['oss_host'];
$rt = parse_url($url);
$arr = explode('.', $rt['host']);
$bucket = array_shift($arr);
$endpoint = $rt['scheme'] . '://' . join('.', $arr);
}
$oss_config = array(
"ALIOSS_ACCESS_KEY_ID" => $common_config['ALIOSS_ACCESS_KEY_ID'],
"ALIOSS_ACCESS_KEY_SECRET" => $common_config["ALIOSS_ACCESS_KEY_SECRET"],
"end_point" => $endpoint,
"bucket" => $bucket
);
spl_autoload_register(function($class){
$path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
$file = VENDOR_DIR . "/../app/Common/Util" . DIRECTORY_SEPARATOR . $path . '.php';
if (file_exists($file)) {
require_once $file;
}
});
if($file_info['state'] != 'SUCCESS'){
return json_encode($file_info);
}
$oss_client = new \OSS\OssClient($oss_config['ALIOSS_ACCESS_KEY_ID'], $oss_config['ALIOSS_ACCESS_KEY_SECRET'], $oss_config['end_point'],$is_cname);
$header_options = array(\OSS\OssClient::OSS_HEADERS => $oss_type['oss_meta']);
$file = realpath(VENDOR_DIR . '/../www' . $file_info['url']);
$r = $oss_client->uploadFile($oss_config['bucket'], trim($file_info['url'], '/'), $file, $header_options);
unlink($file);
if(isset($oss_type['oss_public_host'])){
$public_url = parse_url($oss_type['oss_public_host']);
$internal_url = parse_url($oss_type['oss_host']);
$oss_request_url = str_replace($internal_url['host'], $public_url['host'], $r['oss-request-url']);
}
else{
$oss_request_url = $r['oss-request-url'];
}
$file_info['url'] = parseUrl($oss_request_url , 0, $_GET['url_prefix'], $_GET['url_suffix']);
return json_encode($file_info);
}
else{
/**
* 得到上传文件所对应的各个参数,数组结构
* array(
* "state" => "", //上传状态,上传成功时必须返回"SUCCESS"
* "url" => "", //返回的地址
* "title" => "", //新文件名
* "original" => "", //原始文件名
* "type" => "" //文件类型
* "size" => "", //文件大小
* )
*/
/* 返回数据 */
$file_info = $up->getFileInfo();
$file_info['url'] = parseUrl($file_info['url'], $_GET['urldomain'], $_GET['url_prefix'], $_GET['url_suffix']);
return json_encode($file_info);
}
<file_sep>/asset/libs/ueditor/php/action_crawler.php
<?php
/**
* 抓取远程图片
* User: Jinqn
* Date: 14-04-14
* Time: 下午19:18
*/
set_time_limit(0);
include("Uploader.class.php");
/* 上传配置 */
$config = array(
"pathFormat" => $CONFIG['catcherPathFormat'],
"maxSize" => $CONFIG['catcherMaxSize'],
"allowFiles" => $CONFIG['catcherAllowFiles'],
"oriName" => "remote.png"
);
$fieldName = $CONFIG['catcherFieldName'];
/* 抓取远程图片 */
$list = array();
if (isset($_POST[$fieldName])) {
$source = $_POST[$fieldName];
} else {
$source = $_GET[$fieldName];
}
$oss = $_GET['oss'];
if($oss){
$type = $_GET['type'];
if(!$type){
$type = 'image';
}
$oss_type = $common_config['UPLOAD_TYPE_' . strtoupper($type)];
$is_cname=false;
if ($oss_type['oss_options'] && $oss_type['oss_options']['bucket']) {
$bucket=$oss_type['oss_options']['bucket'];
$endpoint = $oss_type['oss_host'];
$is_cname=true;
}else{
$url = $oss_type['oss_host'];
$rt = parse_url($url);
$arr = explode('.', $rt['host']);
$bucket = array_shift($arr);
$endpoint = $rt['scheme'] . '://' . join('.', $arr);
}
$oss_config = array(
"ALIOSS_ACCESS_KEY_ID" => $common_config['ALIOSS_ACCESS_KEY_ID'],
"ALIOSS_ACCESS_KEY_SECRET" => $common_config["ALIOSS_ACCESS_KEY_SECRET"],
"end_point" => $endpoint,
"bucket" => $bucket
);
spl_autoload_register(function($class){
$path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
$file = VENDOR_DIR . "/../app/Common/Util" . DIRECTORY_SEPARATOR . $path . '.php';
if (file_exists($file)) {
require_once $file;
}
});
$oss_client = new \OSS\OssClient($oss_config['ALIOSS_ACCESS_KEY_ID'], $oss_config['ALIOSS_ACCESS_KEY_SECRET'], $oss_config['end_point'],$is_cname);
$header_options = array(\OSS\OssClient::OSS_HEADERS => $oss_type['oss_meta']);
$oss_client->setConnectTimeout(30);
foreach ($source as $imgUrl) {
$item = new Uploader($imgUrl, $config, "remote");
$info = $item->getFileInfo();
$file = realpath(VENDOR_DIR . '/../www' . $info['url']);
$r = $oss_client->uploadFile($oss_config['bucket'], trim($info['url'], '/'), $file, $header_options);
unlink($file);
if(isset($oss_type['oss_public_host'])){
$public_url = parse_url($oss_type['oss_public_host']);
$internal_url = parse_url($oss_type['oss_host']);
$oss_request_url = str_replace($internal_url['host'], $public_url['host'], $r['oss-request-url']);
}
else{
$oss_request_url = $r['oss-request-url'];
}
$info['url'] = parseUrl($oss_request_url , 0, $_GET['url_prefix'], $_GET['url_suffix']);
array_push($list, array(
"state" => $info["state"],
"url" => $info["url"],
"size" => $info["size"],
"title" => htmlspecialchars($info["title"]),
"original" => htmlspecialchars($info["original"]),
"source" => $imgUrl
));
}
/* 返回抓取数据 */
return json_encode(array(
'state'=> count($list) ? 'SUCCESS':'ERROR',
'list'=> $list
));
}
else{
foreach ($source as $imgUrl) {
$item = new Uploader($imgUrl, $config, "remote");
$info = $item->getFileInfo();
$info['url'] = parseUrl($info['url'], $_GET['urldomain'], $_GET['url_prefix'], $_GET['url_suffix']);
array_push($list, array(
"state" => $info["state"],
"url" => $info["url"],
"size" => $info["size"],
"title" => htmlspecialchars($info["title"]),
"original" => htmlspecialchars($info["original"]),
"source" => $imgUrl
));
}
/* 返回抓取数据 */
return json_encode(array(
'state'=> count($list) ? 'SUCCESS':'ERROR',
'list'=> $list
));
}
<file_sep>/src/Library/Qscmf/Builder/FormBuilder.class.php
<?php
namespace Qscmf\Builder;
use Illuminate\Support\Str;
use Qscmf\Builder\FormType\FormTypeRegister;
/**
* 表单页面自动生成器
*/
class FormBuilder extends BaseBuilder implements \Qscmf\Builder\GenButton\IGenButton {
use FormTypeRegister;
use \Qscmf\Builder\GenButton\TGenButton;
private $_post_url; // 表单提交地址
private $_form_items = array(); // 表单项目
private $_extra_items = array(); // 额外已经构造好的表单项目
private $_form_data = array(); // 表单数据
private $_ajax_submit = true; // 是否ajax提交
private $_custom_html;
private $_form_item_Filter = null;
private $_readonly = false;
private $_bottom = [];
private $_show_btn = true; // 是否展示按钮
private $_form_template;
private $_form_data_key = 'id'; // 数据主键字段名
private $_primary_key = '_pk'; // 备份主键
private $_btn_def_class = 'qs-form-btn';
private $_button_list;
private $_submit_btn_title = '确定';
private string $_gid;
/**
* 初始化方法
* @return $this
*/
protected function _initialize() {
$module_name = 'Admin';
$this->_template = __DIR__ .'/Layout/'.$module_name.'/form.html';
$this->_form_template = __DIR__ . '/formbuilder.html';
self::registerFormType();
self::registerButtonType();
self::setGid(Str::uuid()->getHex());
}
public function setGid($gid):self{
$this->_gid = $gid;
return $this;
}
public function getGid():string{
return $this->_gid;
}
public function setReadOnly($readonly){
$this->_readonly = $readonly;
return $this;
}
public function setFormType($type_name, $type_cls){
$this->_form_type[$type_name] = $type_cls;
}
public function setCustomHtml($custom_html){
$this->_custom_html = $custom_html;
return $this;
}
public function addBottom($html){
array_push($this->_bottom, $html);
return $this;
}
/**
* 直接设置表单项数组
* @param $form_items 表单项数组
* @return $this
*/
public function setExtraItems($extra_items) {
$this->_extra_items = $extra_items;
return $this;
}
/**
* 设置表单提交地址
* @param $url 提交地址
* @return $this
*/
public function setPostUrl($post_url) {
$this->_post_url = $post_url;
return $this;
}
public function setFormItemFilter(\Closure $filter){
$this->_form_item_Filter = $filter;
return $this;
}
/**
* 加入一个表单项
* @param string $name item名
* @param string $type item类型(取值参考系统配置FORM_ITEM_TYPE)
* @param string $title item标题
* @param string $tip item提示说明
* @param array $options item options
* @param string $extra_class item项额外样式,如使用hidden则隐藏item
* @param string $extra_attr item项额外属性
* @param string|array $auth_node item权限点
* @return $this
*/
public function addFormItem($name, $type, $title = '', $tip = '', $options = array(), $extra_class = '', $extra_attr = '', $auth_node = [], $item_option = []) {
$item['name'] = $name;
$item['type'] = $type;
$item['title'] = $title;
$item['tip'] = $tip;
$item['options'] = $options;
$item['extra_class'] = $extra_class;
$item['extra_attr'] = $extra_attr;
$item['auth_node'] = $auth_node;
$item['item_option'] = $item_option;
$this->_form_items[] = $item;
return $this;
}
/**
* 设置表单表单数据
* @param $form_data 表单数据
* @return $this
*/
public function setFormData($form_data) {
$this->_form_data = $form_data;
return $this;
}
/**
* 设置提交方式
* @param $title 标题文本
* @return $this
*/
public function setAjaxSubmit($ajax_submit = true) {
$this->_ajax_submit = $ajax_submit;
return $this;
}
public function setSubmitBtnTitle($title){
$this->_submit_btn_title = $title;
return $this;
}
public function setDataKeyName($form_data_key) {
$this->_form_data_key = $form_data_key;
return $this;
}
public function getDataKeyName()
{
return $this->_form_data_key;
}
protected function backupPk(){
$this->_form_data[$this->_primary_key] = $this->_form_data[$this->_form_data_key];
}
public function getPrimaryKey(){
return $this->_primary_key;
}
public function getBtnDefClass(){
return $this->_btn_def_class;
}
/**
* 加入一按钮
* 在使用预置的几种按钮时,比如我想改变编辑按钮的名称
* 那么只需要$builder->addButton('edit', array('title' => '换个马甲'))
* 如果想改变地址甚至新增一个属性用上面类似的定义方法
* 因为添加右侧按钮的时候你并没有办法知道数据ID,于是我们采用__data_id__作为约定的标记
* __data_id__会在display方法里自动替换成数据的真实ID
* @param string $type 按钮类型,取值参考registerBaseRightButtonType
* @param array|null $attribute 按钮属性,一个定义标题/链接/CSS类名等的属性描述数组
* @param string $tips 按钮提示
* @param string|array $auth_node 按钮权限点
* @param string|array|object $options 按钮options
* @return $this
*/
public function addButton($type, $attribute = null, $tips = '', $auth_node = '', $options = []) {
$this->_button_list[] = $this->genOneButton($type, $attribute, $tips, $auth_node, $options);
return $this;
}
/**
* @deprecated 在v13版本删除, 请使用 build 代替
* 显示页面
*/
public function display($render=false,$charset='',$contentType='',$content='',$prefix='') {
return $this->build($render);
}
public function build($render=false){
$this->backupPk();
//额外已经构造好的表单项目与单个组装的的表单项目进行合并
$this->_form_items = array_merge($this->_form_items, $this->_extra_items);
$this->_button_list = $this->checkAuthNode($this->_button_list);
if ($this->_button_list) {
self::setButtonDomType('button');
$this->_form_data['button_list'] = join('',self::parseButtonList($this->_button_list, $this->_form_data));
}
//编译表单值
foreach ($this->_form_items as &$item) {
if ($this->_form_data) {
if (isset($this->_form_data[$item['name']])) {
$item['value'] = $this->_form_data[$item['name']];
}
}
if($this->_readonly){
$item['item_option'] = array_merge($item['item_option'], ['read_only' => true]);
}
$item['render_content'] = (new $this->_form_type[$item['type']]())->build($item);
}
if($this->_form_item_Filter){
$this->_form_items = call_user_func($this->_form_item_Filter, $this->_form_data, $this->_form_items);
}
// 检测字段的权限点,无权限则unset该item
$this->_form_items = $this->checkAuthNode($this->_form_items);
if(!empty($this->_bottom)){
//保持底部按钮与内容块保持间隔
array_push($this->_bottom, '<br />');
}
$this->assign('custom_html', $this->_custom_html);
$this->assign('meta_title', $this->_meta_title); //页面标题
$this->assign('tab_nav', $this->_tab_nav); //页面Tab导航
$this->assign('post_url', $this->_post_url); //标题提交地址
$this->assign('form_items', $this->_form_items); //表单项目
$this->assign('ajax_submit', $this->_ajax_submit); //是否ajax提交
$this->assign('extra_html', $this->_extra_html); //额外HTML代码
$this->assign('top_html', $this->_top_html); //顶部自定义html代码
$this->assign('form_data', $this->_form_data);
$this->assign('nid', $this->_nid);
$this->assign('read_only', $this->_readonly);
$this->assign('bottom_html', join('', $this->_bottom));
$this->assign('show_btn', $this->_show_btn);
$this->assign('form_builder_path', $this->_form_template);
$this->assign('button_list', $this->_button_list);
$this->assign('content_bottom_html', join('', $this->_content_bottom));
$this->assign('submit_btn_title', $this->_submit_btn_title);
$this->assign('gid', $this->_gid);
if($render){
return parent::fetch($this->_form_template);
}
else{
parent::display($this->_template);
}
}
public function mergeAttr($def_attr, $cus_attr){
$right_btn_def_class = $this->getBtnDefClass();
$right_btn_def_class && $def_attr['class'] = $right_btn_def_class.' '.$def_attr['class'];
$def_attr['type'] = 'button';
return array_merge($def_attr, $cus_attr ?: []);
}
public function setShowBtn($is_show = true){
$this->_show_btn = $is_show;
return $this;
}
}
<file_sep>/asset/libs/label-select/lib/popup/js/popup.js
;
(function($) {
$.fn.popup = function(isShow, opts) {
var scrollTop = Math.max(parseInt($(document).scrollTop()), Math.abs(parseInt($('html').css('marginTop')))),
$this = $(this),
$popupContent = $this.find('.popup-content'),
$page = $('html,body'),
$html = $('html'),
$body = $('body'),
$popupMask = $('.popup-mask'),
$window = $(window),
opt = {},
keyBroad = false;
timer = null;
var defOut = {
onShowBefore: function() {
},
onShowAfter: function() {
},
onCloseAfter: function() {
},
onCloseBefore: function() {
}
};
// $window.on('resize',function (){
// if($window.width() > 720){
// return false;
// }
// keyBroad = !keyBroad;
// if(keyBroad){
// $('.popup-content.active').css({
// transform: 'translate(-50%,-60%)'
// });
// }else{
// $('.popup-content.active').css({
// transform: 'translate(-50%,-50%)'
// });
// }
// });
opt = $.extend(defOut, opts);
if (typeof isShow === 'string') {
if (isShow === 'show') {
show();
} else if (isShow === 'hide') {
hide();
}
}
$('.icon-close-mask').on('click', function() {
hide();
});
function show() {
opt.onShowBefore();
$page.addClass('offcanvas').css({
width: $window.width(),
});
$html.css({
marginTop: -scrollTop + 'px',
height: $window.height(),
left: '50%',
marginLeft: '-' + ($html.width() / 2) + 'px',
overflowY: 'hidden'
});
$popupMask.removeClass('hidden');
setTimeout(function() {
$popupMask.addClass('active');
}, 1);
$this.removeClass('hidden').css({
width: $window.width(),
height: $window.height()
});
setTimeout(function() {
$popupContent.addClass('active');
}, 1);
opt.onShowAfter();
}
function hide() {
if(timer){
return false;
}
timer = setTimeout(function (){
},300);
if(opt.onCloseBefore() === false){
return false;
}
$popupContent.removeClass('active');
$popupMask.removeClass('active').one('transitionend', function() {
$popupMask.addClass('hidden');
$this.addClass('hidden');
$page.removeClass('offcanvas');
$html.css({
marginTop: 0,
left: '0',
marginLeft: 'auto',
overflowY: 'auto'
});
window.scrollTo(0, scrollTop);
opt.onCloseAfter();
});
}
return $this;
}
})(jQuery);<file_sep>/src/Library/Qscmf/Builder/HeaderBuilder.class.php
<?php
namespace Qscmf\Builder;
use Bootstrap\RegisterContainer;
use Qscmf\Builder\NavbarRightType\NavbarRightBuilder;
use Qscmf\Builder\NavbarRightType\Num\Num;
use Qscmf\Builder\NavbarRightType\Self\Self_;
class HeaderBuilder
{
protected $item_list = [];
protected $header_navbar_right_item_type;
public function __construct()
{
$this->registerNavbarRightLiType();
}
protected function registerNavbarRightLiType(){
static $header_navbar_right_item_type = [];
if(empty($header_navbar_right_item_type)) {
$header_navbar_right_item_type = self::registerBaseNavbarRightLiType();
}
$this->header_navbar_right_item_type = $header_navbar_right_item_type;
}
protected function registerBaseNavbarRightLiType(){
return [
'num' => Num::class,
'self' => Self_::class
];
}
public function display(){
$this->item_list = BuilderHelper::checkAuthNode($this->item_list);
if ($this->item_list){
foreach ($this->item_list as $option) {
$tmp = [];
$tmp['li_attr'] = BuilderHelper::compileHtmlAttr($option['li_attribute']);
$tmp['li_html'] = (new $this->header_navbar_right_item_type[$option['type']]())->build($option);
$html = <<<HTML
<li {$tmp['li_attr']}>
{$tmp['li_html']}
</li>
HTML;
RegisterContainer::registerHeaderNavbarRightHtml($html);
}
}
}
/**
*
* 在header加入一个右侧导航项
*
* @param NavbarRightBuilder $navbarRightBuilder
* @return $this
*/
public function addNavbarRightItem(NavbarRightBuilder $navbarRightBuilder){
$this->item_list[] = (array)$navbarRightBuilder;
return $this;
}
}<file_sep>/src/Library/Qscmf/Builder/ListSearchType/Select/Select.class.php
<?php
namespace Qscmf\Builder\ListSearchType\Select;
use Think\View;
use Qscmf\Builder\ListSearchType\ListSearchType;
class Select implements ListSearchType{
public function build(array $item){
$options = $item['options'] instanceof SelectBuilder ? $item['options'] :
$this->buildDefBuilder((array)$item['options']);
!$options->getPlaceholder() && $options->setPlaceholder($item['title']);
$view = new View();
$view->assign('item', $item);
$view->assign('select_opt', $options->toArray());
$view->assign('value', I('get.'.$item['name']));
$content = $view->fetch(__DIR__ . '/select.html');
return $content;
}
protected function buildDefBuilder(array $options):SelectBuilder{
return new SelectBuilder($options);
}
static public function parse(string $key, string $map_key, array $get_data) : array{
if(isset($get_data[$key]) && !qsEmpty($get_data[$key])){
return [$map_key => $get_data[$key]];
}
else{
return [];
}
}
}<file_sep>/asset/libs/log.js
function frontLog (opt){
var defOpt={
url:'/api/jsLog/index'
};
opt = opt || {};
opt=Object.assign(defOpt,opt);
var url=opt.url;//更换url
var utils={
getBrowser:function(){
var sys = {};
var ua = navigator.userAgent.toLowerCase();
var s;
(s = ua.match(/edge\/([\d.]+)/)) ? sys.edge = s[1] :
(s = ua.match(/rv:([\d.]+)\) like gecko/)) ? sys.ie = s[1] :
(s = ua.match(/msie ([\d.]+)/)) ? sys.ie = s[1] :
(s = ua.match(/firefox\/([\d.]+)/)) ? sys.firefox = s[1] :
(s = ua.match(/chrome\/([\d.]+)/)) ? sys.chrome = s[1] :
(s = ua.match(/opera.([\d.]+)/)) ? sys.opera = s[1] :
(s = ua.match(/version\/([\d.]+).*safari/)) ? sys.safari = s[1] : 0;
if (sys.edge) return { browser : "Edge", version : sys.edge };
if (sys.ie) return { browser : "IE", version : sys.ie };
if (sys.firefox) return { browser : "Firefox", version : sys.firefox };
if (sys.chrome) return { browser : "Chrome", version : sys.chrome };
if (sys.opera) return { browser : "Opera", version : sys.opera };
if (sys.safari) return { browser : "Safari", version : sys.safari };
return { browser : "", version : "0" };
},
postError:function(url,data){
url=url||window.location.href;
var sendData=data||{};
var sd=[],keys=Object.keys(sendData);
for(var i=0;i<keys.length;i++){
sd.push(keys[i]+'='+encodeURIComponent(sendData[keys[i]]));
}
var img=document.createElement('img');
img.style.display='none';
img.src=url+'?'+sd.join('&');
setTimeout(function() {
document.body.appendChild(img);
var flag=false;
img.onerror=function(){
if(!flag) {
document.body.removeChild(img);
flag=true;
}
};
img.onload=function(){
if(!flag) {
document.body.removeChild(img);
flag=true;
}
}
}, 0);
}
};
window.onerror=function(m,f,l,c,e){
var browser=utils.getBrowser();
var res={
msg:m,
file:f,
line_no:l,
browser:browser.browser+','+browser.version,
user_agent:navigator.userAgent,
url:window.location.href
};
if(c){
res.col_no=c;
res.stack=e.stack;
}
utils.postError(url,res);
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Fun/Fun.class.php
<?php
namespace Qscmf\Builder\ColumnType\Fun;
use Qscmf\Builder\ColumnType\ColumnType;
class Fun extends ColumnType {
public function build(array &$option, array $data, $listBuilder){
$re = '';
if(preg_match('/(.+)->(.+)\((.+)\)/', $option['value'], $object_matches)){
$object_matches[3] = str_replace('\'', '', $object_matches[3]);
$object_matches[3] = str_replace('"', '', $object_matches[3]);
$param_arr = $this->parseParams($data[$option['name']]??'', $data[$listBuilder->getTableDataListKey()]??'', $object_matches[3]);
if(preg_match('/(.+)\((.+)\)/', $object_matches[1], $object_func_matches)){
$object_func_matches[2] = str_replace('\'', '', $object_func_matches[2]);
$object_func_matches[2] = str_replace('"', '', $object_func_matches[2]);
$object_param_arr = explode(',', $object_func_matches[2]);
$object = call_user_func_array($object_func_matches[1], $object_param_arr);
$re = call_user_func_array(array($object, $object_matches[2]), $param_arr);
}
}
else if(preg_match('/(.+)\((.+)\)/', $option['value'], $func_matches)){
$func_matches[2] = str_replace('\'', '', $func_matches[2]);
$func_matches[2] = str_replace('"', '', $func_matches[2]);
$func_param_arr = $this->parseParams($data[$option['name']]??'', $data[$listBuilder->getTableDataListKey()]??'', $func_matches[2]);
$re = call_user_func_array($func_matches[1], $func_param_arr);
}
return $re;
}
protected function parseParams(string $data_id, string $id, string $params) : array{
$param_arr = explode(',', $params);
foreach($param_arr as &$vo){
$vo = str_replace('__data_id__', $data_id, $vo);
$vo = str_replace('__id__', $id, $vo);
}
return $param_arr;
}
}<file_sep>/src/Library/Qscmf/Builder/GenColumn/IGenColumn.class.php
<?php
namespace Qscmf\Builder\GenColumn;
interface IGenColumn
{
public function registerColumnType();
public function genOneColumnOpt($name, $title, $type = null, $value = '', $editable = false, $tip = '',
$th_extra_attr = '', $td_extra_attr = '', $auth_node = '', $extra_attr = '', $extra_class = '');
public function buildOneColumnItem(&$column, &$data);
public function getTableDataListKey();
}<file_sep>/src/Library/Qscmf/Builder/NavbarRightType/NavbarRightType.class.php
<?php
namespace Qscmf\Builder\NavbarRightType;
abstract class NavbarRightType{
public abstract function build(array &$option);
}<file_sep>/src/Library/Qscmf/Lib/DBCont.class.php
<?php
namespace Qscmf\Lib;
class DBCont{
const LEVEL_MODULE = 1;
const LEVEL_CONTROLLER = 2;
const LEVEL_ACTION = 3;
const FORBIDDEN_STATUS = 0;
const NORMAL_STATUS = 1;
const JOB_STATUS_WAITING = 1;
const JOB_STATUS_RUNNING = 2;
const JOB_STATUS_FAILED = 3;
const JOB_STATUS_COMPLETE = 4;
const YES_BOOL_STATUS = 1;
const NO_BOOL_STATUS = 0;
const CLOSE_TYPE_ALL = 1;
const CLOSE_TYPE_CONNECTION = 2;
static private $_close_type = array(
self::CLOSE_TYPE_ALL => 'all',
self::CLOSE_TYPE_CONNECTION => 'connection'
);
static private $_status = array(
self::NORMAL_STATUS => '正常',
self::FORBIDDEN_STATUS => '禁用'
);
static private $_job_status = array(
self::JOB_STATUS_WAITING => '等待',
self::JOB_STATUS_RUNNING => '运行中',
self::JOB_STATUS_FAILED => '失败',
self::JOB_STATUS_COMPLETE => '完成'
);
static private $_bool_status = array(
self::YES_BOOL_STATUS => '是',
self::NO_BOOL_STATUS => '否'
);
static function __callStatic($name, $arguments)
{
$getListFn = function($var_name){
return self::$$var_name;
};
$getListValueFn = function($var_name) use ($arguments){
return (self::$$var_name)[$arguments[0]];
};
$static_name = '_';
if(preg_match("/get(\w+)List/", $name, $matches)){
$static_name .= parse_name($matches[1]);
$fn = $getListFn;
}
elseif(preg_match("/get(\w+)/", $name, $matches)){
$static_name .= parse_name($matches[1]);
$fn = $getListValueFn;
}
return $fn($static_name);
}
}
<file_sep>/src/Larafortp/CmmMigrate/CmmFreshCommand.php
<?php
namespace Larafortp\CmmMigrate;
use Illuminate\Database\Console\Migrations\FreshCommand;
use Symfony\Component\Console\Input\InputOption;
class CmmFreshCommand extends FreshCommand{
public function __construct()
{
parent::__construct();
}
public function handle()
{
if (! $this->confirmToProceed()) {
return;
}
$database = $this->input->getOption('database');
if ($this->option('drop-views')) {
$this->dropAllViews($database);
$this->info('Dropped all views successfully.');
}
$this->dropAllTables($database);
$this->info('Dropped all tables successfully.');
if ($this->option('drop-types')) {
$this->dropAllTypes($database);
$this->info('Dropped all types successfully.');
}
$this->call('migrate', array_filter([
'--database' => $database,
'--path' => $this->input->getOption('path'),
'--realpath' => $this->input->getOption('realpath'),
'--force' => true,
'--step' => $this->option('step'),
'--no-cmd' => $this->option('no-cmd')
]));
if ($this->needsSeeding()) {
$this->runSeeder($database);
}
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use'],
['drop-views', null, InputOption::VALUE_NONE, 'Drop all tables and views'],
['drop-types', null, InputOption::VALUE_NONE, 'Drop all tables and types (Postgres only)'],
['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'],
['path', null, InputOption::VALUE_OPTIONAL, 'The path to the migrations files to be executed'],
['realpath', null, InputOption::VALUE_NONE, 'Indicate any provided migration file paths are pre-resolved absolute paths'],
['seed', null, InputOption::VALUE_NONE, 'Indicates if the seed task should be re-run'],
['seeder', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder'],
['step', null, InputOption::VALUE_NONE, 'Force the migrations to be run so they can be rolled back individually'],
['no-cmd', null, InputOption::VALUE_NONE, 'dont run command']
];
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Text/Text.class.php
<?php
namespace Qscmf\Builder\ColumnType\Text;
use Qscmf\Builder\ButtonType\Save\TargetFormTrait;
use Qscmf\Builder\ColumnType\ColumnType;
use Qscmf\Builder\ColumnType\EditableInterface;
class Text extends ColumnType implements EditableInterface{
use TargetFormTrait;
public function build(array &$option, array $data, $listBuilder){
return '<span title="' . $data[$option['name']] . '" >' . $data[$option['name']] . '</span>';
}
public function editBuild(&$option, $data, $listBuilder){
$class = "form-control input text ". $this->getSaveTargetForm(). " {$option['extra_class']}";;
return "<input class='{$class}' {$option['extra_attr']} type='text' name='{$option['name']}[]' value='{$data[$option['name']]}' />";
}
}<file_sep>/asset/libs/ueditor/php/controller.php
<?php
//header('Access-Control-Allow-Origin: http://www.baidu.com'); //设置http://www.baidu.com允许跨域访问
//header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //设置允许的跨域header
foreach (array(__DIR__ . '/../../../../../../../vendor/autoload.php', __DIR__ .
'/../../../../../../vendor/autoload.php') as $file) {
if (file_exists($file)) {
define('VENDOR_DIR', dirname($file));
break;
}
}
require_once VENDOR_DIR . '/autoload.php';
$dotenv = \Dotenv\Dotenv::create(VENDOR_DIR . '/..');
$dotenv->load();
date_default_timezone_set("Asia/chongqing");
error_reporting(E_ERROR);
header("Content-Type: text/html; charset=utf-8");
if(file_exists(VENDOR_DIR . '/../app/Common/Conf/ueditor_config.json')){
$config_file = VENDOR_DIR . '/../app/Common/Conf/ueditor_config.json';
}
elseif(file_exists(VENDOR_DIR . '/../app/Common/Conf/ueditor_config.php')){
$config_file = VENDOR_DIR . '/../app/Common/Conf/ueditor_config.php';
}
else{
$config_file = "config.json";
}
$http_config = include VENDOR_DIR . '/../app/Common/Conf/Config/http_config.php';
$upload_config = include VENDOR_DIR . '/../app/Common/Conf/Config/upload_config.php';
$common_config = array_merge((array)$http_config, (array)$upload_config);
define('SITE_URL', env('DOMAIN', $_SERVER['HTTP_HOST']). env('ROOT'));
define('HTTP_PROTOCOL', $_SERVER[$common_config['HTTP_PROTOCOL_KEY']]);
function parseUrl($url, $domain = 0, $url_prefix = '', $url_suffix = ''){
$parsed_url = $url;
if($url_prefix){
$parsed_url = rtrim($url_prefix, '/') . $parsed_url;
}
if($_GET['url_suffix']){
$parsed_url = $parsed_url . $url_suffix;
}
if($_GET['urldomain']){
$parsed_url = HTTP_PROTOCOL . '://' . SITE_URL . $url;
}
return $parsed_url;
}
$extend = pathinfo($config_file, PATHINFO_EXTENSION);
if ($extend === 'php'){
$CONFIG = include $config_file;
}else{
$CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents($config_file)), true);
}
$action = $_GET['action'];
switch ($action) {
case 'config':
$result = json_encode($CONFIG);
break;
/* 上传图片 */
case 'uploadimage':
/* 上传涂鸦 */
case 'uploadscrawl':
/* 上传视频 */
case 'uploadvideo':
/* 上传文件 */
case 'uploadfile':
$result = include("action_upload.php");
break;
/* 获取微信富文本 */
case 'get_wx_rich_text':
$result = include("action_wx_rich_text.php");
break;
/* 列出图片 */
case 'listimage':
$result = include("action_list.php");
break;
/* 列出文件 */
case 'listfile':
$result = include("action_list.php");
break;
/* 抓取远程文件 */
case 'catchimage':
$result = include("action_crawler.php");
break;
default:
$result = json_encode(array(
'state'=> '请求地址出错'
));
break;
}
/* 输出结果 */
if (isset($_GET["callback"])) {
if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
} else {
echo json_encode(array(
'state'=> 'callback参数不合法'
));
}
} else {
echo $result;
}<file_sep>/src/Library/Qscmf/Builder/ListSearchType/SelectText/SelectText.class.php
<?php
namespace Qscmf\Builder\ListSearchType\SelectText;
use Think\View;
use Qscmf\Builder\ListSearchType\ListSearchType;
class SelectText implements ListSearchType{
public function build(array $item){
$view = new View();
$view->assign('item', $item);
$content = $view->fetch(__DIR__ . '/select_text.html');
return $content;
}
static public function parse(array $keys_rule, array $get_data) : array{
if (isset($get_data['key']) && $get_data['word']){
return match(true){
$keys_rule[$get_data['key']]['rule'] === 'fuzzy' => [$keys_rule[$get_data['key']]['map_key'] => ['like', "%{$get_data['word']}%"]],
$keys_rule[$get_data['key']]['rule'] === 'exact' => [$keys_rule[$get_data['key']]['map_key'] => $get_data['word']],
$keys_rule[$get_data['key']]['rule'] instanceof \Closure => $keys_rule[$get_data['key']]['rule']($keys_rule[$get_data['key']]['map_key'], $get_data['word']),
default => E("undefined rule"),
};
}
else{
return [];
}
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/File/File.class.php
<?php
namespace Qscmf\Builder\FormType\File;
use Illuminate\Support\Str;
use Qscmf\Builder\FormType\FileFormType;
use Qscmf\Builder\FormType\FormType;
use Qscmf\Builder\FormType\TUploadConfig;
use Think\View;
class File extends FileFormType implements FormType {
use TUploadConfig;
public function build(array $form_type){
$upload_type = $this->genUploadConfigCls($form_type['extra_attr'], 'file');
$view = new View();
if($form_type['value']){
$file = [];
$file['url'] = showFileUrl($form_type['value']);
if($this->needPreview($file['url'])){
$file['preview_url'] = $this->genPreviewUrl($file['url']);
}
$view->assign('file', $file);
}
$view->assign('form', $form_type);
$view->assign('gid', Str::uuid());
$view->assign('file_ext', $upload_type->getExts());
$view->assign('file_max_size', $upload_type->getMaxSize());
$view->assign('js_fn', $this->buildJsFn());
$content = $view->fetch(__DIR__ . '/file.html');
return $content;
}
}<file_sep>/src/Library/Behavior/InjectHeadBehavior.class.php
<?php
namespace Behavior;
use Illuminate\Support\Str;
class InjectHeadBehavior{
use InjectTrait;
public function run(&$params){
$template_suffix = $params['template_suffix'];
$extend_name = $params['extend_name'];
$this->inject_js($params['content'], $extend_name, $template_suffix);
$this->inject_css($params['content'], $extend_name, $template_suffix);
}
private function inject_js(&$content, $extend_name, $template_suffix){
$tag_begin = C('QS_REGISTER_JS_TAG_BEGIN');
$tag_end = C('QS_REGISTER_JS_TAG_END');
$inject_sign_html = $tag_begin .PHP_EOL. $tag_end;
$can_inject = $this->canInject($extend_name, $content, $template_suffix, $tag_begin);
$content = $can_inject ? str_ireplace('</head>',$inject_sign_html. PHP_EOL .'</head>',$content) : $content;
}
private function inject_css(&$content, $extend_name, $template_suffix){
$tag_begin = C('QS_REGISTER_CSS_TAG_BEGIN');
$tag_end = C('QS_REGISTER_CSS_TAG_END');
$inject_sign_html = $tag_begin .PHP_EOL. $tag_end;
$can_inject = $this->canInject($extend_name, $content, $template_suffix, $tag_begin);
$content = $can_inject ? Str::replaceFirst('<script', $inject_sign_html . PHP_EOL .'<script', $content) : $content;
}
}<file_sep>/src/Library/Qscmf/Builder/TSubBuilder.class.php
<?php
namespace Qscmf\Builder;
trait TSubBuilder
{
public function genQsSubBuilderRowToJs($has_column = 1){
if(IS_POST){
$columns = I('post.columns');
$this->transcodeColumns($columns);
$has_column && !defined('QS_SUB_RENEW_ROW') && define('QS_SUB_RENEW_ROW', 1);
$this->ajaxReturn(['data' => (new SubTableBuilder())->genNewRowHtml($columns)]);
}
}
protected function transcodeColumns(&$columns){
$columns = array_map(function($column){
$column['editable'] = $this->transcodeEditable($column['editable']);
return $column;
}, $columns);
}
protected function transcodeEditable($editable){
return $editable === 'false' ? false : $editable;
}
}<file_sep>/src/Library/Qscmf/Lib/WeixinLogin.class.php
<?php
namespace Qscmf\Lib;
use EasyWeChat\Factory;
use Qscmf\Exception\TestingException;
class WeixinLogin
{
private static $_self;
private $_easy_wechat_app;
private static $_timeout=300;
private $_session_key;
/**
* @return self
*/
public static function getInstance(){
if (self::$_self){
return self::$_self;
}
self::$_self=new self();
return self::getInstance();
}
private function __construct()
{
$config=[
'app_id'=>env('WX_APPID',''),
'secret'=>env('WX_APPSECRET','')
];
$this->_easy_wechat_app=Factory::officialAccount($config);
$this->_session_key=C('WX_INFO_SESSION_KEY',null,'wx_info');
}
public function getInfoForMobile(){
if (session('?'.$this->_session_key)){
return json_decode(session($this->_session_key),true);
}
if (I('get.code') && $wx_info=$this->_easy_wechat_app->oauth->user()){
session($this->_session_key,$wx_info->toJSON());
redirect(session('cur_request_url'));
qs_exit('');
}
$url=HTTP_PROTOCOL.'://'.SITE_URL.$_SERVER[C('URL_REQUEST_URI')];
session('cur_request_url',$url);
$response = $this->_easy_wechat_app->oauth->scopes(['snsapi_userinfo'])
->redirect($url);
$response->send();
qs_exit('');
}
public function getNotifyInfo($uni_code){
if ($info=S('wx_login'.$uni_code)){
if ($info==='no_scan'){
return $info;
}
S('wx_login'.$uni_code,null);
return is_json($info) ? json_decode($info,true) : $info;
}else{
return false;
}
}
public function notify($uni_code,$wx_info){
S('wx_login'.$uni_code,json_encode($wx_info),self::$_timeout);
}
public function getUniCode(){
$uni_code=md5(time()).rand(1000,9999);
if (S('wx_login'.$uni_code)){
return $this->getUniCode();
}
S('wx_login'.$uni_code,'no_scan',self::$_timeout);
return $uni_code;
}
}<file_sep>/src/Library/Qscmf/Controller/WeixinLoginController.class.php
<?php
namespace Qscmf\Controller;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
use Qscmf\Core\QsController;
use Qscmf\Lib\WeixinLogin;
class WeixinLoginController extends QsController
{
public function scan($goto_url='',$mobile_goto_url=''){
$this->_template = __DIR__ .'/../View/WeixinLogin/scan.html';
if (!$goto_url){
$goto_url=U('/',[],true,true);
}else{
$goto_url=urldecode($goto_url);
}
if (!$mobile_goto_url){
$mobile_goto_url=U('/',[],true,true);
}else{
$mobile_goto_url=urldecode($mobile_goto_url);
}
$uni_code=WeixinLogin::getInstance()->getUniCode();
$this->uni_code=$uni_code;
$this->goto_url=$goto_url;
// 手机端应访问的地址
$this->scan_url=U('mobile',['uni_code'=>$uni_code],true,true).'?goto_url='.urlencode($mobile_goto_url);
// PC端轮询地址
$this->check_url=U('checkPcLogin',['uni_code'=>$uni_code],true,true);
$this->display($this->_template);
}
public function qrcode($url){
header('Content-type:image/png');
$options = new QROptions([
'scale' => 50,
'imageBase64'=>false
]);
echo (new QRcode($options))->render(urldecode($url));
}
public function mobile($uni_code,$goto_url){
$wx_info=WeixinLogin::getInstance()->getInfoForMobile();
if ($wx_info){
WeixinLogin::getInstance()->notify($uni_code,$wx_info);
redirect(urldecode($goto_url));
}
}
public function checkPcLogin($uni_code){
$info=WeixinLogin::getInstance()->getNotifyInfo($uni_code);
if (!$info){
// uni_code过期,需要刷新页面
$this->ajaxReturn([
'status'=>0,
'info'=>'need_refresh'
]);
}
if ($info==='no_scan'){
// 未扫码或通知PC端
$this->ajaxReturn([
'status'=>2,
'info'=>'no_scan'
]);
}
session(C('WX_INFO_SESSION_KEY',null,'wx_info'),json_encode($info));
$this->ajaxReturn([
'status'=>1,
'info'=>$info
]);
}
}<file_sep>/src/Library/Qscmf/Controller/ConfigCacheController.class.php
<?php
namespace Qscmf\Controller;
use Think\Controller;
class ConfigCacheController extends Controller {
public function clear(){
S('DB_CONFIG_DATA', null);
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Status/Status.class.php
<?php
namespace Qscmf\Builder\ColumnType\Status;
use Qscmf\Builder\ColumnType\ColumnType;
class Status extends ColumnType {
public function build(array &$option, array $data, $listBuilder){
$re = '';
switch($data[$option['name']]){
case '0':
$re = '<i class="fa fa-ban text-danger"></i>';
break;
case '1':
$re = '<i class="fa fa-check text-success"></i>';
break;
}
return $re;
}
}<file_sep>/src/Library/Qscmf/Builder/ListSearchType/Self/Self_.class.php
<?php
namespace Qscmf\Builder\ListSearchType\Self;
use Qscmf\Builder\ListSearchType\ListSearchType;
class Self_ implements ListSearchType{
public function build(array $item){
return $item['options']['value']?:'';
}
}<file_sep>/src/Testing/InteractsWithTpConsole.php
<?php
namespace Testing;
trait InteractsWithTpConsole{
public function cli(...$args){
global $argv;
$command = $args[0];
$argv = $args;
return $this->runTpCliAsSanbox($command);
}
protected function runTpCliAsSanbox($command){
global $argv;
global $_SERVER;
$pipePath = "/tmp/test.pipe";
if( file_exists( $pipePath ) ){
unlink($pipePath);
}
if( !posix_mkfifo( $pipePath, 0666 ) ){
exit('make pipe false!' . PHP_EOL);
}
$pid = pcntl_fork();
if( $pid == 0 ){
define("IS_CGI", 0);
define("IS_CLI", true);
$_SERVER['argv'] = $argv;
require ROOT_PATH . '/' . $command;
$content = ob_get_contents();
$file = fopen( $pipePath, 'w' );
fwrite( $file, $content);
exit();
}else{
$file = fopen( $pipePath, 'r' );
$content = fread( $file, 99999999 ) . PHP_EOL;
pcntl_wait($status);
}
return $content;
}
public function runTp(\Closure $callback){
global $argv;
global $testingCallback;
$testingCallback = $callback;
$command = 'www/index.php';
$args[1] = '/Qscmf/Testing/index';
$argv = $args;
$re_serialize = $this->runTpCliAsSanbox($command);
return \Opis\Closure\unserialize($re_serialize);
}
}<file_sep>/src/Library/Qscmf/Builder/ColumnType/Textarea/Textarea.class.php
<?php
namespace Qscmf\Builder\ColumnType\Textarea;
use Qscmf\Builder\ButtonType\Save\TargetFormTrait;
use Qscmf\Builder\ColumnType\ColumnType;
use Qscmf\Builder\ColumnType\EditableInterface;
class Textarea extends ColumnType implements EditableInterface{
use TargetFormTrait;
public function build(array &$option, array $data, $listBuilder){
return "<textarea class='form-control input text' style='width: 100%;' disabled title='{$option['name']}'>{$data[$option['name']]}</textarea>";
}
public function editBuild(&$option, $data, $listBuilder){
$class = "form-control input text ". $this->getSaveTargetForm(). " {$option['extra_class']}";
return "<div class='input-control'> <textarea class='{$class}' name='{$option['name']}[]' {$option['extra_attr']}>{$data[$option['name']]}</textarea> </div>";
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/FormTypeRegister.class.php
<?php
namespace Qscmf\Builder\FormType;
use Bootstrap\RegisterContainer;
use Qscmf\Builder\FormType\Address\Address;
use Qscmf\Builder\FormType\Arr\Arr;
use Qscmf\Builder\FormType\Board\Board;
use Qscmf\Builder\FormType\Checkbox\Checkbox;
use Qscmf\Builder\FormType\City\City;
use Qscmf\Builder\FormType\Citys\Citys;
use Qscmf\Builder\FormType\Date\Date;
use Qscmf\Builder\FormType\Datetime\Datetime;
use Qscmf\Builder\FormType\District\District;
use Qscmf\Builder\FormType\Districts\Districts;
use Qscmf\Builder\FormType\Editormd\Editormd;
use Qscmf\Builder\FormType\File\File;
use Qscmf\Builder\FormType\Files\Files;
use Qscmf\Builder\FormType\Hidden\Hidden;
use Qscmf\Builder\FormType\Icon\Icon;
use Qscmf\Builder\FormType\Key\Key;
use Qscmf\Builder\FormType\Num\Num;
use Qscmf\Builder\FormType\Password\Password;
use Qscmf\Builder\FormType\Picture\Picture;
use Qscmf\Builder\FormType\PictureIntercept\PictureIntercept;
use Qscmf\Builder\FormType\Pictures\Pictures;
use Qscmf\Builder\FormType\PicturesIntercept\PicturesIntercept;
use Qscmf\Builder\FormType\Province\Province;
use Qscmf\Builder\FormType\Radio\Radio;
use Qscmf\Builder\FormType\Select\Select;
use Qscmf\Builder\FormType\Select2\Select2;
use Qscmf\Builder\FormType\SelectOther\SelectOther;
use Qscmf\Builder\FormType\Self\Self_;
use Qscmf\Builder\FormType\Static_\Static_;
use Qscmf\Builder\FormType\Tags\Tags;
use Qscmf\Builder\FormType\Text\Text;
use Qscmf\Builder\FormType\Textarea\Textarea;
use Qscmf\Builder\FormType\Ueditor\Ueditor;
trait FormTypeRegister{
private $_form_type = [];
protected function registerFormType(){
static $form_type = [];
if(empty($form_type)) {
$base_form_type = self::registerBaseFormType();
$form_type = array_merge($base_form_type, RegisterContainer::getFormItems());
}
$this->_form_type = $form_type;
}
protected function registerBaseFormType(){
return [
'address' => Address::class,
'array' => Arr::class,
'ueditor' => Ueditor::class,
'board' => Board::class,
'checkbox' => Checkbox::class,
'city' => City::class,
'citys' => Citys::class,
'date' => Date::class,
'datetime' => Datetime::class,
'district' => District::class,
'districts' => Districts::class,
'editormd' => Editormd::class,
'file' => File::class,
'files' => Files::class,
'hidden' => Hidden::class,
'icon' => Icon::class,
'key' => Key::class,
'num' => Num::class,
'password' => Password::class,
'picture' => Picture::class,
'picture_intercept' => PictureIntercept::class,
'pictures' => Pictures::class,
'pictures_intercept' => PicturesIntercept::class,
'province' => Province::class,
'radio' => Radio::class,
'select' => Select::class,
'select2' => Select2::class,
'select_other' => SelectOther::class,
'self' => Self_::class,
'static' => Static_::class,
'tags' => Tags::class,
'text' => Text::class,
'textarea' => Textarea::class
];
}
}<file_sep>/src/Library/Behavior/InitAuthChainBehavior.class.php
<?php
namespace Behavior;
class InitAuthChainBehavior
{
public function run(&$_data){
\Qscmf\Core\AuthChain::init();
}
}<file_sep>/src/Library/Qscmf/Builder/SubTableBuilder.class.php
<?php
namespace Qscmf\Builder;
use Org\Util\StringHelper;
use Qscmf\Builder\ButtonType\Save\Save;
use Think\View;
class SubTableBuilder implements \Qscmf\Builder\GenColumn\IGenColumn {
use \Qscmf\Builder\GenColumn\TGenColumn;
private $_table_header = [];
private $_items = [];
private $_template;
private $_unique_id;
private $_data = [];
private $_hide_btn;
private $_set_add_btn;
private $_col_readonly = false;
private $_table_column_list = array(); // 表格标题字段
private $_new_row_position;
const NEW_ROW_AT_FIRST = 'first';
const NEW_ROW_AT_LAST = 'last';
public function __construct($hide_btn=false){
$this->_template = __DIR__ . '/subTableBuilder.html';
$this->_unique_id = StringHelper::keyGen();
$this->_hide_btn=$hide_btn;
$this->_new_row_position = self::NEW_ROW_AT_LAST;
self::registerColumnType();
}
protected function unsetSaveMark(){
Save::$target_form = "";
}
public function addTableHeader($name, $width, $tip=''){
$header['name'] = $name;
$header['width'] = $width;
$header['tip'] = $tip;
$this->_table_header[] = $header;
return $this;
}
public function addFormItem($name, $type, $options = [],$readonly=false,$extra_class='',$extra_attr='',
$auth_node = '') {
$item['name'] = $name;
$item['type'] = $type;
$item['options'] = $options;
$item['readonly'] = $readonly;
$item['extra_class'] = $extra_class;
$item['extra_attr'] = $extra_attr;
$item['auth_node'] = $auth_node;
$this->_items[] = $item;
return $this;
}
public function setData($data, $has_col_options = true) {
if ($has_col_options === true){
$this->setDataWithColOptions($data);
}else{
$this->setFormData($data);
}
return $this;
}
protected function setDataWithColOptions($data){
$form_data = array_map(function ($item){
return array_column($item, 'value', 'name');
}, $data);
$this->_data = $form_data;
return $this;
}
public function setFormData($data) {
$this->_data = $data;
return $this;
}
public function setAddBtn($set_add_btn){
$this->_set_add_btn = $set_add_btn;
return $this;
}
public function makeHtml(){
self::combinedColumnOptions();
$this->unsetSaveMark();
$this->_table_column_list = $this->checkAuthNode($this->_table_column_list);
$this->genPerRowWithData($this->_data);
$view = new View();
$view->assign('table_header', $this->_table_header); // 表格的列
$view->assign('table_column_list', $this->_table_column_list); // 表格的列
$view->assign('table_id', $this->_unique_id);
$view->assign('data', $this->_data);
$view->assign('hide_btn', $this->_hide_btn);
$view->assign('set_add_btn', $this->_set_add_btn);
$view->assign('column_html', $this->buildRows($this->_data));
$view->assign('column_css_and_js_str', $this->getUniqueColumnCssAndJs());
$view->assign('new_row_pos', $this->_new_row_position);
return $view->fetch($this->_template);
}
protected function checkAuthNode($check_items){
return BuilderHelper::checkAuthNode($check_items);
}
private function combinedColumnOptions(){
foreach ($this->_items as $item){
$item['readonly'] = $this->_col_readonly ?:$item['readonly'];
$col_arr = [
'name' => $item['name'],
'title' => '',
'editable' => !$item['readonly'],
'type' => $item['type'],
'value' => $item['options'],
'tip' => null,
'th_extra_attr' => null,
'td_extra_attr' => null,
'auth_node' => $item['auth_node'],
'extra_class' => $item['extra_class'],
'extra_attr' => $item['extra_attr'],
];
extract($col_arr);
$column = self::genOneColumnOpt($name,$title,$type,$value,$editable,$tip,$th_extra_attr,$td_extra_attr,
$auth_node,$extra_attr,$extra_class);
$this->_table_column_list[] = $column;
}
}
protected function initData($column_options){
return [array_map(function($name) use(&$new_data){
return '';
}, array_column($column_options, 'name', 'name'))];
}
protected function genPerRowWithData(&$column_data = [], $column_options = []){
$column_options = $column_options?:$this->_table_column_list;
$column_data = !empty($column_data) ? $column_data : self::initData($column_options);
foreach ($column_data as &$data){
foreach ($column_options as $k => &$column) {
$this->buildOneColumnItem($column, $data);
}
}
}
public function genNewRowHtml($options = []){
$this->genPerRowWithData($column_data, $options);
$html = $this->buildOneRow($column_data[0], $options);
return $html;
}
protected function buildOneRow($item_data, $options = []){
$html = '<tr class="data-row">';
foreach ($options as $k => $column){
$html .= "<td {$column['td_extra_attr']} class='sub_item_{$column['type']}'>{$item_data[$column['name']]}</td>";
}
!$this->_hide_btn && $html .= "<td> <button type='button' class='btn btn-danger btn-sm' onclick="."$(this).parents('tr').remove();".">删除</button> </td>";
$html .= '</tr>';
return $html;
}
protected function buildRows($column_data, $options = []){
$options = $options ?: $this->_table_column_list;
$html = '';
foreach($column_data as $item_data){
$html .= $this->buildOneRow($item_data, $options);
}
if($this->_hide_btn){
return $html;
}
if($this->_new_row_position === self::NEW_ROW_AT_LAST){
$html = $html . $this->addButtonHtml();
}
if($this->_new_row_position === self::NEW_ROW_AT_FIRST){
$html = $this->addButtonHtml() . $html;
}
return $html;
}
protected function addButtonHtml() : string{
$header_count = count($this->_table_header) + 1;
$btn_text = $this->_set_add_btn ?: '添加新字段';
$html = <<<html
<tr id="{$this->_unique_id}_add-panel">
<td colspan="{$header_count}" class="text-center">
<span class="pull-left tip text-danger"></span>
<button type="button" class="btn btn-sm btn-default " id="{$this->_unique_id}_addField">{$btn_text}</button>
</td>
</tr>
html;
return $html;
}
public function setColReadOnly($col_readonly){
$this->_col_readonly = $col_readonly;
return $this;
}
public function setNewRowPos(string $position){
$this->_new_row_position = $position;
return $this;
}
}<file_sep>/src/Library/Qscmf/Builder/FormType/TUploadConfig.class.php
<?php
namespace Qscmf\Builder\FormType;
trait TUploadConfig
{
protected function genUploadConfigCls($form_extra, $def_type){
$type = $this->getType($form_extra, $def_type);
return new UploadConfig($type);
}
protected function getType($form_extra, $def_type){
if (!$form_extra){
return $def_type;
}
$regex = '/(data-url)(\s*=\s*[\"|\'])(\S*)([\"|\'])/';
$r = preg_match($regex, $form_extra, $matches);
if (!$r){
return $def_type;
}
$url = $matches[3];
$method = $this->getMethod($url);
if(strtolower(substr($method,0,6))=='upload') {
$type = strtolower(substr($method, 6));
}
return $type ?? $def_type;
}
protected function getMethod($url){
$url = urldecode($url);
isUrl($url) && $url = str_replace(HTTP_PROTOCOL."://".SITE_URL,'',$url);
$sub_root = str_replace('-', '\-',trim(__ROOT__, '/'));
$pattern[0] = "/^(\/$sub_root\/)/";
$pattern[1] = "/^\s+|\s+$/";
$pattern[2] = "/^\//";
$url = preg_replace($pattern, '', $url);
$spe_index = strpos($url, '?');
if ($spe_index !== false){
$url_arr = parse_url($url);
$path = $url_arr['path'];
}else{
$path = $url;
}
$ext_index = strpos($path, '.');
$ext_index !== false && $path = substr($path, 0, strpos($path, '.'));
$path_arr = explode("/", $path);
return $path_arr[2];
}
}
|
8bbae4bd0e1992e1e16252290c1209ff82056eee
|
[
"JavaScript",
"Markdown",
"PHP"
] | 144 |
PHP
|
tiderjian/think-core
|
05c8e96825f1996b4336319ff96a7f819f472272
|
11b6cb7a257423d5ac22474c6a5d4857644726bd
|
refs/heads/main
|
<file_sep>const express = require('express')
// const cors = require('cors')
const db = require('./db')
const routes = require('./routes')
const { PORT } = require('./config')
db()
const app = express()
app.use(express.json())
app.use(routes)
app.listen(PORT, function () {
console.log(this.address().port)
})
<file_sep>const router = require('express').Router()
const farmer = require('./farmer')
router.use('/farmer', farmer)
// export module
module.exports = router
<file_sep>const { Farmer } = require('../../models')
const validator = require('./validator')
const postFarmer = async ({ body }, res, next) => {
try {
const [invalid, validFarmer] = validator(body)
if (invalid) {
res.status(200).json({
invalid
})
}
const newFarmer = new Farmer(validFarmer)
const savedFarmer = await newFarmer.save()
res.status(200).json({
success: true,
savedFarmer
})
} catch (e) {
next(e)
}
}
module.exports = { postFarmer }
<file_sep>const { Schema, model } = require('mongoose')
const Harvest = new Schema({
quantity: {
type: Number,
min: 0,
max: 999999999,
required: true
},
quantityUnit: {
type: String,
trim: true,
minlength: 1,
maxlength: 255,
required: true
},
price: {
type: Number,
min: 0,
max: 999999999,
required: true
},
date: {
type: Date,
required: true
}
}, { _id: false })
const FarmerSchema = new Schema({
name: {
type: String,
trim: true,
minlength: 3,
maxlength: 255,
required: true
},
harvestType: {
type: String,
trim: true,
minlength: 3,
maxlength: 255,
required: true
},
coordinates: {
type: [Number, Number],
maxlength: 2,
required: true
},
area: {
type: Number,
min: 0,
max: 999999999,
required: true
},
currentHarvest: {
type: Harvest
},
nextHarvest: {
type: Harvest
}
}, {
timestamps: {
createdAt: 'created',
updatedAt: 'updated'
}
})
module.exports = model('Farmer', FarmerSchema)
<file_sep>module.exports = {
PORT: 8080,
MONGODB_URL: process.env.MONGODB_URL || 'mongodb://localhost:27017/manggislombok',
MONGODB_OPT: {
useNewUrlParser: true,
useUnifiedTopology: true
},
HARVEST_TYPE: ['KANGKUNG', 'MANGGIS'],
HARVEST_UNIT: ['ikat', 'kg']
}
|
2d7fbac8102a6dc1b7bd21e5c15d61be743866d7
|
[
"JavaScript"
] | 5 |
JavaScript
|
manggislombok/backend
|
8849807f6e41ea4a6026bc23affca8ed43772e32
|
361033099ab03219fee7f553970bb90ae413121d
|
refs/heads/master
|
<file_sep>//
// Created by ductn on 14/06/2016.
//
#ifndef PROFILESERVICE_MEMCACHED_H
#define PROFILESERVICE_MEMCACHED_H
#include "Cache.h"
#include "MemcachedModel.h"
namespace profileservice {
class Memcached : public Cache {
private:
Memcached();
MemcachedModel *memcachedModel;
public:
static Memcached *getInstance();
GetResult getData(std::string key);
bool setData(std::string key, std::string value);
bool removeData(std::string key);
};
}
#endif //THRIFTSERVICECPP_MEMCACHED_H
<file_sep>/*
* 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.
*/
/*
* File: DatabaseModel.cpp
* Author: ductn
*
* Created on June 17, 2016, 10:34 AM
*/
#include "DatabaseModel.h"
DatabaseModel::DatabaseModel() : socket(new TSocket("127.0.0.1", 9091)),
transport(new TFramedTransport(socket)), protocol(new TBinaryProtocol(transport)),
client(protocol) {
transport->open();
}
DatabaseModel* DatabaseModel::getInstance() {
static std::mutex mutex;
static DatabaseModel* instance = NULL;
if (instance == NULL) {
std::lock_guard<std::mutex> guard(mutex);
if (instance == NULL) {
instance = new DatabaseModel();
}
}
return instance;
}
GetResult DatabaseModel::getData(std::string key) {
databaseservice::GetResult result;
client.getData(result, key);
GetResult _return;
_return.__set_isNull(result.isNull);
if (!result.isNull) {
_return.__set_value(result.value);
}
return _return;
}
bool DatabaseModel::setData(std::string key, std::string value) {
return client.setData(key, value);
}
bool DatabaseModel::removeData(std::string key) {
return client.removeData(key);
}<file_sep>//
// Created by ductn on 14/06/2016.
//
#include "Buffer.h"
#include "HashMap.h"
using namespace profileservice;
Buffer *Buffer::getBuffer(std::string bufferType) {
if (bufferType == "HashMap") {
return HashMap::getInstance();
} else {
return NULL;
}
}
<file_sep>/*
* 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.
*/
/*
* File: FriendsListServiceHandler.h
* Author: ductn
*
* Created on July 11, 2016, 10:57 AM
*/
#ifndef FRIENDSLISTSERVICEHANDLER_H
#define FRIENDSLISTSERVICEHANDLER_H
#include "FriendsListService.h"
namespace friendslistservice {
class FriendsListServiceHandler : virtual public FriendsListServiceIf {
public:
FriendsListServiceHandler();
void getFriendsList(std::vector<std::string> & _return, const std::string& ID) override;
bool setFriend(const std::string& ID1, const std::string& ID2) override;
bool removeFriend(const std::string& ID1, const std::string& ID2) override;
};
}
#endif /* FRIENDSLISTSERVICEHANDLER_H */
<file_sep>//
// Created by ductn on 14/06/2016.
//
#ifndef PROFILESERVICE_CACHE_H
#define PROFILESERVICE_CACHE_H
#include <string>
namespace profileservice {
class Cache {
public:
virtual std::vector<std::string> getFriendsList(std::string ID) = 0;
virtual bool setFriend(std::string ID1, std::string ID2) = 0;
virtual bool removeFriend(std::string ID1, std::string ID2) = 0;
static Cache *getCache(std::string cacheType);
};
}
#endif //CACHE_H
<file_sep>//
// Created by ductn on 14/06/2016.
//
#include "HashMap.h"
using namespace profileservice;
HashMap::HashMap() {
hashMapModel = HashMapModel::getInstance();
}
HashMap* HashMap::getInstance() {
static HashMap instance;
return &instance;
}
GetResult HashMap::getData(std::string key) {
return hashMapModel->getData(key);
}
bool HashMap::setData(std::string key, std::string value) {
return hashMapModel->setData(key, value);
}
bool HashMap::removeData(std::string key) {
return hashMapModel->removeData(key);
}
<file_sep>#
# Generated - do not edit!
#
# NOCDDL
#
CND_BASEDIR=`pwd`
CND_BUILDDIR=build
CND_DISTDIR=dist
# Debug configuration
CND_PLATFORM_Debug=GNU-Linux
CND_ARTIFACT_DIR_Debug=dist/Debug/GNU-Linux
CND_ARTIFACT_NAME_Debug=friendslistservice
CND_ARTIFACT_PATH_Debug=dist/Debug/GNU-Linux/friendslistservice
CND_PACKAGE_DIR_Debug=dist/Debug/GNU-Linux/package
CND_PACKAGE_NAME_Debug=friendslistservice.tar
CND_PACKAGE_PATH_Debug=dist/Debug/GNU-Linux/package/friendslistservice.tar
# Release configuration
CND_PLATFORM_Release=GNU-Linux
CND_ARTIFACT_DIR_Release=dist/Release/GNU-Linux
CND_ARTIFACT_NAME_Release=friendslistservice
CND_ARTIFACT_PATH_Release=dist/Release/GNU-Linux/friendslistservice
CND_PACKAGE_DIR_Release=dist/Release/GNU-Linux/package
CND_PACKAGE_NAME_Release=friendslistservice.tar
CND_PACKAGE_PATH_Release=dist/Release/GNU-Linux/package/friendslistservice.tar
#
# include compiler specific variables
#
# dmake command
ROOT:sh = test -f nbproject/private/Makefile-variables.mk || \
(mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk)
#
# gmake command
.PHONY: $(shell test -f nbproject/private/Makefile-variables.mk || (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk))
#
include nbproject/private/Makefile-variables.mk
<file_sep>//
// Created by ductn on 14/06/2016.
//
#include "HashMapModel.h"
using namespace profileservice;
HashMapModel::HashMapModel() {
// hashMap = new std::unordered_map<std::string, std::string>();
}
HashMapModel *HashMapModel::getInstance() {
static HashMapModel instance;
return &instance;
}
std::unordered_map<std::string, std::string>* HashMapModel::getUnorderMap() {
return &(HashMapModel::getInstance()->hashMap);
}
GetResult HashMapModel::getData(std::string key) {
GetResult return_;
std::lock_guard<std::mutex> guard(mutex);
auto search = hashMap.find(key);
if (search != hashMap.end()) {
return_.__set_isNull(false);
return_.__set_value(search->second);
} else {
return_.isNull = true;
}
return return_;
}
bool HashMapModel::setData(std::string key, std::string value) {
std::lock_guard<std::mutex> guard(mutex);
hashMap[key] = value;
return true;
}
bool HashMapModel::removeData(std::string key) {
std::lock_guard<std::mutex> guard(mutex);
hashMap.erase(key);
return true;
}
<file_sep>//
// Created by ductn on 14/06/2016.
//
#include "Memcached.h"
using namespace profileservice;
Memcached::Memcached() {
memcachedModel = MemcachedModel::getInstance();
}
Memcached *Memcached::getInstance() {
static Memcached instance;
return &instance;
}
GetResult Memcached::getData(std::string key) {
return memcachedModel->getData(key);
}
bool Memcached::setData(std::string key, std::string value) {
return memcachedModel->setData(key, value);
}
bool Memcached::removeData(std::string key) {
return memcachedModel->removeData(key);
}
<file_sep>//
// Created by ductn on 14/06/2016.
//
#include "Cache.h"
#include "Memcached.h"
using namespace profileservice;
Cache *Cache::getCache(std::string cacheType) {
if (cacheType == "Memcached") {
return Memcached::getInstance();
} else {
return nullptr;
}
}
<file_sep>//
// Created by ductn on 14/06/2016.
//
#include "Database.h"
using namespace profileservice;
Database::Database() : dbModel(DatabaseModel::getInstance()) {
}
Database* Database::getInstance() {
static std::mutex mutex;
static Database* instance = NULL;
if (instance == NULL) {
std::lock_guard<std::mutex> guard(mutex);
if (instance == NULL) {
instance = new Database();
}
}
return instance;
}
GetResult Database::getData(std::string key) {
return dbModel->getData(key);
}
bool Database::setData(std::string key, std::string value) {
return dbModel->setData(key, value);
}
bool Database::removeData(std::string key) {
return dbModel->removeData(key);
}
<file_sep>//
// Created by ductn on 14/06/2016.
//
#ifndef PROFILESERVICE_BUFFER_H
#define PROFILESERVICE_BUFFER_H
#include <string>
namespace profileservice {
class Buffer {
public:
virtual std::vector<std::string> getFriendsList(std::string ID) = 0;
virtual bool setFriend(std::string ID1, std::string ID2) = 0;
virtual bool removeFriend(std::string ID1, std::string ID2) = 0;
static Buffer *getBuffer(std::string bufferType);
};
}
#endif //THRIFTSERVICECPP_BUFFER_H
<file_sep>/*
* 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.
*/
/*
* File: MemcachedModel.h
* Author: ductn
*
* Created on June 9, 2016, 4:06 PM
*/
#ifndef PROFILESERVICE_CACHEMODEL_H
#define PROFILESERVICE_CACHEMODEL_H
#include <libmemcached/memcached.hpp>
#include <mutex>
namespace profileservice {
class MemcachedModel {
private:
memcache::Memcache mc;
std::mutex mtx;
MemcachedModel();
public:
static MemcachedModel *getInstance();
GetResult getData(std::string key);
bool setData(std::string key, std::string value0);
bool removeData(std::string key);
};
}
#endif /* MEMCACHEDMODEL_H */
<file_sep>/*
* 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.
*/
/*
* File: MemcachedHandler.cpp
* Author: ductn
*
* Created on June 7, 2016, 2:16 PM
*/
#include "MemcachedModel.h"
#include <iostream>
#include <vector>
using namespace profileservice;
MemcachedModel::MemcachedModel() {
mc = memcache::Memcache("localhost", 11211);
mc.flush();
}
MemcachedModel *MemcachedModel::getInstance() {
static MemcachedModel instance;
return &instance;
}
GetResult MemcachedModel::getData(std::string key) {
std::vector<char> result;
GetResult return_;
std::lock_guard<std::mutex> guard(mtx);
bool success = mc.get(key, result);
if (success) {
return_.__set_isNull(false);
return_.__set_value(std::string(result.data()));
} else {
return_.__set_isNull(true);
}
return return_;
}
bool MemcachedModel::setData(std::string key, std::string value) {
std::lock_guard<std::mutex> guard(mtx);
bool success = mc.set(key, std::vector<char>(value.begin(), value.end()), 0, 0);
return success;
}
bool MemcachedModel::removeData(std::string key) {
std::lock_guard<std::mutex> guard(mtx);
bool success = mc.remove(key);
return success;
}
<file_sep>//
// Created by ductn on 14/06/2016.
//
#ifndef PROFILESERVICE_HASHMAP_H
#define PROFILESERVICE_HASHMAP_H
#include "Buffer.h"
#include "HashMapModel.h"
namespace profileservice {
class HashMap : public Buffer {
private:
HashMapModel *hashMapModel;
HashMap();
public:
static HashMap *getInstance();
std::vector<std::string> getFriendsList(std::string ID) = 0;
bool setFriend(std::string ID1, std::string ID2) = 0;
bool removeFriend(std::string ID1, std::string ID2) = 0;
};
}
#endif //THRIFTSERVICECPP_HASHMAP_H<file_sep>/*
* 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.
*/
/*
* File: DatabaseModel.h
* Author: ductn
*
* Created on June 17, 2016, 10:34 AM
*/
#ifndef PROFILESERVICE_DATABASEMODEL_H
#define PROFILESERVICE_DATABASEMODEL_H
#include "DatabaseService.h"
#include <thrift/transport/TSocket.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/TFDTransport.h>
#include <mutex>
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace profileservice;
namespace profileservice {
class DatabaseModel {
public:
static DatabaseModel* getInstance();
std::vector<std::string> getFriendsList(std::string ID) = 0;
bool setFriend(std::string ID1, std::string ID2) = 0;
bool removeFriend(std::string ID1, std::string ID2) = 0;
private:
boost::shared_ptr<TSocket> socket;
boost::shared_ptr<TTransport> transport;
boost::shared_ptr<TProtocol> protocol;
databaseservice::DatabaseServiceClient client;
DatabaseModel();
};
}
#endif /* DATABASEMODEL_H */
<file_sep>//
// Created by ductn on 14/06/2016.
//
#ifndef PROFILESERVICE_DATABASE_H
#define PROFILESERVICE_DATABASE_H
#include <string>
#include "DatabaseModel.h"
#include <mutex>
namespace profileservice {
class Database {
public:
virtual std::vector<std::string> getFriendsList(std::string ID) = 0;
virtual bool setFriend(std::string ID1, std::string ID2) = 0;
virtual bool removeFriend(std::string ID1, std::string ID2) = 0;
static Database* getInstance();
private:
Database();
boost::shared_ptr<DatabaseModel> dbModel;
};
}
#endif //THRIFTSERVICECPP_DATABASE_H
<file_sep>//
// Created by ductn on 14/06/2016.
//
#ifndef PROFILESERVICE_HASHMAPMODEL_H
#define PROFILESERVICE_HASHMAPMODEL_H
#include <string>
#include <unordered_map>
#include <mutex>
namespace profileservice {
class HashMapModel {
private:
static HashMapModel *instance;
HashMapModel();
std::unordered_map<std::string, std::string> hashMap;
std::mutex mutex;
public:
static HashMapModel *getInstance();
static std::unordered_map<std::string, std::string>* getUnorderMap();
GetResult getData(std::string key);
bool setData(std::string key, std::string value);
bool removeData(std::string key);
};
}
#endif //THRIFTSERVICECPP_HASHMAPMODEL_H
<file_sep>/*
* 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.
*/
/*
* File: FriendsListServiceHandler.cpp
* Author: ductn
*
* Created on July 11, 2016, 10:57 AM
*/
#include "FriendsListServiceHandler.h"
using namespace friendslistservice;
FriendsListServiceHandler::FriendsListServiceHandler() {
}
void FriendsListServiceHandler::getFriendsList(std::vector<std::string>& _return, const std::string& ID) {
// using boost join algorithm: split
return;
}
bool FriendsListServiceHandler::setFriend(const std::string& ID1, const std::string& ID2) {
// TODO: implement
return true;
}
bool FriendsListServiceHandler::removeFriend(const std::string& ID1, const std::string& ID2) {
// TODO: implement
return true;
}
|
2e6407b1a9d17c9798f867a862b2a4e61704ed19
|
[
"Makefile",
"C++"
] | 19 |
C++
|
darkprince2702/FriendsListService
|
3edb0c97180b485946314def541ff2884b9cb520
|
43e4d7144eeb5fe792ab327654e26cd9e2c7a229
|
refs/heads/master
|
<repo_name>MaryBreenLyles/DailyCodingProblem<file_sep>/problem2_prodArray_not_i/answer.java
/*
-------------------------------------------------------
Question
-------------------------------------------------------
Good morning! Here's your coding interview problem for today.
This problem was asked by Uber.
Given an array of integers, return a new array such that each element at index i
of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be
[120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
Follow-up: what if you can't use division?.
-------------------------------------------------------
Algorithm Explanation
-------------------------------------------------------
The idea is to get the product of all the left side values,
the product of all the right side values,
and then multipuly them together
[1, 2, 3, 4]
[23,12,8,6] - Output
[1,1,2,6] - Product of Left Side Elts
[24, 12, 4, 1] - Product of Right Side Elts
[24,12,8,6] - Output
**TAKE AWAY**
It is super helpful to try to frame the problem in as many ways as you can.
*/
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
int right=1,left=1;
for(int i=0;i<n;i++){
res[i]=1;
}
for (int i=0;i<n;i++) {
res[i]*=left;
left*=nums[i];
}
for(int i=n-1;i>=0;i--) {
res[i]*=right;
right*=nums[i];
}
return res;
}
<file_sep>/problem2_prodArray_not_i/kurt_answer.py
#https://www.onlinegdb.com/online_python_compiler
'''
-------------------------------------------------------
Question
-------------------------------------------------------
Good morning! Here's your coding interview problem for today.
This problem was asked by Uber.
Given an array of integers, return a new array such that each element at index i
of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be
[120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
Follow-up: what if you can't use division?
-------------------------------------------------------
Algorithm Explanation
-------------------------------------------------------
Basic Idea: Get the product of the array. Then, iterate through and divide that product
by the current value to get the product of all elements except self. Place at index and continue.
'''
def problem2(ints):
intsProduct = 1
for num in ints:
intsProduct *= num
answer = []
for num in ints:
answer.append(int(intsProduct/num))
return answer
print(problem2([1,2,3,4,5]))
#Things I did wrong
# - I originally forgot to cast to an int, so the array came back as doubles. Java would help with this
# - Didnt account for 0s. Fixed this in the Java case.
<file_sep>/problem15_randomStreamElement_selection/mollie_kurt_answer.py
#https://www.onlinegdb.com/online_python_compiler
'''
-------------------------------------------------------
Question
-------------------------------------------------------
This problem was asked by Facebook.
Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability.
-------------------------------------------------------
Algorithm Explanation
-------------------------------------------------------
probEisWritten: [1/1, 1/2, 1/3, 1/4, 1/5]
E: [ a , b , c , d , e ]
answer = null; #start
answer = a #fist read from stream
answer = b #1/2 probability its b...b is chosen
answer = b #1/3 failed
answer = b #1/4 failed
answer = e #1/5 passed
answer is e
p(A is not overwritten, i.e. returns A) = 1/2 * 2/3 * 3/4 * 4/5 = 1/5
p(B is not overwritten) = 1/2 *2/3*3/4*4/5 = 1/5
^p(B even gets written in)
p(C is not overwritten) = 1/2*1/3 *3/4*4/5 = 1/5
^p(C even gets written in
.
.
.
Since the probability that each element is not overwritten (i.e. that it is saved as the return value) is 1/5 for every element. Therefore, a return element is picked with uniform probability.
-------------------------------------------------------
TAKE AWAYS
-------------------------------------------------------
Always frame and reframe the problem.
Think about more tangible framings (in this one we thought about rolling a dice for each element, but just add one to the dice for each element).
But also think about what is actually being done and whether there might be an alternative way to do it.
'''
import random
def pick(big_stream):
random_element = None
for i, e in enumerate(big_stream):
if i == 0:
random_element = e
elif random.randint(1, i + 1) == 1:
random_element = e
return random_element
<file_sep>/problem1_two_num_sum/Mollie_answer.java
public class MolliesAnswersIsValid{
public static void main(String []args){
int [] A = {30, 40, 13, 12, 50, 2, 13, 14, 22};
int k = 24;
if(isSumK(A, k) == true){
System.out.println("true");
}
else{
System.out.println("false");
}
}
static boolean isSumK(int [] A, int k) {
for(int i=0; i<A.length; i++) {
if( A[i] >= k ){
continue;
}
else{
for(int j=i+1; j<A.length; j++){
if( A[i]+A[j]==k ){
return true;
}
}
}
}
return false;
}
}
<file_sep>/problem5_first_class_func/Mollie_kurt_answer.py
#https://www.onlinegdb.com/online_python_compiler
def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(pair):
def first (val1, val2):
return val1
return pair(first)
def cdr(pair):
def second(val1, val2):
return val2
return pair(second)
print(car(cons(3, 4)))
print(cdr(cons(3, 4)))<file_sep>/README.md
DailyCodingProblem
Here we will keep our daily coding problems!!
<file_sep>/problem13_distinct_substring/mollie_kurt_answer.py
#https://www.onlinegdb.com/online_python_compiler
'''
-------------------------------------------------------
Question
-------------------------------------------------------
This problem was asked by Amazon.
Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb".
-------------------------------------------------------
Algorithm Explanation
-------------------------------------------------------
'''
def Problem13(S, K):
p1 = 0
p2 = 0
longest = 0
distinct = 0
letterMap = {}
count = 0
while p2 < len(S):
if S[p2] not in letterMap:
letterMap[S[p2]] = 1
distinct += 1
elif distinct <= K:
letterMap[S[p2]] += 1
if distinct > K:
longest = max(longest, count)
letterMap[S[p1]] -= 1
if letterMap[S[p1]] == 0:
distinct -= 1
letterMap.pop(S[p1])
p1 += 1
count -= 1
if distinct <= K:
p2 += 1
count += 1
else:
p2 += 1
count += 1
return max(longest, count)
S = "abcccbbbbdabcabcabcabc"
print(Problem13(S, 3))<file_sep>/problem10_job_schedule/mollie_kurt_answer.py
'''
This problem was asked by Apple.
Implement a job scheduler which takes in a function f and an integer n, and calls f after n seconds.
# Key Things Learned:
- Use the Thread class from threading to run code async
- The Thread class utilize the combination of Keyword arguments and default parameters, allowing us to only pass arguments we care about
- If we want to use every value in a list as arguments to a function, we can simply do: function(*list)
'''
import threading
import time
def waitAndExecute(f, seconds, argsToFunction):
time.sleep(seconds)
f(*argsToFunction)
def scheduleJob(f, seconds, args):
threading.Thread(target=waitAndExecute, args=(f,seconds, args)).start()
def say(msg):
print(msg)
scheduleJob(f=say, seconds=2, args=["Third"])
scheduleJob(f=say, seconds=1, args=["Second"])
scheduleJob(f=say, seconds=3, args=["Fourth"])
print("First!")
<file_sep>/problem8_count_UnivalTrees/kurt_answer.java
import java.util.Queue;
import java.util.LinkedList;
import java.lang.Math.*;
public class Problem8 {
public static class Node {
public int val;
public Node left;
public Node right;
public Node(int val, Node left, Node right){
this.val = val;
this.left = left;
this.right = right;
}
}
// Turns Tree into a string delimited with commas
public static int isUnival(Node node){
int countLeftUnival = 0;
int countRightUnival = 0;
if (node == null){
return 0;
}
countLeftUnival = isUnival(node.left);
countRightUnival = isUnival(node.right);
boolean lIsUnival = (countLeftUnival >= 0);
boolean rIsUnival = (countRightUnival >= 0);
int totalUniVals = Math.abs(countLeftUnival) + Math.abs(countRightUnival);
if (rIsUnival && lIsUnival && (node.right == null || node.right.val == node.val)
&& (node.left == null || node.left.val == node.val)){
return totalUniVals+1;
}
return totalUniVals;
}
// Build a little test guy
public static Node makeTestTree1(){
return new Node(0,
new Node(0,
new Node(0, null, null),
new Node(0, null,
new Node(1, null, null))
),
new Node(0, new Node(1, null, null), null)
);
}
// Build a little test guy
public static Node makeTestTree2(){
return new Node(0,
new Node(0,
new Node(0, null, null),
new Node(0, null,
new Node(0, null, null))
),
new Node(0, new Node(0, null, null), null)
);
}
public static void main(String args[]) {
System.out.println(isUnival(makeTestTree1()));
System.out.println(isUnival(makeTestTree2()));
}
}
<file_sep>/problem13_distinct_substring/answer.py
'''by Amazon.
Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb", so your function should return 3.'''
from collections import deque
s = 'abcccbbbbdabcabcabcabcabcccbbbbdabcabcabcabcabcccbbbbdabcabcabcabc'
k = 3
def longest_substring(s, k):
len_substring = 0
substring = deque()
i = 0
if k == 0:
return 0
else:
while i < len(s):
substring.append(s[i])
if len(set(substring)) == k:
if len(substring) > len_substring:
len_substring = len(substring)
elif len(set(substring)) > k:
substring.popleft()
i += 1
return len_substring
print longest_substring(s, k)
<file_sep>/problem2_prodArray_not_i/Mollie_answer.py
''' 1) DIVISION - O(2n): Won't work for Array values of zero
2) NO DIVISION - O(): Will work for Array vals of zero '''
''' REMEMBER INDENTATION '''
''' #### This shit still not workin ###
Error -
B[i] = B[i]*A[j]
IndexError: list index out of range
'''
''' 1) Can't take zero in A (DIVISION)'''
def prodNoti_NoZero(A):
prod = 1
B = [0] * len(A) #B is an array of zeros
for i in A:
prod = prod*A[i]
for i in A:
B[i] = (prod/A[i])
return B
''' 2) Can take zero in A (NO DIVISION) '''
def prodNoti_canZero(A):
B = [1] * len(A) #B is an array of ones
for i in A:
for j in A:
if j==i:
continue
else:
B[i] = B[i]*A[j]
return B
guyz = [3, 2, 1]
print(prodNoti_canZero(guyz))
<file_sep>/problem16_api/mollie_kurt_answer.py
'''
You run an e-commerce website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API:
record(order_id): adds the order_id to the log
get_last(i): gets the ith last element from the log. i is guaranteed to be smaller than or equal to N.
You should be as efficient with time and space as possible.
'''
# record order ids as they come in and then only store up to N, removing IDs
# that are too far in the past (greater than N ids ago)
#import array as arr
class Api:
# N has a default value, it does not need to be passed into constructor
def __init__(self, N=100):
self.N = N
self.index = -1
self.my_dict = [0]*N
def getCurrIndex(self, i):
return i % self.N # CIRCULARLY COUNTING INDEX
def record(self, order_id):
self.index += 1
self.my_dict[self.getCurrIndex(self.index)] = order_id
def get_last(self, last):
print(self.my_dict[self.getCurrIndex(self.index-last+1)])
my_api = Api(7)
my_api.record(12)
my_api.record(35)
my_api.record(40)
my_api.record(100)
my_api.record(13) #i=4
my_api.record(28)
my_api.record(42)
my_api.record(22)
my_api.record(12)
my_api.record(78)
print(my_api.my_dict)
# N=7
my_api.get_last(6)
<file_sep>/problem12_fib_steps/mollie_kurt_answer.py
#https://www.onlinegdb.com/online_python_compiler
'''
-------------------------------------------------------
Question
-------------------------------------------------------
This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time.
Given N, write a function that returns the number of unique ways you can climb the staircase.
The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number
from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5
steps at a time.
-------------------------------------------------------
Algorithm Explanation
-------------------------------------------------------
We realized that this was the Fib sequence + 1, so we wrote the Fib sequence, and made a
helper function to call the Fib(n + 1). This solved the first part of the problem.
For the follow up, we verified that modifying the fib function to return fib(n-a) + fin(n-b) + fib(n-c)...etc
(where a, b, and c are members of the "valid steps to climb" set) would yield the correct result.
So, we made a function that creates a custom fib function based on the set of numbers.
'''
def createFib(listOfValidSteps):
def customFib(n):
if n <= 0:
return 0
if n == 1:
return 1
sumFibs = 0
for validSteps in listOfValidSteps:
sumFibs += customFib(n - validSteps)
return sumFibs
return customFib
def numWays(n):
customFib = createFib([1,3,5])
return customFib(n+1)
print(numWays(30))<file_sep>/problem3_serialize_deserializeTrees/mollie_kurt_answer_revised.java
/*
-------------------------------------------------------
Question
-------------------------------------------------------
Given the root to a binary tree, implement serialize(root), which serializes the tree into a
string, and deserialize(s), which deserializes the string back into the tree.
-------------------------------------------------------
Algorithm Explanation
-------------------------------------------------------
Basic Idea: We walk the tree using recursion, and build a string representation. The string
uses 'null' to denote a leaf. Below is a picture of a tree and its equivalent representation.
1 1,
/ \ 2,
2 3 4,
/ \ / null,
4 5 7 null,
\ 5,
6 null,
6,
null,
null,
3,
7,
null,
null,
null
We can use a similar recursive approach to build the tree again
from the string.
-------------------------------------------------------
Revisions
-------------------------------------------------------
- Actually made seralize return an answer rather than using static
- Demonstrating method overloading by naming the two seralize and deserailze methods the same
- Utilized string builder to reduce complexity by O(answer.length) for each string append
- Changed the seralize base case to a leaf node, and the unit of work to seralize left seralize right.
*/
import java.util.Queue;
import java.util.LinkedList;
import java.lang.StringBuilder;
public class Problem3 {
//UTILITY METHODS////////////////////
//Basic Node Class
public static class Node {
public String val;
public Node left;
public Node right;
public Node(String val, Node left, Node right){
this.val = val;
this.left = left;
this.right = right;
}
}
//Builds a test tree with the Node Class
public static Node makeTestTree(){
return new Node("1",
new Node("2",
new Node("4", null, null),
new Node("5", null,
new Node("6", null, null))
),
new Node("3", new Node("7", null, null), null)
);
}
//Turn a string into a queue, splitting the string into elements based on the delimiter
public static Queue<String> stringToQueue(String str, char delimiter){
char[] charArray = str.toCharArray();
String curWord = "";
Queue<String> queueAns = new LinkedList<String>();
for (int i = 0; i < charArray.length; i++){
if (charArray[i] != delimiter){
curWord += charArray[i] ;
}else{
queueAns.add(curWord);
curWord = "";
}
}
return queueAns;
}
//MAIN METHODS////////////////////
public final static String emptyMarker = "null"; // in case we want to change later
// (final means constant)
//Setup for seralization; defines the answer variable and kicks off the recursion
public static String seralize(Node node){
StringBuilder answer = new StringBuilder("");
return seralize(node, answer).toString();
}
//Recursivley creates a string representing the passed in Tree
public static StringBuilder seralize(Node node, StringBuilder answer){
//If at leaf, add null
if (node == null){
answer.append(emptyMarker + ",");
return answer;
}
answer.append(node.val + ","); // Add current nodes value to the answer
answer = seralize(node.left, answer); // Seralize the left subtree
answer = seralize(node.right, answer); // Seralize the right subtree
//Climb back up the tree
return answer;
}
//Setup for deserialization; converts the string into a queue and kicks of the recursion
public static Node deserialize(String answer){
Queue<String> queueAns = stringToQueue(answer, ',');
return deserialize(queueAns);
}
//Recursivley creates a tree from a string representation
public static Node deserialize(Queue<String> queueAns){
String curr = queueAns.remove();
// if reach the "null" string, return/make the child null
if(curr.equals("null")){
return null;
}
// Otherwise, create a new node with the current value
// and recurse to create the left and right subtrees
else{
return new Node(curr, deserialize(queueAns), deserialize(queueAns));
}
}
public static void main(String args[]) {
//Node testTree = makeTestTree();
//seralize(testTree);
//System.out.println("Tree Seralized: " + answer);
//Node tree = deserialize(answer);
boolean thisWorks = deserialize(seralize(makeTestTree())).left.left.val.equals("4");
System.out.println(thisWorks);
}
}
<file_sep>/resources/FirstClassFunction_example.py
# If functions are first class then you can:
# - pass it into another function as a variable
# - return it from a function
# - modify it
# - assign it to a variable
def modList(f, listNums):
return f(listNums)
def reverse(listNums):
ansList = []
for i in range(len(listNums)-1, -1, -1): # from listNums.length-1 to 0 (not inclusive, hence -1), decrement -1
ansList.append(listNums[i])
return ansList
## return the reversed list
listNums = [1,2,2,4,5,6]
print(modList(reverse, listNums))
<file_sep>/problem1_two_num_sum/kurt_answer.py
#https://www.onlinegdb.com/online_python_compiler
'''
-------------------------------------------------------
Question
-------------------------------------------------------
This problem was recently asked by Google.
Given a list of numbers and a number k, return whether any two numbers from the
list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
-------------------------------------------------------
First Algorithm Explanation
-------------------------------------------------------
My idea is to sort the array, and close in on the answer with two pointers.
O(nlogn) + O(n/2)
However, this is not one pass.
'''
def sumOfAnyTwoEqualsK(nums, k):
#Sort the array and place pointers at each end
nums.sort()
p1 = 0
p2 = len(nums) - 1
#Move pointers inward based on if the current sum is too low or too high
while p1 != p2:
sum = nums[p1] + nums[p2]
if sum < k:
p1 += 1
elif sum > k:
p2 -= 1
else:
return str(nums[p1]) + " and " + str(nums[p2])
return "False"
array = [3,10,1,6,22,34,4,1,4]
print(sumOfAnyTwoEqualsK(array, 9))
<file_sep>/problem4_Find_lowest_missing_+/Mollie_Kurt_answer.java
/*
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words,
find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers
as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.
*/
public class Problem4 {
public static int findLowestPositiveMissingNumber(int[] A){
//Put all values into corresponding array index
for (int i = 0; i < A.length; i++){
//At each index, we contually swap the current value with the value in its corresponding index.
//We continue doing this as long as the current value is:
// - within the array length
// - greater than 0
// - and not already in place* (equal to the current index)
while(A[i] < A.length && A[i] > 0 && A[i] != i+1){
//*if value appears more than once and is already
// in place, ignore and mark 0 so its never swapped again (duplicate case)
if (A[i] == A[A[i]-1]){
A[i] = 0;
break;
}
//Put value into corresponding index by swapping.
int temp1 = A[i];
int temp2 = A[A[i]-1];
A[A[i]-1] = temp1;
A[i] = temp2;
//Continue the while loop on this index in case we swapped with another number we can
//put in its correct place.
}
}
//Climb sorted positive numbers until we find a hole and return its "ideal" value;
//meaning that number doesn't exist, otherwise it would be at its index.
for (int i = 0; i < A.length; i++){
if (A[i] != i+1){
return i+1;
}
}
//When all indexes are in place, return one plus the highest value
return A.length+1;
}
public static void main(String args[]) {
int[] nums = {1,2,3,4,5,6};
int answer = findLowestPositiveMissingNumber(nums);
}
}
<file_sep>/problem11_autocomplete/mollie_kurt_answer.py
'''
This problem was asked by Twitter.
Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix.
For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal].
Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries.
'''
# FIRST: preprocess the Dictionary
# - params: list of words
# - returns: hashmap*
# *(don't need to return sorted
# array b/c arrays are passed by reference & it just
# be operated on by the method with no need to return modified array)
def preProcess(words): #(return map)
words.sort() # alphabetize array
letterMap = {} # define a map
currLetter = ''
for i, word in enumerate(words):
if word[0] != currLetter:
letterMap[word[0]] = i # stores value of beginning index for each 1st letter
currLetter = word[0]
return letterMap
# Now find if words in letterMap contain prefix queryS
def autoComplete(queryS, words):
letterMap = preProcess(words)
sLength = len(queryS)
results = []
for i, word in enumerate(words):
if sLength < len(word) and word[:sLength]==queryS:
results.append(word)
return results
test = ["dog", "bat", "apple", "cat", "dank", "dock", "d"]
print(autoComplete("a", test))
|
e1c5a4bccfa5fbbf18e0c4a2bf6741fe58d30416
|
[
"Markdown",
"Java",
"Python"
] | 18 |
Java
|
MaryBreenLyles/DailyCodingProblem
|
8b6ea5ad65b2b68264be61a40757a7112d31a6c6
|
c81d1654acbdf2bfba16398d0d59b92d702236b2
|
refs/heads/master
|
<file_sep>
FROM dockerfile/elasticsearch:latest
RUN apt-get update && apt-get install -y \
python-virtualenv \
python-pip
WORKDIR /search
RUN virtualenv .venv && \
.venv/bin/pip install elasticsearch==0.4.3
ADD elasticsearch.yml /elasticsearch/config/elasticsearch.yml
RUN /elasticsearch/bin/plugin -install \
elasticsearch/elasticsearch-analysis-icu/2.3.0 && \
/elasticsearch/bin/plugin -install mobz/elasticsearch-head
ADD . /search
# TODO: sleep could be replaced with more of a polling wait for startup
RUN /elasticsearch/bin/elasticsearch & \
sleep 8 && \
curl -s localhost:9200/_nodes/_all/plugins | python -m json.tool && \
.venv/bin/python create_index.py
<file_sep>
#
# main application
#
webapp:
image: readthedocs/webapp
environment:
DJANGO_SETTINGS_MODULE: 'webapp_settings'
volumes_from:
- configs
volumes:
- './user_builds:/rtd/user_builds'
ports:
- 8080:8000
links:
- database
- redis
- search
#
# data volume container with a dev version of django settings
#
configs:
image: readthedocs/configs
#
# database for the webapp
#
database:
image: readthedocs/database
#
# task queue broker, and cache
#
redis:
image: redis:latest
#
# search index for documentation and projects
#
search:
image: readthedocs/search
ports:
- 8081:9200
#
# task workers for building documentation
#
builder:
image: readthedocs/builder
environment:
DJANGO_SETTINGS_MODULE: 'webapp_settings'
volumes_from:
- configs
volumes:
- './user_builds:/rtd/user_builds'
links:
- redis
- webapp
- database # see github.com/rtfd/readthedocs.org/issues/987
<file_sep>
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'docs',
'USER': 'docs',
'PASSWORD': '<PASSWORD>',
'HOST': 'localhost',
'PORT': '5432',
}
}
LOG_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s"
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': LOG_FORMAT,
'datefmt': "%d/%b/%Y %H:%M:%S"
},
},
'handlers': {
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'': {
'handlers': ['console'],
'level': 'INFO',
},
}
}
<file_sep>#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.sqlite")
sys.path.append('readthedocs')
from django.contrib.auth.models import User
User.objects.create_superuser('admin', '<EMAIL>', '<PASSWORD>')
<file_sep>import logging
from indexes import (
Index,
PageIndex,
ProjectIndex,
SectionIndex,
)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
# Create the index.
index = Index()
index_name = index.timestamped_index()
index.create_index(index_name)
index.update_aliases(index_name)
# Update mapping
proj = ProjectIndex()
proj.put_mapping()
page = PageIndex()
page.put_mapping()
sec = SectionIndex()
sec.put_mapping()
<file_sep>
from pyquery import PyQuery as pq
import requests
@when(u'I view {url}')
def step_impl(context, url):
context.response = requests.get(context.base_url + url)
@then(u'I should see a list of projects')
def step_impl(context):
assert context.response.status_code == 200
page = pq(context.response.text)
projects = page("li.module-item")
assert len(projects) == 14
<file_sep>#
# readthedocs.org - webapp
#
FROM readthedocs/base
# TODO: use gunicorn
EXPOSE 8000
CMD ../venv/bin/python ./manage.py runserver 0.0.0.0:8000
<file_sep>#
# readthedocs.org - base image
#
FROM ubuntu:14.10
MAINTAINER <EMAIL>
RUN apt-get update && apt-get install -y \
python-dev \
python-pip \
python-virtualenv \
git \
build-essential \
libxml2-dev \
libxslt1-dev \
zlib1g-dev \
libpq-dev
ADD deploy_requirements.txt /rtd/deploy_requirements.txt
ADD pip_requirements.txt /rtd/pip_requirements.txt
ADD deploy /rtd/deploy
WORKDIR /rtd
RUN virtualenv venv && venv/bin/pip install \
-r deploy_requirements.txt \
--find-links /rtd/deploy/wheels
ADD . /rtd
RUN mkdir /rtd/user_builds
RUN mkdir /rtd/readthedocs/webapp_settings/
ENV PYTHONPATH /rtd/
WORKDIR /rtd/readthedocs
<file_sep>#
# readthedocs.org - documentation builder image
#
FROM readthedocs/base
# For some reason the task running runs virtualenv-2.7
RUN ln -s /usr/bin/virtualenv /usr/bin/virtualenv-2.7
# Dependencies for building documentation
RUN apt-get update && apt-get install -y \
texlive-latex-base \
texlive-latex-extra \
texlive-latex-recommended \
texlive-fonts-recommended
CMD ../venv/bin/python manage.py celery worker -l INFO
<file_sep>
# Elasticsearch settings.
ES_HOSTS = ['localhost:9200']
ES_DEFAULT_NUM_REPLICAS = 1
ES_DEFAULT_NUM_SHARDS = 1
<file_sep>#
# readthedocs.org - configs image
#
FROM busybox:latest
ADD . /rtd/readthedocs/webapp_settings/
VOLUME /rtd/readthedocs/webapp_settings/
CMD echo
<file_sep>
def before_all(context):
context.base_url = 'http://localhost:8080'
<file_sep>#
# readthedocs.org - database image
#
FROM readthedocs/base
RUN apt-get update && apt-get install -y \
postgresql-9.4 \
postgresql-contrib-9.4
ADD local_settings.py /rtd/readthedocs/local_settings.py
ADD create_superuser.py /rtd/readthedocs/create_superuser.py
USER postgres
# See https://github.com/rtfd/readthedocs.org/issues/773
# for the reason behind `migrate projects 0001` line
RUN /etc/init.d/postgresql start && \
psql --command "CREATE USER docs WITH SUPERUSER PASSWORD '<PASSWORD>';" && \
createdb docs && \
../venv/bin/python ./manage.py syncdb --noinput && \
../venv/bin/python ./manage.py migrate projects 0001 && \
../venv/bin/python ./manage.py migrate && \
../venv/bin/python ./create_superuser.py && \
../venv/bin/python ./manage.py loaddata test_data && \
/etc/init.d/postgresql stop
ADD etc/pg_hba.conf /etc/postgresql/9.4/main/pg_hba.conf
RUN echo "listen_addresses='*'" >> /etc/postgresql/9.4/main/postgresql.conf
# Add VOLUMEs to allow backup of config, logs and databases
VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
EXPOSE 5432
CMD ["/usr/lib/postgresql/9.4/bin/postgres", "-D", "/var/lib/postgresql/9.4/main", "-c", "config_file=/etc/postgresql/9.4/main/postgresql.conf"]
<file_sep>from readthedocs.settings.base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'docs',
'USER': 'docs',
'PASSWORD': '<PASSWORD>',
'HOST': 'database_1',
'PORT': '5432',
}
}
LOG_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s"
LOGGING['loggers'] = {
'': {
'handlers': ['console'],
'level': 'DEBUG',
},
}
DEBUG = True
TEMPLATE_DEBUG = False
CELERY_ALWAYS_EAGER = False
SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_HTTPONLY = False
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': 'redis_1:6379',
'PREFIX': 'docs',
'OPTIONS': {
'DB': 1,
'PARSER_CLASS': 'redis.connection.HiredisParser'
},
},
}
REDIS = {
'host': 'redis_1',
'port': 6379,
'db': 0,
}
BROKER_URL = 'redis://redis_1:6379/0'
CELERY_RESULT_BACKEND = 'redis://redis_1:6379/0'
# Elasticsearch settings.
ES_HOSTS = ['search_1:9200']
SLUMBER_USERNAME = 'test'
SLUMBER_PASSWORD = '<PASSWORD>'
SLUMBER_API_HOST = 'http://webapp:8000'
WEBSOCKET_HOST = 'localhost:8088'
PRODUCTION_DOMAIN = 'localhost:8080'
USE_SUBDOMAIN = False
NGINX_X_ACCEL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
# Lock builds for 10 minutes
REPO_LOCK_SECONDS = 300
# Don't re-confirm existing accounts
ACCOUNT_EMAIL_VERIFICATION = 'none'
# For testing locally.
CORS_ORIGIN_WHITELIST = (
'localhost:8080',
'webapp_1:8000',
)
|
bd4284ceaff40aef634f71c7da8c0e78a27aa0fc
|
[
"Python",
"Dockerfile",
"YAML"
] | 14 |
Dockerfile
|
tescalada/readthedocs.org
|
f2531c25e59b5c79d87e71ef998c04a16937c76c
|
9ef16ab882d8fd912c523030b7ef5fada73c75f8
|
refs/heads/master
|
<file_sep><?php
//CREATE CONNECTION
$conn = mysqli_connect('localhost', 'root', 'alainquanta', 'phpblog');
//Check Connection
if(mysql_connect_errno()){
//Connection Failed
echo 'Failed to connect to Mysql' . mysql_connect_errno();
}
?><file_sep><?php
$user = ['name' => 'Alain', 'email' => '<EMAIL>', 'age'=> 20];
//accept array of objects to save it to cookie
$user = serialize($user);
setcookie('user', $user, time() + 3600);
$user = unserialize($_COOKIE['user']);
echo $user['name'] . $user['email']
?><file_sep>
<?php
//VALIDATION SANITATION
//Check for posted data
if(filter_has_var(INPUT_POST, 'data')){
// echo 'Data Found';
}else{
// echo 'No Data';
}
//email validation
if(filter_has_var(INPUT_POST, 'data')){
$email = $_POST['data'];
//Remove illegal characters
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// echo $email. '<br>';
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
// echo 'Email is Valid';
}else{
// echo 'Email is not valid';
}
// if(filter_input(INPUT_POST, 'data', FILTER_VALIDATE_EMAIL)){
// echo 'Email is Valid';
// }else{
// echo 'Email is not valid';
// }
}
//validate is to check
#FILTER VALIDATE BOOLEAN
#FILTER VALIDATE EMAIL
#FILTER VALIDATE FLOAT
#FILTER VALIDATE INT
#FILTER VALIDATE IP
#FILTER VALIDATE REGEXP
#FILTER VALIDATE URL
//sanitize is to remove
#FILTER SANITIZE EMAIL
#FILTER SANITIZE ENCODED
#FILTER SANITIZE NUMBER FLOAT
#FILTER SANITIZE NUMBER INT
#FILTER SANITIZE SPECIAL CHARS
#FILTER SANITIZE STRING
#FILTER SANITIZE URL
//validate int
$var = 23;
if(filter_var($var, FILTER_VALIDATE_INT)){
// echo $var . 'is a number';
}else{
// echo $var . 'is not a number';
}
//sanitize int
$var2 = 'asd23reffgf342';
// var_dump(filter_var($var2, FILTER_SANITIZE_NUMBER_INT));
//filter array
$filters = array(
"data" => FILTER_VALIDATE_EMAIL,
"data2" => array(
"filter" => FILTER_VALIDATE_INT,
"options" => array(
"min_range" => 1,
"max_range" => 100
)
)
);
// print_r(filter_input_array(INPUT_POST, $filters))
$arr = array(
"name" => '<NAME>',
"age" => '20',
"email" => "<EMAIL>"
);
$filter2 = array(
"name" => array(
"filter" => FILTER_CALLBACK,
"options" => "ucwords"
),
"age" => array(
"filter" => FILTER_VALIDATE_INT,
"options" => array(
"min" => 1,
"max" => 50
)
),
"email" => FILTER_VALIDATE_EMAIL
);
print_r(filter_var_array($arr, $filter2))
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="data">
<input type="text" name="data2">
<button type="submit"> Submit </button>
</form><file_sep><?php
$people[] = 'Alain';
$people[] = 'Braum';
$people[] = 'Cass';
$people[] = 'Deidara';
$people[] = 'Elementor';
$people[] = 'Fakuna';
$people[] = 'Growlithe';
$people[] = 'Hello';
$people[] = 'Igloo';
$people[] = 'Jump';
$people[] = 'Kali';
$people[] = 'Libra';
$people[] = 'Mango';
$people[] = 'Nice';
$people[] = 'Ophra';
$people[] = 'Peso';
$people[] = 'Quadra';
$people[] = 'Rector';
$people[] = 'Sauna';
$people[] = 'Talon';
$people[] = 'Ursula';
$people[] = 'Victor';
$people[] = 'Winner';
$people[] = 'Xyra';
$people[] = 'Yen';
//Get Query String
$q = $_REQUEST['q'];
$suggestion = '';
//Get Suggestions
if($q !== ""){
$q = strtoupper($q);
$len = strlen($q);
foreach($people as $person){
if(stristr($q, substr($person, 0, $len))){
if($suggestion === ''){
$suggestion = $person;
}else {
$suggestion .= ", $person";
}
}
}
}
echo $suggestion === "" ? "No Suggestion" : $suggestion;
?><file_sep><?php
class Person{
private $name;
private $email;
private static $ageLimit = 40;
//Create a Constructor
public function __construct($name, $email){
$this->name = $name;
$this->email = $email;
echo __CLASS__ . 'Created';
}
//Deconstruct
public function __destruct(){
echo __CLASS__ . 'Created';
}
//Getter and Setter
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
public function setEmail($name){
$this->name = $name;
}
public function getEmail(){
return $this->name;
}
public static function getAgeLimit(){
return self::$ageLimit;
}
}
echo Person::getAgeLimit();
// $person1 = new Person('Aali', '<EMAIL>');
// echo $person1->getName();
// $person1->setName('<NAME>');
// echo $person1->getName();
//INHERITANCE
class Customer extends Person{
private $balance;
//Create a constuctor
public function __construct($name, $email, $balance){
parent::__construct($name, $email, $balance);
$this->balance = $balance;
echo 'A new' . __CLASS__ . 'has been created';
}
public function setBalance($balance){
$this->balance = $balance;
}
public function getBalance(){
return $this->balance. '<br>';
}
}
$customer1 = new Customer('Andrew', '<EMAIL>', 100);
echo $customer1->getBalance();<file_sep><?php
// if(isset($_GET['name'])){
// echo htmlentities($_GET['name']);
// }
#PHP TO JS Equivalent
// ------------------
#substr = slice
#returns a proportion of a string
$output = substr('Hello', 1,4);
#strlen = .length
#return the lengths of a string including the space
$output2 = strlen('Alain');
#strpos
#find the first occurence of a sub string and its case sensitive
$output3 = strpos('Alain Dimabuyo', 'D');
#strrpos
#find the last occurence of a sub string
$output4 = strrpos('Alain Dimabuyo', 'a');
#trim = split
#strips whitespace - usefull in forms
$text = 'Hello World !';
$textTrimmed = trim($text);
#strtoupper = toUppeCase
#make everything string to uppercase
$output5 = strtoupper('alain dimabuyo');
#strtolower = toLowerCase
#make string to lowercase
$output6 = strtolower('ALAIN dimabuyo');
#ucwords
#capitalize every first letter of each word
$output7 = ucwords('alain dimabuyo');
#str_replace = takes two parameters (word to be replaced, word to replace);
$output8 = str_replace('World', 'alain', $text);
#is_string = typeOF
#check if value is String
$output9 = is_string($text);
$output10 = array(10 , '10' , 10.5, '10.5');
foreach($output10 as $val){
if(is_string($val)){
// echo "{$val} is a fucking string <br>";
}
}
#PHP TERNARY OPERATION IS THE SAME IN JS
$age = 20;
$score = 15;
#NESTED Ternary operations
echo 'Your score is:' .($score > 10 ? ($age > 10 ? "GOod" : "Best") : ($age > 10 ? "Bad" : "Worst"));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Lesson 10</title>
</head>
<body>
<form method="GET" action="index.php">
<div>
<label for="">Name</label>
<input type="text" name="name">
</div>
<div>
<label for="">Email</label>
<input type="text" name="email">
</div>
<input type="submit" value="Submit">
</form>
</body>
</html><file_sep><?php
require('db.php');
$query = 'SELECT * FROM posts';
//GET RESULT
$result = mysqli_query($conn, $query);
//FETCH DATA
$posts = mysql_fetch_all($result, MYSQLI_ASSOC);
var_dump($posts);
//Free Result
mysqli_free_result($result);
//Close COnnection
mysqli_close($conn);
|
45bdc06af7f1c598cfc3948ae44f9457951a4603
|
[
"PHP"
] | 7 |
PHP
|
alaindimabuyo/php-cheat-sheet
|
c233a6a80f085ac9f29c941ee242c5509f481944
|
4e615ea789cee92278709348cc42917e136ddeaa
|
refs/heads/master
|
<repo_name>Aditya-06/Adopt-me<file_sep>/README.md
# Adopt-me
Pet Adoption Website
### Install dependencies:
```
npm install
```
### Run Website on Local Machine:
```
npm run dev
```
Screenshots:

<file_sep>/src/App.js
import React, { useState } from 'react';
import { render } from 'react-dom';
import SearchParams from './SearchParams';
import { Link, Router } from '@reach/router';
import Details from './Details';
import ThemeContext from './ThemeContext';
const App = () => {
/*
return React.createElement(
'div',
{},
// Childern inside the div
[
React.createElement('h1', {}, 'Adopt Me'),
React.createElement(Pet, {
name: 'Max',
animal: 'Dog',
breed: 'Shepard',
}),
React.createElement(Pet, {
name: 'Iron',
animal: 'bird',
breed: 'Love',
}),
React.createElement(Pet, {
name: 'Steel',
animal: 'Sheep',
breed: 'Shaun',
}),
]
);
*/
const themeHook = useState('');
return (
<React.StrictMode>
<ThemeContext.Provider value={themeHook}>
<div>
<header>
<Link to="/">Adopt Me! </Link>
</header>
<Router>
<SearchParams path="/" />
<Details path="/details/:id" />
</Router>
</div>
</ThemeContext.Provider>
</React.StrictMode>
);
};
render(<App />, document.getElementById('root'));
|
1415bb00326509c20319af5c37636a24480a7afc
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
Aditya-06/Adopt-me
|
f944df0af7017144c61141e78d07b37e1187a77b
|
4828c9d41d40c9d03b72b1b24c9d1be943a349cc
|
refs/heads/main
|
<repo_name>aladdin120/CounterSwift<file_sep>/Counter/ViewController.swift
import UIKit
class ViewController: UIViewController {
private var label = UILabel()
private var tapButton = UIButton()
private var resetButton = UIButton()
private var counter = 0 {
didSet {
label.text = counter.description
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Counter"
view.backgroundColor = .orange
view.addSubview(tapButton)
view.addSubview(label)
resetButton.setTitle("Reset", for: .normal)
resetButton.addTarget(self, action: #selector(resetCounter), for: .touchUpInside)
resetButton.setTitleColor(.purple, for: .normal)
tapButton.backgroundColor = .purple
tapButton.setTitle("TAP", for: .normal)
tapButton.addTarget(self, action: #selector(tapAction), for: .touchUpInside)
tapButton.translatesAutoresizingMaskIntoConstraints = false
label.text = counter.description
label.font = UIFont.systemFont(ofSize: 30, weight: .medium)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tapButton.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 30),
tapButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
label.centerYAnchor.constraint(equalTo: view.centerYAnchor),
label.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: resetButton)
//label = UILabel(frame: CGRect(x: view.frame.midX, y: view.frame.midY, width: 40, height: 40))
}
@objc func tapAction() {
counter += 1
}
@objc func resetCounter() {
counter = 0
}
}
|
5bb09c190cac92cfcd00a9f6c270fcf7750b6070
|
[
"Swift"
] | 1 |
Swift
|
aladdin120/CounterSwift
|
246eabd464d04b715d2d64774022aef9b69bdee1
|
e3f5cf4708e7072eefb499b99a5fa34282c68f33
|
refs/heads/master
|
<file_sep>// banner.js
import Component from '../../base/component';
class Banner extends Component {
constructor(options) {
super(Object.assign({}, options));
// this.page.setData({
// "__banner__.materialType": -1,
// "__banner__.banners": []
// });
this.page.tapComponentBanner = this.tapComponentBanner;
}
show(data) {
let list = data.materialList;
if (data.materialType == 13) {
if (list instanceof Array) {
let banners = [];
list.forEach(banner => {
banners.push(banner);
})
this.page.setData({
"__banner__.materialType": 13,
"__banner__.materialList": banners
});
}
}
}
/**
* Called By wue.$wueComponentIndex
*/
process(data) {
return data;
}
tapComponentBanner(e) {
console.log('banner index = ' + e.target.dataset.index);
}
}
export default Banner;<file_sep>//index.js
//获取应用实例
var app = getApp()
Page({
data: {
pageInfo: null
},
//事件处理函数
bindViewTap: function() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad: function () {
let wue = app.wue(this);
this.$wueNavigationTab = wue.$wueNavigationTab;
this.$wueBanner = wue.$wueBanner;
this.$wueSingleImage = wue.$wueSingleImage;
this.$wueMultiImage = wue.$wueMultiImage;
this.$wueNormalGroupGoods = wue.$wueNormalGroupGoods;
console.log('onLoad');
this.getPageInfo();
},
getPageInfo: function () {
let that = this;
wx.request({
url: app.getServices('mengdianApp/getPageInfo'),
data: {
"pageSize": 20,
"BaseAppVersion": "4.9.0",
"channel": "AppBuyerHome",
"_sign_": "95BB77B1CB9A39DBF32AF8EC4C65EFE5",
"hardware": "iPhone8,2",
"SystemVersion": "10.3.3",
"appIdentifier": "com.hs.yjseller",
"spreadChannel": "app store",
"BaseAppType": "ios",
"page": 1
},
method: "POST",
success: function (response) {
that.setData({
pageInfo: response.data.data
})
that.$wueNavigationTab.show(that.data.pageInfo.navChannel);
that.$wueBanner.show(that.data.pageInfo.materialList[0]);
that.$wueMultiImage.show(that.data.pageInfo.materialList[1]);
that.$wueSingleImage.show(that.data.pageInfo.materialList[2]);
that.$wueNormalGroupGoods.show(that.data.pageInfo.materialList[3]);
},
fail: function (error) {
console.log('error = ' + error);
}
});
}
})
<file_sep>// wue/component/multi-image/img.js
import Component from '../../base/component';
class MultiImage extends Component {
constructor(options) {
super(Object.assign({}, options));
// this.page.setData({
// "__multiImage__": null,
// "__multiImage__.width": "100rpx",
// "__multiImage__.height": "100rpx"
// });
this.page.tapComponentMultiImage = this.tapComponentMultiImage;
}
show(data) {
if (data.materialType == 3) {
let width = getApp().globalData.systemInfo.screenWidth / data.column;
let height = width * data.ratio;
this.page.setData({
"__multiImage__": data,
"__multiImage__.width": width + 'px',
"__multiImage__.height": height + 'px'
});
}
}
/**
* Called By wue.$wueComponentIndex
*/
process(data) {
if (data.materialType == 3) {
let width = getApp().globalData.systemInfo.screenWidth / data.column;
let height = width * data.ratio;
data['width'] = width + 'px';
data['height'] = height + 'px';
return data;
}
}
tapComponentMultiImage(e) {
console.log('[tapComponentMultiImage] index = ' + e.currentTarget.dataset.index);
}
}
export default MultiImage;<file_sep>const BASE_URL = 'https://api.vd.cn/';
const postData = {
"BaseAppVersion": "4.10.0",
"hardware": "iPhone8,2",
"SystemVersion": "11.0",
"appIdentifier": "com.hs.yjseller",
"spreadChannel": "WxSmallApp",
"BaseAppType": "ios"
}
function getServices(relativeUrl) {
return BASE_URL + relativeUrl;
}
function request(obj) {
let data = postData;
for(let key in obj.data) {
if(obj.data.hasOwnProperty(key)) {
data[key] = obj.data[key];
}
}
wx.request({
url: getServices(obj.url),
data: data,
method: "POST",
success: function (response) {
obj.success(response);
},
fail: function (error) {
console.log('error = ' + error);
if (obj.hasOwnProperty('fail')) {
obj.fail(error);
}
},
complete: function (){
if (obj.hasOwnProperty('complete')) {
obj.complete();
}
}
});
}
export default request;<file_sep>// wue/component/bubble/bubble.js
import Component from '../../base/component';
class Bubble extends Component {
constructor(options) {
super(Object.assign({}, options));
this.page.tapComponentBubble = this.tapComponentBubble;
}
show(data) {
let bubble = {
curIndex: 0,
hidden: true
};
let list = data.materialList;
if (list instanceof Array) {
let items = [];
list.forEach(item => {
items.push(item);
});
bubble.items = items;
}
this.page.setData({
"__bubble__": bubble
});
if (bubble.items != null && bubble.items.length > 0) {
this.start();
}
}
/**
* 每6秒交替显示/隐藏
*/
start() {
let that = this.page;
setInterval(() => {
let items = that.data.__bubble__.items.length;
let curIndex = that.data.__bubble__.curIndex;
let hidden = !that.data.__bubble__.hidden;
that.setData({
"__bubble__.curIndex": hidden ? curIndex : (curIndex + 1) % items,
"__bubble__.hidden": hidden
})
}, 6000);
}
tapComponentBubble(e) {
}
}
export default Bubble;<file_sep>import NavigationTab from './component/navigation-tab/tab';
import Banner from './component/banner/banner';
import SingleImage from './component/single-image/img';
import MultiImage from './component/multi-image/img';
import NormalGroupGoods from './component/goods/normal-group/goods';
import Tabbar from './component/tabbar/tabbar';
import Bubble from './component/bubble/bubble';
/**
* 组件集合
*/
import ComponentIndex from './index/index';
export default function (scope) {
console.log('----- comp index list -----');
console.log('scope = ' + JSON.stringify(scope));
console.log('---------------------------');
let wue = {
$wueNavigationTab: new NavigationTab(scope),
$wueBanner: new Banner(scope),
$wueSingleImage: new SingleImage(scope),
$wueMultiImage: new MultiImage(scope),
$wueNormalGroupGoods: new NormalGroupGoods(scope),
$wueTabbar: new Tabbar(scope),
$wueBubble: new Bubble(scope)
};
wue.$wueComponentIndex = new ComponentIndex(scope, wue);
return wue;
}<file_sep>//app.js
import wue from './wue/wue';
import request from './config/server';
App({
// 通用组件
wue,
// 获取服务真实接口地址
request,
onLaunch: function() {
this.getSystemInfo();
//调用API从本地缓存中获取数据
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
},
getUserInfo: function(cb) {
var that = this
if (this.globalData.userInfo) {
typeof cb == "function" && cb(this.globalData.userInfo)
} else {
//调用登录接口
wx.getUserInfo({
withCredentials: false,
success: function(res) {
that.globalData.userInfo = res.userInfo
typeof cb == "function" && cb(that.globalData.userInfo)
}
})
}
},
getSystemInfo: function() {
let that = this;
wx.getSystemInfo({
success: function (res) {
that.globalData.systemInfo = res;
}
});
},
globalData: {
userInfo: null,
systemInfo: null
}
})
<file_sep>// wue/views/tabbar/tabbar.js
import Component from '../../base/component';
class Tabbar extends Component {
constructor(options) {
super(Object.assign({}, options));
this.page.tapComponentTabbar = this.tapComponentTabbar;
}
show(data) {
let tabbar = {};
let list = data.navList;
if (list instanceof Array) {
let tabItems = [];
list.forEach(item => {
tabItems.push(item);
})
tabbar['tabItems'] = tabItems;
}
tabbar['curIndex'] = 0;
tabbar['icon'] = tabbar['tabItems'][0].focusTitleIconUrl;
this.page.setData({
"__tabbar__": tabbar,
});
}
tapComponentTabbar(e) {
let index = e.currentTarget.dataset.index;
let icon = this.data.__tabbar__.tabItems[index].focusTitleIconUrl;
this.setData({
"__tabbar__.curIndex": index,
"__tabbar__.icon": icon,
});
}
}
export default Tabbar;<file_sep>// pages/home/home.js
var app = getApp();
Page({
data: {
pageInfo: null,
scrollViewHeight: 0
},
onLoad: function () {
let wue = app.wue(this);
this.$wueNavigationTab = wue.$wueNavigationTab;
this.$wueComponentIndex = wue.$wueComponentIndex;
this.$wueTabbar = wue.$wueTabbar;
this.$wueBubble = wue.$wueBubble;
console.log('onLoad');
this.setData({
scrollViewHeight: (app.globalData.systemInfo.windowHeight - 32 - 50) + 'px'
})
this.getTabbar();
this.getPageInfo();
this.getBubble();
},
getTabbar: function() {
let that = this;
app.request({
url: 'mengdianApp/getMdTabbar',
data: {
"_sign_": "CA88EF8B23F3824C1F11EDC80B6497D4",
},
success: function (response) {
that.$wueTabbar.show(response.data.data);
}
})
},
getBubble: function() {
let that = this;
app.request({
url: 'mengdianApp/getHomeRecommendBubble',
data: {
"_sign_": "28A97A58184039C5FD7DB3790EA380FF",
"timeStamp": "2017-09-27T14:25:06.522Z"
},
success: function (response) {
that.$wueBubble.show(response.data.data);
}
})
},
getPageInfo: function () {
let that = this;
app.request({
url: 'mengdianApp/getPageInfo',
data: {
"pageSize": 20,
"channel": "AppBuyerHome",
"_sign_": "95BB77B1CB9A39DBF32AF8EC4C65EFE5",
"page": this.customData.page
},
success: function (response) {
let pi = that.data.pageInfo;
if (that.customData.page > 1) {
pi.materialList.push(...response.data.data.materialList);
} else {
pi = response.data.data;
}
that.setData({
pageInfo: pi
});
that.$wueNavigationTab.show(that.data.pageInfo.navChannel);
that.$wueComponentIndex.show(that.data.pageInfo.materialList);
},
complete: function(){
wx.hideNavigationBarLoading();
wx.stopPullDownRefresh();
}
});
},
onPullDownRefresh: function() {
console.log('onPullDownRefresh');
this.customData.page = 1;
wx.showNavigationBarLoading();
this.getPageInfo();
},
onReachBottom: function() {
console.log('onReachBottom page = ' + this.customData.page);
this.customData.page++;
wx.showNavigationBarLoading();
this.getPageInfo();
},
customData: {
page: 1
}
})<file_sep>class Component {
constructor(options) {
// console.log('[component] options = ' + JSON.stringify(options));
this.__init();
}
__init() {
let pages = getCurrentPages();
this.page = pages[pages.length - 1];
}
}
export default Component;<file_sep>// wue/component/single-img/img.js
import Component from '../../base/component';
class SingleImage extends Component {
constructor(options) {
super(Object.assign({}, options));
// this.page.setData({
// "__singleImage__.height": "10rpx",
// "__singleImage__.item": null
// });
this.page.tapComponentSingleImage = this.tapComponentSingleImage;
}
show(data) {
if (data.materialType == 0) {
let ratio = data.ratio;
let height = (ratio * getApp().globalData.systemInfo.screenWidth) + 'px';
this.page.setData({
"__singleImage__": data,
"__singleImage__.height": height
});
}
}
process(data) {
if (data.materialType == 0) {
let ratio = data.ratio;
let height = (ratio * getApp().globalData.systemInfo.screenWidth) + 'px';
data['height'] = height;
return data;
}
}
tapComponentSingleImage(e) {
console.log('[SingleImage] tap = ' + JSON.stringify(e));
}
}
export default SingleImage;
|
94977428aca80cf7940a85b1c664c589cf52cca7
|
[
"JavaScript"
] | 11 |
JavaScript
|
joselyncui/WUE
|
3d6acbc577a0ca24fe0b46dd3e36ade33dc297f4
|
32d7025592004edc5ba3af975687c1051310cd62
|
refs/heads/master
|
<repo_name>Sir-Diox/Unit-Guide<file_sep>/filters.js
var unitsListConstruction = [];
var allArrays = [];
var result = [];
var chosenFiltersArray = [];
var chosenFilterTitles = [];
var iterator = 0;
$("body").on("click", ".ctn input, div.ctn, .chosen-filter, .ctn-range input", function () {
var obj = $(this);
generateFiltersResult(obj);
});
function generateFiltersResult(obj) {
setTimeout(function () {
document.body.scrollTop = document.documentElement.scrollTop = 0;
if ($(obj).hasClass("chosen-filter")) {
var val = $(obj).attr("value");
val = val.replace(/\s+/g, '');
$(obj).remove();
$(".ctn").each(function () {
if ($(this).attr("value").replace(/\s+/g, '') == val) {
$(this).children().eq(0).prop("checked", false);
if ($(this).hasClass("ctn-range")) {
$(this).hide();
$(this).parent().children("input").val("");
}
}
});
if ($(".chosen-filter").length == 0) {
$(".chosen-filters-container").hide();
$(".filter-results-count").html($(".filter-results .unit-box").length);
}
}
if ($(obj).parent().hasClass("ctn-range")) {
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
if ($(obj).parent().parent().hasClass("Mcost")) {
$(".Mcost .ctn-range").hide();
$("#mcost-from").val("");
$("#mcost-to").val("");
}
if ($(obj).parent().parent().hasClass("Ecost")) {
$(".Ecost .ctn-range").hide();
$("#ecost-from").val("");
$("#ecost-to").val("");
}
}
$(".filter-results").html("");
allArrays = [];
result = [];
$(".mobile-hide").eq(1).hide();
$(".units-content").hide();
$(".main-banner").hide();
var ARMList = [];
var COREList = [];
$(".Side .ctn").each(function () {
if ($(this).children().eq(0).is(':checked')) {
var valueName = $(this).attr("value");
if (valueName == "ARM") {
$(".units-content .unit-box").each(function () {
if ($(this).attr("side") == "arm" && !$(this).hasClass("lab-space")) {
ARMList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
}
if (valueName == "CORE") {
$(".units-content .unit-box").each(function () {
if ($(this).attr("side") == "core" && !$(this).hasClass("lab-space")) {
COREList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
}
setTimeout(function () {
var union = [...new Set([...ARMList, ...COREList])];
allArrays.push(union);
}, 0.01);
}
});
var tier1List = [];
var tier2List = [];
var tier3List = [];
$(".Tier .ctn").each(function () {
if ($(this).children().eq(0).is(':checked')) {
var valueName = $(this).attr("value");
if (valueName == "Tier 1") {
$(".tier-1-content .unit-box").each(function () {
if (!$(this).hasClass("lab-space")) {
tier1List.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
}
if (valueName == "Tier 2") {
$(".tier-2-content .unit-box").each(function () {
if (!$(this).hasClass("lab-space")) {
tier2List.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
}
if (valueName == "Tier 3") {
$(".tier-3-content .unit-box").each(function () {
if (!$(this).hasClass("lab-space")) {
tier3List.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
}
setTimeout(function () {
var union = [...new Set([...tier1List, ...tier2List, ...tier3List])];
allArrays.push(union);
}, 0.01);
}
});
var kbotsList = [];
var vehiclesList = [];
var hovercraftsList = [];
var shipsList = [];
var aircraftsList = [];
var seaplanesList = [];
var commandersList = [];
$(".UnitsKind .ctn").each(function () {
if ($(this).children().eq(0).is(':checked')) {
var valueName = $(this).attr("value");
if (valueName == "Kbots") {
$(".kbots .unit-box").each(function () {
if (!$(this).hasClass("lab-space")) {
kbotsList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
}
if (valueName == "Vehicles") {
$(".vehicles .unit-box").each(function () {
if (!$(this).hasClass("lab-space")) {
vehiclesList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
}
if (valueName == "Hovercrafts") {
$(".hovercrafts .unit-box").each(function () {
if (!$(this).hasClass("lab-space")) {
hovercraftsList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
}
if (valueName == "Ships") {
$(".ships .unit-box").each(function () {
if (!$(this).hasClass("lab-space")) {
shipsList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
}
if (valueName == "Aircrafts") {
$(".aircrafts .unit-box").each(function () {
if (!$(this).hasClass("lab-space")) {
aircraftsList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
}
if (valueName == "Seaplanes") {
$(".seaplanes .unit-box").each(function () {
if (!$(this).hasClass("lab-space")) {
seaplanesList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
}
//if (valueName == "Commanders") {
// $(".commanders .unit-box").each(function () {
// if (!$(this).hasClass("lab-space")) {
// commandersList.push($(this).parent().wrap('<p/>').parent().html());
// }
// });
//}
setTimeout(function () {
var union = [...new Set([...kbotsList, ...vehiclesList, ...hovercraftsList, ...shipsList, ...aircraftsList, ...seaplanesList, ...commandersList])];
allArrays.push(union);
}, 0.01);
}
});
var buildingsList = [];
var unitsList = [];
$(".Type .ctn").each(function () {
if ($(this).children().eq(0).is(':checked')) {
var valueName = $(this).attr("value");
if (valueName == "Buildings") {
$(".buildings-section .unit-box").each(function () {
buildingsList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
});
setTimeout(function () {
allArrays.push(buildingsList);
}, 0.01);
}
if (valueName == "Units") {
$(".units-content .unit-box").each(function () {
if (!($(this).parents(".buildings-section").length || $(this).hasClass("lab-space"))) {
unitsList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
setTimeout(function () {
allArrays.push(unitsList);
}, 0.01);
}
}
});
$(".Role .ctn").each(function () {
var fighterUnitsList = [];
var consList = [];
var consListNames = [];
var unitsListAA = [];
var radarUnitsList = [];
var radarUnitsNamesList = [];
var jammerUnitsList = [];
var jammerUnitsNamesList = [];
var scoutUnitsList = [];
if ($(this).children().eq(0).is(':checked')) {
var valueName = $(this).attr("value");
if (valueName == "Fighter") {
$(".units-content .unit-box").each(function () {
if ($(this).attr("w1") != undefined && (!$(this).parent().parent().parent().parent().parent().hasClass("buildings-section") && $(this).attr("uname") != "Mechanic" && $(this).attr("uname") != "Angler" && $(this).attr("uname") != "Refuge" && $(this).attr("uname") != "Decoy Commander" && $(this).attr("uname") != "Commander")) {
fighterUnitsList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
setTimeout(function () {
allArrays.push(fighterUnitsList);
}, 0.01);
}
if (valueName == "Builder/supporter") {
for (i = 0; i < csvObj.length; i++) {
if (csvObj[i].builder == 1 && csvObj[i].canmove == 1 && csvObj[i].maxvelocity > 0.5) {
consListNames.push(csvObj[i].name);
}
}
$(".units-content .unit-box").each(function () {
if (consListNames.includes($(this).attr("uname"))) {
consList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
setTimeout(function () {
allArrays.push(consList);
}, 0.01);
}
if (valueName == "Anti air") {
$(".units-content .unit-box").each(function () {
if (!($(this).attr("w1-aa") == undefined && $(this).attr("w2-aa") == undefined && $(this).attr("w3-aa") == undefined)) {
unitsListAA.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
setTimeout(function () {
allArrays.push(unitsListAA);
}, 0.01);
}
//if (valueName == "Defense") {
// $(".units-content .unit-box").each(function () {
// if ($(this).attr("urole") == "defense") {
// defenseUnitsList.push($(this).parent().wrap('<p/>').parent().html());
// }
// });
// setTimeout(function () {
// allArrays.push(defenseUnitsList);
// }, 0.01);
//}
if (valueName == "Radar") {
for (i = 0; i < csvObj.length; i++) {
if (csvObj[i].radardistance > 1100) {
radarUnitsNamesList.push(csvObj[i].name);
}
}
$(".units-content .unit-box").each(function () {
if (radarUnitsNamesList.includes($(this).attr("uname")) && !$(this).hasClass("lab-space")) {
radarUnitsList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
setTimeout(function () {
allArrays.push(radarUnitsList);
}, 0.01);
}
if (valueName == "Jammer") {
for (i = 0; i < csvObj.length; i++) {
if (csvObj[i].radardistancejam > 100) {
jammerUnitsNamesList.push(csvObj[i].name);
}
}
$(".units-content .unit-box").each(function () {
if (jammerUnitsNamesList.includes($(this).attr("uname"))) {
jammerUnitsList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
setTimeout(function () {
allArrays.push(jammerUnitsList);
}, 0.01);
}
if (valueName == "Scout") {
$(".units-content .unit-box").each(function () {
if ($(this).attr("urole") == "scout") {
scoutUnitsList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
setTimeout(function () {
allArrays.push(scoutUnitsList);
}, 0.01);
}
}
});
var mcostUnitsNamesList = [];
var mcostUnitsList = [];
$(".Mcost").each(function () {
if ($(this).attr("value") == "Mcost" && $(obj).hasClass("btn-filter") || $(".Mcost .ctn-range input").is(':checked')) {
var mcostFrom = parseFloat($("#mcost-from").val());
var mcostTo = parseFloat($("#mcost-to").val());
if (!isNaN(mcostTo) || !isNaN(mcostFrom)) {
$(".Mcost .ctn-range").show();
$(".Mcost .ctn-range input").prop("checked", "true");
for (i = 0; i < csvObj.length; i++) {
if (parseFloat(csvObj[i].buildcostmetal) >= mcostFrom && parseFloat(csvObj[i].buildcostmetal) <= mcostTo) {
mcostUnitsNamesList.push(csvObj[i].name);
}
}
$(".units-content .unit-box").each(function () {
if (mcostUnitsNamesList.includes($(this).attr("uname")) && !$(this).hasClass("lab-space")) {
mcostUnitsList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
setTimeout(function () {
allArrays.push(mcostUnitsList);
}, 0.01);
} else {
$(".Mcost .ctn-range").hide();
$("#mcost-from").val("");
$("#mcost-to").val("");
}
}
});
var ecostUnitsNamesList = [];
var ecostUnitsList = [];
$(".Ecost").each(function () {
if ($(this).attr("value") == "Ecost" && $(obj).hasClass("btn-filter") || $(".Ecost .ctn-range input").is(':checked')) {
var ecostFrom = parseFloat($("#ecost-from").val());
var ecostTo = parseFloat($("#ecost-to").val());
if (!isNaN(ecostTo) || !isNaN(ecostFrom)) {
$(".Ecost .ctn-range").show();
$(".Ecost .ctn-range input").prop("checked", "true");
for (i = 0; i < csvObj.length; i++) {
if (parseFloat(csvObj[i].buildcostenergy) >= ecostFrom && parseFloat(csvObj[i].buildcostenergy) <= ecostTo) {
ecostUnitsNamesList.push(csvObj[i].name);
}
}
$(".units-content .unit-box").each(function () {
if (ecostUnitsNamesList.includes($(this).attr("uname")) && !$(this).hasClass("lab-space")) {
ecostUnitsList.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
setTimeout(function () {
allArrays.push(ecostUnitsList);
}, 0.01);
} else {
$(".Ecost .ctn-range").hide();
}
}
});
$(".Speed").each(function () {
$(this).children(".ctn").each(function () {
if ($(this).children().eq(0).is(':checked')) {
var unitsListNameMs = [];
var unitsListMs = [];
if ($(this).is("[from]") || $(this).is("[to]")) {
var movementFrom = parseFloat($(this).attr("from"));
var movementTo = parseFloat($(this).attr("to"));
$("#movement-from").val($(this).attr("from"));
$("#movement-to").val($(this).attr("to"));
}
//else {
// var movementFrom = $("#movement-from").val();
// var movementTo = $("#movement-to").val();
//}
for (i = 0; i < csvObj.length; i++) {
if (parseFloat(csvObj[i].maxvelocity) >= movementFrom && parseFloat(csvObj[i].maxvelocity) <= movementTo) {
unitsListNameMs.push(csvObj[i].name);
}
}
$(".units-content .unit-box").each(function () {
if (unitsListNameMs.includes($(this).attr("uname"))) {
unitsListMs.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
setTimeout(function () {
allArrays.push(unitsListMs);
}, 0.01);
}
});
});
// if ($(this).children().eq(0).is(':checked')) {
// var valueName = $(this).attr("value");
// }
//});
setTimeout(function () {
if (allArrays.length >= 2) {
result = allArrays.shift().filter(function (v) {
return allArrays.every(function (a) {
return a.indexOf(v) !== -1;
});
});
$(".filter-results").html("");
var uniq = [...new Set(result)];
for (i = 0; i < uniq.length; i++) {
$(".filter-results").append(uniq[i]);
}
}
else if (allArrays.length == 1) {
$(".filter-results").html("");
var uniq = [...new Set(allArrays[0])];
for (i = 0; i < uniq.length; i++) {
$(".filter-results").append(uniq[i]);
}
}
else {
$(".filter-results").html("");
$(".unit-box").each(function () {
if (!$(this).hasClass("lab-space")) {
result.push($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
}
});
var uniq = [...new Set(result)];
for (i = 0; i < uniq.length; i++) {
$(".filter-results").append(uniq[i]);
}
}
appendChosenFiltersList(obj);
chosenFiltersArray = [];
allArrays = [];
result = [];
if ($(".chosen-filter").length == 0) {
$(".chosen-filters-container").hide();
$(".filter-results-count").html($(".filter-results .unit-box").length);
} else {
$(".chosen-filters-container").show();
$(".filter-results-count").html($(".filter-results .unit-box").length);
showOrHideClearAllFilters();
}
}, 0.5);
}, 0.01);
}
function appendChosenFiltersList(obj) {
chosenFiltersArray = [];
chosenFilterTitles = [];
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
if (($(obj).attr("value") == "Mcost" || $(".Mcost .ctn-range input").is(':checked')) && !$(obj).parent().hasClass("ctn-range")) {
chosenFiltersArray.push($("#mcost-from").val() + " - " + $("#mcost-to").val());
$(".Mcost .ctn-range").attr("value", $("#mcost-from").val() + " - " + $("#mcost-to").val());
chosenFilterTitles.push("M cost");
}
if (($(obj).attr("value") == "Ecost" || $(".Ecost .ctn-range input").is(':checked')) && !$(obj).parent().hasClass("ctn-range")) {
chosenFiltersArray.push($("#ecost-from").val() + " - " + $("#ecost-to").val());
$(".Ecost .ctn-range").attr("value", $("#ecost-from").val() + " - " + $("#ecost-to").val());
chosenFilterTitles.push("E cost");
}
$(".ctn input").each(function () {
if ($(this).is(':checked') && !$(this).parent().hasClass("ctn-range")) {
chosenFiltersArray.push($(this).parent().text());
chosenFilterTitles.push($(this).parent().parent().attr("name"));
}
});
$(".chosen-filters-list").html("");
for (i = 0; i < chosenFiltersArray.length; i++) {
$(".chosen-filters-list").append("<span class='chosen-filter' value='" + chosenFiltersArray[i] + "'><span class='filter-title'>" + chosenFilterTitles[i] + ": </span>" + chosenFiltersArray[i] + "<span class='close-btn'>✖</span></span>" + " ");
}
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
setInputFilter(document.getElementById("mcost-from"), function (value) {
return /^\d*\.?\d*$/.test(value);
});
setInputFilter(document.getElementById("mcost-to"), function (value) {
return /^\d*\.?\d*$/.test(value);
});
setInputFilter(document.getElementById("ecost-from"), function (value) {
return /^\d*\.?\d*$/.test(value);
});
setInputFilter(document.getElementById("ecost-to"), function (value) {
return /^\d*\.?\d*$/.test(value);
});
function setInputFilter(textbox, inputFilter) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function (event) {
textbox.addEventListener(event, function () {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
});
});
}
function showOrHideClearAllFilters() {
if ($('.chosen-filter').length >= 2) {
$(".chosen-filters-list").append('<button class="normal-button filters-x-clearall ug-button">Remove filters</button>');
}
else {
$(".filters-x-clearall").remove();
}
}
$("body").on("mouseover", ".filters-x-clearall", function () {
$(".chosen-filter .close-btn").css("color", "#dea73c");
});
$("body").on("mouseleave", ".filters-x-clearall", function () {
$(".chosen-filter .close-btn").css("color", "");
});
$('body').on('click', '.filters-x-clearall', function () {
$(".chosen-filters-container").hide();
$(".ctn input").each(function () {
$(this).prop("checked", false);
});
$("input[type='text']").val("");
$(".ctn-range").hide();
$(".chosen-filters-list").children().remove();
generateFiltersResult();
showOrHideClearAllFilters();
});
$("body").on("click", ".filters-btn", function () {
var obj = $(this).parent().children().eq(1);
activateFilters(obj[0].children[0]);
});
function activateFilters(obj) {
obj.classList.toggle('active');
if (obj.classList[1] == "active") {
$(".filters-results-container").show();
$(".chosen-filters-container").hide();
//$(".tier-buttons").hide();
$(".tier-buttons").animate({ width: 'toggle' }, 300);
$(".navbar").animate({
'margin-left': 'auto',
'margin-right': 'auto'
}, 500);
$(".nav-elements-container").animate({
'max-width': '1920px',
}, 500);
$(".mobile-hide").eq(1).hide(500);
$(".units-content").hide(500);
$(".main-banner").hide("500", function () {
$(".filters-menu").show(300);
generateFiltersResult();
});
}
else {
$(".filters-results-container").hide();
$(".chosen-filters-container").hide();
$(".tier-buttons").animate({ width: 'toggle' }, 300);
//$(".navbar").animate({
// 'margin-left': 'auto',
// 'margin-right': 'auto'
//}, 500);
$(".nav-elements-container").animate({
'max-width': '1444px',
}, 500);
$(".mobile-hide").eq(1).show(500);
$(".units-content").show(500);
$(".main-banner").show("500", function () {
$(".filters-menu").hide(300);
});
}
}<file_sep>/unit-type.js
function setLabelParametersAndValues(unitType) {
if (unitType.isFighter) {
if (unitData.isAntiAir1 == 1 && unitData.isAntiAir2 == undefined && unitData.isAntiAir3 == undefined) {
firstParameter = "Damage per second:";
} else {
firstParameter = "Damage per second:";
}
secondParameter = "Damage per shot:";
thirdParameter = "Range:";
fourthParameter = "Health:";
fifthParameter = "Movement speed:";
sixthParameter = "Sight range:";
}
else if (unitType.isFighterDpsOnly) {
firstParameter = "Damage per second:";
secondParameter = "Range:";
thirdParameter = "Health:";
fourthParameter = "Movement speed:";
fifthParameter = "Sight range:";
}
else if (unitType.isAirFigther) {
firstParameter = "Damage per second:";
secondParameter = "Range:";
thirdParameter = "Health:";
fourthParameter = "Flying speed:";
fifthParameter = "Sight range:";
}
else if (unitType.isBomber) {
firstParameter = "Damage per bomb:";
secondParameter = "Health:";
thirdParameter = "Flying speed:";
fourthParameter = "Sight range:";
}
else if (unitType.isAntiAirBuilding) {
firstParameter = "Damage per second:";
secondParameter = "Range:";
thirdParameter = "Health:";
fourthParameter = "Sight range:";
}
else if (unitType.isMine) {
firstParameter = "Max explosion damage:";
secondParameter = "Explosion range:";
thirdParameter = "Health:";
}
else if (unitType.isClawlingBomb) {
firstParameter = "Max explosion damage:";
secondParameter = "Explosion range:";
thirdParameter = "Health:";
fourthParameter = "Movement speed:";
fifthParameter = "Sight range:";
}
else if (unitType.isNuke) {
firstParameter = "Max explosion damage:";
secondParameter = "Explosion range:";
thirdParameter = "Health:";
}
else if (unitType.isCons) {
firstParameter = "Build speed:";
secondParameter = "Build range:";
thirdParameter = "Health:";
fourthParameter = "Movement speed:";
fifthParameter = "Sight range:";
}
else if (unitType.isCom) {
firstParameter = "Build speed:";
secondParameter = "Build range:";
thirdParameter = "Health:";
fourthParameter = "Movement speed:";
fifthParameter = "Sight range:";
}
else if (unitType.isAirCons) {
firstParameter = "Build speed:";
secondParameter = "Build range:";
thirdParameter = "Health:";
fourthParameter = "Flying speed:";
fifthParameter = "Sight range:";
}
else if (unitType.isSemiCon) {
firstParameter = "Build speed (assisting):";
secondParameter = "Build range:";
thirdParameter = "Health:";
fourthParameter = "Movement speed:";
fifthParameter = "Sight range:";
}
else if (unitType.isBuilding) {
firstParameter = "Health:";
secondParameter = "Sight Range:";
}
else if (unitType.isLab) {
firstParameter = "Build speed:";
secondParameter = "Health:";
thirdParameter = "Sight Range:";
}
else if (unitType.isEco) {
firstParameter = "Health:";
}
else if (unitType.isAirUnit) {
firstParameter = "Damage per second:";
secondParameter = "Range:";
thirdParameter = "Health:";
fourthParameter = "Flying speed";
}
else if (unitType.isDefenseShootingBuilding) {
if (unitData.isAntiAir1 == 1) {
firstParameter = "Damage per second:";
}
else {
firstParameter = "Damage per second:";
}
secondParameter = "Damage per shot:";
thirdParameter = "Range:";
fourthParameter = "Health:";
fifthParameter = "Sight range:";
}
else if (unitType.isDefenseShootingBuildingDpsOnly) {
firstParameter = "Damage per second:";
secondParameter = "Range:";
thirdParameter = "Health:";
fourthParameter = "Sight range:";
}
else if (unitType.isEnergySupplier) {
firstParameter = "Health:"
}
else if (unitType.isMetalSupplier) {
firstParameter = "Build Speed:"
secondParameter = ""
thirdParameter = "Health:";
}
else if (unitType.isRadarAndJammerUnit) {
firstParameter = "Radar range:";
secondParameter = "Jammer range:";
thirdParameter = "Health:";
fourthParameter = "Movement speed:";
fifthParameter = "Sight range:";
}
else if (unitType.isRadarAndJammerAircraft) {
firstParameter = "Radar range:";
secondParameter = "Jammer range:";
thirdParameter = "Health:";
fourthParameter = "Flying speed:";
fifthParameter = "Sight range:";
}
else if (unitType.isRadarAndJammerBuilding) {
firstParameter = "Radar range";
secondParameter = "Jammer range:";
thirdParameter = "Health:";
fourthParameter = "Sight range:";
}
else if (unitType.isRadarBuilding) {
firstParameter = "Radar range:";
secondParameter = "Health:";
thirdParameter = "Sight range:";
}
else if (unitType.isRadarUnit) {
firstParameter = "Radar range:";
secondParameter = "Health:";
thirdParameter = "Movement speed:";
fourthParameter = "Sight range:";
}
else if (unitType.isJammerBuilding) {
firstParameter = "Jammer range:";
secondParameter = "Health:";
thirdParameter = "Sight range:";
}
else if (unitType.isJammerUnit) {
firstParameter = "Jammer range:";
secondParameter = "Health:";
thirdParameter = "Movement speed:";
fourthParameter = "Sight range:";
}
else if (unitType.isJammerAircraft) {
firstParameter = "Jammer range:";
secondParameter = "Health:";
thirdParameter = "Flying speed:";
fourthParameter = "Sight range:";
}
else if (unitType.isUndefinedUnit) {
firstParameter = "Health:";
secondParameter = "Movement speed:";
thirdParameter = "Sight range:";
}
else if (unitType.isUndefinedAircraft) {
firstParameter = "Health:";
secondParameter = "Flying speed:";
thirdParameter = "Sight range:";
}
else if (unitType.isUndefinedBuilding) {
firstParameter = "Health:";
thirdParameter = "Sight range:";
}
else {// undefined building
firstParameter = "Health:";
secondParameter = "Sight range:";
}
}
function checkUnitType() {
var unitTypeObj = {
isFighter: false,
isFighterDpsOnly: false,
isBuilding: false,
isAirFigther: false,
isBomber: false,
isAntiAir: false,
isCons: false,
isAirCons: false,
isSemiCon: false, // rector, flea, etc.
isLab: false,
isEco: false,
isDefenseShootingBuilding: false,
isDefenseShootingBuildingDpsOnly: false,
isRadarBuilding: false, // radar range
isRadarUnit: false, // radar range
isRadarAndJammerAircraft: false,
isRadarAndJammerBuilding: false,
isRadarAndJammerUnit: false,
isRadarBuilding: false,
isJammerUnit: false,
isJammerAircraft: false,
isJammerBuilding: false,
isEnergySupplier: false, // +energy per second (+2500 with adj. bonus)
isMetalSupplier: false, // +max metal per second, energy drain
isMine: false,
isClawlingBomb: false,
isNuke: false,
isBuildingType:false,
isUndefined: false,
}
if (unitData.builder != 1 && (unitData.jammerRange == "" || unitData.jammerRange == "0") && unitData.canAttack == 1 && unitData.isMineOrClawlingBomb != 1 && unitData.canMove == 1 && unitData.movementSpeed < 4 && unitData.name != "Decimator" && unitData.name != "Mechanic") { // is fighting unit/building?
if (unitData.name == "Voyeur" || unitData.name == "Marky" || unitData.name == "Seer" || unitData.name == "Informer") {
unitTypeObj.isRadarUnit = true;
}
else if (unitData.canMove == 1) {
if (unitData.onlyDps == 1)
unitTypeObj.isFighterDpsOnly = true;
else {
if (unitData.name == "Croc" || unitData.name == "Gimp" || unitData.name == "Triton" || unitData.name == "Defiler") {
unitData.HP = unitData.HP / 4;
}
unitTypeObj.isFighter = true;
}
}
}
else if (unitData.builder != 0 && unitData.builder != "" && (unitData.jammerRange == "" || unitData.jammerRange == "0") && unitData.movementSpeed != "" || unitData.name == "Mechanic") // is cons, semi-con
{
if (unitData.builder != 0 && unitData.canMove == 1 && unitData.canBuild != "" && unitData.movementSpeed < 4 || unitData.name == "Mechanic") {
if (unitData.name == "Podger" || unitData.name == "Spoiler") {
unitData.HP = unitData.HP / 4;
}
if (unitData.name.includes("Commander")) {
unitTypeObj.isCom = true;
} else {
unitTypeObj.isCons = true;
}
}
else if (unitData.movementSpeed > 4) {
unitTypeObj.isAirCons = true;
}
else if (unitData.canMove == 1 && unitData.canBuild == "") {
unitTypeObj.isSemiCon = true;
}
}
else if (unitData.movementSpeed >= 3.15 && unitData.jammerRange == "") { // is air figthing unit?
if (unitData.name == "Peeper" || unitData.name == "Fink" || unitData.name == "Sky Crane" || unitData.name == "Emissary" || unitData.name == "Valkyrie" || unitData.name == "Atlas") {
unitTypeObj.isUndefinedAircraft = true;
}
else if (unitData.reloadTime_w1 == undefined) {
unitTypeObj.isBomber = true;
}
else {
unitTypeObj.isAirFigther = true;
}
}
else if (unitData.movementSpeed < 0.5 || unitData.movementSpeed == "" && unitData.isMineOrClawlingBomb != 1) { // is building?
unitTypeObj.isBuildingType = true;
if (unitData.canMove == 1) {
unitTypeObj.isLab = true;
}
else if (unitData.canAttack == 1) {
if (unitData.name == "Geothermal Powerplant") {
unitTypeObj.isEco = true;
}
else if (unitData.name == "Galactic Gate") {
unitTypeObj.isUndefinedBuilding = true;
}
else if (unitData.name == "Retaliator" || unitData.name == "Neutralizer" || unitData.name == "Silencer" || unitData.name == "Repulsor") { // is nuke?
unitTypeObj.isNuke = true;
}
else {
if (unitData.onlyDps == 1)
unitTypeObj.isDefenseShootingBuildingDpsOnly = true;
else {
unitTypeObj.isDefenseShootingBuilding = true;
}
}
}
else if (unitData.radarRange != 0 && unitData.radarRange != "") { // is radar or jammer building?
if (unitData.radarRange != 0 && unitData.jammerRange != "") {
unitTypeObj.isRadarAndJammerBuilding = true;
}
else {
unitTypeObj.isRadarBuilding = true;
}
}
else if (unitData.jammerRange != "" && (unitData.name != "Surveyor" || unitData.name != "Scanner")) { // is jammer building?
unitTypeObj.isJammerBuilding = true;
}
else if (unitData.isEco) {
unitTypeObj.isEco = true;
if (unitData.minEnergyIncome != undefined) {
unitTypeObj.isEnergySupplier = true;
}
else {
unitTypeObj.isMetalSupplier = true;
}
}
else {
unitTypeObj.isBuilding = true;
}
}
else if (unitData.isMineOrClawlingBomb == 1) { // is mine or crawling bomb?
if (unitData.canMove == 1)
unitTypeObj.isClawlingBomb = true;
else {
unitTypeObj.isMine = true;
}
}
else if (unitData.radarRange != 0 && unitData.radarRange != "" && unitData.radarRange > 100) { // is radar unit or radar+jammer unit?
if (unitData.jammerRange != "" && unitData.movementSpeed > 4) {
if (unitData.radarRange > 200) {
unitTypeObj.isRadarAndJammerAircraft = true;
}
else {
unitTypeObj.isJammerAircraft = true;
}
}
else if (unitData.jammerRange != "" && unitData.movementSpeed < 3) {
unitTypeObj.isRadarAndJammerUnit = true;
}
else if (unitData.radarRange > 400 && unitData.canMove == 1) {
unitTypeObj.isRadarUnit = true;
}
}
else if (unitData.jammerRange != "") { // is jammer only unit?
if (unitData.jammerRange != "" && unitData.movementSpeed > 4) {
unitTypeObj.isJammerAircraft = true;
}
else if (unitData.jammerRange != "" && unitData.canMove == 1) {
unitTypeObj.isJammerUnit = true;
}
}
else {
if (unitData.movementSpeed > 0.5 && unitData.movementSpeed < 4) {
unitTypeObj.isUndefinedUnit = true;
}
else if (unitData.movementSpeed >= 4) {
unitTypeObj.isUndefinedAircraft = true;
} else {
unitTypeObj.isUndefined = true;
}
}
return unitTypeObj;
}<file_sep>/unit-parameters.js
var unitData = {
name: '',
energyCost: '',
metalCost: '',
HP: 10,
movementSpeed: 3,
flyingSpeed: 10,
description: '',
canMove: '',
canAttack: '',
energyStorage: '',
energyMake: '',
metalMake: '',
imgSrc: '',
side: '',
acceleration: '',
summoningCode: '',
sightRange: 0,
dps: "",
range: "",
biggestRange: "", //biggest of few weapons
dps: "",
buildRange: "",
canBuild: "",
radarRange: "",
jammerRange: "",
isMineOrClawlingBomb: 0,
explosionDamage: "",
maxDamagePerShot: "", // biggest of few weapons
builder:"",
isAntiAir1:"",
isAntiAir2:"",
isAntiAir3:"",
isEco:false,
minEnergyIncome:"",
maxEnergyIncome:"",
maxMetalCostForE:"",
minMetalCostForE:"",
ratioMin:"",
ratioMax: "",
reloadTime_w1: "",
reloadTime_w2: "",
reloadTime_w3: "",
sup1: "",
sup2: "",
p1:"",
p2:"",
p3:"",
p4: "",
weapon1ObjectName:"",
weapon2ObjectName:"",
weapon3ObjectName: "",
onlyDps: "",
buildTime: "",
energyMake: "",
energyUse: "",
turnRate: "",
cloakCost: "",
energyStorage: "",
metalStorage: ""
}
var weaponsData = {
w1 : {
objName: "",
name: "",
tolerance: "",
aoe: "",
velocity: "",
turnRate: "",
energyPerShot: ""
},
w2 : {
objName: "",
name: "",
tolerance: "",
aoe: "",
velocity: "",
turnRate: "",
energyPerShot: ""
},
w3 : {
objName: "",
name: "",
tolerance: "",
aoe: "",
velocity: "",
turnRate: "",
energyPerShot: ""
}
}
var keywords = ["Cloakable", "Self-Heal", "Self Heal", "Anti-Stun", "Stealth", "Amphibious", "Stun Immunity", "Upgradable", "Adjacency Bonus", "Stun Resistance", "Guided", "Radar Jammed", "Targeting", "Upgrades to Chaingun", "AA missiles", "Adj. Bonus"]
var ShineEffect = { //only for bars with 10/10
ForDPS: "",
ForDPS2: "",
ForDPS3: "",
ForDamagePerShot: "",
ForDamagePerShot1: "",
ForDamagePerShot2: "",
ForHP :"",
ForMS :"",
ForFS :"", // flying speed
ForRange: "",
ForRange2: "",
ForRange3: "",
ForSightD :"",
ForBuildSpeed :"",
ForExplosionDamage: "",
ForExplosionRange: "",
ForMaxMetalCostForE: "",
ForMinMetalCostForE: "",
ForRadarRange: "",
ForJammerRange:""
}
var boxShadowsStyleDps = ""; //only for bars with 10/10
var boxShadowsStyleDps2 = "";
var boxShadowsStyleDps3 = "";
var boxShadowsStyleDamagePerShot = "";
var boxShadowsStyleDamagePerShot2 = "";
var boxShadowsStyleDamagePerShot3 = "";
var boxShadowsStyleRange = "";
var boxShadowsStyleRange2 = "";
var boxShadowsStyleRange3 = "";
var boxShadowsStyleMovementSpeed = "";
var boxShadowsStyleFlyingSpeed = "";
var boxShadowsStyleHP = "";
var boxShadowsStylesightRange = "";
var boxShadowsStyleBuildSpeed = "";
var boxShadowsStyleBuildRange = "";
var boxShadowsStyleRadarRange = "";
var boxShadowsStyleJammerRange = "";
var boxShadowsStyleExplosionDamage = "";
var boxShadowsMinMetalCostForE = "";
var boxShadowsMaxMetalCostForE = "";
var boxShadowsStyleExplosionRange = "";
var x;
var y;
var screenWidth; //available user's screen width
var screenHeight; //available user's screen height, excluding toolbars etc.
var framePreviewHeight;
var previewPosition = {
top: 0,
left: 0
};
var unitTypeObj;
var pulsingStyle = "box-shadow: 0px 0px 12px #5EE947;";
var barHP_SrcImg;
var movementSpeed_SrcImg;
var flyingSpeed_SrcImg;
var dps_SrcImg;
var dps2_SrcImg;// for 2nd weapon in detailed info
var dps3_SrcImg;// for 3rd weapon
var damagePerShot_SrcImg;
var damagePerShot2_SrcImg;
var damagePerShot3_SrcImg;
var range_SrcImg;
var range2_SrcImg;
var range3_SrcImg;
var buildSpeed_SrcImg;
var explosionDamage_SrcImg;
var buildRange_SrcImg;
var sightRange_SrcImg;
var jammerRange_SrcImg;
var radarRange_SrcImg;
var explosionRange_SrcImg;
var maxMetalCostForE_SrcImg;
var minMetalCostForE_SrcImg;
var firstParameter = "";
var secondParameter = "";
var thirdParameter="";
var fourthParameter="";
var fifthParameter="";
var sixthParameter="";
var rangeOfParameters ={
dps : {
h0: 10,
h05: 30,
h1: 60,
h15: 90,
h2: 105,
h25: 120,
h3: 150,
h35: 200,
h4: 240,
h45: 300,
h5: 400,
h55: 600,
h6: 800,
h65: 1200,
h7: 1500,
h75: 1800,
h8: 2100,
h85: 3000,
h9: 5000,
h95: 8000,
h10: 20000
},
damagePerShot: {
h0: 20,
h05: 30,
h1: 60,
h15: 90,
h2: 120,
h25: 180,
h3: 250,
h35: 320,
h4: 400,
h45: 500,
h5: 650,
h55: 790,
h6: 850,
h65: 990,
h7: 1100,
h75: 1400,
h8: 1900,
h85: 2500,
h9: 3500,
h95: 4900,
h10: 100000
},
range : {
h0: 120,
h05: 160,
h1: 180,
h15: 220,
h2: 250,
h25: 280,
h3: 310,
h35: 399,
h4: 500,
h45: 570,
h5: 650,
h55: 750,
h6: 850,
h65: 970,
h7: 1050,
h75: 1200,
h8: 1320,
h85: 1500,
h9: 2200,
h95: 6000,
h10: 20000
},
explosionRange: {
h0: 20,
h2: 128,
h4: 256,
h6: 320,
h8: 480,
h10: 720
},
HP : {
h0: 8,
h05: 200,
h1: 384,
h15: 525,
h2: 856,
h25: 1355,
h3: 1988,
h35: 2840,
h4: 4060,
h45: 4900,
h5: 5985,
h55: 10000,
h6: 15000,
h65: 20000,
h7: 34000,
h75: 80000,
h8: 120000,
h85: 150000,
h9: 181000,
h95: 250000,
h10: 2000000
},
movementSpeed : {
h0: 0,
h05: 0.65,
h1: 0.675,
h15: 0.75,
h2: 0.825,
h25: 0.9,
h3: 0.975,
h35: 1.05,
h4: 1.1,
h45: 1.2,
h5: 1.275,
h55: 1.35,
h6: 1.5,
h65: 1.7,
h7: 1.8,
h75: 2,
h8: 2.15,
h85: 2.4,
h9: 2.7,
h95: 3,
h10: 3.3
},
flyingSpeed : {
h0: 4,
h05: 4.8,
h1: 5,
h15: 6.3,
h2: 6.5,
h25: 0.9,
h3: 6.75,
h35: 7,
h4: 7.2,
h45: 7.5,
h5: 9,
h55: 9.2,
h6: 9.5,
h65: 9.7,
h7: 10,
h75: 10.5,
h8: 11,
h85: 11.25,
h9: 12,
h95: 13,
h10: 14
},
sightRange : {
h0: 64,
h05: 96,
h1: 128,
h15: 192,
h2: 224,
h25: 256,
h3: 288,
h35: 320,
h4: 352,
h45: 384,
h5: 448,
h55: 480,
h6: 512,
h65: 576,
h7: 672,
h75: 768,
h8: 896,
h85: 1024,
h9: 1344,
h95: 1536,
h10: 1792
},
buildSpeed : {
h0: 0,
h05: 30,
h1: 60,
h15: 90,
h2: 120,
h25: 150,
h3: 180,
h35: 210,
h4: 240,
h45: 270,
h5: 300,
h55: 360,
h6: 390,
h65: 420,
h7: 450,
h75: 480,
h8: 510,
h85: 570,
h9: 630,
h95: 720,
h10: 10000
},
buildRange : {
h0: 0,
h05: 40,
h1: 60,
h2: 80,
h3: 100,
h4: 120,
h5: 140,
h6: 180,
h7: 200,
h8: 240,
h9: 300,
h10: 400
},
damageExplosion : {
h2: 1200,
h4: 2400,
h6: 4800,
h8: 9600,
h10: 19200
},
energyMetalCostRatio : {
h1: 9,
h2: 7.2,
h3: 6,
h4: 5,
h5: 4,
h6: 3.5,
h7: 2.8,
h8: 2.3,
h9: 1.9,
h10: 1.6
},
radarRange: {
h0: 400,
h05: 700,
h1: 1000,
h15: 1350,
h2: 1600,
h25: 1760,
h3: 2000,
h35: 2500,
h4: 2800,
h45: 3200,
h5: 4000,
h55: 4500,
h6: 5000,
h65: 5500,
h7: 6000,
h75: 6400,
h8: 6600,
h85: 6800,
h9: 6990,
h95: 7100,
h10: 10000
},
jammerRange: {
h0: 200,
h05: 250,
h1: 300,
h15: 400,
h2: 450,
h25: 500,
h3: 600,
h35: 650,
h4: 700,
h45: 750,
h5: 800,
h55: 850,
h6: 900,
h65: 1000,
h7: 1100,
h75: 1150,
h8: 1200,
h85: 1300,
h9: 1400,
h95: 1600,
h10: 10000
}
}
function setParameterBars(){
// for HP
if(unitData.HP <= rangeOfParameters.HP.h0){
barHP_SrcImg="parameter-bars/0.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h05){
barHP_SrcImg="parameter-bars/0.5.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h1){
barHP_SrcImg="parameter-bars/1.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h15){
barHP_SrcImg="parameter-bars/1.5.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h2){
barHP_SrcImg="parameter-bars/2.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h25){
barHP_SrcImg="parameter-bars/2.5.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h3){
barHP_SrcImg="parameter-bars/3.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h35){
barHP_SrcImg="parameter-bars/3.5.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h4){
barHP_SrcImg="parameter-bars/4.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h45){
barHP_SrcImg="parameter-bars/4.5.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h5){
barHP_SrcImg="parameter-bars/5.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h55){
barHP_SrcImg="parameter-bars/5.5.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h6){
barHP_SrcImg="parameter-bars/6.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h65){
barHP_SrcImg="parameter-bars/6.5.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h7){
barHP_SrcImg="parameter-bars/7.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h75){
barHP_SrcImg="parameter-bars/7.5.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h8){
barHP_SrcImg="parameter-bars/8.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h85){
barHP_SrcImg="parameter-bars/8.5.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h9){
barHP_SrcImg="parameter-bars/9.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h95){
barHP_SrcImg="parameter-bars/9.5.svg";
}
else if(unitData.HP <= rangeOfParameters.HP.h10){
barHP_SrcImg="parameter-bars/10.svg";
boxShadowsStyleHP = pulsingStyle;
ShineEffect.ForHP = "shine-effect";
}
// for DPS
if(unitData.dps =="Too random to show"){
dps_SrcImg="parameter-bars/0.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h0){
dps_SrcImg="parameter-bars/0.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h05){
dps_SrcImg="parameter-bars/0.5.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h1){
dps_SrcImg="parameter-bars/1.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h15){
dps_SrcImg="parameter-bars/1.5.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h2){
dps_SrcImg="parameter-bars/2.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h25){
dps_SrcImg="parameter-bars/2.5.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h3){
dps_SrcImg="parameter-bars/3.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h35){
dps_SrcImg="parameter-bars/3.5.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h4){
dps_SrcImg="parameter-bars/4.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h45){
dps_SrcImg="parameter-bars/4.5.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h5){
dps_SrcImg="parameter-bars/5.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h55){
dps_SrcImg="parameter-bars/5.5.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h6){
dps_SrcImg="parameter-bars/6.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h65){
dps_SrcImg="parameter-bars/6.5.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h7){
dps_SrcImg="parameter-bars/7.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h75){
dps_SrcImg="parameter-bars/7.5.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h8){
dps_SrcImg="parameter-bars/8.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h85){
dps_SrcImg="parameter-bars/8.5.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h9){
dps_SrcImg="parameter-bars/9.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h95){
dps_SrcImg="parameter-bars/9.5.svg";
}
else if(unitData.overallDps <= rangeOfParameters.dps.h10){
dps_SrcImg="parameter-bars/10.svg";
boxShadowsStyleDps = pulsingStyle;
ShineEffect.ForDPS = "shine-effect";
}
// for range
if(unitData.biggestRange <= rangeOfParameters.range.h0){
range_SrcImg="parameter-bars/0.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h05){
range_SrcImg="parameter-bars/0.5.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h1){
range_SrcImg="parameter-bars/1.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h15){
range_SrcImg="parameter-bars/1.5.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h2){
range_SrcImg="parameter-bars/2.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h25){
range_SrcImg="parameter-bars/2.5.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h3){
range_SrcImg="parameter-bars/3.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h35){
range_SrcImg="parameter-bars/3.5.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h4){
range_SrcImg="parameter-bars/4.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h45){
range_SrcImg="parameter-bars/4.5.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h5){
range_SrcImg="parameter-bars/5.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h55){
range_SrcImg="parameter-bars/5.5.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h6){
range_SrcImg="parameter-bars/6.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h65){
range_SrcImg="parameter-bars/6.5.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h7){
range_SrcImg="parameter-bars/7.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h75){
range_SrcImg="parameter-bars/7.5.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h8){
range_SrcImg="parameter-bars/8.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h85){
range_SrcImg="parameter-bars/8.5.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h9){
range_SrcImg="parameter-bars/9.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h95){
range_SrcImg="parameter-bars/9.5.svg";
}
else if(unitData.biggestRange <= rangeOfParameters.range.h10){
range_SrcImg="parameter-bars/10.svg";
boxShadowsStyleRange = pulsingStyle;
ShineEffect.ForRange = "shine-effect";
}
// for explosion range
if (unitData.biggestRange <= rangeOfParameters.explosionRange.h0) {
explosionRange_SrcImg = "parameter-bars/0.svg";
}
else if (unitData.biggestRange <= rangeOfParameters.explosionRange.h2) {
explosionRange_SrcImg = "parameter-bars/2.svg";
}
else if (unitData.biggestRange <= rangeOfParameters.explosionRange.h4) {
explosionRange_SrcImg = "parameter-bars/4.svg";
}
else if (unitData.biggestRange <= rangeOfParameters.explosionRange.h6) {
explosionRange_SrcImg = "parameter-bars/6.svg";
}
else if (unitData.biggestRange <= rangeOfParameters.explosionRange.h8) {
explosionRange_SrcImg = "parameter-bars/8.svg";
}
else if (unitData.biggestRange <= rangeOfParameters.explosionRange.h10) {
explosionRange_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleExplosionRange = pulsingStyle;
ShineEffect.ForExplosionRange = "shine-effect";
}
// for movement speed
if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h0){
movementSpeed_SrcImg="parameter-bars/0.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h05){
movementSpeed_SrcImg="parameter-bars/0.5.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h1){
movementSpeed_SrcImg="parameter-bars/1.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h15){
movementSpeed_SrcImg="parameter-bars/1.5.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h2){
movementSpeed_SrcImg="parameter-bars/2.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h25){
movementSpeed_SrcImg="parameter-bars/2.5.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h3){
movementSpeed_SrcImg="parameter-bars/3.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h35){
movementSpeed_SrcImg="parameter-bars/3.5.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h4){
movementSpeed_SrcImg="parameter-bars/4.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h45){
movementSpeed_SrcImg="parameter-bars/4.5.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h5){
movementSpeed_SrcImg="parameter-bars/5.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h55){
movementSpeed_SrcImg="parameter-bars/5.5.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h6){
movementSpeed_SrcImg="parameter-bars/6.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h65){
movementSpeed_SrcImg="parameter-bars/6.5.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h7){
movementSpeed_SrcImg="parameter-bars/7.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h75){
movementSpeed_SrcImg="parameter-bars/7.5.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h8){
movementSpeed_SrcImg="parameter-bars/8.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h85){
movementSpeed_SrcImg="parameter-bars/8.5.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h9){
movementSpeed_SrcImg="parameter-bars/9.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h95){
movementSpeed_SrcImg="parameter-bars/9.5.svg";
}
else if(unitData.movementSpeed <= rangeOfParameters.movementSpeed.h10){
movementSpeed_SrcImg="parameter-bars/10.svg";
boxShadowsStyleMovementSpeed = pulsingStyle;
ShineEffect.ForMS = "shine-effect";
}
// for flying speed
if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h0){
flyingSpeed_SrcImg="parameter-bars/0.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h05){
flyingSpeed_SrcImg="parameter-bars/0.5.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h1){
flyingSpeed_SrcImg="parameter-bars/1.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h15){
flyingSpeed_SrcImg="parameter-bars/1.5.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h2){
flyingSpeed_SrcImg="parameter-bars/2.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h25){
flyingSpeed_SrcImg="parameter-bars/2.5.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h3){
flyingSpeed_SrcImg="parameter-bars/3.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h35){
flyingSpeed_SrcImg="parameter-bars/3.5.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h4){
flyingSpeed_SrcImg="parameter-bars/4.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h45){
flyingSpeed_SrcImg="parameter-bars/4.5.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h5){
flyingSpeed_SrcImg="parameter-bars/5.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h55){
flyingSpeed_SrcImg="parameter-bars/5.5.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h6){
flyingSpeed_SrcImg="parameter-bars/6.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h65){
flyingSpeed_SrcImg="parameter-bars/6.5.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h7){
flyingSpeed_SrcImg="parameter-bars/7.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h75){
flyingSpeed_SrcImg="parameter-bars/7.5.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h8){
flyingSpeed_SrcImg="parameter-bars/8.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h85){
flyingSpeed_SrcImg="parameter-bars/8.5.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h9){
flyingSpeed_SrcImg="parameter-bars/9.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h95){
flyingSpeed_SrcImg="parameter-bars/9.5.svg";
}
else if(unitData.flyingSpeed <= rangeOfParameters.flyingSpeed.h10){
flyingSpeed_SrcImg="parameter-bars/10.svg";
boxShadowsStyleFlyingSpeed = pulsingStyle;
ShineEffect.ForFS = "shine-effect";
}
// for sight distance
if(unitData.sightRange <= rangeOfParameters.sightRange.h0){
sightRange_SrcImg="parameter-bars/0.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h05){
sightRange_SrcImg="parameter-bars/0.5.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h1){
sightRange_SrcImg="parameter-bars/1.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h15){
sightRange_SrcImg="parameter-bars/1.5.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h2){
sightRange_SrcImg="parameter-bars/2.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h25){
sightRange_SrcImg="parameter-bars/2.5.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h3){
sightRange_SrcImg="parameter-bars/3.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h35){
sightRange_SrcImg="parameter-bars/3.5.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h4){
sightRange_SrcImg="parameter-bars/4.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h45){
sightRange_SrcImg="parameter-bars/4.5.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h5){
sightRange_SrcImg="parameter-bars/5.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h55){
sightRange_SrcImg="parameter-bars/5.5.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h6){
sightRange_SrcImg="parameter-bars/6.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h65){
sightRange_SrcImg="parameter-bars/6.5.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h7){
sightRange_SrcImg="parameter-bars/7.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h75){
sightRange_SrcImg="parameter-bars/7.5.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h8){
sightRange_SrcImg="parameter-bars/8.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h85){
sightRange_SrcImg="parameter-bars/8.5.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h9){
sightRange_SrcImg="parameter-bars/9.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h95){
sightRange_SrcImg="parameter-bars/9.5.svg";
}
else if(unitData.sightRange <= rangeOfParameters.sightRange.h10){
sightRange_SrcImg="parameter-bars/10.svg";
boxShadowsStylesightRange = pulsingStyle;
ShineEffect.ForSightD = "shine-effect";
}
// for build speed
if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h0){
buildSpeed_SrcImg="parameter-bars/0.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h05){
buildSpeed_SrcImg="parameter-bars/0.5.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h1){
buildSpeed_SrcImg="parameter-bars/1.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h15){
buildSpeed_SrcImg="parameter-bars/1.5.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h2){
buildSpeed_SrcImg="parameter-bars/2.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h25){
buildSpeed_SrcImg="parameter-bars/2.5.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h3){
buildSpeed_SrcImg="parameter-bars/3.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h35){
buildSpeed_SrcImg="parameter-bars/3.5.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h4){
buildSpeed_SrcImg="parameter-bars/4.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h45){
buildSpeed_SrcImg="parameter-bars/4.5.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h5){
buildSpeed_SrcImg="parameter-bars/5.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h55){
buildSpeed_SrcImg="parameter-bars/5.5.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h6){
buildSpeed_SrcImg="parameter-bars/6.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h65){
buildSpeed_SrcImg="parameter-bars/6.5.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h7){
buildSpeed_SrcImg="parameter-bars/7.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h75){
buildSpeed_SrcImg="parameter-bars/7.5.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h8){
buildSpeed_SrcImg="parameter-bars/8.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h85){
buildSpeed_SrcImg="parameter-bars/8.5.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h9){
buildSpeed_SrcImg="parameter-bars/9.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h95){
buildSpeed_SrcImg="parameter-bars/9.5.svg";
}
else if(unitData.buildSpeed <= rangeOfParameters.buildSpeed.h10){
buildSpeed_SrcImg="parameter-bars/10.svg";
boxShadowsStylesightRange = pulsingStyle;
ShineEffect.ForBuildSpeed = "shine-effect";
}
// for build range
if(unitData.buildRange <= rangeOfParameters.buildRange.h0){
buildRange_SrcImg="parameter-bars/0.svg";
}
else if(unitData.buildRange <= rangeOfParameters.buildRange.h05){
buildRange_SrcImg="parameter-bars/0.5.svg";
}
else if(unitData.buildRange <= rangeOfParameters.buildRange.h1){
buildRange_SrcImg="parameter-bars/1.svg";
}
else if(unitData.buildRange <= rangeOfParameters.buildRange.h2){
buildRange_SrcImg="parameter-bars/2.svg";
}
else if(unitData.buildRange <= rangeOfParameters.buildRange.h3){
buildRange_SrcImg="parameter-bars/3.svg";
}
else if(unitData.buildRange <= rangeOfParameters.buildRange.h4){
buildRange_SrcImg="parameter-bars/4.svg";
}
else if(unitData.buildRange <= rangeOfParameters.buildRange.h5){
buildRange_SrcImg="parameter-bars/5.svg";
}
else if(unitData.buildRange <= rangeOfParameters.buildRange.h6){
buildRange_SrcImg="parameter-bars/6.svg";
}
else if(unitData.buildRange <= rangeOfParameters.buildRange.h7){
buildRange_SrcImg="parameter-bars/7.svg";
}
else if(unitData.buildRange <= rangeOfParameters.buildRange.h8){
buildRange_SrcImg="parameter-bars/8.svg";
}
else if(unitData.buildRange <= rangeOfParameters.buildRange.h9){
buildRange_SrcImg="parameter-bars/9.svg";
}
else if(unitData.buildRange <= rangeOfParameters.buildRange.h10){
buildRange_SrcImg="parameter-bars/10.svg";
boxShadowsStyleBuildRange = pulsingStyle;
ShineEffect.ForBuildRange = "shine-effect";
}
// for Explosion Damage
if(unitData.explosionDamage <= rangeOfParameters.damageExplosion.h2){
explosionDamage_SrcImg="parameter-bars/2.svg";
}
else if(unitData.explosionDamage <= rangeOfParameters.damageExplosion.h4){
explosionDamage_SrcImg="parameter-bars/4.svg";
}
else if(unitData.explosionDamage <= rangeOfParameters.damageExplosion.h6){
explosionDamage_SrcImg="parameter-bars/6.svg";
}
else if(unitData.explosionDamage <= rangeOfParameters.damageExplosion.h8){
explosionDamage_SrcImg="parameter-bars/8.svg";
}
else if(unitData.explosionDamage <= rangeOfParameters.damageExplosion.h10){
explosionDamage_SrcImg="parameter-bars/10.svg";
boxShadowsStyleExplosionDamage = pulsingStyle;
ShineEffect.ForExplosionDamage = "shine-effect";
}
// for MIN Energy income / metal cost RATIO
if(unitData.minMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h1){
minMetalCostForE_SrcImg="parameter-bars/1.svg";
}
else if(unitData.minMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h2){
minMetalCostForE_SrcImg="parameter-bars/2.svg";
}
else if(unitData.minMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h3){
minMetalCostForE_SrcImg="parameter-bars/3.svg";
}
else if(unitData.minMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h4){
minMetalCostForE_SrcImg="parameter-bars/4.svg";
}
else if(unitData.minMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h5){
minMetalCostForE_SrcImg="parameter-bars/5.svg";
}
else if(unitData.minMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h6){
minMetalCostForE_SrcImg="parameter-bars/6.svg";
}
else if(unitData.minMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h7){
minMetalCostForE_SrcImg="parameter-bars/7.svg";
}
else if(unitData.minMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h8){
minMetalCostForE_SrcImg="parameter-bars/8.svg";
}
else if(unitData.minMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h9){
minMetalCostForE_SrcImg="parameter-bars/9.svg";
}
else if(unitData.minMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h10){
minMetalCostForE_SrcImg="parameter-bars/10.svg";
boxShadowsMinMetalCostForE = pulsingStyle;
ShineEffect.ForMinMetalCostForE = "shine-effect";
}
// for MAX Energy income / metal cost RATIO
if(unitData.maxMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h1){
maxMetalCostForE_SrcImg="parameter-bars/1.svg";
}
else if(unitData.maxMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h2){
maxMetalCostForE_SrcImg="parameter-bars/2.svg";
}
else if(unitData.maxMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h3){
maxMetalCostForE_SrcImg="parameter-bars/3.svg";
}
else if(unitData.maxMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h4){
maxMetalCostForE_SrcImg="parameter-bars/4.svg";
}
else if(unitData.maxMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h5){
maxMetalCostForE_SrcImg="parameter-bars/5.svg";
}
else if(unitData.maxMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h6){
maxMetalCostForE_SrcImg="parameter-bars/6.svg";
}
else if(unitData.maxMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h7){
maxMetalCostForE_SrcImg="parameter-bars/7.svg";
}
else if(unitData.maxMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h8){
maxMetalCostForE_SrcImg="parameter-bars/8.svg";
}
else if(unitData.maxMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h9){
maxMetalCostForE_SrcImg="parameter-bars/9.svg";
}
else if(unitData.maxMetalCostForE >= rangeOfParameters.energyMetalCostRatio.h10){
maxMetalCostForE_SrcImg="parameter-bars/10.svg";
boxShadowsMaxMetalCostForE = pulsingStyle;
ShineEffect.ForMaxMetalCostForE = "shine-effect";
}
//damage per shot
if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h0) {
damagePerShot_SrcImg = "parameter-bars/0.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h05) {
damagePerShot_SrcImg = "parameter-bars/0.5.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h1) {
damagePerShot_SrcImg = "parameter-bars/1.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h15) {
damagePerShot_SrcImg = "parameter-bars/1.5.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h2) {
damagePerShot_SrcImg = "parameter-bars/2.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h25) {
damagePerShot_SrcImg = "parameter-bars/2.5.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h3) {
damagePerShot_SrcImg = "parameter-bars/3.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h35) {
damagePerShot_SrcImg = "parameter-bars/3.5.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h4) {
damagePerShot_SrcImg = "parameter-bars/4.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h45) {
damagePerShot_SrcImg = "parameter-bars/4.5.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h5) {
damagePerShot_SrcImg = "parameter-bars/5.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h55) {
damagePerShot_SrcImg = "parameter-bars/5.5.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h6) {
damagePerShot_SrcImg = "parameter-bars/6.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h65) {
damagePerShot_SrcImg = "parameter-bars/6.5.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h7) {
damagePerShot_SrcImg = "parameter-bars/7.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h75) {
damagePerShot_SrcImg = "parameter-bars/7.5.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h8) {
damagePerShot_SrcImg = "parameter-bars/8.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h85) {
damagePerShot_SrcImg = "parameter-bars/8.5.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h9) {
damagePerShot_SrcImg = "parameter-bars/9.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h95) {
damagePerShot_SrcImg = "parameter-bars/9.5.svg";
}
else if (unitData.maxDamagePerShot <= rangeOfParameters.damagePerShot.h10) {
damagePerShot_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleDamagePerShot = pulsingStyle;
ShineEffect.ForDamagePerShot = "shine-effect";
}
//radar range
if (unitData.radarRange <= rangeOfParameters.radarRange.h0) {
radarRange_SrcImg = "parameter-bars/0.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h05) {
radarRange_SrcImg = "parameter-bars/0.5.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h1) {
radarRange_SrcImg = "parameter-bars/1.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h15) {
radarRange_SrcImg = "parameter-bars/1.5.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h2) {
radarRange_SrcImg = "parameter-bars/2.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h25) {
radarRange_SrcImg = "parameter-bars/2.5.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h3) {
radarRange_SrcImg = "parameter-bars/3.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h35) {
radarRange_SrcImg = "parameter-bars/3.5.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h4) {
radarRange_SrcImg = "parameter-bars/4.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h45) {
radarRange_SrcImg = "parameter-bars/4.5.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h5) {
radarRange_SrcImg = "parameter-bars/5.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h55) {
radarRange_SrcImg = "parameter-bars/5.5.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h6) {
radarRange_SrcImg = "parameter-bars/6.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h65) {
radarRange_SrcImg = "parameter-bars/6.5.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h7) {
radarRange_SrcImg = "parameter-bars/7.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h75) {
radarRange_SrcImg = "parameter-bars/7.5.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h8) {
radarRange_SrcImg = "parameter-bars/8.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h85) {
radarRange_SrcImg = "parameter-bars/8.5.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h9) {
radarRange_SrcImg = "parameter-bars/9.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h95) {
radarRange_SrcImg = "parameter-bars/9.5.svg";
}
else if (unitData.radarRange <= rangeOfParameters.radarRange.h10) {
radarRange_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleRadarRange = pulsingStyle;
ShineEffect.ForRadarRange = "shine-effect";
}
//jammer range
if (unitData.jammerRange <= rangeOfParameters.jammerRange.h0) {
jammerRange_SrcImg = "parameter-bars/0.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h05) {
jammerRange_SrcImg = "parameter-bars/0.5.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h1) {
jammerRange_SrcImg = "parameter-bars/1.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h15) {
jammerRange_SrcImg = "parameter-bars/1.5.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h2) {
jammerRange_SrcImg = "parameter-bars/2.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h25) {
jammerRange_SrcImg = "parameter-bars/2.5.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h3) {
jammerRange_SrcImg = "parameter-bars/3.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h35) {
jammerRange_SrcImg = "parameter-bars/3.5.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h4) {
jammerRange_SrcImg = "parameter-bars/4.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h45) {
jammerRange_SrcImg = "parameter-bars/4.5.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h5) {
jammerRange_SrcImg = "parameter-bars/5.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h55) {
jammerRange_SrcImg = "parameter-bars/5.5.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h6) {
jammerRange_SrcImg = "parameter-bars/6.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h65) {
jammerRange_SrcImg = "parameter-bars/6.5.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h7) {
jammerRange_SrcImg = "parameter-bars/7.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h75) {
jammerRange_SrcImg = "parameter-bars/7.5.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h8) {
jammerRange_SrcImg = "parameter-bars/8.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h85) {
jammerRange_SrcImg = "parameter-bars/8.5.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h9) {
jammerRange_SrcImg = "parameter-bars/9.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h95) {
jammerRange_SrcImg = "parameter-bars/9.5.svg";
}
else if (unitData.jammerRange <= rangeOfParameters.jammerRange.h10) {
jammerRange_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleJammerRange = pulsingStyle;
ShineEffect.ForJammerRange = "shine-effect";
}
}
function setParameterBarsForManyWeapons() {
//damage per shot 1
if (weapons.w1 <= rangeOfParameters.damagePerShot.h0) {
damagePerShot_SrcImg = "parameter-bars/0.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h05) {
damagePerShot_SrcImg = "parameter-bars/0.5.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h1) {
damagePerShot_SrcImg = "parameter-bars/1.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h15) {
damagePerShot_SrcImg = "parameter-bars/1.5.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h2) {
damagePerShot_SrcImg = "parameter-bars/2.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h25) {
damagePerShot_SrcImg = "parameter-bars/2.5.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h3) {
damagePerShot_SrcImg = "parameter-bars/3.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h35) {
damagePerShot_SrcImg = "parameter-bars/3.5.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h4) {
damagePerShot_SrcImg = "parameter-bars/4.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h45) {
damagePerShot_SrcImg = "parameter-bars/4.5.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h5) {
damagePerShot_SrcImg = "parameter-bars/5.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h55) {
damagePerShot_SrcImg = "parameter-bars/5.5.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h6) {
damagePerShot_SrcImg = "parameter-bars/6.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h65) {
damagePerShot_SrcImg = "parameter-bars/6.5.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h7) {
damagePerShot_SrcImg = "parameter-bars/7.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h75) {
damagePerShot_SrcImg = "parameter-bars/7.5.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h8) {
damagePerShot_SrcImg = "parameter-bars/8.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h85) {
damagePerShot_SrcImg = "parameter-bars/8.5.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h9) {
damagePerShot_SrcImg = "parameter-bars/9.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h95) {
damagePerShot_SrcImg = "parameter-bars/9.5.svg";
}
else if (weapons.w1 <= rangeOfParameters.damagePerShot.h10) {
damagePerShot_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleDamagePerShot = pulsingStyle;
ShineEffect.ForDamagePerShot = "shine-effect";
}
//damage per shot 2
if (weapons.w2 <= rangeOfParameters.damagePerShot.h0) {
damagePerShot2_SrcImg = "parameter-bars/0.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h05) {
damagePerShot2_SrcImg = "parameter-bars/0.5.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h1) {
damagePerShot2_SrcImg = "parameter-bars/1.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h15) {
damagePerShot2_SrcImg = "parameter-bars/1.5.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h2) {
damagePerShot2_SrcImg = "parameter-bars/2.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h25) {
damagePerShot2_SrcImg = "parameter-bars/2.5.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h3) {
damagePerShot2_SrcImg = "parameter-bars/3.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h35) {
damagePerShot2_SrcImg = "parameter-bars/3.5.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h4) {
damagePerShot2_SrcImg = "parameter-bars/4.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h45) {
damagePerShot2_SrcImg = "parameter-bars/4.5.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h5) {
damagePerShot2_SrcImg = "parameter-bars/5.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h55) {
damagePerShot2_SrcImg = "parameter-bars/5.5.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h6) {
damagePerShot2_SrcImg = "parameter-bars/6.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h65) {
damagePerShot2_SrcImg = "parameter-bars/6.5.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h7) {
damagePerShot2_SrcImg = "parameter-bars/7.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h75) {
damagePerShot2_SrcImg = "parameter-bars/7.5.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h8) {
damagePerShot2_SrcImg = "parameter-bars/8.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h85) {
damagePerShot2_SrcImg = "parameter-bars/8.5.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h9) {
damagePerShot2_SrcImg = "parameter-bars/9.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h95) {
damagePerShot2_SrcImg = "parameter-bars/9.5.svg";
}
else if (weapons.w2 <= rangeOfParameters.damagePerShot.h10) {
damagePerShot2_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleDamagePerShot2 = pulsingStyle;
ShineEffect.ForDamagePerShot2 = "shine-effect";
}
//damage per shot 3
if (weapons.w3 <= rangeOfParameters.damagePerShot.h0) {
damagePerShot3_SrcImg = "parameter-bars/0.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h05) {
damagePerShot3_SrcImg = "parameter-bars/0.5.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h1) {
damagePerShot3_SrcImg = "parameter-bars/1.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h15) {
damagePerShot3_SrcImg = "parameter-bars/1.5.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h2) {
damagePerShot3_SrcImg = "parameter-bars/2.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h25) {
damagePerShot3_SrcImg = "parameter-bars/2.5.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h3) {
damagePerShot3_SrcImg = "parameter-bars/3.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h35) {
damagePerShot3_SrcImg = "parameter-bars/3.5.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h4) {
damagePerShot3_SrcImg = "parameter-bars/4.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h45) {
damagePerShot3_SrcImg = "parameter-bars/4.5.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h5) {
damagePerShot3_SrcImg = "parameter-bars/5.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h55) {
damagePerShot3_SrcImg = "parameter-bars/5.5.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h6) {
damagePerShot3_SrcImg = "parameter-bars/6.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h65) {
damagePerShot3_SrcImg = "parameter-bars/6.5.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h7) {
damagePerShot3_SrcImg = "parameter-bars/7.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h75) {
damagePerShot3_SrcImg = "parameter-bars/7.5.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h8) {
damagePerShot3_SrcImg = "parameter-bars/8.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h85) {
damagePerShot3_SrcImg = "parameter-bars/8.5.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h9) {
damagePerShot3_SrcImg = "parameter-bars/9.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h95) {
damagePerShot3_SrcImg = "parameter-bars/9.5.svg";
}
else if (weapons.w3 <= rangeOfParameters.damagePerShot.h10) {
damagePerShot3_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleDamagePerShot3 = pulsingStyle;
ShineEffect.ForDamagePerShot3 = "shine-effect";
}
// for DPS 1
if (weapons.w1_dps == "Too random to show") {
dps_SrcImg = "parameter-bars/0.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h05) {
dps_SrcImg = "parameter-bars/0.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h05) {
dps_SrcImg = "parameter-bars/0.5.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h1) {
dps_SrcImg = "parameter-bars/1.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h15) {
dps_SrcImg = "parameter-bars/1.5.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h2) {
dps_SrcImg = "parameter-bars/2.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h25) {
dps_SrcImg = "parameter-bars/2.5.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h3) {
dps_SrcImg = "parameter-bars/3.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h35) {
dps_SrcImg = "parameter-bars/3.5.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h4) {
dps_SrcImg = "parameter-bars/4.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h45) {
dps_SrcImg = "parameter-bars/4.5.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h5) {
dps_SrcImg = "parameter-bars/5.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h55) {
dps_SrcImg = "parameter-bars/5.5.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h6) {
dps_SrcImg = "parameter-bars/6.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h65) {
dps_SrcImg = "parameter-bars/6.5.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h7) {
dps_SrcImg = "parameter-bars/7.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h75) {
dps_SrcImg = "parameter-bars/7.5.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h8) {
dps_SrcImg = "parameter-bars/8.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h85) {
dps_SrcImg = "parameter-bars/8.5.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h9) {
dps_SrcImg = "parameter-bars/9.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h95) {
dps_SrcImg = "parameter-bars/9.5.svg";
}
else if (weapons.w1_dps <= rangeOfParameters.dps.h10) {
dps_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleDps = pulsingStyle;
ShineEffect.ForDPS = "shine-effect";
}
// for DPS 2
if (weapons.w2_dps == "Too random to show") {
dps2_SrcImg = "parameter-bars/0.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h05) {
dps2_SrcImg = "parameter-bars/0.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h05) {
dps2_SrcImg = "parameter-bars/0.5.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h1) {
dps2_SrcImg = "parameter-bars/1.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h15) {
dps2_SrcImg = "parameter-bars/1.5.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h2) {
dps2_SrcImg = "parameter-bars/2.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h25) {
dps2_SrcImg = "parameter-bars/2.5.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h3) {
dps2_SrcImg = "parameter-bars/3.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h35) {
dps2_SrcImg = "parameter-bars/3.5.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h4) {
dps2_SrcImg = "parameter-bars/4.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h45) {
dps2_SrcImg = "parameter-bars/4.5.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h5) {
dps2_SrcImg = "parameter-bars/5.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h55) {
dps2_SrcImg = "parameter-bars/5.5.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h6) {
dps2_SrcImg = "parameter-bars/6.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h65) {
dps2_SrcImg = "parameter-bars/6.5.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h7) {
dps2_SrcImg = "parameter-bars/7.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h75) {
dps2_SrcImg = "parameter-bars/7.5.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h8) {
dps2_SrcImg = "parameter-bars/8.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h85) {
dps2_SrcImg = "parameter-bars/8.5.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h9) {
dps2_SrcImg = "parameter-bars/9.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h95) {
dps2_SrcImg = "parameter-bars/9.5.svg";
}
else if (weapons.w2_dps <= rangeOfParameters.dps.h10) {
dps2_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleDps2 = pulsingStyle;
ShineEffect.ForDPS2 = "shine-effect";
}
// for DPS 2
if (weapons.w3_dps == "Too random to show") {
dps3_SrcImg = "parameter-bars/0.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h05) {
dps3_SrcImg = "parameter-bars/0.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h05) {
dps3_SrcImg = "parameter-bars/0.5.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h1) {
dps3_SrcImg = "parameter-bars/1.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h15) {
dps3_SrcImg = "parameter-bars/1.5.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h2) {
dps3_SrcImg = "parameter-bars/2.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h25) {
dps3_SrcImg = "parameter-bars/2.5.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h3) {
dps3_SrcImg = "parameter-bars/3.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h35) {
dps3_SrcImg = "parameter-bars/3.5.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h4) {
dps3_SrcImg = "parameter-bars/4.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h45) {
dps3_SrcImg = "parameter-bars/4.5.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h5) {
dps3_SrcImg = "parameter-bars/5.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h55) {
dps3_SrcImg = "parameter-bars/5.5.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h6) {
dps3_SrcImg = "parameter-bars/6.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h65) {
dps3_SrcImg = "parameter-bars/6.5.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h7) {
dps3_SrcImg = "parameter-bars/7.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h75) {
dps3_SrcImg = "parameter-bars/7.5.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h8) {
dps3_SrcImg = "parameter-bars/8.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h85) {
dps3_SrcImg = "parameter-bars/8.5.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h9) {
dps3_SrcImg = "parameter-bars/9.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h95) {
dps3_SrcImg = "parameter-bars/9.5.svg";
}
else if (weapons.w3_dps <= rangeOfParameters.dps.h10) {
dps3_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleDps3 = pulsingStyle;
ShineEffect.ForDPS3 = "shine-effect";
}
// for range 1
if (weapons.w1_r <= rangeOfParameters.range.h0) {
range_SrcImg = "parameter-bars/0.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h05) {
range_SrcImg = "parameter-bars/0.5.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h1) {
range_SrcImg = "parameter-bars/1.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h15) {
range_SrcImg = "parameter-bars/1.5.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h2) {
range_SrcImg = "parameter-bars/2.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h25) {
range_SrcImg = "parameter-bars/2.5.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h3) {
range_SrcImg = "parameter-bars/3.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h35) {
range_SrcImg = "parameter-bars/3.5.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h4) {
range_SrcImg = "parameter-bars/4.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h45) {
range_SrcImg = "parameter-bars/4.5.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h5) {
range_SrcImg = "parameter-bars/5.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h55) {
range_SrcImg = "parameter-bars/5.5.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h6) {
range_SrcImg = "parameter-bars/6.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h65) {
range_SrcImg = "parameter-bars/6.5.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h7) {
range_SrcImg = "parameter-bars/7.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h75) {
range_SrcImg = "parameter-bars/7.5.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h8) {
range_SrcImg = "parameter-bars/8.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h85) {
range_SrcImg = "parameter-bars/8.5.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h9) {
range_SrcImg = "parameter-bars/9.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h95) {
range_SrcImg = "parameter-bars/9.5.svg";
}
else if (weapons.w1_r <= rangeOfParameters.range.h10) {
range_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleRange = pulsingStyle;
ShineEffect.ForRange = "shine-effect";
}
// for range 2
if (weapons.w2_r <= rangeOfParameters.range.h0) {
range2_SrcImg = "parameter-bars/0.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h05) {
range2_SrcImg = "parameter-bars/0.5.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h1) {
range2_SrcImg = "parameter-bars/1.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h15) {
range2_SrcImg = "parameter-bars/1.5.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h2) {
range2_SrcImg = "parameter-bars/2.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h25) {
range2_SrcImg = "parameter-bars/2.5.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h3) {
range2_SrcImg = "parameter-bars/3.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h35) {
range2_SrcImg = "parameter-bars/3.5.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h4) {
range2_SrcImg = "parameter-bars/4.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h45) {
range2_SrcImg = "parameter-bars/4.5.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h5) {
range2_SrcImg = "parameter-bars/5.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h55) {
range2_SrcImg = "parameter-bars/5.5.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h6) {
range2_SrcImg = "parameter-bars/6.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h65) {
range2_SrcImg = "parameter-bars/6.5.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h7) {
range2_SrcImg = "parameter-bars/7.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h75) {
range2_SrcImg = "parameter-bars/7.5.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h8) {
range2_SrcImg = "parameter-bars/8.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h85) {
range2_SrcImg = "parameter-bars/8.5.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h9) {
range2_SrcImg = "parameter-bars/9.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h95) {
range2_SrcImg = "parameter-bars/9.5.svg";
}
else if (weapons.w2_r <= rangeOfParameters.range.h10) {
range2_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleRange2 = pulsingStyle;
ShineEffect.ForRange2 = "shine-effect";
}
// for range 3
if (weapons.w3_r <= rangeOfParameters.range.h0) {
range3_SrcImg = "parameter-bars/0.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h05) {
range3_SrcImg = "parameter-bars/0.5.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h1) {
range3_SrcImg = "parameter-bars/1.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h15) {
range3_SrcImg = "parameter-bars/1.5.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h2) {
range3_SrcImg = "parameter-bars/2.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h25) {
range3_SrcImg = "parameter-bars/2.5.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h3) {
range3_SrcImg = "parameter-bars/3.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h35) {
range3_SrcImg = "parameter-bars/3.5.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h4) {
range3_SrcImg = "parameter-bars/4.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h45) {
range3_SrcImg = "parameter-bars/4.5.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h5) {
range3_SrcImg = "parameter-bars/5.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h55) {
range3_SrcImg = "parameter-bars/5.5.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h6) {
range3_SrcImg = "parameter-bars/6.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h65) {
range3_SrcImg = "parameter-bars/6.5.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h7) {
range3_SrcImg = "parameter-bars/7.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h75) {
range3_SrcImg = "parameter-bars/7.5.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h8) {
range3_SrcImg = "parameter-bars/8.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h85) {
range3_SrcImg = "parameter-bars/8.5.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h9) {
range3_SrcImg = "parameter-bars/9.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h95) {
range3_SrcImg = "parameter-bars/9.5.svg";
}
else if (weapons.w3_r <= rangeOfParameters.range.h10) {
range3_SrcImg = "parameter-bars/10.svg";
boxShadowsStyleRange3 = pulsingStyle;
ShineEffect.ForRange3 = "shine-effect";
}
}<file_sep>/README.md
# Unit-Guide
TA: ESC Unit Guide
|
7fedb0d7167255c7d98ae1193e7e2084420c89e2
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
Sir-Diox/Unit-Guide
|
1d87f41d6488ade98aafa5759d7d1abf28e2de4f
|
3f156ef0311d0d82372864b4e1670d5e4dc8913f
|
refs/heads/master
|
<file_sep>Friendster Brown Bag Series Presents...
##Yeoman: Improve Your Workflow
In this episode of the Frienster Brown Bag series, I will do a demo at how the Yeoman Workflow can help you improve your Front End development workflow with tools from [Yeoman](http://yeoman.io) itself, [Grunt](http://gruntjs.com) and [Bower](http://bower.io).
### More
The goal here is to setup a very basic development environment and using [generator-simple](https://github.com/robdodson/generator-simple) is the perfect Yeoman generator. Yeoman's default [generator-webapp](https://github.com/yeoman/generator-webapp) is far from a basic setup.
### Presentation Slides
- [Yeoman: Improve Your Workflow]( https://docs.google.com/presentation/d/1Ond7Ss3qXOJwOPh7s3B-Xtr-B4njcz03jLtfNWuOdEA/pub?start=false&loop=false&delayms=5000)
### Credits
Many thanks to the wonderful [Yeoman](http://yeoman.io) itself, [Grunt](http://gruntjs.com) and [Bower](http://bower.io) and [generator-simple](http://github.com/robdodson/generator-simple). Rock on!
<file_sep>'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Load all grunt tasks
require('load-grunt-tasks')(grunt);
// Show elapsed time at the end
require('time-grunt')(grunt);
// Project configuration.
grunt.initConfig({
// Metadata.
pkg: grunt.file.readJSON('package.json'),
/* Project Settings */
yeoman: {
//Paths
app: './',
},
connect: {
server: {
options: {
hostname: 'localhost',
port: 9000,
livereload: true
}
}
},
watch: {
options: {
livereload: true
},
grunt: {
files: ['Gruntfile.js']
},
target: {
files: ['index.html', 'styles/**/*.css', 'scripts/**/*.js']
},
compass: {
files: ['styles/src/**/*.scss'],
}
},
/*compass: { // Task
dist: { // Target
options: { // Target options
sassDir: 'sass',
cssDir: 'css',
environment: 'production'
}
},
dev: { // Another target
options: {
sassDir: 'styles/**',
cssDir: 'css'
}
}
}*/
compass: {
options: {
sassDir: '<%= yeoman.app %>/styles/src',
cssDir: 'styles',
importPath: '<%= yeoman.app %>/bower_components',
httpImagesPath: '/images',
httpGeneratedImagesPath: '/images/generated',
httpFontsPath: '/styles/fonts',
relativeAssets: false,
assetCacheBuster: false
},
server: {
options: {
debugInfo: true
}
}
},
// Remove the .tmp directory which contains the compiled sass files
clean: [ 'styles/**/*.css', '<% yeoman.app %>.sass-cache/' ],
});
//grunt.loadNpmTasks('grunt-contrib-compass');
grunt.registerTask('serve', function(){
// Grunt task for starting a server
/*'connect',
'compass',
'watch',*/
});
// Default task.
grunt.registerTask('default', [
'connect',
'clean',
'compass',
'watch',
]);
};
|
ee83f57aec36cc0d0023db867117040d3357d55b
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
mcometa/yeoman-demo
|
90242a1fbb219e539992e0375b3b40ab2ee209da
|
b147ec485cca786a0825a38786894a9707b47b05
|
refs/heads/master
|
<file_sep><?php
echo '╡Бйтнд╪Ч';
var_dumo('hello word');
?>
|
5085dfe82c8ba2430cef54f3b6fdde95dccb9df6
|
[
"PHP"
] | 1 |
PHP
|
shxcat/pro
|
ac00eb955266031db010c8fdc0784f1c5b6afc12
|
0602b0d3808b2344e4e0266d6f65f6db0a17a14e
|
refs/heads/master
|
<repo_name>pbauerochse/packtpub-current-ebook<file_sep>/README.md
# packtpub-current-ebook
Packtpub graciously offers a free tech related ebook to anyone who signed up. This script makes a call to the packtpub website,
extracts the information of the current free ebook and displays it in a notification window.

The sole purpose of this script is to be run at system startup of my local computer so I wouldn't forget to check the current offer.
## Usage
This script has only been tested on a Linux (Mint) system. There's no guarantee, that it will work on any other system (I especially doubt that it will work on Windows), although I tried to
be as OS independent as possible.
Running `npm install -g` should put the script on your path so you should be able to invoke it with `packtpub-current-ebook` from your console / bash.
## Credits
This script depends on the following libraries. All credits for those libraries go to their corresponding authors
* cheerio - https://github.com/cheeriojs/cheerio
* request - https://github.com/request/request
* node-notifier - https://github.com/mikaelbr/node-notifier
<file_sep>/index.js
#!/usr/bin/env node
/* Copyright (c) 2016, <NAME>
*
* 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.
*/
const request = require('request');
const cheerio = require('cheerio');
const exec = require('child_process').exec;
const notifier = require('node-notifier');
const packtpubUrl = 'https://www.packtpub.com/packt/offers/free-learning/';
// fetch the html from the free ebook packtpub page
request(packtpubUrl, function(error, response,html) {
if (!error && response.statusCode == 200) {
processPacktpubResponse(html);
}
// no error handling. if it works, it works.
});
// handle the packtpub response
function processPacktpubResponse(html) {
const $ = cheerio.load(html);
const $currentFreeEbookSection = $('.dotd-main-book-summary');
if ($currentFreeEbookSection.length > 0) {
displayFreeEbookInformation($currentFreeEbookSection);
}
}
// extracts the free ebook details from the section and shows a notification
function displayFreeEbookInformation($currentFreeEbookSection) {
// extract the title
const $titleSection = $currentFreeEbookSection.find('.dotd-title');
const ebookTitle = $titleSection.find('h2').text().trim();
// remove clutter which is not needed for the description
$titleSection.remove();
$currentFreeEbookSection.find('.eighteen-days-countdown-bar').remove();
// extract the description
const ebookDescription = $currentFreeEbookSection.text().trim();
showEbookNotification(ebookTitle, ebookDescription);
}
// show notification
function showEbookNotification(title, description) {
notifier.notify({
'title': 'Free Packtpub Ebook: ' + title,
'message': description + '\n\nDownload at: ' + packtpubUrl
});
}
|
a4571c3c74f898629f39133d75763b2e3bb48792
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
pbauerochse/packtpub-current-ebook
|
2594dfc486414eaa9206e0505991f247c6ccc68c
|
e74eef0745dcb1c7fcf7e77f7ddda83432175d03
|
refs/heads/master
|
<file_sep>adal==1.2.7
applicationinsights==0.11.10
azure-common==1.1.27
azure-core==1.19.1
azure-graphrbac==0.61.1
azure-mgmt-authorization==0.61.0
azure-mgmt-containerregistry==8.2.0
azure-mgmt-core==1.3.0
azure-mgmt-keyvault==9.2.0
azure-mgmt-resource==13.0.0
azure-mgmt-storage==11.2.0
azureml-cli-common==1.36.0
azureml-core==1.33.0
azureml-pipeline-core==1.36.0
azureml-telemetry==1.36.0
azureml-train-core==1.36.0
azureml-train-restclients-hyperdrive==1.36.0
backports.tempfile==1.0
backports.weakref==1.0.post1
certifi==2021.10.8
cffi==1.15.0
charset-normalizer==2.0.7
contextlib2==0.6.0.post1
cryptography==3.4.8
docker==4.4.4
idna==3.3
isodate==0.6.0
jeepney==0.7.1
jmespath==0.10.0
jsonpickle==2.0.0
msrest==0.6.21
msrestazure==0.6.4
ndg-httpsclient==0.5.1
oauthlib==3.1.1
pathspec==0.9.0
pyasn1==0.4.8
pycparser==2.20
PyJWT==2.3.0
pyOpenSSL==20.0.1
python-dateutil==2.8.2
pytz==2021.3
requests==2.26.0
requests-oauthlib==1.3.0
ruamel.yaml==0.17.4
ruamel.yaml.clib==0.2.6
SecretStorage==3.3.1
six==1.16.0
urllib3==1.26.5
websocket-client==1.2.1
<file_sep>from azureml.core.model import Model
from azureml.core import Workspace
model_path = "/Users/luca/Projects/triton-inference-server/models"
ws = Workspace.from_config()
model = Model.register(
model_path=model_path,
model_name="test-triton-model",
model_framework=Model.Framework.MULTI,
workspace=ws
)
<file_sep>import argparse
import sys
from urllib.request import Request, urlopen
import numpy as np
import cv2
import tritonclient.http as httpclient
from tritonclient.utils import InferenceServerException
class_map = {
1: "sedan_vehicle",
2: "sedan_vehicle_whole",
3: "suv_vehicle",
4: "suv_vehicle_whole",
5: "van_vehicle",
6: "van_vehicle_whole",
7: "bus_vehicle",
8: "bus_vehicle_whole",
9: "truck_vehicle",
10: "truck_vehicle_whole",
11: "heavyequipment_vehicle",
12: "heavyequipment_vehicle_whole",
13: "wheel",
14: "plate",
}
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--model-name", type=str, required=True, help="Name of model")
parser.add_argument(
"-x",
"--model-version",
type=str,
required=False,
default="",
help="Version of model. Default is to user latest version",
)
parser.add_argument("-u", "--url", type=str, required=False, default="localhost:8000", help="Model Name")
parser.add_argument("--image-filename", type=str, nargs="?", default=None, help="Input image / Input folder.")
return parser.parse_args()
def generate_request(image_data, input_name, outputs, dtype):
client = httpclient
input = client.InferInput(input_name, image_data.shape, dtype)
input.set_data_from_numpy(image_data)
outputs_ = []
for output in outputs:
output_name = output["name"]
outputs_.append(client.InferRequestedOutput(output_name))
return input, outputs_, args.model_name, args.model_version
def postprocess(width, height, raw_result):
result = {
"width": width,
"height": height,
"boxes": raw_result.as_numpy("detection_boxes").squeeze().tolist(),
"scores": raw_result.as_numpy("detection_scores").squeeze().tolist(),
"classes": list(map(lambda x: class_map[int(x)], raw_result.as_numpy("detection_classes").squeeze())),
}
return result
def get_bboxes(raw_result, threshold):
boxes = raw_result["boxes"]
scores = raw_result["scores"]
classes = raw_result["classes"]
img_width = raw_result["width"]
img_height = raw_result["height"]
pred_bboxes = []
for index, score in enumerate(scores):
cls_name = classes[index]
if score >= threshold:
box = boxes[index]
left, right = map(lambda x: x * img_width, (box[1], box[3]))
top, bottom = map(lambda x: x * img_height, (box[0], box[2]))
bbox = [cls_name, score, left, top, right, bottom]
pred_bboxes.append(bbox)
return pred_bboxes
def get_aimmo_results(bbox_result):
json_result = {}
json_result["attributes"] = {}
annos = []
for anno_id, bbox in enumerate(bbox_result):
anno_id_encoded = str(anno_id).zfill(3).encode()
left, top, right, bottom = map(lambda x: int(round(x)), bbox[2:])
anno = {}
anno["type"] = "bbox"
anno["points"] = [[left, top], [right, top], [right, bottom], [left, bottom]]
anno["label"] = bbox[0]
anno["attributes"] = {"score": bbox[1]}
annos.append(anno)
json_result["annotations"] = annos
return json_result
if __name__ == "__main__":
args = parse_args()
try:
triton_client = httpclient.InferenceServerClient(url=args.url)
except Exception as e:
print("client creation failed: " + str(e))
sys.exit(1)
try:
model_metadata = triton_client.get_model_metadata(model_name=args.model_name, model_version=args.model_version)
except InferenceServerException as e:
print("failed to retrieve the metadata: " + str(e))
sys.exit(1)
try:
model_config = triton_client.get_model_config(model_name=args.model_name, model_version=args.model_version)
except InferenceServerException as e:
print("failed to retrieve the config: " + str(e))
sys.exit(1)
input_name = model_metadata["inputs"][0]["name"]
outputs = model_metadata["outputs"]
dtype = model_metadata["inputs"][0]["datatype"]
req = Request("file://" + args.image_filename, headers={"User-Agent": "Mozilla/5.0"})
resp = urlopen(req)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
img_height, img_width, _ = image.shape
image_data = image.reshape((1, img_height, img_width, 3)).astype(np.uint8)
input, outputs_, model_name, model_version = generate_request(image_data, input_name, outputs, dtype)
try:
response = triton_client.infer(args.model_name, inputs=[input], model_version=model_version, outputs=outputs_)
except InferenceServerException as e:
print("inference failed: " + str(e))
sys.exit(1)
result = postprocess(img_height, img_width, response)
pred_bboxes = get_bboxes(result, 0.5)
pred_aimmo = get_aimmo_results(pred_bboxes)
|
56457b7d53b02d1ba5a844201f23662530432580
|
[
"Python",
"Text"
] | 3 |
Text
|
namwooo/triton-inference-server
|
d3fed046b86458d16b7229af6a8ee83764815e06
|
e8cfe51c815659014e0ab9578da41542d648a233
|
refs/heads/master
|
<repo_name>VasileRoxana/Remote-Controlled-Car<file_sep>/proiect_final.ino
#include "IRremote.h"
#define M1A 5
#define M1B 6
#define M2A 9
#define M2B 10
#define trigPin 11
#define echoPin 13
int rec = 3;
int speedM1 = 255, speedM2 = 255;
IRrecv irrecv(rec); // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'
void fw();
void bw();
void left();
void right();
void stop();
bool goesFW = true;
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(rec, INPUT);
pinMode(M1A, OUTPUT);
pinMode(M1B, OUTPUT);
pinMode(M2A, OUTPUT);
pinMode(M2B, OUTPUT);
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
void loop()
{
float duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) * 0.0344;
if (distance <= 5 && goesFW == true)
stop();
if (irrecv.decode( & results))
{
translateIR();
irrecv.resume();
}
}
void translateIR()
{
switch (results.value)
{
case 0xFF38C7: //FW//
{
goesFW = true;
speedM1 = 255;
speedM2 = 255;
fw(speedM1, speedM2);
break;
}
case 0x488F3CBB: //FW//
{
goesFW = true;
speedM1 = 255;
speedM2 = 255;
fw(speedM1, speedM2);
break;
}
case 0xFF4AB5: //BW//
{
goesFW = false;
speedM1 = 255;
speedM2 = 255;
bw(speedM1, speedM2);
break;
}
case 0x1BC0157B: //BW//
{
goesFW = false;
speedM1 = 255;
speedM2 = 255;
bw(speedM1, speedM2);
break;
}
case 0xFF42BD: //LEFT//
{
speedM1 = 200;
speedM2 = 10;
if (goesFW == true)
{
fw(speedM1, speedM2);
break;
}
else
{
bw(speedM1, speedM2);
break;
}
}
case 0x32C6FDF7: //LEFT//
{
speedM1 = 200;
speedM2 = 10;
if (goesFW == true)
{
fw(speedM1, speedM2);
break;
}
else
{
bw(speedM1, speedM2);
break;
}
}
case 0xFF52AD: //RIGHT//
{
speedM2 = 200;
speedM1 = 10;
if (goesFW == true)
{
fw(speedM1, speedM2);
break;
}
else
{
bw(speedM1, speedM2);
break;
}
}
case 0x3EC3FC1B: //RIGHT//
{
speedM2 = 200;
speedM1 = 10;
if (goesFW == true)
{
fw(speedM1, speedM2);
break;
}
else
{
bw(speedM1, speedM2);
break;
}
}
case 0xFF22DD: //SPIN LEFT
{
spinLeft();
break;
}
case 0x52A3D41F: //SPIN LEFT
{
spinLeft();
break;
}
case 0xF02FD: //SPIN RIGHT
{
spinRight();
break;
}
case 0xD7E84B1B: //SPIN RIGHT
{
spinRight();
break;
}
default:
stop();
}
delay(50);
}
void fw(int val1, int val2)
{
analogWrite(M1A, val1);
digitalWrite(M1B, 0);
analogWrite(M2A, val2);
digitalWrite(M2B, 0);
}
void bw(int val1, int val2)
{
analogWrite(M1B, val1);
digitalWrite(M1A, 0);
analogWrite(M2B, val2);
digitalWrite(M2A, 0);
}
void spinLeft()
{
digitalWrite(M1A, 1);
digitalWrite(M1B, 0);
digitalWrite(M2A, 0);
digitalWrite(M2B, 1);
}
void spinRight()
{
digitalWrite(M1A, 0);
digitalWrite(M1B, 1);
digitalWrite(M2A, 1);
digitalWrite(M2B, 0);
}
void stop()
{
digitalWrite(M1A, LOW);
digitalWrite(M1B, LOW);
digitalWrite(M2A, LOW);
digitalWrite(M2B, LOW);
}
<file_sep>/README.md
# Proiect-final
Proiectul meu final consta intr-un robot masinuta controlat prin telecomanda ce foloseste doua motoare dc. Este alimentat de 4 baterii AA reincarcabile. Controlul se face din butoanele 7, 8, 9 si 5, avand rol de sageti. Odata apasat un buton robotul merge pana apesi pe alt buton (daca este alt buton de control o sa faca actiunea respectiva, daca e altul se opreste).
BOM:
https://docs.google.com/spreadsheets/d/1_GYeWjBXVv_4aekasxN6_g4DxXadq2Kq5P1_7F1olAA/edit#gid=1564006692&range=D2
|
e6b343eae4c57e548025195332ca7479df9a5ac7
|
[
"Markdown",
"C++"
] | 2 |
C++
|
VasileRoxana/Remote-Controlled-Car
|
71cbc9e76a6c30fe28a802feed4c26cd88e8720d
|
50bd2d64074123fe7406e6d27549d51645386538
|
refs/heads/master
|
<repo_name>zac-arnold/sunreturn<file_sep>/README.md
# SUNRETURN
Sunreturn is an independent record label based in Tāmaki Makaurau, Aotearoa. We strive to amplify the work of artists who find freedom in imagining new and unique sounds.
Facebook: https://bit.ly/2GJhQqE
Instagram: https://bit.ly/3jT1f1D
Spotify: https://spoti.fi/3lC0EC7
Youtube: https://bit.ly/3iXK8KJ
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). On the off chance you're keen to use SR's website as a template make sure you check out Create React App's script instructions. <file_sep>/src/App.js
import React from 'react';
import { HashRouter as Router, Route } from 'react-router-dom'
import Artist from './Artist'
import Home from './Home'
import Nav from './Nav';
const App = (props) => {
return (
<Router>
<div>
<Route path="/" component={Nav} />
<Route exact path='/' component={Home} />
<Route path='/:artist' component={Artist} />
</div>
</Router>
);
}
export default App;
<file_sep>/src/Artist.js
import React from 'react';
import { Route } from 'react-router-dom'
import Dsplogo from './Dsplogo';
import lineup from './lineupdata.json'
import './Artist.css';
function Artist (props){
const artist = lineup.artists.filter((artist) => artist.name === props.match.params.artist)[0]
return (
<>
<div className="artistcomp n1">
< Route component={Dsplogo}/>
<img className="artistphoto" src={ artist.img } alt=""></img>
<a href={artist.pcredlink} className="hypelinka" target="blank" rel="noopener noreferrer"><p className="hypelink pcred">Photo Credit: {artist.pcredt}</p></a>
<h1 className="artistname">{props.match.params.artist} </h1>
<p className="bio"> {artist.bio} </p>
</div>
<div className="artistcomp n2">
<img className="artistphoto" src={ artist.img } alt=""></img>
<h1 className="artistname">{props.match.params.artist} </h1>
<p className="bio"> {artist.bio} </p>
<a href={artist.pcredlink} className="hypelinka" target="blank" rel="noopener noreferrer"><p className="hypelink pcred">Photo Credit: {artist.pcredt}</p></a>
< Route component={Dsplogo}/>
</div>
</>
);
}
export default Artist<file_sep>/src/email.js
import React from 'react'
function email() {
return (
<div>
{/* <!-- Begin Mailchimp Signup Form --> */}
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css" />
<style type="text/css">
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own Mailchimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="https://gmail.us3.list-manage.com/subscribe/post?u=471d69b246badde0891d12bae&id=811e1a4288" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<div id="mc_embed_signup_scroll">
<h2>Subscribe</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address <span class="asterisk">*</span></label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" />
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true">
<input type="text" name="b_471d69b246badde0891d12bae_811e1a4288" tabindex="-1" value=""/>
</div>
<div class="clear">
<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button" />
</div>
</div>
</form>
</div>
{/* <!--End mc_embed_signup--> */}
</div>
)
}
export default email
<file_sep>/src/srartist.js
const srartist = {
info: [
{
id: 1,
name: 'AMEMALIA',
description: "Amamelia is the musical project of <NAME>, a musician and songwriter currently based in Auckland. Her music combines breaks normally found in Jungle & Drum & Bass with a sugary synthetic pop sensibility. Throughout 2020 Amamelia has been teasing her audience with So Good and Sad and Lonely feat Junny, two singles from her debut album WOW! (due out before the years end via Sunreturn).Outside of Amamelia, Amelia can be found creating ambient soundscapes in caves as Old Chips, playing in queerbo pop-punk band Babyteeth and performing as one half of synth pop duo Fimo. In the past she's been the mastermind behind the romantic jangle of Polyester (fka as Kip McGrath), and one third of queer DJ trio PWB . She is currently host of 95bFM's illustrious chart show, the 95bFM Top 10.",
image: 'public/Amamelia - Photo Credit <NAME>.jpeg',
credit: "<NAME>",
bandcamp: "https://amamelia.bandcamp.com/",
spotify: "https://open.spotify.com/artist/7BjYtpKbFrgy8EX8REsjhW?si=qfA3AMyORyOFZtLhJCBF8Q",
youtube: "https://www.youtube.com/playlist?list=PL3_-29X9BmxMRTNKOtqG15P4TYhHzj9ed",
instagram: "",
facebook: "https://www.facebook.com/amamelianz/",
},
{
id: 2,
name: '<NAME>',
description: "Amamelia is the musical project of <NAME>, a musician and songwriter currently based in Auckland. Her music combines breaks normally found in Jungle & Drum & Bass with a sugary synthetic pop sensibility. Throughout 2020 Amamelia has been teasing her audience with So Good and Sad and Lonely feat Junny, two singles from her debut album WOW! (due out before the years end via Sunreturn).Outside of Amamelia, Amelia can be found creating ambient soundscapes in caves as Old Chips, playing in queerbo pop-punk band Babyteeth and performing as one half of synth pop duo Fimo. In the past she's been the mastermind behind the romantic jangle of Polyester (fka as Kip McGrath), and one third of queer DJ trio PWB . She is currently host of 95bFM's illustrious chart show, the 95bFM Top 10.",
image: 'a',
credit: "<NAME>",
bandcamp: "https://babyzionov.bandcamp.com/",
spotify: "https://open.spotify.com/artist/4RLTd4Vi9dfNeEKMnmylaO?si=lOx41DDJTveJZJeZhcgCKw",
youtube: "https://www.youtube.com/playlist?list=PL3_-29X9BmxOkkdFlPFN3P6jo8ufz8cKs",
instagram: "https://www.instagram.com/babyzionov/",
facebook: "https://www.facebook.com/babyzionov/",
},
{
id: 3,
name: 'DATELINE',
description: "Dateline is the musical project of <NAME>, a musician and songwriter currently based in Hastings. Her band is made up of the cream of Auckland's indie and alternative crop featuring <NAME> (Hans Pucket), Priya Sami (fka Trip Pony, Sami Sisters) and Ruby Walsh (Lips, Trip Pony). Earlier in the year Dateline supported US artist Jaysom and their scorching set was recorded and released as Dateline Live! The EP comes off the back of two hot singles, If You Want It and Such A Bitch. Those songs were recorded by Dateline's original band members <NAME> (The Beths) <NAME> (The Naenae Express) and Ruby Walsh (Trip Pony). Before the year is over Dateline will hit the studio for another round of recording!",
image: 'a',
credit: "<NAME>",
bandcamp: "https://dateline.bandcamp.com/",
spotify: "https://open.spotify.com/artist/1qmkqOcRV8vy61b2zBBeFm?si=Sr__jEuaRUKHrqucvz5zJw",
youtube: "https://www.youtube.com/playlist?list=PL3_-29X9BmxO3X_bFj3-XzC9QDWkH3bF_",
instagram: "https://www.instagram.com/dateline2.0/",
facebook: "https://www.facebook.com/Dateline2.0/",
},
{
id: 4,
name: 'GREEN GROVE',
description: "Green Grove is the musical project of <NAME>, a musician and songwriter currently based in Auckland. Green Grove's music is for deep listening, creating lush electronic worlds inspired by Lounge and Library Music. Durham has wholeheartedly immersed himself into Auckland's independent music scene, initially as the guitarist of New Gum Sarn, and then swiftly into groups such as Guardian Singles, Bozo, PG/VG and as a live sound engineer at Whammy Bar. Following the release of 2019's Machine Music, Green Grove has pivoted to a contemplative sound palette, with his live set embodying mindful ambience and graceful soundscapes.",
image: 'a',
credit: "<NAME>",
bandcamp: "https://greengrove.bandcamp.com/",
spotify: "https://open.spotify.com/artist/4Or9cUnJdgeT8tQ0SP7PrV?si=76-IAgTjQlqqHJBBwt9KXw",
youtube: "https://www.youtube.com/playlist?list=PL3_-29X9BmxOJviy25j6hwBNpTIhU7Un_",
instagram: "https://www.instagram.com/darimfennick/",
facebook: "https://www.facebook.com/Greengrov3/",
},
{
id: 5,
name: '<NAME>',
description: "<NAME> is the musical project of <NAME>, a musician and songwriter currently based in Auckland. Keria didn’t discover music at a particular point in their life, it was always there, whether it was attending Flying Nun gigs with family as a kid and starting to sing and play guitar and piano at an early age. At high school, they connected with other passionate musicians and added bass and keyboards/synths to his repertoire, as well as beginning to experiment with recording and live music production. Before starting their own solo projects as K M T P, Paterson played with Auckland indie faves Polyester, as well as with <NAME>’s “bedroom stadium pop” project Dirty Pixels.",
image: 'a',
credit: "<NAME>",
bandcamp: "https://kmtp.bandcamp.com/album/p-s-c-u-soon",
spotify: "https://open.spotify.com/artist/3PW65WLXS6nvUaNquvoXvO?si=DRYvU2R6Q-KKQxCwOGdTRA",
youtube: "https://www.youtube.com/playlist?list=PL3_-29X9BmxPHHVcoX1ichAnwOBCIk-uk",
instagram: "https://www.instagram.com/kmtpmakesmusic/",
facebook: "https://www.facebook.com/kmtpmakesmusic/",
},
]
}<file_sep>/src/Home.js
import React from 'react';
import './Home.css';
function Home() {
return (
<div className="">
<div className="grid-container catnum">
<div className="grid-item">
<a href="https://www.youtube.com/playlist?list=PL3_-29X9BmxOJviy25j6hwBNpTIhU7Un_" alt="" target="blank" rel="noopener noreferrer">
<img src="./MachineMusic.jpg" alt=""></img>
</a>
<p className="">SR001</p>
<p className="">Green Grove - Machine Music</p>
</div>
<div className="grid-item">
<a href="https://www.youtube.com/playlist?list=PL3_-29X9BmxO3X_bFj3-XzC9QDWkH3bF_" alt="" target="blank" rel="noopener noreferrer">
<img src="./DatelineLive.jpg" alt=""></img>
</a>
<p className="">SR002</p>
<p className="">Dateline - Dateline Live!</p>
</div>
<div className="grid-item">
<a href="https://www.youtube.com/playlist?list=PL3_-29X9BmxOkkdFlPFN3P6jo8ufz8cKs" alt="" target="blank" rel="noopener noreferrer">
<img src="./BBZ.jpg" alt=""></img>
</a>
<p className="">SR003</p>
<p className="">Baby Zionov - ....And You Are The Bitch</p>
</div>
<div className="grid-item">
<a href="https://www.youtube.com/playlist?list=PL3_-29X9BmxPHHVcoX1ichAnwOBCIk-uk" alt="" target="blank" rel="noopener noreferrer">
<img src="./KMTPPSCUSOON.jpg" alt=""></img>
</a>
<p className="">SR004</p>
<p className="">K M T P - P.S. C U SOON</p>
</div>
<div className="grid-item">
<a href="https://www.youtube.com/playlist?list=PL3_-29X9BmxMRTNKOtqG15P4TYhHzj9ed" alt="" target="blank" rel="noopener noreferrer">
<img src="./AmameliaWow.jpg" alt=""></img>
</a>
<p className="">SR005</p>
<p className="">Amamelia - WOW!</p>
</div>
<div className="grid-item">
<a href="https://www.youtube.com/watch?v=r8fF4wJuvh0" alt="" target="blank" rel="noopener noreferrer">
<img className=""src="./green grove cover.png" alt=""></img>
</a>
<p className="">SR006</p>
<p className="">Green Grove - Of Isthmus</p>
</div>
<div className="grid-item">
<a href="https://www.youtube.com/watch?v=55OXd9oePzo" alt="" target="blank" rel="noopener noreferrer">
<img className=""src="./PNClubDinos.jpg" alt=""></img>
</a>
<p className="">SR007</p>
<p className="">Power Nap - Club Dinos</p>
</div>
</div>
</div>
);
}
export default Home;
<file_sep>/src/Dsplogo.js
import React from 'react'
import lineup from './lineupdata.json'
import './Artist.css';
function Dsplogo(props) {
const artist = lineup.artists.filter((artist) => artist.name === props.match.params.artist)[0]
return (
<>
<span className="artistLogo">
<a href={ artist.socialMedia.bandcamp } target="blank" rel="noopener noreferrer"><img src='/Bandcamp.png' className="artistsoclogo" alt="logo" /></a>
<a href={ artist.socialMedia.spotify} target="blank" rel="noopener noreferrer"><img src='/Spotify.png' className="artistsoclogo" alt="logo" /></a>
<a href={ artist.socialMedia.youtube} target="blank" rel="noopener noreferrer"><img src='/Youtube.png' className="artistsoclogo" alt="logo" /></a>
<a href={ artist.socialMedia.instagram} target="blank" rel="noopener noreferrer"><img src='/Instagram.png' className="artistsoclogo" alt="logo" /></a>
<a href={ artist.socialMedia.facebook} target="blank" rel="noopener noreferrer"><img src='/Facebook.svg' className="artistsoclogo" alt="logo" /></a>
</span>
</>
)
}
export default Dsplogo
|
6a429631fcae56d873ca2ab41227b08bd2ea3759
|
[
"Markdown",
"JavaScript"
] | 7 |
Markdown
|
zac-arnold/sunreturn
|
395ced3bbbbe671099570ff2352bcc08ba9f2c1e
|
84465e1d1b332fc1449b0b890ea2d7dac34cc2ca
|
refs/heads/master
|
<repo_name>JannaJahana/Calculator-demo<file_sep>/src/com/mypackage/Subtract.java
package com.mypackage;
public class Subtract {
public int subtraction(int a,int b){
return a-b;
}
}
<file_sep>/README.md
# Calculator-demo
A basic implementation of calculator
|
8804b2a24d8a1650fbb8fdb150ab0dddaaf61961
|
[
"Markdown",
"Java"
] | 2 |
Java
|
JannaJahana/Calculator-demo
|
e14d6548180c7754d645b10412c5ea981197b47f
|
0237b50356a03d14d84bc72567efaae35e8b07ee
|
refs/heads/master
|
<repo_name>chiewen/RoadINS<file_sep>/test/experiment.cpp
//
// Created by chiewen on 2015/12/6.
//
#include <gtest/gtest.h>
#include <thread>
#include "../src/network/Node.h"
#include "../src/network/Trajectory.h"
#include "../src/algorithm/INS.h"
#include "../src/network/RoadNetwork.h"
#include "../src/algorithm/VStar.h"
#include "../src/network/TrajectoryConstructor.h"
#include "../src/util/TimePrinter.h"
typedef typename vector<shared_ptr<MknnProcessor>>::iterator MPIter;
void print_result(string name, MPIter start, MPIter end) {
vector<long> v_page, v_server, v_client, v_communication;
for (auto &p = start; p != end; p++) {
v_page.push_back((*p)->num_page());
v_server.push_back((*p)->num_server());
v_client.push_back((*p)->num_client());
v_communication.push_back((*p)->num_communication());
}
cout << name << ":\t"
<< accumulate(v_page.begin(), v_page.begin() + 3, 0) / 3 << "\t"
<< accumulate(v_server.begin(), v_server.begin() + 3, 0) / 3 << "\t"
<< accumulate(v_client.begin(), v_client.begin() + 3, 0) / 3 << "\t"
<< accumulate(v_communication.begin(), v_communication.begin() + 3, 0) / 3 << "\t";
}
void execute(const vector<PNode> &nodes, vector<Trajectory> &trajectories, int k, int x, int step) {
for (auto &t: trajectories)
t.setStep(step);
vector<shared_ptr<MknnProcessor>> mps;
mps.reserve(12);
for (int i = 0; i < 6; ++i)
mps.emplace_back(make_shared<VStar>(k, x));
for (int i = 0; i < 6; ++i)
mps.emplace_back(make_shared<INS>(k));
for (int i = 0; i < 12; i++)
mps[i]->move(trajectories[i]);
print_result("VR", mps.begin(), mps.begin() + 3);
print_result("VD", mps.begin() + 3, mps.begin() + 6);
print_result("IR", mps.begin() + 6, mps.begin() + 9);
print_result("ID", mps.begin() + 9, mps.end());
cout << endl;
}
TEST(Experiment, First) {
auto &nodes = RoadNetwork::get_mutable_instance();
int length = 500;
int k = 10;
int x = 6;
int step = 40;
vector<Trajectory> trajectories;
trajectories.reserve(12);
cout << "\n============= experiment start at " << TimePrinter::now << " =============\n" << endl;
for (int i = 0; i < 1200; i += 400) {
auto traj = TrajectoryConstructor::construct_random(nodes[i], length, step);
trajectories.emplace_back(traj);
}
cout << "R " << TimePrinter::now << endl;
vector<thread> vt;
mutex m_traj;
for (int i = 0; i < 1200; i += 400)
vt.emplace_back([i, length, step, &m_traj, &trajectories, &nodes]() {
auto t = TrajectoryConstructor::construct_shortest_path(nodes[i], length, step);
lock_guard<mutex> {m_traj};
trajectories.push_back(t);
});
for (auto &t : vt)
t.join();
cout << "D " << TimePrinter::now << endl;
copy(trajectories.begin(), trajectories.begin() + 6, back_inserter(trajectories));
for (int r = 0; r < 8; r++) {
cout << endl << "ratio = 0.05 to 0.11 step 0.005" << endl;
for (double ratio = 0.05; ratio <= 0.11; ratio += 0.005) {
RoadNetwork::reset_ratio(ratio);
execute(nodes, trajectories, k, x, step);
}
}
// cout << endl << "step = 10 to 100 step 5" << endl;
// for (int i = 10; i < 100; i += 5)
// execute(nodes, trajectories, k, x, i);
//
// cout << endl << "x = 1 to 10" << endl;
// for (int i = 1; i < 20; i++)
// execute(nodes, trajectories, k, i, step);
//
// cout << endl << "k = 1 to 20" << endl;
// for (int i = 1; i < 20; i++)
// execute(nodes, trajectories, i, x, step);
}
TEST(Experiment, Cardinal) {
int length = 100;
int k = 10;
int x = 6;
int step = 40;
for (int e = 0; e < 5; e++) {
cout << "\n============= " << e << "th experiment start at " << TimePrinter::now << " =============\n" << endl;
vector<Trajectory> trajectories;
cout << endl << "cardinal 5000 to 260000 step 5000" << endl;
for (long i = 5000; i < 260000; i += 5000) {
RoadNetwork::reset(0, i);
auto &nodes = RoadNetwork::get_mutable_instance();
trajectories.clear();
trajectories.reserve(12);
for (int i = 0; i < 1200; i += 400) {
auto traj = TrajectoryConstructor::construct_random(nodes[i], length, step);
trajectories.emplace_back(traj);
}
vector<thread> vt;
mutex m_traj;
for (int i = 0; i < 1200; i += 400)
vt.emplace_back([i, length, step, &m_traj, &trajectories, &nodes]() {
int j = i;
do {
while (nodes[j]->nearest_site.second < 0) j++;
auto t = TrajectoryConstructor::construct_shortest_path(nodes[j++], length, step);
if (!t.has_next()) continue;
else {
lock_guard<mutex> {m_traj};
trajectories.push_back(t);
break;
}
} while (true);
});
for (auto &t : vt)
t.join();
copy(trajectories.begin(), trajectories.begin() + 6, back_inserter(trajectories));
execute(nodes, trajectories, k, x, step);
}
}
}
TEST(Experiment, Length) {
auto &nodes = RoadNetwork::get_mutable_instance();
int k = 10;
int x = 6;
int step = 40;
cout << "\n============= experiment start at " << TimePrinter::now << " =============\n" << endl;
vector<Trajectory> trajectories;
for (int l = 0; l < 8; l++) {
cout << endl << "length 50 to 1000 step 50" << endl;
for (long length = 50; length < 850; length += 50) {
trajectories.clear();
trajectories.reserve(12);
for (int j = 0; j < 12000; j += 4000) {
auto traj = TrajectoryConstructor::construct_random(nodes[j], length, step);
trajectories.emplace_back(traj);
}
vector<thread> vt;
mutex m_traj;
for (int k = 0; k < 12000; k += 4000)
vt.emplace_back([k, length, step, &m_traj, &trajectories, &nodes]() {
int j = k;
do {
while (nodes[j]->nearest_site.second < 0) j++;
auto t = TrajectoryConstructor::construct_shortest_path(nodes[j++], length, step);
if (!t.has_next()) continue;
else {
lock_guard<mutex> {m_traj};
trajectories.push_back(t);
break;
}
} while (true);
});
for (auto &t : vt)
t.join();
copy(trajectories.begin(), trajectories.begin() + 6, back_inserter(trajectories));
execute(nodes, trajectories, k, x, step);
}
}
}<file_sep>/test/test_fixture.cpp
//
// Created by chiewen on 2015/11/10.
//
#include "test_fixture.h"
void NodesNetTest::SetUp() {
}<file_sep>/src/algorithm/VStar.cpp
//
// Created by chiewen on 2015/11/24.
//
#include "VStar.h"
#include "Dijkstra.h"
VStar::VStar(int k, int x) : k(k), x(x) { }
void VStar::move(Trajectory trajectory) {
client_start();
ordered_k_x.clear();
ordered_k_x.reserve(k + x);
calculate(trajectory.get_then_forward());
for (auto pos = trajectory.get_then_forward(); trajectory.has_next();
pos = trajectory.get_then_forward()) {
++total_step;
if (!validate_knn(pos)) ++communication, calculate(pos);
}
client_pause();
}
void VStar::calculate(const pair<PRoad, double> &pos) {
client_to_server();
Dijkstra::top_k_vstar(pos, k + x, ordered_k_x, page);
q_b = pos;
z = ordered_k_x[k + x - 1];
z_dist = Dijkstra::distance_to(pos.first->to.lock(), pos.second, z);
server_to_client();
}
bool VStar::validate_knn(const pair<PRoad, double> &pos) {
long from_id = pos.first->from.lock()->id;
long to_id = pos.first->to.lock()->id;
auto pFrom = frrMap.find(from_id);
if (pFrom == frrMap.end()) {
map<long, double> topk;
Dijkstra::top_k_with_distance(pos.first->from.lock(), k + x, ordered_k_x, topk);
pFrom = frrMap.insert(make_pair(from_id, topk)).first;
}
auto pTo = frrMap.find(to_id);
if (pTo == frrMap.end()) {
map<long, double> topk;
Dijkstra::top_k_with_distance(pos.first->to.lock(), k + x, ordered_k_x, topk);
pTo = frrMap.insert(make_pair(to_id, topk)).first;
}
bool should_recalculate = true;
bool should_communicate = false;
while (should_recalculate) {
should_recalculate = false;
for (int i = 0; i < k + x - 1; i++)
if (min(pTo->second[ordered_k_x[i]->id] + pos.second,
pFrom->second[ordered_k_x[i]->id] + pos.second - pos.second) >
min(pTo->second[ordered_k_x[i + 1]->id] + pos.second,
pFrom->second[ordered_k_x[i + 1]->id] + pos.second - pos.second)) {
if (x > k) should_communicate = true;
swap(ordered_k_x[i], ordered_k_x[i + 1]);
should_recalculate = true;
}
}
if (should_communicate) communication += 1;
if (z->id != ordered_k_x[k + x - 1]->id) {
z = ordered_k_x[k + x - 1];
z_dist = Dijkstra::distance_to_bidirection(q_b, z);
}
return z_dist > Dijkstra::distance_to_bidirection(pos, ordered_k_x[k - 1]) +
min(Dijkstra::distance_to_bidirection(pos, q_b.first->to.lock()) + q_b.second,
Dijkstra::distance_to_bidirection(pos, q_b.first->from.lock()) + q_b.first->distance -
q_b.second);
}
<file_sep>/src/util/ptr_node_comp.cpp
//
// Created by Chiewen on 2015/11/16.
//
#include "../network/Node.h"
bool ptr_node_less::operator()(const PNode &pn1, const PNode &pn2) { return pn1->id < pn2->id; }
<file_sep>/src/algorithm/VStar.h
//
// Created by chiewen on 2015/11/24.
//
#ifndef ROADINS_VSTAR_H
#define ROADINS_VSTAR_H
#include <map>
#include "MknnProcessor.h"
using namespace std;
class VStar : public MknnProcessor {
private:
int k;
int x;
vector<PNode> ordered_k_x;
pair<PRoad, double> q_b;
PNode z;
double z_dist;
typedef map<long, map<long, double>> FrrMap;
FrrMap frrMap;
public:
VStar(int k, int x);
void move(Trajectory trajectory);
void calculate(const pair<PRoad, double> &pos);
bool validate_knn(const pair<PRoad, double> &pos);
};
#endif //ROADINS_VSTAR_H
<file_sep>/src/network/TrajectoryConstructor.cpp
//
// Created by chiewen on 2015/11/10.
//
#include <iostream>
#include <set>
#include <algorithm>
#include "TrajectoryConstructor.h"
#include "../algorithm/Dijkstra.h"
using namespace std;
Trajectory TrajectoryConstructor::construct_random(
const PNode &source_node, int roads_count, int step) {
vector<PRoad> roads;
set<long> already_have;
PNode current_node(source_node);
for (; roads.size() < roads_count;) {
auto next_road = find_if(current_node->roads.begin(), current_node->roads.end(),
[&](const PRoad &ptr) {
return already_have.find(ptr->to.lock()->id) == already_have.end();
});
already_have.insert(current_node->id);
if (next_road == current_node->roads.end()) {
current_node = roads.back()->from.lock();
roads.pop_back();
}
else {
roads.emplace_back(*next_road);
current_node = (*next_road)->to.lock();
}
}
return Trajectory(roads, step);
}
Trajectory TrajectoryConstructor::construct_shortest_path(const PNode &source_node,
long length, int step) {
return Trajectory(Dijkstra::shortest_path_length(source_node, length), step);
}
<file_sep>/src/network/Trajectory.cpp
//
// Created by chiewen on 2015/11/10.
//
#include <numeric>
#include "Node.h"
#include "Trajectory.h"
Trajectory::Trajectory(const vector<PRoad> &roads, double step) : roads(roads), step(step) {
current_road = this->roads.begin();
if (current_road != roads.end())
dist_to = (*current_road)->distance;
}
bool Trajectory::has_next() {
return current_road != roads.end();
}
pair<PRoad, double> Trajectory::get_then_forward() {
auto result = make_pair(*current_road, dist_to);
if (dist_to > step) dist_to -= step;
else {
double dist_from = step - dist_to;
advance(current_road, 1);
while (has_next() && dist_from > (*current_road)->distance) {
dist_from -= (*current_road)->distance;
advance(current_road, 1);
}
dist_to = current_road != roads.end() ? (*current_road)->distance - dist_from : numeric_limits<double>::max();
}
return result;
}
double Trajectory::getStep() const {
return step;
}
void Trajectory::setStep(double step) {
this->step = step;
}
double Trajectory::total_distance() {
return accumulate(roads.begin(), roads.end(), 0.0, [](double sum, const weak_ptr<Road> &ptr) {
return sum + ptr.lock()->distance;
});
}
Trajectory::roads_type::difference_type Trajectory::road_count() {
return roads.size();
}
<file_sep>/test/top_k_test.cpp
//
// Created by chiewen on 2015/11/13.
//
#include "gtest/gtest.h"
#include "test_fixture.h"
#include "../src/algorithm/Dijkstra.h"
TEST_F(NodesNetTest, TopK) {
// set<long> top_k;
// set<weak_ptr<Node>, ptr_node_less> ptr_top_k;
// auto topk = Dijkstra::top_k(nodes[0], 0, 5000, top_k, ptr_top_k);
// transform(topk.begin(), topk.end(), ostream_iterator<long>(cout, "\n"), [](const weak_ptr<Node> &n){
// return n.lock()->id;
// });
}<file_sep>/src/network/Road.h
//
// Created by chiewen on 2015/11/6.
//
#ifndef ROADINS_ROAD_H
#define ROADINS_ROAD_H
#include <memory>
#include <utility>
#include "Node.h"
using namespace std;
struct Road {
weak_ptr<Node> from;
weak_ptr<Node> to;
double distance;
Road(const PNode &t1, const PNode &t2, double distance);
};
typedef shared_ptr<Road> PRoad;
#endif //ROADINS_ROAD_H
<file_sep>/src/algorithm/INS.h
//
// Created by chiewen on 2015/11/13.
//
#ifndef ROADINS_MKNN_H
#define ROADINS_MKNN_H
#include "../network/Trajectory.h"
#include "MknnProcessor.h"
class INS : public MknnProcessor {
int k;
set<long> top_k, ins;
set<PNode, ptr_node_less> ptr_top_k;
public:
INS(int k) : k(k) { }
void move(Trajectory trajectory);
void refresh(int k, set<long> &top_k, set<PNode, ptr_node_less> &ptr_top_k, set<long> &ins,
const pair<PRoad, double> &pos);
};
#endif //ROADINS_MKNN_H
<file_sep>/src/network/Trajectory.h
//
// Created by chiewen on 2015/11/10.
//
#ifndef ROADINS_TRAJECTORY_H
#define ROADINS_TRAJECTORY_H
#include <memory>
#include <vector>
#include "Road.h"
using namespace std;
class Trajectory {
public:
typedef vector<PRoad> roads_type;
Trajectory(const vector<PRoad> &roads, double step = 50);
Trajectory(const Trajectory &trajectory) {
step = trajectory.step;
roads = trajectory.roads;
current_road = roads.begin();
dist_to = 0;
}
pair<PRoad, double> get_then_forward();
roads_type::difference_type road_count();
bool has_next();
double total_distance();
double getStep() const;
void setStep(double step);
private:
double step;
roads_type roads;
roads_type::iterator current_road;
double dist_to;
};
#endif //ROADINS_TRAJECTORY_H
<file_sep>/src/util/TimePrinter.cpp
//
// Created by chiewen on 2015/11/7.
//
#include "TimePrinter.h"
TimePrinter TimePrinter::now;
ostream& operator << (ostream &out, const TimePrinter &timePrinter) {
auto t = time(nullptr);
out << put_time(localtime(&t), "%H:%M:%S");
return out;
}<file_sep>/src/network/TrajectoryConstructor.h
//
// Created by chiewen on 2015/11/10.
//
#ifndef ROADINS_DIRECTIONALTRAJECTORYCONSTRUCTOR_H
#define ROADINS_DIRECTIONALTRAJECTORYCONSTRUCTOR_H
#include "Trajectory.h"
struct TrajectoryConstructor {
static Trajectory construct_random(const PNode &source_node, int roads_count, int step);
static Trajectory construct_shortest_path(const PNode &source_node, long length, int step);
};
#endif //ROADINS_DIRECTIONALTRAJECTORYCONSTRUCTOR_H
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.3)
project(RoadINS)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
include_directories(D:/work/lib/googletest-master/googletest/include D:/work/lib/boost_1_59_0)
set(SOURCE_FILES src/main.cpp src/network/Node.h src/network/Road.h src/io/DataReader.cpp src/io/DataReader.h src/network/Node.cpp src/network/Node.cpp src/network/Node.h src/network/Road.cpp src/algorithm/Dijkstra.cpp src/algorithm/Dijkstra.h src/util/TimePrinter.cpp src/util/TimePrinter.h src/network/Trajectory.cpp src/network/Trajectory.h test/trajectory_test.cpp src/network/TrajectoryConstructor.cpp src/network/TrajectoryConstructor.h test/test_fixture.h test/test_fixture.cpp test/top_k_test.cpp src/algorithm/INS.cpp src/algorithm/INS.h src/util/ptr_node_comp.h src/network/RoadNetwork.cpp src/network/RoadNetwork.h src/util/ptr_node_comp.cpp src/algorithm/MknnProcessor.h src/algorithm/VStar.cpp src/algorithm/VStar.h test/experiment.cpp test/experiment_multi.cpp)
aux_source_directory(test DIR_TEST)
add_executable(RoadINS ${SOURCE_FILES} ${DIR_TEST})
target_link_libraries(RoadINS D:/work/lib/googletest-master/googletest/lib/libgtest.a D:/work/lib/boost_1_59_0/stage/lib/libboost_timer-mgw52-mt-d-1_59.a D:/work/lib/boost_1_59_0/stage/lib/libboost_chrono-mgw52-mt-d-1_59.a D:/work/lib/boost_1_59_0/stage/lib/libboost_system-mgw52-mt-d-1_59.a)
<file_sep>/src/util/ptr_node_comp.h
//
// Created by chiewen on 2015/11/15.
//
#ifndef ROADINS_PTR_NODE_COMP_H
#define ROADINS_PTR_NODE_COMP_H
class Node;
using namespace std;
struct ptr_node_less {
bool operator()(const shared_ptr<Node> &pn1, const shared_ptr<Node> &pn2);
};
#endif //ROADINS_PTR_NODE_COMP_H
<file_sep>/src/network/RoadNetwork.h
//
// Created by Chiewen on 2015/11/16.
//
#ifndef ROADINS_ROADNETWORK_H
#define ROADINS_ROADNETWORK_H
#include "boost/serialization/singleton.hpp"
#include "Node.h"
#include "../util/ptr_node_comp.h"
#include "../io/DataReader.h"
using boost::serialization::singleton;
class RoadNetwork : public singleton<vector<PNode>> {
static struct _init {
_init();
} __init;
public:
static void reset(double ratio = 0, long length = 0);
static void add_sites(const vector<PNode> &nodes, double ratio);
static void set_nearest(const vector<PNode> &nodes);
static void reset_ratio(double ratio);
};
#endif //ROADINS_ROADNETWORK_H
<file_sep>/src/network/RoadNetwork.cpp
//
// Created by Chiewen on 2015/11/16.
//
#include <regex>
#include <iostream>
#include <thread>
#include "RoadNetwork.h"
#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/xml_parser.hpp"
#include "boost/core/ignore_unused.hpp"
#include "../algorithm/Dijkstra.h"
#include "../util/TimePrinter.h"
#include "boost/timer/timer.hpp"
RoadNetwork::_init RoadNetwork::__init;
RoadNetwork::_init::_init() {
boost::ignore_unused(__init);
reset();
}
void RoadNetwork::reset(double ratio, long length) {
using namespace boost::property_tree;
ptree pt;
read_xml("D:\\work\\Code\\RoadINS\\conf.xml", pt);
const string file_path = pt.get<string>("conf.file_path");
if (ratio == 0) ratio = pt.get<double>("conf.site_ratio");
vector<PNode> nodes = DataReader::read_data(file_path, length);
cout << "nodes num: " << nodes.size() << endl;
cout << "roads num: " << accumulate(nodes.begin(), nodes.end(), 0, [](long sum, const PNode &node) {
return sum + node->roads.size();
}) << endl;
add_sites(nodes, ratio);
set_nearest(nodes);
get_mutable_instance().swap(nodes);
}
void RoadNetwork::add_sites(const vector<PNode> &nodes, double ratio) {
double sum = 0;
long i = 1;
for (auto &n: nodes) {
sum += ratio;
if (sum > i) {
i++;
n->isSite = true;
}
}
}
void RoadNetwork::set_nearest(const vector<PNode> &nodes) {
boost::timer::cpu_timer timer;
auto thread_num = thread::hardware_concurrency();
auto block_size = nodes.size() / thread_num;
auto calc_dijkstra_block = [&](long s, long t) {
for (long i = s; i < t; i++) Dijkstra::find_nearest(nodes[i]);
};
vector<thread> threads_nearest;
for (int i = 0; i < thread_num - 1; i++)
threads_nearest.emplace_back(calc_dijkstra_block, block_size * i, block_size * (i + 1));
calc_dijkstra_block(block_size * (thread_num - 1), nodes.size());
for_each(threads_nearest.begin(), threads_nearest.end(), mem_fn(&thread::join));
auto calc_voronoi = [&](long s, long t) {
for (long i = s; i < t; i++)
for (auto &r: nodes[i]->roads) {
if (r->from.lock()->nearest_site.second >= 0 && r->to.lock()->nearest_site.second >= 0 &&
r->from.lock()->nearest_site.first.lock()->id != r->to.lock()->nearest_site.first.lock()->id) {
lock_guard<mutex> {r->from.lock()->nearest_site.first.lock()->mutex_voronoi};
r->from.lock()->nearest_site.first.lock()->voronoi_neighbors.insert(
r->to.lock()->nearest_site.first.lock()->id);
}
}
};
vector<thread> threads_voronoi;
for (int i = 0; i < thread_num - 1; i++)
threads_voronoi.emplace_back(calc_voronoi, block_size * i, block_size * (i + 1));
calc_voronoi(block_size * (thread_num - 1), nodes.size());
for_each(threads_voronoi.begin(), threads_voronoi.end(), mem_fn(&thread::join));
}
void RoadNetwork::reset_ratio(double ratio) {
auto &nodes = get_mutable_instance();
for (auto &n : nodes) {
n->isSite = false;
n->voronoi_neighbors.clear();
}
add_sites(nodes, ratio);
set_nearest(nodes);
}
<file_sep>/src/io/DataReader.h
//
// Created by chiewen on 2015/11/7.
//
#ifndef ROADINS_DATAREADER_H
#define ROADINS_DATAREADER_H
#include <vector>
#include <string>
#include "../network/Node.h"
#include "../network/Road.h"
using namespace std;
class DataReader {
public:
static vector<PNode> read_data(const string &name, long length = 0);
private:
static void read_nodes(const string &name, vector<PNode> &all_nodes, long length = 0);
static void read_roads(const string &name, vector<PNode> &all_nodes);
static vector<string> read_file(const string &name);
};
#endif //ROADINS_DATAREADER_H
<file_sep>/src/algorithm/MknnProcessor.h
//
// Created by chiewen on 2015/11/24.
//
#ifndef ROADINS_MKNNPROCESSOR_H
#define ROADINS_MKNNPROCESSOR_H
#include <chrono>
#include "../network/Trajectory.h"
using namespace std;
class MknnProcessor {
chrono::steady_clock::time_point start_time_server;
chrono::steady_clock::time_point start_time_client;
chrono::steady_clock::duration duration_server;
chrono::steady_clock::duration duration_client;
protected:
MknnProcessor() : total_step(0), communication(0), page(0),
duration_server(chrono::steady_clock::duration()),
duration_client(chrono::steady_clock::duration()) { }
long communication;
long page;
void server_start() { start_time_server = chrono::steady_clock::now(); }
void server_pause() { duration_server += chrono::steady_clock::now() - start_time_server; }
void client_start() { start_time_client = chrono::steady_clock::now(); }
void client_pause() { duration_client += chrono::steady_clock::now() - start_time_client; }
void client_to_server() {
client_pause();
server_start();
}
void server_to_client() {
server_pause();
client_start();
}
public:
long total_step;
long num_server() { return (long) chrono::duration_cast<chrono::milliseconds>(duration_server).count(); }
long num_client() { return (long) chrono::duration_cast<chrono::milliseconds>(duration_client).count(); }
long num_page() { return page; }
long num_communication() { return communication; }
virtual void move(Trajectory trajectory) = 0;
};
#endif //ROADINS_MKNNPROCESSOR_H
<file_sep>/src/algorithm/Dijkstra.h
//
// Created by chiewen on 2015/11/7.
//
#ifndef ROADINS_DIJKSTRA_H
#define ROADINS_DIJKSTRA_H
#include <memory>
#include <map>
#include <vector>
#include <set>
#include "../network/Node.h"
#include "../util/ptr_node_comp.h"
#include "../network/Road.h"
using namespace std;
class Dijkstra {
public:
static void find_nearest(const PNode &ptr_node);
static void top_k(const PNode &ptr_node,
double dist_to_node, int k, set<long> &top_k,
set<PNode, ptr_node_less> &ptr_top_k, long &page);
static void top_k_vstar(const pair<PRoad, double> &pos, int k, vector<PNode> &top_k, long &page);
static void top_k_with_distance(const PNode &ptr_node, int k, const vector<PNode> &ordered_k_x,
map<long, double> &top_k);
static vector<PRoad>
shortest_path(const PNode &ptr_from, const PNode &ptr_to);
static vector<PRoad>
shortest_path_length(const PNode &ptr_from, long length);
static bool verify(int k, const PNode &query_object, double dist_to_next,
const set<long> &top_k, const set<long> &ins);
static double distance_to(const PNode &ptr_from, double dist, const PNode &ptr_to);
static double distance_to_bidirection(const pair<PRoad, double> &pos, const PNode &ptr_to);
private:
typedef map<long, pair<double, PNode>> known_map;
};
#endif //ROADINS_DIJKSTRA_H
<file_sep>/src/algorithm/Dijkstra.cpp
//
// Created by chiewen on 2015/11/7.
//
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include "Dijkstra.h"
using namespace std;
void Dijkstra::find_nearest(const PNode &ptr_node) {
known_map known_nodes;
known_nodes[ptr_node->id] = make_pair(0.0, ptr_node);
typedef vector<pair<PNode, double>> neighbor_vec;
set<long> searched;
bool found = false;
while (!known_nodes.empty()) {
typedef known_map::value_type map_value;
auto min = min_element(known_nodes.begin(), known_nodes.end(),
[](const map_value &l, const map_value &r) { return l.second.first < r.second.first; });
auto p_min = min->second.second;
if (p_min->isSite) {
ptr_node->nearest_site = make_pair(p_min, min->second.first);
found = true;
break;
}
auto d_min = min->second.first;
searched.insert(p_min->id);
known_nodes.erase(min);
for (auto &n: p_min->roads) {
auto pn = PNode(n->to);
if (searched.find(pn->id) != searched.end()) continue;
auto m = known_nodes.find(pn->id);
if (m == known_nodes.end())
known_nodes[pn->id] = make_pair(d_min + n->distance, pn);
else if (m->second.first > d_min + n->distance)
m->second.first = d_min + n->distance;
}
}
if (!found) ptr_node->nearest_site = make_pair(ptr_node, -1);
}
void Dijkstra::top_k(const PNode &ptr_node, double dist_to_node, int k,
set<long> &top_k, set<PNode, ptr_node_less> &ptr_top_k, long &page) {
known_map known_nodes;
known_nodes[ptr_node->id] = make_pair(dist_to_node, ptr_node);
ptr_top_k.clear();
set<long> searched;
while (!known_nodes.empty()) {
typedef known_map::value_type map_value;
auto min = min_element(known_nodes.begin(), known_nodes.end(),
[](const map_value &l, const map_value &r) { return l.second.first < r.second.first; });
auto p_min = min->second.second;
if (p_min->isSite) {
ptr_top_k.insert(p_min);
if (ptr_top_k.size() == k) break;
}
auto d_min = min->second.first;
searched.insert(p_min->id);
known_nodes.erase(min);
for (auto &n: p_min->roads) {
++page;
auto pn = PNode(n->to);
if (searched.find(pn->id) != searched.end()) continue;
auto m = known_nodes.find(pn->id);
if (m == known_nodes.end())
known_nodes[pn->id] = make_pair(d_min + n->distance, pn);
else if (m->second.first > d_min + n->distance)
m->second.first = d_min + n->distance;
}
}
top_k.clear();
transform(ptr_top_k.begin(), ptr_top_k.end(), inserter(top_k, top_k.begin()),
[](const PNode &n) { return n->id; });
}
void Dijkstra::top_k_vstar(const pair<PRoad, double> &pos, int k, vector<PNode> &top_k, long &page) {
known_map known_nodes;
known_nodes.insert(make_pair(pos.first->to.lock()->id, make_pair(pos.second, pos.first->to.lock())));
known_nodes.insert(make_pair(pos.first->from.lock()->id,
make_pair(pos.first->distance - pos.second, pos.first->from.lock())));
top_k.clear();
set<long> searched;
while (!known_nodes.empty()) {
typedef known_map::value_type map_value;
auto min = min_element(known_nodes.begin(), known_nodes.end(),
[](const map_value &l, const map_value &r) { return l.second.first < r.second.first; });
auto p_min = min->second.second;
if (p_min->isSite) {
top_k.push_back(p_min);
if (top_k.size() == k) break;
}
auto d_min = min->second.first;
searched.insert(p_min->id);
known_nodes.erase(min);
for (auto &n: p_min->roads) {
++page;
auto pn = PNode(n->to);
if (searched.find(pn->id) != searched.end()) continue;
auto m = known_nodes.find(pn->id);
if (m == known_nodes.end())
known_nodes[pn->id] = make_pair(d_min + n->distance, pn);
else if (m->second.first > d_min + n->distance)
m->second.first = d_min + n->distance;
}
}
}
vector<PRoad> Dijkstra::shortest_path(const PNode &ptr_from, const PNode &ptr_to) {
vector<PRoad> result;
map<long, tuple<double, PNode, PRoad>> known_nodes;
known_nodes.insert(make_pair(ptr_from->id, make_tuple(0, ptr_from, nullptr)));
map<long, PRoad> searched;
while (!known_nodes.empty()) {
typedef remove_reference<decltype(known_nodes)>::type::value_type map_value;
auto min = min_element(known_nodes.begin(), known_nodes.end(),
[](const map_value &l, const map_value &r) {
return get<0>(l.second) < get<0>(r.second);
});
auto p_min = get<1>(min->second);
auto d_min = get<0>(min->second);
searched.insert(make_pair(p_min->id, get<2>(min->second)));
known_nodes.erase(min);
if (p_min->id == ptr_to->id) {
for (auto previous = searched[p_min->id]; previous; previous = searched.at(previous->from.lock()->id))
result.push_back(previous);
break;
}
else
for (auto &n: p_min->roads) {
auto pn = PNode(n->to);
if (searched.find(pn->id) != searched.end()) continue;
auto m = known_nodes.find(pn->id);
if (m == known_nodes.end())
known_nodes.insert(make_pair(pn->id, make_tuple(d_min + n->distance, pn, n)));
else if (get<0>(m->second) > d_min + n->distance) {
get<0>(m->second) = d_min + n->distance;
get<2>(m->second) = n;
}
}
}
return result;
}
bool Dijkstra::verify(int k, const PNode &query_object, double dist_to_next,
const set<long> &top_k, const set<long> &ins) {
known_map known_nodes;
known_nodes.insert(make_pair(query_object->id, make_pair(dist_to_next, query_object)));
int count = 0;
set<long> searched;
while (!known_nodes.empty()) {
typedef known_map::value_type map_value;
auto min = min_element(known_nodes.begin(), known_nodes.end(),
[](const map_value &l, const map_value &r) { return l.second.first < r.second.first; });
auto p_min = min->second.second;
if (p_min->isSite) {
if (find(top_k.begin(), top_k.end(), p_min->id) == top_k.end()) return false;
if (++count == k) return true;
}
auto d_min = min->second.first;
searched.insert(p_min->id);
known_nodes.erase(min);
for (auto &n: p_min->roads) {
auto pn = PNode(n->to);
auto nearest_id = pn->nearest_site.first.lock()->id;
if (ins.find(nearest_id) == ins.end() && top_k.find(nearest_id) == top_k.end()) continue;
if (searched.find(pn->id) != searched.end()) continue;
auto m = known_nodes.find(pn->id);
if (m == known_nodes.end())
known_nodes[pn->id] = make_pair(d_min + n->distance, pn);
else if (m->second.first > d_min + n->distance)
m->second.first = d_min + n->distance;
}
}
return false;
}
double Dijkstra::distance_to(const PNode &ptr_from, double dist, const PNode &ptr_to) {
auto roads = shortest_path(ptr_from, ptr_to);
return dist + accumulate(roads.begin(), roads.end(), 0,
[](double i, const PRoad &r) { return i + r->distance; });
}
void Dijkstra::top_k_with_distance(const PNode &ptr_node, int k, const vector<PNode> &ordered_k_x,
map<long, double> &top_k) {
known_map known_nodes;
known_nodes.insert(make_pair(ptr_node->id, make_pair(0, ptr_node)));
top_k.clear();
set<long> searched;
while (!known_nodes.empty()) {
typedef known_map::value_type map_value;
auto min = min_element(known_nodes.begin(), known_nodes.end(),
[](const map_value &l, const map_value &r) { return l.second.first < r.second.first; });
auto p_min = min->second.second;
if (find_if(ordered_k_x.begin(), ordered_k_x.end(), [&p_min](const PNode &p) {
return p->id == p_min->id;
}) != ordered_k_x.end()) {
top_k.insert(make_pair(p_min->id, min->second.first));
if (top_k.size() == k) break;
}
auto d_min = min->second.first;
searched.insert(p_min->id);
known_nodes.erase(min);
for (auto &n: p_min->roads) {
auto pn = PNode(n->to);
if (searched.find(pn->id) != searched.end()) continue;
auto m = known_nodes.find(pn->id);
if (m == known_nodes.end())
known_nodes[pn->id] = make_pair(d_min + n->distance, pn);
else if (m->second.first > d_min + n->distance)
m->second.first = d_min + n->distance;
}
}
}
double Dijkstra::distance_to_bidirection(const pair<PRoad, double> &pos, const PNode &ptr_to) {
return min(distance_to(pos.first->to.lock(), pos.second, ptr_to),
distance_to(pos.first->from.lock(), pos.first->distance - pos.second, ptr_to));
}
vector<PRoad> Dijkstra::shortest_path_length(const PNode &ptr_from, long length) {
vector<PRoad> result;
map<long, tuple<double, PNode, PRoad>> known_nodes;
known_nodes.insert(make_pair(ptr_from->id, make_tuple(0, ptr_from, nullptr)));
map<long, pair<PRoad, int>> searched;
// int max = 0;
while (!known_nodes.empty()) {
typedef remove_reference<decltype(known_nodes)>::type::value_type map_value;
auto min = min_element(known_nodes.begin(), known_nodes.end(),
[](const map_value &l, const map_value &r) {
return get<0>(l.second) < get<0>(r.second);
});
auto p_min = get<1>(min->second);
auto d_min = get<0>(min->second);
int dist = 0;
if (get<2>(min->second) != nullptr) {
auto pr = searched.find(get<2>(min->second)->from.lock()->id);
if (pr != searched.end()) dist = pr->second.second + 1;
}
// if (dist > max) max = dist;
searched.insert(make_pair(p_min->id, make_pair(get<2>(min->second), dist)));
known_nodes.erase(min);
if (dist >= length) {
for (auto previous = searched[p_min->id]; previous.first; previous = searched.at(previous.first->from.lock()->id))
result.push_back(previous.first);
break;
}
else
for (auto &n: p_min->roads) {
auto pn = PNode(n->to);
if (searched.find(pn->id) != searched.end()) continue;
auto m = known_nodes.find(pn->id);
if (m == known_nodes.end())
known_nodes.insert(make_pair(pn->id, make_tuple(d_min + n->distance, pn, n)));
else if (get<0>(m->second) > d_min + n->distance) {
get<0>(m->second) = d_min + n->distance;
get<2>(m->second) = n;
}
}
}
// if (result.empty()) cerr << "empty at " << max << endl;
return result;
}
<file_sep>/test/net_test.cpp
//
// Created by Chiewen on 2015/11/6.
//
#include <iostream>
#include <algorithm>
#include "gtest/gtest.h"
#include "../src/io/DataReader.h"
#include "test_fixture.h"
#include "../src/network/Trajectory.h"
#include "../src/network/RoadNetwork.h"
#include "../src/network/TrajectoryConstructor.h"
TEST_F(NodesNetTest, Traj) {
auto &nodes = RoadNetwork::get_mutable_instance();
auto t = TrajectoryConstructor::construct_random(nodes[0], 500, 50);
cout << to_string(t.total_distance()) << "\t" << t.road_count() << "\t" <<to_string(t.total_distance()/50)<< endl;
}
<file_sep>/src/algorithm/INS.cpp
//
// Created by chiewen on 2015/11/13.
//
#include <algorithm>
#include <set>
#include "INS.h"
#include "Dijkstra.h"
void INS::move(Trajectory trajectory) {
client_start();
top_k.clear();
ins.clear();
refresh(k, top_k, ptr_top_k, ins, trajectory.get_then_forward());
for (auto pos = trajectory.get_then_forward(); trajectory.has_next(); pos = trajectory.get_then_forward()) {
if (!Dijkstra::verify(k, pos.first->to.lock(), pos.second, top_k, ins))
++communication, refresh(k, top_k, ptr_top_k, ins, pos);
++total_step;
}
client_pause();
}
void INS::refresh(int k, set<long> &top_k, set<PNode, ptr_node_less> &ptr_top_k, set<long> &ins,
const pair<PRoad, double> &pos) {
client_to_server();
Dijkstra::top_k(pos.first->to.lock(), pos.second, k, top_k, ptr_top_k, page);
ins.clear();
for (auto &t : ptr_top_k) {
auto &neighbors = t->voronoi_neighbors;
set_difference(neighbors.begin(), neighbors.end(), top_k.begin(), top_k.end(), inserter(ins, ins.end()));
}
server_to_client();
}
<file_sep>/src/network/Node.h
//
// Created by chiewen on 2015/11/7.
//
#ifndef ROADINS_NODE_H
#define ROADINS_NODE_H
#include <vector>
#include <memory>
#include <mutex>
#include <set>
#include "../util/ptr_node_comp.h"
using namespace std;
class Road;
struct Node {
long id;
bool isSite = false;
double x, y;
pair<weak_ptr<Node>, double> nearest_site;
set<long> voronoi_neighbors;
mutex mutex_voronoi;
vector<shared_ptr<Road>> roads;
mutex mutex_roads;
Node(long id, double x, double y);
};
typedef shared_ptr<Node> PNode;
#endif //ROADINS_NODE_H
<file_sep>/src/network/Node.cpp
//
// Created by chiewen on 2015/11/7.
//
#include "Node.h"
#include "Road.h"
#include "../util/ptr_node_comp.h"
using namespace std;
Node::Node(long id, double x, double y) : id(id), x(x), y(y) { }<file_sep>/src/io/DataReader.cpp
//
// Created by chiewen on 2015/11/7.
//
#include <iostream>
#include <fstream>
#include <regex>
#include <thread>
#include <future>
#include "DataReader.h"
#include "../util/TimePrinter.h"
#include "boost/timer/timer.hpp"
using namespace std;
vector<PNode> DataReader::read_data(const string &name, long length) {
vector<PNode> all_nodes;
read_nodes(name, all_nodes, length);
read_roads(name, all_nodes);
return all_nodes;
}
void DataReader::read_nodes(const string &name, vector<PNode> &all_nodes, long length) {
boost::timer::cpu_timer timer;
cout << endl << "start reading node file from " << name << ".co " << TimePrinter::now << endl;
vector<string> vec_lines = read_file(name + ".co");
cout << "file reading finished at " << TimePrinter::now << " now parsing..." << endl;
auto thread_num = thread::hardware_concurrency();
long node_length = length == 0 ? (long)vec_lines.size() : length;
auto block_size = node_length / thread_num;
regex reg_node("v (\\d*) (-?\\d*) (\\d*)");
auto construct_nodes = [&](long s, long t) -> vector<PNode> {
vector<PNode> nodes;
smatch m;
for (int i = s; i < t; i++) {
if (regex_search(vec_lines[i].cbegin(), vec_lines[i].cend(), m, reg_node))
nodes.push_back(make_shared<Node>(stol(m.str(1)), stod(m.str(2)), stod(m.str(3))));
}
return nodes;
};
vector<future<vector<PNode>>> vec_future;
for (long i = 0; i < thread_num - 1; i++)
vec_future.push_back(async(launch::async, construct_nodes, block_size * i, block_size * (i + 1)));
auto nodes = construct_nodes(block_size * (thread_num - 1), node_length);
for (auto &f: vec_future) {
auto v = f.get();
all_nodes.insert(all_nodes.end(), v.begin(), v.end());
}
all_nodes.insert(all_nodes.end(), nodes.begin(), nodes.end());
cout << "nodes finished." << TimePrinter::now << "\t" << timer.format() << endl;
}
vector<string> DataReader::read_file(const string &name) {
vector<string> vec_lines;
string line;
ifstream node_file(name);
for (int i = 0; i < 7; i++) getline(node_file, line);
while (getline(node_file, line)) vec_lines.push_back(line);
node_file.close();
return vec_lines;
}
void DataReader::read_roads(const string &name, vector<PNode> &all_nodes) {
boost::timer::cpu_timer timer;
cout << endl << "start reading road file from " << name << ".gr " << TimePrinter::now << endl;
vector<string> vec_lines = read_file(name + ".gr");
cout << "file reading finished at " << TimePrinter::now << " now parsing..." << endl;
auto thread_num = thread::hardware_concurrency();
auto block_size = vec_lines.size() / thread_num;
regex reg_road("a (\\d*) (\\d*) (\\d*)");
auto insert_road = [&](long s, long t) {
smatch m;
for (long i = s; i < t; i++) {
if (regex_search(vec_lines[i].cbegin(), vec_lines[i].cend(), m, reg_road)) {
auto a1 = lower_bound(all_nodes.begin(), all_nodes.end(), make_shared<Node>(stol(m.str(1)), 0, 0),
[](const PNode &a, const PNode &b) {
return a->id < b->id;
});
auto a2 = lower_bound(all_nodes.begin(), all_nodes.end(), make_shared<Node>(stol(m.str(2)), 0, 0),
[](const PNode &a, const PNode &b) {
return a->id < b->id;
});
if (a1 != all_nodes.end() && a2 != all_nodes.end()) {
//we use the dataset as undirected graph
if (find_if((*a1)->roads.begin(), (*a1)->roads.end(), [&a2](const PRoad &r) {
return r->to.lock()->id == (*a2)->id;
}) != (*a1)->roads.end())
continue;
auto road = make_shared<Road>(*a1, *a2, stod(m.str(3)));
{
lock_guard<mutex> {(*a1)->mutex_roads};
(*a1)->roads.push_back(road);
}
auto road1 = make_shared<Road>(*a2, *a1, stod(m.str(3)));
lock_guard<mutex> {(*a2)->mutex_roads};
(*a2)->roads.push_back(road1);
}
}
}
};
vector<thread> vec_threads;
for (int i = 0; i < thread_num - 1; i++)
vec_threads.emplace_back(insert_road, block_size * i, block_size * (i + 1));
insert_road(block_size * (thread_num - 1), vec_lines.size());
for_each(vec_threads.begin(), vec_threads.end(), mem_fn(&thread::join));
cout << "finish reading roads " << TimePrinter::now << "\t" << timer.format() << endl;
}
<file_sep>/test/experiment_multi.cpp
//
// Created by chiewen on 2015/12/10.
//
#include <gtest/gtest.h>
#include <thread>
#include "../src/network/Node.h"
#include "../src/network/Trajectory.h"
#include "../src/algorithm/INS.h"
#include "../src/network/RoadNetwork.h"
#include "../src/algorithm/VStar.h"
#include "../src/network/TrajectoryConstructor.h"
#include "../src/util/TimePrinter.h"
typedef typename vector<shared_ptr<MknnProcessor>>::iterator MPIter;
void print_result1(string name, MPIter start, MPIter end) {
vector<long> v_page, v_server, v_client, v_communication;
for (auto &p = start; p != end; p++) {
v_page.push_back((*p)->num_page());
v_server.push_back((*p)->num_server());
v_client.push_back((*p)->num_client());
v_communication.push_back((*p)->num_communication());
}
sort(v_page.begin(), v_page.end());
sort(v_server.begin(), v_server.end());
sort(v_client.begin(), v_client.end());
sort(v_communication.begin(), v_communication.end());
cout << name << ":\t"
<< accumulate(v_page.begin() + 4, v_page.begin() + 8, 0) / 4 << "\t"
<< accumulate(v_server.begin() + 4, v_server.begin() + 8, 0) / 4 << "\t"
<< accumulate(v_client.begin() + 4, v_client.begin() + 8, 0) / 4 << "\t"
<< accumulate(v_communication.begin() + 4, v_communication.begin() + 8, 0) / 4 << "\t";
}
void execute1(const vector<PNode> &nodes, int length, int k, int x, int step) {
vector<Trajectory> trajectories;
trajectories.reserve(10);
// cout << "\n============= experiment start at " << TimePrinter::now << " =============" << endl;
for (int i = 0; i < 100000; i += 20000)
trajectories.emplace_back(TrajectoryConstructor::construct_random(nodes[i], length, step));
cout << "R " << TimePrinter::now << "\t";
for (int i = 0; i < 100000; i += 20000)
trajectories.emplace_back(TrajectoryConstructor::construct_shortest_path(nodes[i], length, step));
cout << "D " << TimePrinter::now << "\t";
vector<shared_ptr<MknnProcessor>> vs;
vs.reserve(10);
for (int i = 0; i < 10; ++i)
vs.emplace_back(make_shared<VStar>(k, x));
vector<shared_ptr<MknnProcessor>> ins;
for (int i = 0; i < 10; ++i)
ins.emplace_back(make_shared<INS>(k));
cout << "moving " << TimePrinter::now << "\t";
for (int i = 0; i < 10; ++i)
vs[i]->move(trajectories[i]);
for (int i = 0; i < 10; ++i)
ins[i]->move(trajectories[i]);
print_result1("VR", vs.begin(), vs.begin() + 5);
print_result1("VD", vs.begin() + 5, vs.end());
print_result1("IR", ins.begin(), ins.begin() + 5);
print_result1("ID", ins.begin() + 5, ins.end());
cout << endl;
}
void execute1(const vector<PNode> &nodes, vector<Trajectory> &trajectories, int k, int x, int step) {
for (auto &t: trajectories)
t.setStep(step);
vector<shared_ptr<MknnProcessor>> mps;
mps.reserve(48);
for (int i = 0; i < 24; ++i)
mps.emplace_back(make_shared<VStar>(k, x));
for (int i = 0; i < 24; ++i)
mps.emplace_back(make_shared<INS>(k));
vector<thread> vt;
vt.reserve(12);
for (int j = 0; j < 4; ++j) {
for (int i = 12 * j; i < 12 * (j + 1); i++)
vt.emplace_back([&mps, i, &trajectories]() {
mps[i]->move(trajectories[i]);
});
for (auto &t : vt) t.join();
vt.clear();
}
print_result1("VR", mps.begin(), mps.begin() + 12);
print_result1("VD", mps.begin() + 12, mps.begin() + 24);
print_result1("IR", mps.begin() + 24, mps.begin() + 36);
print_result1("ID", mps.begin() + 36, mps.end());
cout << endl;
}
TEST(Experiment, Multi) {
auto &nodes = RoadNetwork::get_mutable_instance();
int length = 500;
int k = 10;
int x = 6;
int step = 40;
vector<Trajectory> trajectories;
trajectories.reserve(48);
cout << "\n============= experiment start at " << TimePrinter::now << " =============\n" << endl;
for (int i = 0; i < 120000; i += 40000) {
auto traj = TrajectoryConstructor::construct_random(nodes[i], length, step);
trajectories.emplace_back(traj);
trajectories.emplace_back(traj);
trajectories.emplace_back(traj);
trajectories.emplace_back(traj);
}
cout << "R " << TimePrinter::now << endl;
vector<thread> vt;
mutex m_traj;
for (int i = 0; i < 120000; i += 40000)
vt.emplace_back([i, length, step, &m_traj, &trajectories, &nodes]() {
auto t = TrajectoryConstructor::construct_shortest_path(nodes[i], length, step);
lock_guard<mutex> {m_traj};
trajectories.push_back(t);
trajectories.push_back(t);
trajectories.push_back(t);
trajectories.push_back(t);
});
for (auto &t : vt)
t.join();
cout << "D " << TimePrinter::now << endl;
copy(trajectories.begin(), trajectories.begin() + 24, back_inserter(trajectories));
// cout << endl << "k = 1 to 20" << endl;
// for (int i = 1; i < 20; i++)
// execute(nodes, trajectories, i, x, step);
// cout << endl << "x = 5 to 20" << endl;
// for (int i = 1; i < 20; i++)
// execute(nodes, trajectories, k, i, step);
cout << endl << "step = 50 to 2000 step 50" << endl;
for (int i = 50; i < 1000; i += 25)
execute1(nodes, trajectories, k, x, i);
cout << endl << "ratio = 0.25 to 5 step 0.25" << endl;
for (double ratio = 0.05; ratio <= 0.11; ratio += 0.005) {
RoadNetwork::reset_ratio(ratio);
execute1(nodes, trajectories, k, x, step);
}
}
<file_sep>/test/test_fixture.h
//
// Created by chiewen on 2015/11/10.
//
#ifndef ROADINS_TEST_FIXTURE_H
#define ROADINS_TEST_FIXTURE_H
#include <gtest/gtest.h>
#include "../src/network/Node.h"
#include "../src/io/DataReader.h"
#include "../src/util/ptr_node_comp.h"
class NodesNetTest : public ::testing::Test {
protected:
vector<PNode> nodes;
virtual void SetUp();
};
#endif //ROADINS_TEST_FIXTURE_H
<file_sep>/test/trajectory_test.cpp
//
// Created by chiewen on 2015/11/10.
//
#include <gtest/gtest.h>
#include <boost/timer/timer.hpp>
#include "../src/network/Node.h"
#include "../src/network/Trajectory.h"
#include "test_fixture.h"
#include "../src/algorithm/INS.h"
#include "../src/network/RoadNetwork.h"
#include "../src/algorithm/VStar.h"
#include "../src/network/TrajectoryConstructor.h"
#include "../src/util/TimePrinter.h"
TEST(Trajectory, Simple) {
auto n0 = make_shared<Node>(0, 0, 0);
auto n1 = make_shared<Node>(1, 0, 0);
auto n2 = make_shared<Node>(2, 0, 0);
vector<PRoad> roads;
roads.push_back(make_shared<Road>(n0, n1, 100));
roads.push_back(make_shared<Road>(n1, n2, 120));
Trajectory t1{move(roads), 25};
ASSERT_EQ(t1.total_distance(), 220);
for (int i = 0; i < 4; i++) t1.get_then_forward();
ASSERT_EQ(t1.get_then_forward().second, 120);
for (int i = 0; i < 4; i++) t1.get_then_forward();
ASSERT_EQ(t1.has_next(), false);
}
//TEST_F(NodesNetTest, Construct) {
//
// auto traj = TrajectoryConstructor::construct_random(nodes[0], 50);
//
// ASSERT_EQ(traj.road_count(), 50);
//
// while (traj.has_next()) {
// auto c = traj.get_then_forward();
// cout << c.first->from.lock()->id << ":" << c.first->to.lock()->id
// << "(" << c.first->distance << ")" << "-->" << c.second << endl;
// }
//}
TEST_F(NodesNetTest, Construct) {
auto &nodes = RoadNetwork::get_mutable_instance();
auto path2 = TrajectoryConstructor::construct_random(nodes[100], 500, 50);
cout << "path 2 " << path2.road_count() << endl;
auto path1 = TrajectoryConstructor::construct_shortest_path(
nodes[0], 500, 50);
cout << "path 1 " << path1.road_count() << endl;
{
VStar vs(10, 6);
cout << "VS " << TimePrinter::now << endl;
boost::timer::cpu_timer timer;
vs.move(path1);
cout << "VS\ntimer: " << timer.format();
cout << "page:" << vs.num_page() << endl;
cout << "server:" << vs.num_server() << endl;
cout << "client:" << vs.num_client() << endl;
cout << "communication:" << vs.num_communication() << endl;
cout << "total step:" << vs.total_step << endl << endl;
cout << "VS" << TimePrinter::now << endl;
INS ins(10);
cout << "INS " << TimePrinter::now << endl;
boost::timer::cpu_timer timer1;
ins.move(path1);
cout << "INS\ntimer: " << timer1.format();
cout << "page:" << ins.num_page() << endl;
cout << "server:" << ins.num_server() << endl;
cout << "client:" << ins.num_client() << endl;
cout << "communication:" << ins.num_communication() << endl;
cout << "total step:" << ins.total_step << endl << endl;
}
{
VStar vs(10, 6);
cout << "VS " << TimePrinter::now << endl;
boost::timer::cpu_timer timer;
vs.move(path2);
cout << "VS\ntimer: " << timer.format();
cout << "page:" << vs.num_page() << endl;
cout << "server:" << vs.num_server() << endl;
cout << "client:" << vs.num_client() << endl;
cout << "communication:" << vs.num_communication() << endl;
cout << "total step:" << vs.total_step << endl << endl;
INS ins(10);
cout << "INS " << TimePrinter::now << endl;
boost::timer::cpu_timer timer1;
ins.move(path2);
cout << "INS\ntimer: " << timer1.format();
cout << "page:" << ins.num_page() << endl;
cout << "server:" << ins.num_server() << endl;
cout << "client:" << ins.num_client() << endl;
cout << "communication:" << ins.num_communication() << endl;
cout << "total step:" << ins.total_step << endl << endl;
}
}<file_sep>/src/util/TimePrinter.h
//
// Created by chiewen on 2015/11/7.
//
#ifndef ROADINS_TIMEPRINTER_H
#define ROADINS_TIMEPRINTER_H
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
struct TimePrinter {
static TimePrinter now;
};
ostream& operator << (ostream &out, const TimePrinter &timePrinter);
#endif //ROADINS_TIMEPRINTER_H
<file_sep>/src/network/Road.cpp
//
// Created by chiewen on 2015/11/7.
//
#include "Road.h"
Road::Road(const PNode &t1, const PNode &t2, double distance) :
from(t1), to(t2), distance(distance) { }
|
ca865ab1f67a1e71351d8720d1ce8212ad29c573
|
[
"C",
"CMake",
"C++"
] | 31 |
C++
|
chiewen/RoadINS
|
d4b3a821a0e50a2caebd27c1a50103e494127386
|
e0b225af2ccad5a910807425ce9ca9fef43d0b0e
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.