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>twigz826/Oystercard<file_sep>/lib/oystercard.rb require_relative 'station' require_relative 'journey' class Oystercard DEFAULT_BALANCE = 0 MAX_BALANCE = 90 MIN_FARE = 1 attr_reader :balance, :journeys, :journey def initialize(balance = DEFAULT_BALANCE) @balance = balance @journeys = [] end def top_up(amount) raise "Max balance of #{MAX_BALANCE} exceeded" if amount + @balance > MAX_BALANCE @balance += amount end def touch_in(station) touch_out(nil) if !@journey.nil? raise "Insufficient balance, balance must exceed #{MIN_FARE}" if @balance < MIN_FARE @journey = Journey.new(station) end def touch_out(station) @journey = Journey.new if @journey == nil @journeys.push(@journey.exit(station)) complete_journey end def complete_journey deduct(@journey.fare) @journey = nil end private def deduct(amount) @balance -= amount end end <file_sep>/README.md ## Oystercard This program was written as part of week 2 of the [Makers Academy](https://makers.tech) coding bootcamp. The task was to create a program in ruby that emulates the oystercard system that was previously used in the London Underground transport system. This repo was built using alternating pair programming following a TDD approach. ## User stories We were given the following user stories as a guide to help us build the program: ``` In order to use public transport As a customer I want money on my card In order to keep using public transport As a customer I want to add money to my card In order to protect my money As a customer I don't want to put too much money on my card In order to pay for my journey As a customer I need my fare deducted from my card In order to get through the barriers As a customer I need to touch in and out In order to pay for my journey As a customer I need to have the minimum amount for a single journey In order to pay for my journey As a customer I need to pay for my journey when it's complete In order to pay for my journey As a customer I need to know where I've travelled from In order to know where I have been As a customer I want to see to all my previous trips In order to know how far I have travelled As a customer I want to know what zone a station is in In order to be charged correctly As a customer I need a penalty charge deducted if I fail to touch in or out In order to be charged the correct amount As a customer I need to have the correct fare calculated ``` ## How to use the app Clone the current repository ``` $ git clone https://github.com/twigz826/oystercard.git ``` Go to the root directory of the cloned repo and run bundle ``` $ bundle ``` Run irb to run the app from the command line and play with the code ``` $ irb -r ./lib/oystercard ``` Run rspec to run the tests ``` $ rspec ``` <file_sep>/spec/oystercard_spec.rb require 'oystercard' describe Oystercard do let(:card) { described_class.new } let(:toppedup_card) { described_class.new(Oystercard::MAX_BALANCE) } let(:entry_station){ double :entry_station } let(:exit_station){ double :exit_station } let(:journey){ {entry_station: entry_station, exit_station: exit_station} } describe '#balance' do it "starts with a balance of 0" do expect(card.balance).to eq 0 end end describe '#top_up' do it { is_expected.to respond_to(:top_up).with(1).argument } it "adds money on to an oystercard" do expect { card.top_up(5) }.to change { card.balance }.by(5) end it "returns an error if the max balance permitted is exceeded" do expect { toppedup_card.top_up (5) }.to raise_error("Max balance of #{Oystercard::MAX_BALANCE} exceeded") end end describe '#touch_out' do it "deducts the minimum fare on touch_out" do toppedup_card.touch_in(entry_station) expect { toppedup_card.touch_out(exit_station) }.to change { toppedup_card.balance }.by(-Oystercard::MIN_FARE) end end describe '#touch_in' do it "throws an error if a card with insufficient balance touches in" do expect { card.touch_in(entry_station) }.to raise_error("Insufficient balance, balance must exceed #{Oystercard::MIN_FARE}") end end describe '#journeys' do it "initially has no journeys stored" do expect(toppedup_card.journeys).to be_empty end end end <file_sep>/lib/station.rb class Station attr_reader :name, :zone_number def initialize(name, zone_number) @name = name @zone_number = zone_number end end <file_sep>/spec/station_spec.rb require 'station' describe Station do let(:station) { described_class.new("Bank", 1) } it "knows its name" do expect(station.name).to eq "Bank" end it "knows its zone number" do expect(station.zone_number).to eq 1 end end <file_sep>/lib/journey.rb class Journey PENALTY_FARE = 6 MIN_FARE = 1 attr_reader :entry_station, :exit_station def initialize(entry_station = nil) @entry_station = entry_station @complete = false end def exit(station = nil) @exit_station = station @complete = true self end def fare penalty? ? PENALTY_FARE : MIN_FARE end def complete? @complete end private def penalty? (@entry_station.nil? || @exit_station.nil?) end end <file_sep>/Process.md # GUIDE ## Step 1 1. `bundle init` - initializes Gemfile 2. `rvm install 2.7.1` - install required version of ruby 3. Added this to the Gemfile: ``` group :development, :test do gem "rspec" end ``` 4. Add `ruby '2.7.1'` to the Gemfile 5. `bundle` - installs necessary gems ## Step 2 Create first spec file, with Oystercard class. ## Step 3 Create first ruby script, with Oystercard class. ## Step 4 1. First issue created with irb test that fails ``` irb -r "./lib/oystercard" 2.7.1 :001 > card = Oystercard.new 2.7.1 :002 > card.balance NoMethodError (undefined method `balance' for #<Oystercard:0x00007f7eef1b8c88>) ``` 2. Wrote a unit test to check whether oystercard balance starts at 0. 3. Wrote code to make the test pass 4. Replaced balance method with an instance variable in initialize and an attr_reader ## Step 5 1. Feature test saved to issues. 2. Unit tests created 3. Code written to make tests pass ## Step 6 1. Feature test for max balance saved to issues. 2. Unit test to raise error when max balance exceeded. 3. Code written ## Step 7 1. Feature test for deducting money. 2. Unit test to allow deduct method to reduce balance. 3. Code written ## Step 8 1. Feature test for touch_in, touch_out and in_journey? 2. Unit tests for all three methods to influence the in_journey? status (between true and false) 3. Code written ## Step 9 1. Feature test to check min balance on touch in 2. Unit tests to raise error if insufficient balance on touch_in 3. Code written ## Step 10 1. Feature test to charge on touch_out 2. Unit tests to change balance on touch_out 3. Code written ## Step 11 1. Feature test to charge on touch_out 2. Unit tests to change balance on touch_out 3. Code written
8c16f61207ed39880b788f773aea51bf6c7a4d18
[ "Markdown", "Ruby" ]
7
Ruby
twigz826/Oystercard
4ecb8c3b712b4a83b9cd6f6c7d0d5d33f9632aa5
576c6b6a0308c785567d2a62987021e4c3da272b
refs/heads/master
<file_sep>#!/bin/bash helm init --kube-context docker-for-desktop helm upgrade nginx-ingress stable/nginx-ingress --install \ --kube-context docker-for-desktop \ --namespace kube-system \ --set rbac.create=true \ --set controller.service.externalTrafficPolicy=Local helm upgrade postgresql stable/postgresql --install \ --namespace nextcloud \ --kube-context docker-for-desktop \ --set postgresqlPassword=<PASSWORD> \ --set postgresqlUsername=nextcloud \ --set postgresqlDatabase=nextcloud \ --set securityContext.fsGroup=0 \ --set securityContext.runAsUser=0 \ --set persistence.enabled=false \ --set extraEnv[0].name=NAMI_LOG_LEVEL \ --set extraEnv[0].value=trace helm upgrade minio stable/minio --install \ --namespace nextcloud \ --kube-context docker-for-desktop \ --set accessKey=myaccesskey \ --set secretKey=mysecretkey \ --set ingress.enabled=true \ --set ingress.hosts[0]=minio.127.0.0.1.xip.io \ --set persistence.size=100Mi helm upgrade redis stable/redis --install \ --namespace nextcloud \ --kube-context docker-for-desktop \ --set cluster.enabled=false \ --set usePassword=false \ --set master.persistence.size=100Mi [ -d docker ] || git clone https://github.com/nextcloud/docker.git docker build --tag nextcloud docker helm upgrade --install nextcloud \ --namespace nextcloud \ --kube-context docker-for-desktop \ ./helm-chart/ <file_sep>#!/bin/bash helm delete --purge minio helm delete --purge nextcloud helm delete --purge nginx-ingress helm delete --purge postgresql helm delete --purge redis kubectl --context docker-for-desktop delete ns nextcloud <file_sep># nextcloud-minikube Run NextCloud on minikube Use `run.sh` to build and deploy. After deployed open http://nextcloud.127.0.0.1.xip.io/ (admin/admin) Minio web interface is available at http://minio.127.0.0.1.xip.io (myaccesskey/mysecretkey) Please read [ANALYSIS.md](ANALYSIS.md)<file_sep># Further Improvements ### Amazon * Use **Amazon RDS** instead of postgresql helm chart * Use **Amazon ElastiCache** instead of redis helm chart * Use **S3** instead of minio helm chart ### Private Cloud * Use **Postgres Operator** or VMs with **stolon** instead of postgresql helm chart * Use **Redis Operator** instead of redis helm chart * Use **OpenStack swift** or **Distributed Minio** ### Image I'm using kubernetes default implementation on docker for windows. On AWS persistent volume claims will work without declaring persistent volumes first. Can't run more then one replica of application now. Problem is that it stores its version on disk. Also it detects clean volume as fresh install and tryes to perform installation process which is unsuccessful because of 'admin user is already exists in database' error. To solve this problem the entrypoint.sh has to be refactored: * Store current version in external storage (database or s3 bucket) * put version.php to the path where application expects it to be Additional application plugins could be integrated into the image. ### IaC * Use **terraform** for managing all cloud services
24c4ad8952a1778af2f6feb922fcc0db27d8e48b
[ "Markdown", "Shell" ]
4
Shell
matchish/nextcloud-minikube
d433491782626d7ccfb6b3f33ff5238b7ae7582a
bf59008b9cea3922a430ac49e6941bfb40f17f9d
refs/heads/master
<file_sep>import numpy as np from solve_sys import solve_linear_system from bisect import bisect_left from tabulate import TabulatedFunction class Interpolation: def __init__(self, tabulated_function, interpolation_coefficients): self.coefficients = interpolation_coefficients self.function = tabulated_function def _evaluate_polynomial(x, x_left, poly): t = x - x_left return poly[0] + poly[1] * t + poly[2] * t**2 / 2 + poly[3] * t**3 / 6 def __call__(self, x): position = bisect_left(self.function.grid, x) - 1 if position < 0: return self.function[0] return Interpolation._evaluate_polynomial(x, self.function.grid[position], self.coefficients[position]) def interpolate(tabulated_function): n = len(tabulated_function.grid) - 1 grid = tabulated_function.grid matrix = np.zeros((n-1, n-1)) values = np.zeros((n-1,)) for i in range(1, n): h0 = grid[i] - grid[i-1] h1 = grid[i+1] - grid[i] df0 = tabulated_function[i] - tabulated_function[i-1] df1 = tabulated_function[i+1] - tabulated_function[i] matrix[i-1, i-1] = 2 * (h0 + h1) if i > 1: matrix[i-1, i-2] = h0 if i+1 < n: matrix[i-1, i] = h1 values[i-1] = 6 * (df1/h1 - df0/h0) zs = solve_linear_system(matrix, values) polynomials = [] for i in range(n): f0 = tabulated_function[i] f1 = tabulated_function[i+1] h = grid[i+1] - grid[i] z0 = (zs[i-1] if i > 0 else 0) z1 = (zs[i] if i+1 < n else 0) polynomials.append([ f0, (f1-f0)/h - z1*h/6 - z0*h/3, z0, (z1-z0)/h ]) return Interpolation(tabulated_function, polynomials) '''grid = [1, 2, 3, 4, 5, 6] values = [1.0002, 1.0341, 0.6, 0.40105, 0.1, 0.23975] tabulated = TabulatedFunction(grid, values) print interpolate(tabulated).coefficients''' <file_sep>from tabulate import TabulatedFunction, generate_uniform_grid, tabulate def integrate(function, left, right, n): grid = generate_uniform_grid(left, right, n) values = [] first = 0.5*(grid[1] - grid[0])*(function(left)) last = 0.5*(grid[1] - grid[0])*(function(right)) sum = 0 values.append(first) for i in range(1, len(grid) - 1): value = 0.5*(grid[i + 1] - grid[i - 1])*function(grid[i]) sum += value values.append(sum) sum += last values.append(sum) return TabulatedFunction(grid=grid, values=values) # return zip(grid, values) '''func = lambda x: x**2 left = 0 right = 5 n = 21 print integrate(func, left, right, n).values''' <file_sep>from math import * import numpy as np from tabulate import generate_uniform_grid, tabulate from integrate import integrate from serializer import save_tabulated from cauchy import solve_cauchy from interpolation import Interpolation, interpolate from differentiate import differentiate import matplotlib.pyplot as plt import matplotlib def get_S(parameters): expression = "lambda t: " + str(parameters['S(t)']) return eval(expression) def get_z(parameters): expression = "lambda t: " + str(parameters['z(t)']) return eval(expression) def get_rho(parameters): expression = "lambda w: " + str(parameters['p(w)']) return eval(expression) def check_tabulation(rho_function, z_function, S_function, T): tabulated_rho = tabulate(rho_function, generate_uniform_grid(0, T, 21)) tabulated_z = tabulate(z_function, generate_uniform_grid(0, T, 21)) tabulated_S = tabulate(S_function, generate_uniform_grid(0, T, 21)) save_tabulated(tabulated_rho, 'files/tabulated_rho.txt') save_tabulated(tabulated_z, 'files/tabulated_z.txt') save_tabulated(tabulated_S, 'files/tabulated_S.txt') def check_cauchy(function, x_0, y_0): solution = solve_cauchy(function, x_0, y_0, 0, 1, 21) np.savetxt('files/cauchy.txt', solution) def check_integration(rho_function): integrated_rho = integrate(rho_function, 0, 1, 21) np.savetxt('files/rho_integrated.txt', integrated_rho.values) def check_interpolation(rho_function, z_function, S_function, T): tabulated_rho = tabulate(rho_function, generate_uniform_grid(0, T, 21)) tabulated_z = tabulate(z_function, generate_uniform_grid(0, T, 21)) tabulated_S = tabulate(S_function, generate_uniform_grid(0, T, 21)) integrated_rho = integrate(rho_function, 0, 1, 21) interpolated_rho = interpolate(tabulated_rho).coefficients interpolated_z = interpolate(tabulated_z).coefficients interpolated_S = interpolate(tabulated_S).coefficients interpolated_U = interpolate(integrated_rho).coefficients np.savetxt('files/interpolated_rho.txt', interpolated_rho) np.savetxt('files/interpolated_S.txt', interpolated_S) np.savetxt('files/interpolated_z.txt', interpolated_z) np.savetxt('files/interpolated_U.txt', interpolated_U) def solve(**parameters): rho_function = get_rho(parameters) S_function = get_S(parameters) z_function = get_z(parameters) beta = parameters['Beta'] T = parameters['T'] x_0 = parameters['x_0'] y_0 = parameters['y_0'] num_nodes = parameters['Num of grid nodes'] check_tabulation(rho_function, z_function, S_function, T) # check_cauchy(z_function, x_0, y_0) check_integration(rho_function) check_interpolation(rho_function, z_function, S_function, T) integrated_rho = integrate(rho_function, 0, 1, 21) derivative = differentiate(z_function, 0, 1, 21) right_part = np.zeros(21) for i in range(21): right_part[i] = integrated_rho[i]*derivative[i] np.savetxt('files/right_part', right_part) x = solve_cauchy(right_part, x_0, y_0, 0, 1, 21) np.savetxt('files/x.txt', x) tabulated_S = tabulate(S_function, generate_uniform_grid(0, T, 21)) S = np.asarray(tabulated_S.values) x = np.asarray(x) right_y = beta*(tabulated_S.values - x) np.savetxt('files/right_y.txt', right_y) y = solve_cauchy(right_y, x_0, y_0, 0, 1, 21) np.savetxt('files/y.txt', y) ns = np.arange(10, 3001, 10) errors1 = ns plt.rc('text', usetex=True) plt.xlabel('$\log n$') plt.ylabel('$\log E$') plt.plot(ns, errors1, label=r'$\sin(e^{2t})$') plt.legend(loc=1) plt.savefig('fig.png', bbox_inches='tight', figsize=(1, 1.6)) <file_sep>from tabulate import generate_uniform_grid def differentiate(function, left, right, n): grid = generate_uniform_grid(left, right, n) derivative = [0.0] for i in range(len(grid) - 1): diff = float (function(grid[i + 1]) - function(grid[i])) / (grid[i + 1] - grid[i]) derivative.append(diff) return derivative <file_sep>from tkinter import * import solver from PIL import Image, ImageTk fields = 'S(t)', 'z(t)', 'p(w)', 'x_0', 'y_0', 'T', 'Num of grid nodes', 'Beta', 'Start Beta', 'Final Beta' def fetch(entries): for entry in entries: field = entry[0] text = entry[1].get() print('%s: "%s"' % (field, text)) def makeform(root, fields): entries = [] for field in fields: row = Frame(root) lab = Label(row, width=15, text=field, anchor='w') ent = Entry(row) row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) ent.pack(side=RIGHT, expand=YES, fill=X) entries.append((field, ent)) return entries def solve(entries, automatic=False): parameters = {} for entry in entries: if entry[0] == 'S(t)' or entry[0] == 'p(w)' or entry[0] == 'z(t)': parameters[entry[0]] = entry[1].get() else: try: parameters[entry[0]] = float(entry[1].get()) except ValueError: if entry[0] == 'Beta' and automatic: continue if (entry[0] == 'Start beta' or entry[0] == 'Final Beta') \ and not automatic: continue return solver.solve(**parameters) if __name__ == '__main__': root = Tk() ents = makeform(root, fields) path = r"test.png" photo = ImageTk.PhotoImage(file=path) label = Label(image=photo) canv = Canvas(root, width=600, height=400) canv.create_image(1, 1, anchor=NW, image=photo) canv.place(x=200, y=320) label = Label(root, image=photo) root.bind('<Return>', (lambda event, e=ents: fetch(e))) b0 = Button(root, text="Solve", command=(lambda e=ents: solve(e))) b0.pack(side=LEFT, padx=5, pady=5) b2 = Button(root, text='Quit', command=root.quit) b2.pack(side=LEFT, padx=5, pady=5) root.mainloop() <file_sep>def save_tabulated(function, filename): with open(filename, 'w') as fout: fout.write(serialize_tabulated(function)) # print(serialize_tabulated(function), file=fout) # print(serialize_tabulated(function), end='', file=fout) '''def save_cauchy(solution, filename): with open(filename, 'w') as fout: print(solve_cauchy(), end='', file=fout)''' def serialize_tabulated(function): result = '' for (argument, value) in zip(function.grid, function.values): result += '{} {}\n'.format(argument, value) return result <file_sep># Num_Methods To run this application: python3 start.py <file_sep>from numpy import linspace class TabulatedFunction: def __init__(self, grid, values): self.grid = grid self.values = values def __getitem__(self, key): return self.values[key] def generate_uniform_grid(left, right, n): return linspace(left, right, num=n) def tabulate(function, grid): return TabulatedFunction(grid=grid, values=[function(x) for x in grid]) <file_sep>import numpy as np def solve_linear_system(A, y): wide_A = np.hstack((A.astype(float), np.array([y]).T.astype(float))) for i in range(min(A.shape[0], A.shape[1])): max_index = i + np.argmax(np.abs(wide_A[i:, i])) if wide_A[max_index, i] == 0: print('No solution.') raise ValueError() wide_A[[i, max_index], :] = wide_A[[max_index, i], :] for j in range(A.shape[0]): if j == i: continue wide_A[j] -= (wide_A[j, i] / wide_A[i, i]) * wide_A[i] wide_A[i] /= wide_A[i, i] return wide_A[:, -1] <file_sep>from tabulate import generate_uniform_grid class Cauchy_Solution: def __init__(self, grid, solutions): self.grid = grid self.y = solutions def solve_cauchy(f, x_0, y_0, left, right, n): y_prev = y_0 y = [y_0] grid = generate_uniform_grid(left, right, n) for i in range(1, len(grid)): y_i = y_prev + (grid[i] - grid[i - 1])*(f[i - 1]) # y_i = y_prev + (grid[i] - grid[i - 1])*f(grid[i - 1], y_prev) y.append(y_i) y_prev = y_i # return zip(grid, y) return y # return Cauchy_Solution(grid, y) '''f = lambda x, y: x**2 - 2*y x_0 = 0 y_0 = 1 left = 0 right = 1 n = 11 #print solve_cauchy(f, x_0, y_0, left, right, n)'''
1c332b4cd46379bcc2fb0d692f856e648e768cb6
[ "Markdown", "Python" ]
10
Python
infected-mushroom/Num_Methods
3e674d2e95c1df3f08ef5a6cf4ab24cf29ae2632
7097e160ffa9808ffbb2922c35f0cf9a8498b0ab
refs/heads/master
<repo_name>jonschipp/ewhois-query<file_sep>/ewhois-query.sh #!/bin/bash usage() { cat <<EOF Query the ewhois.com engine. * Whois Lookup * Reverse IP Lookup * Reverse Adsense ID Lookup * Reverse Google Analytics ID Lookup Query Options: -w <dns> Whois -r <ip> Reverse IP -a <id> Adsense ID -g <id> Analytics ID Processing Options: -D Delete files (cleanup) -N Skip download, file exists -R <file> Read html file from full path -O <file> Write output to file Usage: $0 <option> <query> e.g. $0 -w google.com EOF } browsercheck() { if command -v wget >/dev/null 2>&1; then BROWSER="wget" echo -e "\nWget installed ...using" elif command -v curl >/dev/null 2>&1; then BROWSER="curl" echo -e "\nCurl installed ...using" else echo -e "\nERROR: Neither cURL or Wget are installed or are not in the \$PATH!\n" exit 1 fi } download() { if [ $BROWSER == "curl" ]; then curl -L -o ${QUERY}.html ${URL}/${QUERY} 2>/dev/null fi if [ $BROWSER == "wget" ]; then wget -O ${QUERY}.html ${URL}/${QUERY} 2>/dev/null fi } # option and argument handling while getopts "ha:Dg:NO:r:R:w:" OPTION do case $OPTION in a) QUERY="$OPTARG" TYPE="$OPTION" URL="http://www.ewhois.com/adsense-id" ;; D) DELETE="1" ;; g) QUERY="$OPTARG" TYPE="$OPTION" URL="http://www.ewhois.com/analytics-id" ;; h) usage exit ;; N) SKIP=1 ;; O) LOGFILE="$OPTARG" exec > >(tee "$LOGFILE") 2>&1 ;; r) QUERY="$OPTARG" TYPE="$OPTION" URL="http://www.ewhois.com/ip-address" ;; R) SKIP=1 FPATH="$OPTARG" ;; w) QUERY="$OPTARG" TYPE="$OPTION" URL="http://www.ewhois.com" ;; \?) usage ;; esac done # test & call functions if ! [[ $1 == -* ]]; then usage fi browsercheck if [ "$SKIP" != "1" ];then download fi #if [ ! -z "$FPATH" ]; then #QUERY="$FPATH" #fi # meat if [[ $TYPE == "w" ]]; then echo -e "\n=== [Basic] ===\n" grep -o $QUERY ${QUERY}.html | head -1 | sed 's/\('"$QUERY"'\)/Domain Name: \1/' grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' ${QUERY}.html | sed 's/\(.*\)/IP Address: \1/' | head -1 grep -o " Located near.*" ${QUERY}.html | sed -e 's/^ //' -e 's/<\/div>//' grep -o 'UA-[0-9]\{6\}' ${QUERY}.html | sed 's/^/Google Analytics ID: /' grep -o "<strong>.*other sites sharing this ID" ${QUERY}.html | sed 's/<strong>//;s/<\/strong>//;s/^/ --> /' grep -o '[1-2][0-9]\{3\}-[0-1][1-9]-[0-3][1-9]' ${QUERY}.html | sed 's/^/Last Updated: /' | head -1 echo -e "\n=== [Reverse IP Lookup] ===\n" grep -A 1 "Reverse IP Lookup" ${QUERY}.html | awk 'BEGIN { RS = "<span>" } { print $1 }' | sed '/^</d;s/<\/span>//' awk -F "</*td>|</*tr>" 'BEGIN { RS = "</tr>"; print "\n=== [DNS] ===\n\nHost:\t\tType:\tTTL:\tData:" } ! /div/ && /'"$QUERY"'/ {print $3"\t", $5"\t", $7"\t", $9"\t" }' ${QUERY}.html awk 'BEGIN { print "\n=== [Whois] ===\n" } /<pre>/,/<\/pre>/ { print }' ${QUERY}.html | sed -e '/<img/d' -e '/pre>/d' fi if [[ $TYPE == "r" ]]; then echo -e "\n=== [Basic] ===\n" grep -o '<td><strong>[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}</strong></td>' ${QUERY}.html | sed -e 's/<td><strong>//;s/<\/strong><\/td>//;s/^/IP Address: /' grep -A 2 "IP Location" ${QUERY}.html | grep -o '<strong>.*</strong>' | sed 's/<strong>//;s/<\/strong>//;s/^/IP Location: /' echo -e "\n=== [Sites] ===\n" grep '<strong>.* sites hosted ' ${QUERY}.html | sed 's/<p>//g;s/<strong>//g;s/<\/strong>//g;s/<\/p>//;s/^[ \t]*//' echo sed 's/<\/span>/<\/span>\n/g' ${QUERY}.html | grep -o '<span>.*<\/span>' | sed '/Login/d;/Register/d;/Reverse IP Lookup/d;/<a href/d;s/<span>//;s/<\/span>//;s/^/Hosted: /' i=0 for page in $(grep -o 'page\:[0-9]\{1,3\}' ${QUERY}.html | grep -v 'page:1' | sort | uniq) do let i++ wget -O ${QUERY}.html${i} ${URL}/${QUERY}/${page}/ sed 's/<\/span>/<\/span>\n/g' ${QUERY}.html${i} | grep -o '<span>.*<\/span>' | sed '/Login/d;/Register/d;/Reverse IP Lookup/d;/<a href/d;s/<span>//;s/<\/span>//;s/^/Hosted: /' done echo fi if [[ $TYPE == "g" ]]; then echo -e "\n=== [Reverse Google Analytics ID Lookup] ===\n" grep -o "<strong>.* Analytics ID" ${QUERY}.html | sed 's/<strong>//;s/<\/strong>//;s/^/ --> /;s/$/ '"$QUERY"'\n/' sed 's/<\/span>/<\/span>\n/g' ${QUERY}.html | grep -o '<span>.*<\/span>' | \ sed '/Login/d;/Register/d;/Reverse/d;s/<span>//;s/<\/span>//' echo fi if [[ $TYPE == "a" ]]; then echo -e "\n=== [Reverse Google Adsense ID Lookup] ===\n" grep -o "<strong>.* AdSense ID" ${QUERY}.html | sed 's/<strong>//;s/<\/strong>//;s/^/ --> /;s/$/ '"$QUERY"'\n/' sed 's/<\/span>/<\/span>\n/g' ${QUERY}.html | grep -o '<span>.*<\/span>' | \ sed '/Login/d;/Register/d;/Reverse/d;s/<span>//;s/<\/span>//' echo fi # Cleanup if [[ $DELETE == "1" ]]; then for file in $(ls ${QUERY}.html*) do echo -e "\nRemoving:" echo " --> $file" rm ${QUERY}.html* done fi <file_sep>/README.md # ewhois-query *Note:* Code longer works, ewhois website is different `ewhois-query` - Query the ewhois.com engine from the command-line * Whois Lookup * Reverse IP Lookup * Reverse Adsense ID Lookup * Reverse Google Analytics ID Lookup ## Notes: Each use retrieves the queried page and stores in the current working directory (CWD). <br> `ewhois-query` works on that file off-line *e.g.* `google.com.html`. The extension should <br> not be specified when using the `-N` option *i.e.* google.com not google.com.html. #### Todo (not ranked): * Clean up * Parse Alexa stats * Add option to show recent lookups * Input validation * Fix -R option which reads html file from full path * MAC Vender/OUI Lookup * Parse Reverse Analytics field to -w lookup * Fix UA bug where characters are cut short UA-573017 should be UA-5730170 ## Usage: #### Mandatory Options: `-w` <dns> Whois <br> `-r` <ip> Reverse IP <br> `-a` <id> Adsense ID <br> `-g` <id> Analytics ID <br> #### Non-mandatory options: `-D` Delete file after run otherwise it's stored in CWD *e.g.* `-D -w google.com` <br> `-N` Skip download i.e. use existing file in CWD *e.g.* `-N -w google.com` <br> ~~`-R` Read file from existing file but specify full path (broken)~~ <br> `-O` Write to file (includes stderr + stdout) *e.g.* `-O output.txt` <br> ```shell Usage: ./ewhois-query <option> <query> [-DN] [-O out.txt] ``` ### Examples: ```shell ./ewhois-query -w google.com ./ewhois-query -r google.com ./ewhois-query -a pub-3256770407637090 ./ewhois-query -g UA-183159 ./ewhois-query -N -w google.com ./ewhois-query -O google.txt -D -w google.com ``` ## Author: ***<NAME>*** (keisterstash) <br> jonschipp [ at ] Gmail dot com <br> `sickbits.net`, `<EMAIL>` <br>
2ead333fef0e29e13b5ab9852f57097e9c11a1b8
[ "Markdown", "Shell" ]
2
Shell
jonschipp/ewhois-query
ea6483f9f68756bc4baaf1ff2cbb07431a6dd40e
fa70a28474ad9a78883a1d9555f74af80656f4dc
refs/heads/main
<repo_name>glennjw/DNA-sequence-pairing<file_sep>/README.md # DNA-sequence-pairing Dynamic pair the DNA sequence. This project is to compute the maximum number of permissible letter pairs from the input sequence of 4 letters (A, C, G, U). For these letters, legal pairs are A-U, U-A, G-C, C-G while others (such a G-A) are illegal. In addition, a pairing between two letters is exclusive, e.g., if a letter U on the sequence that is paired with a letter A, that letter U cannot be paired with another letter A. This problem is called Structure Prediction because it is a meaningful abstraction of the significant problem RNA secondary structure prediction in computational biology, where A, C, G, and U are nucleotide bases that constitute RNA sequences. A nucleotide base pair brings two bases physically together, contributing to the structure into which an RNA molecule may form. The maximization of such base pairs corresponds to the minimization of free energy that may stabilize the formed structure. ## How to run > python3 pair.py dna.txt ## Result >AUGUCAGCGUU >{{{.}}.{}.} >max count of pairs >4 <file_sep>/pair.py #!/usr/bin/env python import os import numpy as np # Score function def Score(u, v): if (u,v) in [ ('A','U'), ('U','A') ]: return 2 if (u,v) in [ ('G','C'), ('C','G') ]: return 3 return 0 # Traceback def TraceBack(i,j): pairs = [] def TcBk(i, j): i = int(i) j = int(j) if i <= j: if 0 == fTb[i,j]: return elif -1 == kTb[i,j]: pairs.append((i,j)) TcBk(i+1, j-1) elif -2 == kTb[i,j]: TcBk(i+1, j-1) else: TcBk(i,kTb[i,j]) TcBk(kTb[i,j]+1,j) TcBk(i,j) return pairs def in2ele(list): for i in range(0,len(list)): u = seq[list[i][0]] v = seq[list[i][1]] del list[i] list.insert(i,(u,v)) return list # print function def printSol(pairs): sol = ['.'] * len(seq) for each in pairs: sol[ each[0] ] = '{' sol[ each[1] ] = '}' print('>' + seq + '\n' + ' ' + ''.join(sol) + '\n>' + 'max count of pairs\n' + ' ' + str(len(pairs)) + '\n>' + 'max score\n' + ' ' + str(int(fTb[0][-1])) + '\n' ) def main(): global seq global fTb global kTb # read input cwd = os.getcwd() + '/sequence.txt' readFile = open( cwd, 'r' ) for eachLine in readFile: if eachLine[0] == '>': seq = readFile.next().strip() readFile.close() # DP, function-table, k-table n = len(seq) fTb = np.zeros((len(seq), len(seq))) kTb = np.zeros((len(seq), len(seq))) # inside-out for l in range(0,n): for i in range(0,n-l): j = i+l for k in range(i,j): func2 = fTb[i,k] + fTb[k+1,j] if func2 > fTb[i,j]: fTb[i,j] = func2 kTb[i,j] = k # left-right if Score(seq[i],seq[j]): # if 3 between A-U if 'A' == seq[i] and 'U' == seq[j] : poPairs = in2ele(TraceBack(i+1,j-1)) if ('U','A') and ('G','C') and ('C','G') in poPairs : func1 = fTb[i+1,j-1] + Score(seq[i],seq[j]) if func1 >= fTb[i,j]: fTb[i,j] = func1 kTb[i,j] = -1 else: func1 = fTb[i+1,j-1] if func1 > fTb[i,j]: fTb[i,j] = func1 kTb[i,j] = -2 else: func1 = fTb[i+1,j-1] + Score(seq[i],seq[j]) if func1 >= fTb[i,j]: fTb[i,j] = func1 kTb[i,j] = -1 pairs = TraceBack(0, n-1) printSol(pairs) print fTb print kTb if __name__ == '__main__': main()
7e425dfb61902648742e91751745e475a12b1c32
[ "Markdown", "Python" ]
2
Markdown
glennjw/DNA-sequence-pairing
3a2ad0b7d309e781d80126276e3be471cdf124af
28801610cead425425460888e8cc8a55567e5be8
refs/heads/main
<file_sep>package DesafioAssertiva; import org.junit.Assert; import org.junit.Test; public class TesteCadastro { Cliente cli = new Cliente(); @Test public void atualizar () { Assert.assertEquals("<NAME>",cli.getNome()); Assert.assertEquals("<EMAIL>",cli.getLogin()); Assert.assertEquals("1997",cli.getSenha()); } } /* * */ <file_sep># Campinas Tech Talents - Desafio Asertiva 👩‍💻 O repositório com o conteúdo do desafio final referente o trilha em Java da Assertiva pelo Campinas Tech Talents. Desafio Final CRUD é o acrônimo da expressão do idioma Inglës, Create(Criação), Retrieve(Consulta), Update (Atualização) e Delete (Destruição). Este acrônimo é comumente utilizado para definir as quatro operações básicas usadas em Banco de Dados Relacionais. Elaborar um crud de usuários com os seguintes campos: * Id auto incrementoNome notnull * Login (e-mail) notnull * Senha notnull * Data de cadastro recuperar a data do sistema Criar um menu onde o usuário irá informar qual atividade ele deseja realizar: 1-Cadastrar, 2-Procurar, 3-Alterar ou 4-excluir. Criar a classe JUnit para testar maior parte do código; Dica: Armazenar os dados no banco de dados e utilizar os seguintes comandos:INSERT, SELECT, UPDATE,DELETE Tecnologias utilizadas: * Java 8 * MySQL 8.0.23 * JUnit
48fc20068c7a56717ffa130e8fc4bb65bf308b4a
[ "Markdown", "Java" ]
2
Java
laryscampark/CampinasTechTalents_DesafioAsertiva
f5d692aa47f2a46edae54483b0995437133ad1a4
44d674c55ad8b28eb028df8a9370bb5900cb0f6f
refs/heads/master
<repo_name>PPraskov/Genetic-Algorithm<file_sep>/src/main/java/geneticalgorithm/interfaces/functional/CalculateFitness.java package geneticalgorithm.interfaces.functional; public interface CalculateFitness<R,T> { R calculate(T solution); } <file_sep>/src/main/java/geneticalgorithm/interfaces/functional/Mutation.java package geneticalgorithm.interfaces.functional; public interface Mutation<T> { T mutate(T solutionOne); } <file_sep>/src/main/java/executorservice/Result.java package executorservice; import java.util.ArrayDeque; import java.util.Queue; class Result<R> { private final Object notEmpty; private final Object notFull; private volatile Queue<R> resultList; private volatile int capacity; Result() { this.capacity = 10; this.resultList = new ArrayDeque<>(10); notEmpty = new Object(); notFull = new Object(); } R getResult() { R result = null; boolean condition = false; synchronized (this.resultList) { if (this.resultList.isEmpty()) { condition = true; } } if (condition) { synchronized (this.notEmpty) { try { this.notEmpty.wait(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } } synchronized (this.resultList) { result = this.resultList.poll(); } synchronized (this.notFull) { this.notFull.notify(); } return result; } void submitResult(R result) { boolean condition = false; synchronized (this.resultList) { if (this.resultList.size() >= this.capacity) { condition = true; } } if (condition) { synchronized (this.notFull) { try { this.notFull.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } boolean added = true; synchronized (this.resultList) { while (added) { added = !this.resultList.offer(result); } } synchronized (this.notEmpty) { this.notEmpty.notify(); } } int getSize() { int result; synchronized (this.resultList){ result = this.resultList.size(); } return result; } } <file_sep>/src/main/java/geneticalgorithm/Solution.java package geneticalgorithm; public class Solution<R,T> implements Cloneable{ private T solution; private R fitness; public Solution(T solution) { this.solution = solution; } public R getFitness() { return fitness; } public void setFitness(R fitness) { this.fitness = fitness; } public T getSolution(){ return this.solution; } public void setSolution(T solution) { this.solution = solution; } Class<?> getType() { return solution.getClass(); } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } <file_sep>/src/main/java/geneticalgorithm/interfaces/functional/CompareResults.java package geneticalgorithm.interfaces.functional; public interface CompareResults<R> { int compare(R resultOne,R resultTwo); } <file_sep>/src/main/java/geneticalgorithm/BestSolutionHolder.java package geneticalgorithm; import java.util.concurrent.locks.ReentrantReadWriteLock; class BestSolutionHolder{ private Solution bestSolution; private final ReentrantReadWriteLock lock; BestSolutionHolder(Solution bestSolution) { this.bestSolution = bestSolution; this.lock = new ReentrantReadWriteLock(); } Solution getBestSolution() { try { lock.readLock().lock(); return bestSolution; } finally { lock.readLock().unlock(); } } void setBestSolution(Solution bestSolution) { try { lock.writeLock().lock(); this.bestSolution = bestSolution; } finally { lock.writeLock().unlock(); } } Object getCopy() throws CloneNotSupportedException { return this.bestSolution.clone(); } } <file_sep>/src/main/java/geneticalgorithm/interfaces/functional/CompareSolutions.java package geneticalgorithm.interfaces.functional; public interface CompareSolutions<T> { int compare(T solutionOne, T solutionTwo); }
cd831e0996795b5e742d1826fc97d8cee71c7108
[ "Java" ]
7
Java
PPraskov/Genetic-Algorithm
1cbc0d6fcea3fc32888f746174f4a0537045fb4e
4afc38f2beb4f7443468cbcc9a2238c94f5fe19d
refs/heads/master
<repo_name>nixpulvis/cs4740<file_sep>/README.md # CS4740 Network Security [![Build Status](https://travis-ci.org/nixpulvis/cs4740.svg?branch=master)](https://travis-ci.org/nixpulvis/cs4740) This is the complete collection of work done for Network Security at Northeastern University. These modules and executables are designed to work with Linux and OS X. I have talked with Prof Noubir, about the explicit lack of Windows support. - [Documentation](http://nixpulvis.github.io/cs4740/cs4740/) ## Compilation This project is developed on Rust nightly, to install Rust follow the instructions on [rust-lang.org](https://www.rust-lang.org). If you are on OS X do the following: ```sh brew install multirust multirust override nightly ``` ## Homeworks Some of the modules are in fact part of homeworks, which may have other parts, This list will serve as the index of the files/directories associated with each homework, and how to run them. ### Homework 1 - `reports/destructuring_a_simple_web_request.md` Part 1, report. - `src/chat/` The chat module. - `src/bin/client.rs` The client executable source. - `src/bin/server.rs` The server executable source. To run the server and client run: ```sh cargo run --bin server -- [-p PORT default: 1337] cargo run --bin client -- [-p PORT default: 1337] <ip> ``` ## Labs All labs are done in the `reports/` directory. Since labs tend to be mostly investigatory these labs are generally in the forms of a report. - `reports/lab1/` This lab looks at the configuration of the networking on both a Linux and a Windows VM. ## Other Projects Just for fun there are a some projects not directly required by this course, but related. These are included here as well. ### Ping To run the ping executable simple run the following command, which will send a ICMP echo request to `8.8.8.8`. ```sh cargo run --bin ping ```<file_sep>/src/chat/com.rs use std::result; use std::io; use std::io::Cursor; use std::net::SocketAddr; use std::error; use std::fmt; use mio; use chat::msg::{self, Message}; /// A short-hand for communication results. pub type Result<T> = result::Result<T, Error>; /// A single point from which we can send messages to others. A socket can /// talk to other sockets, and other sockets can talk to us. pub struct Socket { udp: mio::udp::UdpSocket, } impl Socket { /// Create a new socket for communication with messages. /// /// The primary purpose of this function is to bind to a socket from /// the OS. If this fails an error will be returned, otherwise the socket /// is returned. pub fn new(address: &SocketAddr) -> Result<Socket> { let udp = try!(mio::udp::UdpSocket::bound(address)); Ok(Socket { udp: udp }) } /// Receive a message on `&self` returning both the message, and the /// address of the sender. This function does **not** block. /// /// In order to use this method effectively, see `mio::Handler` for /// more information on the event cycle. This function should be called /// in response to a readable `EventSet`. pub fn recv(&self) -> Result<(Message, SocketAddr)> { let mut buf = Vec::new(); match try!(self.udp.recv_from(&mut buf)) { Some(sender) => { let msg = try!(Message::parse(&buf)); Ok((msg, sender)) }, None => Err(Error::Empty), } } /// Send a message to an address. This function does **not** block. /// /// In order to use this method effectively, see `mio::Handler` for /// more information on the event cycle. This function should be called /// in response to a writable `EventSet`. pub fn send(&self, msg: &Message, receiver: &SocketAddr) -> Result<()> { let buf: Vec<u8> = msg.into(); match try!(self.udp.send_to(&mut Cursor::new(buf), receiver)) { Some(unit) => Ok(unit), None => Err(Error::Empty), } } /// Returns the address of the socket if it exists. /// /// Generally there will always be an address, however especially if the /// socket wasn't created using `new` then the socket may not be bound, /// and therefor not have an address assigned. pub fn address(&self) -> Option<SocketAddr> { match self.udp.local_addr() { Ok(addr) => Some(addr), Err(_) => None } } } impl fmt::Display for Socket { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.address() { Some(addr) => write!(f, "socket({})", addr), None => write!(f, "socket(unbound)"), } } } impl mio::Evented for Socket { fn register(&self, selector: &mut mio::Selector, token: mio::Token, interest: mio::EventSet, opts: mio::PollOpt) -> io::Result<()> { self.udp.register(selector, token, interest, opts) } fn reregister(&self, selector: &mut mio::Selector, token: mio::Token, interest: mio::EventSet, opts: mio::PollOpt) -> io::Result<()> { self.udp.reregister(selector, token, interest, opts) } fn deregister(&self, selector: &mut mio::Selector) -> io::Result<()> { self.udp.deregister(selector) } } #[derive(Debug)] pub enum Error { Empty, Msg(msg::Error), Io(io::Error), } impl From<msg::Error> for Error { fn from(err: msg::Error) -> Self { Error::Msg(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::Io(err) } } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Empty => "Empty message", Error::Msg(_) => "Message error", Error::Io(_) => "Io error", } } fn cause(&self) -> Option<&error::Error> { match *self { Error::Empty => None, Error::Msg(ref e) => Some(e), Error::Io(ref e) => Some(e), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Empty => write!(f, "{}", error::Error::description(self)), Error::Msg(ref e) => e.fmt(f), Error::Io(ref e) => e.fmt(f), } } } #[cfg(test)] mod test { mod fixtures { use super::super::*; use std::net::{SocketAddr,SocketAddrV4}; use chat::msg::Message; pub fn socket() -> Socket { let localhost = "127.0.0.1".parse().unwrap(); let address = SocketAddr::V4(SocketAddrV4::new(localhost, 0)); Socket::new(&address).unwrap() } pub fn message() -> Message { Message::greeting() } } // TODO: Write tests. }<file_sep>/reports/destructuring_a_simple_web_request.md # De-structuring a simple web request Let's look at the packets involved with making a request to "nixpulvis.github.io". 1. WiFi 2. ARP 3. DNS 4. TCP / HTTP ## WiFi (802.11) All of the details of making a WiFi connection are not covered here. Frames of note are however, for example the Beacon frame is used to indicate the presence of a WiFi network, and you'll see a lot of these if you listen. There are management frames, control frames and data frames. Management frames are used for example to associate to an AP. Control frames are used for example to request and clear sending data, and then acknowledging it was sent. Data frames contain the actual data being sent. ``` D-LinkIn_67:8f:25 -> Broadcast 802.11 305 Beacon frame, ..., SSID=The Bat Cave ``` ## ARP The client needs to know the how to talk to the gateway router at the data link layer. This requires a MAC address for the gateway. To get this, the client sends a broadcast ARP request for the MAC address of the router. Here is a request and response for our routers MAC address. In this case the router has IP address 192.168.1.1 and we have IP address 192.168.0.106. ``` de:c8:c7:b5:7b:b9 -> Broadcast ARP 42 Who has 192.168.1.1? Tell 192.168.0.106 Netgear_33:93:92 -> de:c8:c7:b5:7b:b9 ARP 42 192.168.1.1 is at 04:a1:51:33:93:92 ``` You can see here that the MAC address of our router is Netgear_33:93:92 which is wiresharks translated way of saying 04:a1:51:33:93:92, because 04:a1:51 is allocated to Netgear. ## DNS When trying to navigate to "nixpulvis.github.io" for example, we first need to know the ip address of "nixpulvis.github.io". A DNS request is sent, and depending on the response more requests may be needed to determine the IP address. For example let's look at the host for how this works. ``` > host nixpulvis.github.io nixpulvis.github.io is an alias for github.map.fastly.net. github.map.fastly.net has address 192.168.3.11 ``` And you can see this by looking at the DNS packets sent when we requested "nixpulvis.github.io". ``` > tshark ... 192.168.0.106 -> 192.168.0.1 DNS 81 Standard query 0xc5a7 A github.map.fastly.net 192.168.0.1 -> 192.168.0.106 DNS 97 Standard query response 0xc5a7 A 192.168.3.11 ... ``` In this case we needed 2 query requests for "nixpulvis.github.io", and then for "github.map.fastly.net". ## TCP / HTTP First we start with the normal three way handshake, to initialize the TCP connection. ``` 192.168.0.106 -> 192.168.3.11 TCP 78 62231→80 [SYN] Seq=0 ... 192.168.3.11 -> 192.168.0.106 TCP 74 80→62231 [SYN, ACK] Seq=0 ... 192.168.0.106 -> 192.168.3.11 TCP 66 62231→80 [ACK] Seq=1 ... ``` The we start talking HTTP, over TCP. HTTP is how we ask for specific resources of the web server, and how the web server responds. For example with the request for "http://nixpulvis.github.io/meta/index.html" we sent the following HTTP packet. ``` 192.168.0.106 -> 192.168.3.11 HTTP 435 GET /meta/index.html HTTP/1.1 192.168.3.11 -> 192.168.0.106 TCP 66 80→62231 [ACK] ... ``` GET is a way of asking to be sent a resource, there are other verbs like PUT and DELETE for example. "/meta/index.html" is the resource's path, a way of structuring data inside of HTTP. ``` 192.168.3.11 -> 192.168.0.106 HTTP 658 HTTP/1.1 200 OK (text/html) 192.168.0.106 -> 192.168.3.11 TCP 66 62231→80 [ACK] ``` Here the response may have been made up of many TCP packets reconstructed into the text that defines the "/meta/index.html" resource. In this case the HTML is used to populate the webpage in addition to and CSS and JavaScript that was requested. After a few seconds the client tears down the connection if it's not being used anymore. This is also a three way handshake. It's worth noting here that the port we're sending from is an OS allocated value of 62612, but the port we're sending to is the standard 80 used for unencrypted HTTP messages. ``` 192.168.0.106 -> 192.168.3.11 TCP 66 62612→80 [FIN, ACK] Seq=364 ... 192.168.3.11 -> 192.168.0.106 TCP 66 80→62612 [FIN, ACK] Seq=5714 ... 192.168.0.106 -> 192.168.3.11 TCP 66 62612→80 [ACK] Seq=365 ... ``` This process is a handshake as well to allow both parties to confirm each other is being closed, however it is possible to only close one side of a TCP connection, in which case the other side will be aware that the connection wasn't closed entirely. <file_sep>/src/macros.rs /// Try or is a generalization of the `try!` macro in that it allows for /// arbitrary expressions to be called in the case of an error. Additionally /// in the case of an error this function will `warn!` it. #[macro_export] macro_rules! try_or { ($expr:expr => $handler:expr) => (match $expr { ::std::result::Result::Ok(v) => v, ::std::result::Result::Err(e) => { warn!("{}", e); $handler }, }) } <file_sep>/src/bin/server.rs extern crate rustc_serialize; extern crate docopt; extern crate cs4740; use std::process::exit; use std::net::{Ipv4Addr,SocketAddr,SocketAddrV4}; const USAGE: &'static str =" Chat Server Usage: server [options] Options: -h, --help Display this help message. -p, --port PORT The port to bind to. "; #[derive(Debug, RustcDecodable)] struct Args { flag_port: Option<u16>, } fn main() { // Initialize the logging infrastructure. ::cs4740::chat::init_logger(); // Parse the arguments. let args: Args = docopt::Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); // Create the server. let localhost = Ipv4Addr::new(127, 0, 0, 1); let port = match args.flag_port { Some(p) => p, None => ::cs4740::chat::server::DEFAULT_PORT, }; let address = SocketAddr::V4(SocketAddrV4::new(localhost, port)); let mut server = ::cs4740::chat::Server::new(address).unwrap_or_else(|e| { println!("Failed to initialize server: {}", e); exit(1); }); // Run the server. server.run().unwrap_or_else(|e| { println!("Failed to run server: {}", e); exit(1); }); } <file_sep>/src/chat/client.rs use std::result; use std::error; use std::fmt; use std::io; use std::io::prelude::*; use std::os::unix::io::FromRawFd; use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use mio; use chat::com; use chat::msg; /// A short-hand for server errors. pub type Result<T> = result::Result<T, Error>; /// A chat client, for use by people interacting with the chat server. The /// client reads from STDIN, sends to the server, and receives messages from /// the server. pub struct Client { event_loop: mio::EventLoop<ClientHandler>, handler: ClientHandler, } impl Client { // TODO: Make this a result. pub fn new(server: SocketAddr) -> Result<Self> { // Try to create the handler for the given server address. let handler = try!(ClientHandler::new(server)); // Try to create an event loop to register the handler. let mut event_loop = try!(mio::EventLoop::new()); // Try to send a greeting to the server. try!(handler.send(&msg::Message::greeting())); // Try to register the handler. TODO: Move this before the greeting? try!(handler.register(&mut event_loop)); // Log the connection. info!("New client on {} connected to {}", handler.socket, server); // Print the prompt. print!("-> "); // We suppress this error later, but here we'll catch it. try!(io::stdout().flush()); // We've got a initialized client, return it. Ok(Client { event_loop: event_loop, handler: handler }) } pub fn run(&mut self) -> Result<()> { self.event_loop.run(&mut self.handler).map_err(|e| e.into()) } } struct ClientHandler { server: SocketAddr, socket: com::Socket, stdin: mio::unix::PipeReader, } impl ClientHandler { // TODO: Make this a result. fn new(server: SocketAddr) -> Result<Self> { // Bind on our localhost. let localhost = Ipv4Addr::new(127, 0, 0, 1); // Port 0 is how we ask for an unused port. let address = SocketAddr::V4(SocketAddrV4::new(localhost, 0)); // Create a OS assigned socket. let socket = try!(com::Socket::new(&address)); // Get an asynchronous IO stream for STDIN. // TODO: Is there a "safe" way to do this? let stdin = unsafe { mio::unix::PipeReader::from_raw_fd(0) }; // We've got a working handler, return it. Ok(ClientHandler { socket: socket, stdin: stdin, server: server }) } fn send(&self, msg: &msg::Message) -> Result<()> { // Send the message to our server over our socket. self.socket.send(msg, &self.server).map_err(|e| e.into()) } fn recv(&self) -> Result<(msg::Message)> { // Receive a message on our socket. let (msg, server) = try!(self.socket.recv()); // Ensure the message is from our server. Note that this is a // pretty mediocre check at the moment, and later we'll want // something more sophisticated. if self.server == server { Ok(msg) } else { Err(Error::InvalidServer) } } fn register(&self, event_loop: &mut mio::EventLoop<Self>) -> Result<()> { let token = mio::Token(0); let events = mio::EventSet::readable(); let poll = mio::PollOpt::edge(); try!(event_loop.register(&self.socket, token, events, poll)); let token = mio::Token(1); try!(event_loop.register(&self.stdin, token, events, poll)); Ok(()) } fn handle_incoming_msg(&self, msg: msg::Message) { // TODO: Read the current state of STDIN. print!("\r"); match msg { msg::Message::Incoming(a, m) => { // TODO: Proper `Display` code. let s = match *m { msg::Message::Greeting => "<wave>".to_string(), msg::Message::Text(ref t) => t.clone(), _ => return, }; println!("<- {:?}: {}", a, s); }, _ => {} } // TODO: Print the saved state of STDIN with the prompt. print!("-> "); try_or!(io::stdout().flush() => return); } } impl mio::Handler for ClientHandler { type Timeout = u32; type Message = (); fn ready(&mut self, _: &mut mio::EventLoop<Self>, token: mio::Token, _: mio::EventSet) { match token { mio::Token(0) => { loop { // TODO: Could use some refactoring with these types. let msg = match self.recv() { Ok(m) => m, Err(e1) => match e1 { Error::Com(e2) => match e2 { com::Error::Empty => break, _ => { warn!("{}", e2); continue; } }, _ => { warn!("{}", e1); continue; }, } }; self.handle_incoming_msg(msg); } }, mio::Token(1) => { // TODO: Loop over stdin messages. let mut buf_stdio = io::BufReader::new(&self.stdin); let mut line = String::new(); try_or!(buf_stdio.read_line(&mut line) => return); let msg = msg::Message::text(line.trim_right()); try_or!(self.send(&msg) => return); print!("-> "); try_or!(io::stdout().flush() => return); }, _ => { warn!("Unexpected token {:?}.", token); } } } } /// An error type for client errors. #[derive(Debug)] pub enum Error { Initialization, InvalidServer, Com(com::Error), Io(io::Error), } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Initialization => "Failed to initialize client", Error::InvalidServer => "Interacting with invalid server", Error::Com(_) => "Communication error", Error::Io(_) => "Io error", } } fn cause(&self) -> Option<&error::Error> { match *self { Error::Initialization => None, Error::InvalidServer => None, Error::Com(ref e) => Some(e), Error::Io(ref e) => Some(e), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Initialization => write!(f, "{}", error::Error::description(self)), Error::InvalidServer => write!(f, "{}", error::Error::description(self)), Error::Com(ref e) => e.fmt(f), Error::Io(ref e) => e.fmt(f), } } } impl From<com::Error> for Error { fn from(err: com::Error) -> Self { Error::Com(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::Io(err) } } <file_sep>/src/bin/client.rs extern crate rustc_serialize; extern crate docopt; extern crate cs4740; use std::str::FromStr; use std::process::exit; use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; const USAGE: &'static str =" Chat Server Usage: client [options] <ip> Options: -h, --help Display this help message. -p, --port PORT The port to bind to. "; #[derive(Debug, RustcDecodable)] struct Args { arg_ip: String, flag_port: Option<u16>, } fn main() { // Initialize the logging infrastructure. ::cs4740::chat::init_logger(); // Parse the arguments. let args: Args = docopt::Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); // Get the IP address of the server we wish to connect to. let localhost = Ipv4Addr::from_str(&args.arg_ip).unwrap_or_else(|e| { println!("Failed to parse arguments: {}", e); exit(1); }); // Get the port of the server we wish to connect to. let port = match args.flag_port { Some(p) => p, None => ::cs4740::chat::server::DEFAULT_PORT, }; // Create the client. let server = SocketAddr::V4(SocketAddrV4::new(localhost, port)); let mut client = ::cs4740::chat::Client::new(server).unwrap_or_else(|e| { println!("Failed to initialize client {}", e); exit(1); }); // Run the client. client.run().unwrap_or_else(|e| { println!("Failed to run client: {}", e); exit(1); }); } <file_sep>/src/chat/mod.rs //! A chat server with a focus on safety and security. While the goals of this //! project are to learn about security and networking, do not assume that this //! chat service is secure. //! //! This chat system follows the typical client/server architecture. Clients //! send messages to the server, and the server then distributes them as //! needed back to some clients. use std::io::{stderr, Write}; use log::{self, LogRecord, LogLevel, LogMetadata, SetLoggerError, LogLevelFilter}; /// Common messages shared between servers and client. pub mod msg; /// Sending and receiving messages over a single socket. pub mod com; /// Clients for users. pub mod client; /// Server hosted chat servers. pub mod server; // Reexports. pub use chat::client::Client; pub use chat::server::Server; struct Logger; impl Logger { fn init() -> Result<(), SetLoggerError> { log::set_logger(|max_log_level| { max_log_level.set(LogLevelFilter::Info); Box::new(Logger) }) } } impl log::Log for Logger { fn enabled(&self, metadata: &LogMetadata) -> bool { metadata.level() <= LogLevel::Info } fn log(&self, record: &LogRecord) { if self.enabled(record.metadata()) { println!("{} - {}", record.level(), record.args()); } } } /// Utility function for starting the logger, and reporting potential issues /// with the initialization. /// /// # Examples /// /// Setup the logger, catching errors and printing them. /// /// ```rust /// #[macro_use] /// extern crate log; /// extern crate cs4740; /// /// fn main() { /// cs4740::chat::init_logger(); /// warn!("This is a warning."); /// } /// ``` pub fn init_logger() { match Logger::init() { Ok(_) => {}, Err(_) => { match writeln!(&mut stderr(), "Couldn't initialize logger.") { Ok(_) => {}, Err(e) => println!("{}", e), } }, } } #[cfg(test)] mod test { mod fixtures { pub fn err() -> Result<u32, u32> { Err(1) } } #[test] fn test_try_or_divergent() { try_or!(fixtures::err() => { assert!(true); return }); } #[test] fn test_try_or_value() { assert_eq!(try_or!(fixtures::err() => 7), 7) } }<file_sep>/Cargo.toml [package] name = "cs4740" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] [dependencies] pnet = "*" docopt = "*" rustc-serialize = "*" byteorder = "*" log = "*" [dependencies.mio] git = "https://github.com/carllerche/mio.git"<file_sep>/src/lib.rs //! A collection of modules and executables for CS4740 (Network Security) at //! Northeastern University. These modules are designed with security in mind, //! however are being created in the spirit of learning, and as such should //! **not** be used for real systems. //! //! # Chat Client/Server //! //! ``` //! use std::net::{Ipv4Addr,SocketAddr,SocketAddrV4}; //! //! let localhost = Ipv4Addr::new(127, 0, 0, 1); //! let server_address = SocketAddr::V4(SocketAddrV4::new(localhost, 1337)); //! //! let mut server = cs4740::chat::Server::new(server_address).unwrap(); //! // or //! let mut client = cs4740::chat::Client::new(server_address).unwrap(); //! ``` #[macro_use] extern crate log; extern crate byteorder; extern crate mio; #[macro_use] mod macros; pub mod chat; <file_sep>/src/chat/server.rs use std::result; use std::error; use std::fmt; use std::io; use std::net::SocketAddr; use mio; use chat::com; use chat::msg; /// The default port which chat servers will bind to. pub const DEFAULT_PORT: u16 = 1337; /// A short-hand for server errors. pub type Result<T> = result::Result<T, Error>; /// A chat server, for serving clients. The server listens on a socket and /// processes messages, potentially responding to a set of clients. pub struct Server { event_loop: mio::EventLoop<ServerHandler>, handler: ServerHandler, } impl Server { pub fn new(address: SocketAddr) -> Result<Self> { // Try to create the handler for the given address. let handler = try!(ServerHandler::new(address)); // Try to create an event loop to register the handler. let mut event_loop = try!(mio::EventLoop::new()); // Try to register the handler. try!(handler.register(&mut event_loop)); // We've got a initialized server, return it. Ok(Server { event_loop: event_loop, handler: handler }) } pub fn run(&mut self) -> Result<()> { self.event_loop.run(&mut self.handler).map_err(|e| e.into()) } } struct ServerHandler { socket: com::Socket, clients: Vec<SocketAddr>, } impl ServerHandler { fn new(address: SocketAddr) -> Result<Self> { let socket = try!(com::Socket::new(&address)); let clients = Vec::new(); info!("New server on {}.", socket); Ok(ServerHandler { socket: socket, clients: clients }) } fn send(&self, msg: &msg::Message, address: &SocketAddr) -> Result<()> { self.socket.send(msg, address).map_err(|e| e.into()) } fn recv(&self) -> Result<(msg::Message, SocketAddr)> { self.socket.recv().map_err(|e| e.into()) } // TODO: Do we like this interface? fn register(&self, event_loop: &mut mio::EventLoop<Self>) -> Result<()> { let token = mio::Token(0); let events = mio::EventSet::readable(); let poll = mio::PollOpt::edge(); try!(event_loop.register(&self.socket, token, events, poll)); Ok(()) } fn handle_msg(&mut self, msg: msg::Message, sender: SocketAddr) { match msg { msg::Message::Greeting => { info!("New client {:?}.", sender); self.clients.push(sender); }, msg::Message::Text(_) => { info!("{:?} from {:?}.", msg, sender); // TODO: SocketAddr's should be used everywhere as // soon as we can convert all addresses to // `SocketAddrV6`s inside the message byte protocol. let sender_hack = match sender { SocketAddr::V4(s) => s, _ => { warn!("IPV6 message received, and ignored."); return } }; // TODO: An incoming message should take another message // not a string of that message. let incoming = msg::Message::incoming(&sender_hack, &msg); for client in &self.clients { if client == &sender { continue } try_or!(self.send(&incoming, &client) => continue); } }, _ => { warn!("Server received {:?}.", msg); } } } } impl mio::Handler for ServerHandler { type Timeout = (); type Message = (); fn ready(&mut self, _: &mut mio::EventLoop<Self>, token: mio::Token, _: mio::EventSet) { match token { mio::Token(0) => { loop { // TODO: Could use some refactoring with these types. let (msg, sender) = match self.recv() { Ok((m, s)) => (m, s), Err(e1) => match e1 { Error::Com(e2) => match e2 { com::Error::Empty => break, _ => { warn!("{}", e2); continue; } }, _ => { warn!("{}", e1); continue; }, } }; self.handle_msg(msg, sender); } }, _ => { warn!("Unexpected token {:?}.", token); }, } } } /// An error type for client errors. #[derive(Debug)] pub enum Error { Initialization, Com(com::Error), Io(io::Error), } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Initialization => "Failed to initialize server", Error::Com(_) => "Communication error", Error::Io(_) => "Io error", } } fn cause(&self) -> Option<&error::Error> { match *self { Error::Initialization => None, Error::Com(ref e) => Some(e), Error::Io(ref e) => Some(e), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Initialization => write!(f, "{}", error::Error::description(self)), Error::Com(ref e) => e.fmt(f), Error::Io(ref e) => e.fmt(f), } } } impl From<com::Error> for Error { fn from(err: com::Error) -> Self { Error::Com(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::Io(err) } } <file_sep>/src/chat/msg.rs use std::error; use std::result; use std::string; use std::fmt; use std::io::Cursor; use std::net::{Ipv4Addr, SocketAddrV4}; use byteorder; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; /// A short-hand for message results. pub type Result<T> = result::Result<T, Error>; /// A message for communication between clients and servers. Messages /// themselves do not keep track of who actually sent them, although some /// do store information about other client or servers to relay information. /// /// Converting to and from `Messages` and bytes is done with `Vec::from` and /// `Message::parse`. A message can always be converted into a vector of bytes /// however not all bytes are valid messages, hence the distinction in the /// functions. #[derive(PartialEq, Clone, Debug)] pub enum Message { /// An incoming message containing a client's message to relay to all other /// clients. Incoming(SocketAddrV4, Box<Message>), /// A greeting message from a client, indicating it should receive incoming /// messages from the server. Greeting, /// A user message containing a single `String`. Text(String), } impl Message { /// Create a new message from a slice of bytes. /// /// # Examples /// /// A greeting message from bytes. /// /// ```rust /// use cs4740::chat::msg::Message; /// /// let msg = Message::parse(&[1]).unwrap(); /// assert_eq!(msg, Message::Greeting); /// ``` pub fn parse(buf: &[u8]) -> Result<Self> { if buf.len() == 0 { return Err(Error::InvalidBytes) } match buf[0] { 0 => { let sock = try!(bytes_as_sock(&buf[1..7])); let msg = if buf.len() < 8 { return Err(Error::InvalidBytes) } else { try!(Message::parse(&buf[7..])) }; Ok(Message::Incoming(sock, Box::new(msg))) }, 1 => { Ok(Message::Greeting) }, 2 => { // TODO: Could do without an allocation. let string = try!(String::from_utf8(Vec::from(&buf[1..]))); Ok(Message::Text(string)) }, _ => Err(Error::UnknownMessage(buf[0])) } } pub fn incoming(address: &SocketAddrV4, msg: &Message) -> Message { Message::Incoming(address.clone(), Box::new(msg.clone())) } pub fn greeting() -> Message { Message::Greeting } /// Returns a new text message. WIP. pub fn text(txt: &str) -> Message { Message::Text(txt.into()) } /// Returns true when `self` is an incoming message. pub fn is_incoming(&self) -> bool { match *self { Message::Incoming(_, _) => true, _ => false } } /// Returns true when `self` is a greeting message. pub fn is_greeting(&self) -> bool { match *self { Message::Greeting => true, _ => false } } /// Returns true when `self` is a text message. pub fn is_text(&self) -> bool { match *self { Message::Text(_) => true, _ => false } } } /// An error type for chat message errors. #[derive(Debug)] pub enum Error { InvalidBytes, UnknownMessage(u8), } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::InvalidBytes => "Invalid message bytes", Error::UnknownMessage(_) => "Unknown message" } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::InvalidBytes => write!(f, "{}", error::Error::description(self)), Error::UnknownMessage(n) => write!(f, "{} ({})", error::Error::description(self), n), } } } impl From<byteorder::Error> for Error { fn from(_: byteorder::Error) -> Self { Error::InvalidBytes } } impl From<string::FromUtf8Error> for Error { fn from(_: string::FromUtf8Error) -> Self { Error::InvalidBytes } } // Vec from Message impl<'a> From<&'a Message> for Vec<u8> { fn from(msg: &Message) -> Self { let mut vec: Vec<u8> = Vec::new(); match *msg { Message::Incoming(ref s, ref m) => { vec.push(0); vec.extend(sock_as_bytes(s)); let x = Vec::<u8>::from(&**m); // TODO: WTF. vec.extend(x); }, Message::Greeting => { vec.push(1); }, Message::Text(ref t) => { vec.push(2); vec.extend(t.clone().into_bytes()); } } vec } } // Private helper functions. fn sock_as_bytes(sock: &SocketAddrV4) -> Vec<u8> { let mut vec = Vec::new(); for short in &(sock.ip().octets()) { vec.write_u8(*short).expect("vec.write_u8"); } vec.write_u16::<BigEndian>(sock.port()).expect("vec.write_u8"); vec } fn bytes_as_sock<'a>(bytes: &'a [u8]) -> Result<SocketAddrV4> { let mut reader = Cursor::new(bytes); let a = try!(reader.read_u8()); let b = try!(reader.read_u8()); let c = try!(reader.read_u8()); let d = try!(reader.read_u8()); let ipv4 = Ipv4Addr::new(a, b, c, d); let port = try!(reader.read_u16::<BigEndian>()); Ok(SocketAddrV4::new(ipv4, port)) } // Tests. #[cfg(test)] mod test { use super::*; mod fixtures { use super::super::*; use std::net::{SocketAddrV4,Ipv4Addr}; pub fn socket_addr() -> SocketAddrV4 { SocketAddrV4::new(Ipv4Addr::new(8, 8, 8, 8), 1337) } pub fn incoming_message() -> (Message, Vec<u8>) { let msg = Message::Incoming(socket_addr(), Box::new(text_message().0)); let bytes = vec![0, 8, 8, 8, 8, 5, 57, 2, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]; (msg, bytes) } pub fn greeting_message() -> (Message, Vec<u8>) { let msg = Message::Greeting; let bytes = vec![1]; (msg, bytes) } pub fn text_message() -> (Message, Vec<u8>) { let msg = Message::Text("Hello World!".into()); let bytes = vec![2, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]; (msg, bytes) } } #[test] fn incoming_message_from_bytes() { let (fmsg, fbytes) = fixtures::incoming_message(); let msg = Message::parse(&fbytes).unwrap(); assert_eq!(msg, fmsg); } // TODO: Test incoming message with a nested message. #[test] fn greeting_from_bytes() { let (fmsg, fbytes) = fixtures::greeting_message(); let msg = Message::parse(&fbytes).unwrap(); assert_eq!(msg, fmsg); } // TODO: Check this test for the string. #[test] fn text_message_from_bytes() { let (fmsg, fbytes) = fixtures::text_message(); let msg = Message::parse(&fbytes).unwrap(); assert_eq!(msg, fmsg); } #[test] fn bytes_from_incoming_message() { let (fmsg, fbytes) = fixtures::incoming_message(); let bytes = Vec::from(&fmsg); assert_eq!(bytes, fbytes) } #[test] fn bytes_from_greeting_message() { let (fmsg, fbytes) = fixtures::greeting_message(); let bytes = Vec::from(&fmsg); assert_eq!(bytes, fbytes) } #[test] fn bytes_from_text_message() { let (fmsg, fbytes) = fixtures::text_message(); let bytes = Vec::from(&fmsg); assert_eq!(bytes, fbytes) } #[test] fn message_from_bad_bytes() { let bytes = vec![]; let msg = Message::parse(&bytes); assert!(msg.is_err()); } #[test] fn unknown_message() { let bytes = vec![60]; let msg = Message::parse(&bytes); match msg.unwrap_err() { Error::UnknownMessage(n) => assert_eq!(n, 60), _ => assert!(false) } } }
99177168a8d63a98152099a5792e10ad53000d2c
[ "Markdown", "Rust", "TOML" ]
12
Markdown
nixpulvis/cs4740
bcf1daf4a4c19a064f38e9b4987ff15d0185ffaf
79fc39df5ee0446337870cfc6cb97eead2c82e57
refs/heads/master
<file_sep><?php $link = 'nope'; include('._-configurations._-/loader.php'); //see if the IP exists for username. if($TibiaMarket->isLogged()){ $userData = $TibiaMarket->userData(); $id = $userData['id']; $getIPs = $odb->prepare("SELECT * FROM `internetprotocols` WHERE `userid` = ? && `ip` = ?"); $getIPs->BindValue(1, $id); $getIPs->BindValue(2, $TibiaMarket->userIP()); $getIPs->execute(); if($getIPs->rowCount() == 0){ $addip = $odb->prepare("INSERT INTO `internetprotocols` (`id`, `userid`, `ip`, `first_time`) VALUES (NULL, ? , ? , CURRENT_TIMESTAMP)"); $addip->BindValue(1, $id); $addip->BindValue(2, $TibiaMarket->userIP()); $addip->execute(); } } //CHECK TO SEE IF BANNED $getbanned = $odb->prepare("SELECT * FROM `banned` WHERE `information` = ? && `type` = ?"); $getbanned->BindValue(1, $TibiaMarket->userIP()); $getbanned->BindValue(2, "IP"); $getbanned->execute(); if($getbanned->rowCount() != 0){ Header("Location: banned"); } //############################# CRON JOB ############################# $today = time(); $getAllAuctionLowerThanDate = $odb->prepare("SELECT * FROM `auctions` WHERE `expire` < ? AND `status` = ?"); $getAllAuctionLowerThanDate->BindValue(1, $today); $getAllAuctionLowerThanDate->BindValue(2, "0"); $getAllAuctionLowerThanDate->execute(); while($record = $getAllAuctionLowerThanDate->fetch(PDO::FETCH_ASSOC)){ //get the highest bidder $getLastBid = $odb->prepare("SELECT * FROM `bids` WHERE `auctionid` = ? ORDER BY `id` DESC LIMIT 1"); $getLastBid->BindValue(1, $record['id']); $getLastBid->execute(); $getLastBidF = $getLastBid->fetch(PDO::FETCH_ASSOC); if(empty($getLastBidF)){ } if($getLastBid->rowCount() == 0){ continue; } //add notificaitons $message = "You have won an auction!"; $link = $siteURL . "auction/" . $record['id']; $insertNotif = $odb->prepare("INSERT INTO `notifications` (`userid`, `message`, `link`, `date`) VALUES(?, ?, ?, ?)"); $insertNotif->BindValue(1, $getLastBidF['userid']); $insertNotif->BindValue(2, $message); $insertNotif->BindValue(3, $link); $insertNotif->BindValue(4, $TibiaMarket->dateTime()); $insertNotif->execute(); print_r($insertNotif->errorInfo()); //close the bid and set the winner $updateAuction = $odb->prepare("UPDATE `auctions` SET `status` = ?, `winner` = ? WHERE `id` = ?"); $updateAuction->BindValue(1, "1"); $updateAuction->BindValue(2, $getLastBidF['userid']); $updateAuction->BindValue(3, $record['id']); $updateAuction->execute(); } //############################# CRON JOB ############################# ?> <!DOCTYPE html> <html lang="en"> <head> <title><?php _echo($siteName);?></title> <base href="<?php _echo($siteURL);?>"> <meta name="description" content="Here you can buy/sell/auction items from the RPG game, Tibia."> <meta charset="UTF-8" /> <meta name=“robots” content=“noindex”> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="css/bootstrap.min.css" /> <link rel="stylesheet" href="css/font-awesome.css" /> <link rel="stylesheet" href="css/fullcalendar.css" /> <link rel="stylesheet" href="css/jquery.jscrollpane.css" /> <link rel="stylesheet" href="css/select2.css" /> <link rel="stylesheet" href="css/jquery-ui.css"> <link rel="stylesheet" href="css/jquery.gritter.css" /> <link rel="stylesheet" href="css/unicorn.css" /> <link rel="stylesheet" href="css/TMcustom.css" /> <script src='https://www.google.com/recaptcha/api.js'></script> <style> .g-recaptcha { width: 100%; } </style> <link href="/img/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <!--[if lt IE 9]> <script type="text/javascript" src="js/respond.min.js"></script> <![endif]--> </head> <body data-color="grey" class="flat"> <div id="wrapper"> <div id="header"> <h1 style="background-size:contain;left:5px;tio:26px;"><a href="index"><?php _echo($siteName);?></a></h1> <a id="menu-trigger" href="#"><i class="fa fa-bars"></i></a> </div> <div id="user-nav"> <ul class="btn-group"> <li class="btn"><a title="" href="#"><i class="fa fa-clock-o"></i> <span class="text">Server Time: <?php _echo($TibiaMarket->dateTime());?></span></a></li> <?php if($TibiaMarket->isLogged()){ ?> <?php $getMyNotifications = $odb->prepare("SELECT * FROM `notifications` WHERE `userid` = ? AND `seen` = ?"); $getMyNotifications->BindValue(1, $userData['id']); $getMyNotifications->BindValue(2, "0"); $getMyNotifications->execute(); $updateNotifications = $odb->prepare("UPDATE `notifications` SET `seen` = ? WHERE `userid` = ?"); $updateNotifications->BindValue(1, "1"); $updateNotifications->BindValue(2, $userData['id']); $updateNotifications->execute(); ?> <li class="btn dropdown" id="menu-messages"><a href="#" data-toggle="dropdown" data-target="#menu-messages" class="dropdown-toggle"><i class="fa fa-envelope"></i> <span class="text">Notifications</span> <span class="label label-danger"><?php _echo($getMyNotifications->rowCount());?></span> <b class="caret"></b></a> <ul class="dropdown-menu messages-menu"> <li class="title"><i class="fa fa-envelope-alt"></i>Notifications</li> <?php while($record = $getMyNotifications->fetch(PDO::FETCH_ASSOC)){ ?> <li class="message-item"> <a href="<?php _echo($record['link']);?>"> <img alt="User Icon" src="img/demo/av1.jpg" /> <div class="message-content"> <span class="message-time"> <?php _echo(date('Y-m-d', strtotime($record['date'])));?> </span> <span class="message-sender"> Auction Information </span> <span class="message"> <?php _echo($record['message']);?> </span> </div> </a> </li> <?php } ?> </ul> </li> <li class="btn"><a title="" href="settings"><i class="fa fa-cog"></i> <span class="text">Settings</span></a></li> <li class="btn"><a title="" href="logout"><i class="fa fa-share"></i> <span class="text">Logout</span></a></li> <?php } ?> </ul> </div> <div id="sidebar"> <ul> <li class=""> <a href="index"> <i class="fa fa-home"></i><span>Market</span> </a> </li> <?php if($TibiaMarket->isLogged()){ ?> <li class=""> <a href="myauctions"> <i class="fa fa-trophy"></i><span>My Auctions</span> </a> </li> <li class=""> <a href="mybids"> <i class="fa fa-star"></i><span>My Bids</span> </a> </li> <li class=""> <a href="characters"> <i class="fa fa-user"></i><span>My Characters</span> </a> </li> <li class=""> <a href="contact"> <i class="fa fa-envelope"></i><span>Contact</span> </a> </li> <li class=""> <a href="logout"> <i class="fa fa-share"></i><span>Logout</span> </a> </li> <?php if($TibiaMarket->userTable($userData['id'], "access_level") > 1 && $TibiaMarket->userTable($userData['id'], "access_level") < 7){ ?> <li class=""> <a href="staffpanel"> <i class="fa fa-flask"></i><span>Staff Panel</span> </a> </li> <?php } }else{ ?> <li class=""> <a href="login"> <i class="fa fa-lock"></i><span>Login</span> </a> </li> <li class=""> <a href="register"> <i class="fa fa-unlock-alt"></i><span>Register</span> </a> </li> <li class=""> <a href="contact"> <i class="fa fa-envelope"></i><span>Contact</span> </a> </li> <?php } ?> </ul> </div><file_sep><?php $config = array( 'host' => 'localhost', 'username' => 'nope', 'password' => '<PASSWORD>', 'dbname' => 'nope' ); try { $odb = new PDO('mysql:host=' . $config['host'] . ';dbname=' . $config['dbname'], $config['username'], $config['password']); $odb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (Exception $e) { echo '<center><b>MySQL Connection Error.</b></center>'; exit; } ?><file_sep><?php include('._._inc_header._._.php'); $getVerifiedCharCount = $odb->prepare("SELECT * FROM `characters` WHERE `userid` = ? AND `status` = ?"); $getVerifiedCharCount->BindValue(1, $userData['id']); $getVerifiedCharCount->BindValue(2, "1"); $getVerifiedCharCount->execute(); if(isset($_GET['id'])){ $validated = false; if(is_numeric($_GET['id'])){ $validateAuctionID = $odb->prepare("SELECT * FROM `auctions` WHERE `id` = ?"); $validateAuctionID->BindValue(1, $_GET['id']); $validateAuctionID->execute(); if($validateAuctionID->rowCount() == 1){ $validated = true; }else{ $TibiaMarket->redirect("index"); } }else{ $TibiaMarket->redirect("index"); } }else{ $TibiaMarket->redirect("index"); } $auctionFetcher = $validateAuctionID->fetch(PDO::FETCH_ASSOC); if($auctionFetcher['status'] == "2"){ $pending = true; } $getLastBid = $odb->prepare("SELECT * FROM `bids` WHERE `auctionid` = ? ORDER BY `id` DESC LIMIT 1"); $getLastBid->BindValue(1, $auctionFetcher['id']); $getLastBid->execute(); $getLastBidF = $getLastBid->fetch(PDO::FETCH_ASSOC); if(empty($getLastBidF['bid'])){ $currentBid = "0"; }else{ $currentBid = $getLastBidF['bid']; } if(isset($_POST['mybidding'])){ if(is_numeric($_POST['mybidding'])){ if($auctionFetcher['status'] == "0" || $auctionFetcher['status'] == "99"){ $myBid = inputSanitize($_POST['mybidding']); $charFromBid = inputSanitize($_POST['charFromBid']); if($auctionFetcher['userid'] == $userData['id']){ $errors[] = "You cannot bid on your own auctions."; } if(!is_numeric($charFromBid)){ $errors[] = "Character not found."; } if($myBid <= $auctionFetcher['minbid']){ $errors[] = "Your bid is lower than the minimum bid of the auction."; }else{ if($myBid <= $currentBid){ $errors[] = "Your bid is lower than the current bid."; } } if($getVerifiedCharCount->rowCount() == 0){ $errors[] = "You do not have a verified character."; } if($TibiaMarket->characterTable($charFromBid, "userid") != $userData['id']){ $errors[] = "You must choose a character in order to make a bid."; } $tenTimesMax = ($currentBid * 10) + 2; if($myBid > $tenTimesMax && $currentBid != 0){ $errors[] = "You cannot bid more than " . number_format($tenTimesMax) . " for the time being."; } if(empty($errors)){ //add my bidf $addMyBid = $odb->prepare("INSERT INTO `bids` (`userid`, `auctionid`, `bid`, `charid`, `date`) VALUES(?, ?, ?, ?, ?)"); $addMyBid->BindValue(1, $userData['id']); $addMyBid->BindValue(2, $auctionFetcher['id']); $addMyBid->BindValue(3, $myBid); $addMyBid->BindValue(4, $charFromBid); $addMyBid->BindValue(5, $TibiaMarket->dateTime()); $addMyBid->execute(); if(empty($getLastBidF['userid'])){ }else{ $message = "You have been outbidded in an auction!"; $link = $siteURL . "auction/" . $auctionFetcher['id']; $insertNotif = $odb->prepare("INSERT INTO `notifications` (`userid`, `message`, `link`, `date`) VALUES(?, ?, ?, ?)"); $insertNotif->BindValue(1, $getLastBidF['userid']); $insertNotif->BindValue(2, $message); $insertNotif->BindValue(3, $link); $insertNotif->BindValue(4, $TibiaMarket->dateTime()); $insertNotif->execute(); } $TibiaMarket->redirect("{$siteURL}auction/" . $auctionFetcher['id']); } }else{ $errors[] = "Auction has already ended"; } }else{ $errors[] = "Your bid must be positive"; } } ?> <div id="content"> <div id="content-header"> <h1>Auction Information</h1> </div> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">Auction Information</a> </div> <div class="row"> <?php if(empty($pending)){ ?> <div class="col-sm-12"> <?php if(isset($errors)){ if(!empty($errors)){ echo '<div class="alert alert-danger">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; foreach($errors as $error){ echo ''.$error.'<br />'; } echo '</div>'; } } ?> </div> <div class="col-sm-6"> <div class="tabbable inline"> <ul class="nav nav-tabs tab-bricky" id="myTab"> <li class="active"> <a data-toggle="tab" href="#panel_tab2_example1"> Information </a> </li> <li> <a data-toggle="tab" href="#panel_tab2_example2"> Bidding History </a> </li> </ul> <div class="tab-content"> <div id="panel_tab2_example1" class="tab-pane in active"> <table class="table table-bordered table-striped table-hover data-table dataTable" id="DataTables_Table_1"> <tbody> <tr class="gradeX odd"> <td class="" style="width: 100px;"> <center>Item</center> </td> <td class=" "> <center><?php _echo($TibiaMarket->itemTable($auctionFetcher['item'], "name"));?></center> </td> </tr> <tr class="gradeX odd"> <td class=""> <center>World</center> </td> <td class=" "> <center><?php _echo($TibiaMarket->worldTable($auctionFetcher['world'], "name"));?></center> </td> </tr> <tr class="gradeX odd"> <td class=""> <center>Character</center> </td> <td class=" "> <center><?php _echo($TibiaMarket->characterTable($auctionFetcher['charid'], "name"));?></center> </td> </tr> <tr class="gradeX odd"> <td class=""> <center>Length</center> </td> <td class=" "> <center><?php _echo($auctionFetcher['length']);?></center> </td> </tr> <tr class="gradeX odd"> <td class=""> <center>Minimum Bid</center> </td> <td class=" "> <center><?php _echo($auctionFetcher['minbid']);?></center> </td> </tr> <tr class="gradeX odd"> <td class=""> <center>Current Bid</center> </td> <td class=" "> <center> <?php if($currentBid == "0"){ _echo("0"); }else{ _echo($currentBid . " by " . $TibiaMarket->characterTable($getLastBidF['charid'], "name")); //$TibiaMarket->userTable($['userid'], "username")); } ?> </center> </td> </tr> <tr class="gradeX odd"> <td class=""> <center>Bidding Ends</center> </td> <td class=" "> <center><?php _echo(date('Y-m-d H:i', $TibiaMarket->auctionTable($auctionFetcher['id'], "expire")));?></center> </td> </tr> <tr class="gradeX odd"> <td class=""> <center>Comment</center> </td> <td class=" "> <center> <?php _echo($auctionFetcher['comment']); ?> </center> </td> </tr> </tbody> </table> </div> <div id="panel_tab2_example2" class="tab-pane"> <table class="table table-bordered table-striped table-hover data-table"> <thead> <tr> <th>Username</th> <th>Bid</th> <th>Date</th> </tr> </thead> <tbody> <?php $getAllBids = $odb->prepare("SELECT * FROM `bids` WHERE `auctionid` = ?"); $getAllBids->BindValue(1, $auctionFetcher['id']); $getAllBids->execute(); while($record = $getAllBids->fetch(PDO::FETCH_ASSOC)){ ?> <tr> <td><center><?php _echo($TibiaMarket->characterTable($record['charid'], "name"));?></center></td> <td><center><?php _echo($record['bid']);?></center></td> <td><center><?php _echo($record['date']);?></center></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> <div class="col-sm-1"></div> <div class="col-sm-4" style="top: 45px;"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-star"></i> </span> <h5>Make a bid</h5> </div> <div class="widget-content nopadding"> <form action="" method="post" class="form-horizontal"> <div class="form-group"> <label class="col-sm-3 control-label">Current Bid</label> <div class="col-sm-9"> <label class="control-label" style="font-weight: normal;"><?php _echo($currentBid);?></label> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Character</label> <div class="col-sm-9"> <select name="charFromBid"> <?php $getAllChars = $odb->prepare("SELECT * FROM `characters` WHERE `userid` = ? AND `status` = ?"); $getAllChars->BindValue(1, $userData['id']); $getAllChars->BindValue(2, "1"); $getAllChars->execute(); while($record = $getAllChars->fetch(PDO::FETCH_ASSOC)){ ?> <option value="<?php _echo($record['id']);?>"> <?php _echo($record['name']);?> </option> <?php } ?> </select> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Your Bid</label> <div class="col-sm-9"> <input type="text" class="form-control input-sm" name="mybidding"> </div> </div> <div class="form-actions"> <?php if($auctionFetcher['status'] == "0"){ if($getVerifiedCharCount->rowCount() == 0){ echo '<button type="submit" class="btn btn-primary btn-sm">You do not have a verified character.</button>'; }else{ echo '<button type="submit" class="btn btn-primary btn-sm">Submit</button>'; } }else{ echo '<button style="margin-left: -105px;" type="submit" class="btn btn-primary btn-sm">Bidding has been ended. Winner is: '; _echo($TibiaMarket->userTable($auctionFetcher['winner'], "username")); echo '</button>'; } ?> </div> </form> </div> </div> </div> <?php } else { echo("This is pending, mate."); } ?> </div> </div> <?php include('._._inc_footer._._.php'); ?><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. */ function handleNav(id, project) { document.getElementById("project1").className = "hidden project trigger-info" document.getElementById("project2").className = "hidden project trigger-info" document.getElementById("project3").className = "hidden project trigger-info" document.getElementById("project4").className = "hidden project trigger-info" document.getElementById("project5").className = "hidden project trigger-info" document.getElementById("aboutme").className = "hidden trigger-info" document.getElementById("resume").className = "hidden trigger-info" document.getElementById("conclusion").className = "hidden trigger-info" /** Handle ID **/ if(project){ document.getElementById(id).className = "nothidden project trigger-info" }else{ document.getElementById(id).className = "nothidden trigger-info" } }<file_sep><?php include('._._inc_header._._.php'); if($TibiaMarket->isLogged() == false){ $TibiaMarket->redirect("login"); } ?> <div id="content"> <?php if($TibiaMarket->isLogged()){ ?> <div id="content-header"> <h1>Staff Hub</h1> <h5>&nbsp&nbsp&nbsp&nbsp&nbspA place for all your staff needs.</h5> </div> <hr> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">[Staff Panel] - <?php include("./php/rank.php"); ?></a> </div> <?php } if($access >= 2 && $access <= 6){ ?> <div class="widget-box"> <div class="widget-title"> <span class="icon"><i class="fa fa-ban"></i></span> <h5><?php include("./php/rank.php"); ?> Tools</h5> <div class="buttons"> <a href="#" class="btn"><i class="fa fa-refresh"></i> <span class="text">Update options</span></a> </div> </div> <div class="widget-content"> <?php //<!-- Founder widgets --> if($access == 6){ include("./staff/newsmaker.php"); include("./staff/imageupdater.php"); include("./staff/staffactivitylog.php"); //<!-- Super Administrator widgets --> } if ($access == 5){ include("./staff/newsmaker.php"); include("./staff/imageupdater.php"); include("./staff/staffactivitylog.php"); //<!-- Administrator widgets --> } if ($access == 4){ include("./staff/newsmaker.php"); include("./staff/imageupdater.php"); //<!-- Super Moderator widgets --> } if ($access == 3){ //<!-- Moderator widgets --> } if ($access == 2){ } ?> </div> </div> <?php } if($access == 0 || $access == 1){ echo "&nbsp&nbsp&nbsp You do not have permission to access this area."; } ?> </div> <?php include('._._inc_footer._._.php'); ?><file_sep> <?php if ($link == 'nope'){ ?> <div class="widget-box"> <div class="widget-title"> <span class="icon pull-right"><i class="fa fa-ellipsis-h"></i></span> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#tab1">Most Recent</a></li> <li class=""><a data-toggle="tab" href="#tab2">TibiaMarket</a></li> <li class=""><a data-toggle="tab" href="#tab3">Fansites</a></li> <li class=""><a data-toggle="tab" href="#tab4">Cipsoft</a></li> <?php if($TibiaMarket->isLogged()){ $user = $TibiaMarket->userData(); if($user['access_level'] > 1){ ?> <li class=""><a data-toggle="tab" href="#tab5">Staff</a></li> <?php } }?> </ul> </div> <div class="widget-content tab-content"> <div id="tab1" class="tab-pane active"> <?php //Query for all news. $newsquery = $odb->prepare("SELECT * FROM `news` WHERE `author` <> ? ORDER BY timestamp DESC LIMIT 5"); $newsquery->BindValue(1, "Staff"); $newsquery->execute(); $sess = $TibiaMarket->getSession(); $query2 = $odb->prepare("SELECT * FROM `users` WHERE `lghash` = ?"); $query2->BindValue(1, $sess); $query2->execute(); $userinfo = $query2->fetch(PDO::FETCH_ASSOC); while($result = $newsquery->fetch(PDO::FETCH_ASSOC)){ $formatted = $TibiaMarket->addhttp($result["url"]); echo ("<p><b>[".$result["author"]."]</b> - <a class='newsticker' href=".$formatted.">\"".$result["description"]."\" </a>"); if($userinfo['access_level'] == 4 && $result["owner"] == $userinfo['username']){ echo('<a href="./staff/delete/'.$result['id'].'" class="tip-top" data-original-title="Delete"><i class="fa fa-times"></i></a>'); } if($userinfo['access_level'] > 4 && $userinfo['access_level'] < 7){ echo('<a href="./staff/delete/'.$result['id'].'" class="tip-top" data-original-title="Delete"><i class="fa fa-times"></i></a>'); } echo ("</p>"); } ?> </div> <div id="tab2" class="tab-pane"> <?php //Query for TibiaMarket News. $newsquery = $odb->prepare("SELECT * FROM `news` WHERE `author` = ? ORDER BY timestamp DESC LIMIT 5"); $newsquery->BindValue(1, "TibiaMarket"); $newsquery->execute(); $sess = $TibiaMarket->getSession(); $query2 = $odb->prepare("SELECT * FROM `users` WHERE `lghash` = ?"); $query2->BindValue(1, $sess); $query2->execute(); $userinfo = $query2->fetch(PDO::FETCH_ASSOC); while($result = $newsquery->fetch(PDO::FETCH_ASSOC)){ $formatted = $TibiaMarket->addhttp($result["url"]); echo ("<p><b>[".$result["author"]."]</b> - <a class='newsticker' href=".$formatted.">\"".$result["description"]."\" </a>"); if($userinfo['access_level'] == 4 && $result["owner"] == $userinfo['username']){ echo('<a href="./staff/delete/'.$result['id'].'" class="tip-top" data-original-title="Delete"><i class="fa fa-times"></i></a>'); } if($userinfo['access_level'] > 4 && $userinfo['access_level'] < 7){ echo('<a href="./staff/delete/'.$result['id'].'" class="tip-top" data-original-title="Delete"><i class="fa fa-times"></i></a>'); } echo ("</p>"); } ?> </div> <div id="tab3" class="tab-pane"> <?php //Query for fansite news. $newsquery = $odb->prepare("SELECT * FROM `news` WHERE `author` <> ? AND `author` <> ? AND `author` <> ? ORDER BY timestamp DESC LIMIT 5"); $newsquery->BindValue(1, "TibiaMarket"); $newsquery->BindValue(2, "Cipsoft"); $newsquery->BindValue(3, "Staff"); $newsquery->execute(); $sess = $TibiaMarket->getSession(); $query2 = $odb->prepare("SELECT * FROM `users` WHERE `lghash` = ?"); $query2->BindValue(1, $sess); $query2->execute(); $userinfo = $query2->fetch(PDO::FETCH_ASSOC); while($result = $newsquery->fetch(PDO::FETCH_ASSOC)){ $formatted = $TibiaMarket->addhttp($result["url"]); echo ("<p><b>[".$result["author"]."]</b> - <a class='newsticker' href=".$formatted.">\"".$result["description"]."\" </a>"); if($userinfo['access_level'] == 4 && $result["owner"] == $userinfo['username']){ echo('<a href="./staff/delete/'.$result['id'].'" class="tip-top" data-original-title="Delete"><i class="fa fa-times"></i></a>'); } if($userinfo['access_level'] > 4 && $userinfo['access_level'] < 7){ echo('<a href="./staff/delete/'.$result['id'].'" class="tip-top" data-original-title="Delete"><i class="fa fa-times"></i></a>'); } echo ("</p>"); } ?> </div> <div id="tab4" class="tab-pane"> <?php //Query for Cipsoft news. $newsquery = $odb->prepare("SELECT * FROM `news` WHERE `author` = ? ORDER BY timestamp DESC LIMIT 5"); $newsquery->BindValue(1, "Cipsoft"); $newsquery->execute(); $sess = $TibiaMarket->getSession(); $query2 = $odb->prepare("SELECT * FROM `users` WHERE `lghash` = ?"); $query2->BindValue(1, $sess); $query2->execute(); $userinfo = $query2->fetch(PDO::FETCH_ASSOC); while($result = $newsquery->fetch(PDO::FETCH_ASSOC)){ $formatted = $TibiaMarket->addhttp($result["url"]); echo ("<p><b>[".$result["author"]."]</b> - <a class='newsticker' href=".$formatted.">\"".$result["description"]."\" </a>"); if($userinfo['access_level'] == 4 && $result["owner"] == $userinfo['username']){ echo('<a href="./staff/delete/'.$result['id'].'" class="tip-top" data-original-title="Delete"><i class="fa fa-times"></i></a>'); } if($userinfo['access_level'] > 4 && $userinfo['access_level'] < 7){ echo('<a href="./staff/delete/'.$result['id'].'" class="tip-top" data-original-title="Delete"><i class="fa fa-times"></i></a>'); } echo ("</p>"); } ?> </div> <?php if($TibiaMarket->isLogged()){ $user = $TibiaMarket->userData(); if($user['access_level'] > 1){ ?> <div id="tab5" class="tab-pane"> <?php //Query for Cipsoft news. $newsquery = $odb->prepare("SELECT * FROM `news` WHERE `author` = ? ORDER BY timestamp DESC LIMIT 5"); $newsquery->BindValue(1, "Staff"); $newsquery->execute(); $sess = $TibiaMarket->getSession(); $query2 = $odb->prepare("SELECT * FROM `users` WHERE `lghash` = ?"); $query2->BindValue(1, $sess); $query2->execute(); $userinfo = $query2->fetch(PDO::FETCH_ASSOC); while($result = $newsquery->fetch(PDO::FETCH_ASSOC)){ $formatted = $TibiaMarket->addhttp($result["url"]); echo ("<p><b>[".$result["author"]."]</b> - <a class='newsticker' href=".$formatted.">\"".$result["description"]."\" </a>"); if($userinfo['access_level'] == 4 && $result["owner"] == $userinfo['username']){ echo('<a href="./staff/delete/'.$result['id'].'" class="tip-top" data-original-title="Delete"><i class="fa fa-times"></i></a>'); } if($userinfo['access_level'] > 4 && $userinfo['access_level'] < 7){ echo('<a href="./staff/delete/'.$result['id'].'" class="tip-top" data-original-title="Delete"><i class="fa fa-times"></i></a>'); } echo ("</p>"); } ?> </div> <?php } }?> </div> </div> <?php } else { echo "Someone is where they're not suppose to be..."; } ?><file_sep><?php session_start(); error_reporting(E_ALL); ini_set('display_errors', 1); date_default_timezone_set('America/New_York'); //http://php.net/manual/en/timezones.php //## - Site Configurations - ##// $siteName = "Tibia Market"; $contactEmail = "nope"; $siteURL = "http://tibiamarket.net/"; // including last slash $rootDir = "/var/public_html/"; // FULL PATH including last slash //## - SMTP Configurations - ##// $fromEmail = "nope"; $smtp_host = "nope"; $smtp_user = "nope"; $smtp_pass = "<PASSWORD>"; $smtp_port = 587; include('dbc.php'); include('TibiaMarket.Class.php'); $TibiaMarket = new TibiaMarket($odb); function _echo($str){ echo nl2br(htmlspecialchars($str)); } if($TibiaMarket->isLogged()){ $userData = $TibiaMarket->userData(); } function createDateRangeArray($strDateFrom,$strDateTo){ $aryRange = array(); $iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4)); $iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4)); if ($iDateTo >= $iDateFrom){ array_push($aryRange, date('Y-m-d', $iDateFrom)); while ($iDateFrom < $iDateTo){ $iDateFrom += 86400; array_push($aryRange, date('Y-m-d', $iDateFrom)); } } return $aryRange; } function SendEmail($to, $subject, $message){ global $smtp_host; global $smtp_user; global $smtp_pass; global $smtp_port; global $fromEmail; global $siteName; require 'PHPMailer/PHPMailerAutoload.php'; $mail = new PHPMailer; $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = $smtp_host; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $smtp_user; // SMTP username $mail->Password = $<PASSWORD>; // SMTP password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = $smtp_port; // TCP port to connect to $mail->setFrom($fromEmail, $siteName); $mail->addAddress($to); $mail->isHTML(true); // Set email format to HTML $mail->Subject = $subject; $mail->Body = nl2br($message); //$mail->AltBody = $message; if(!$mail->send()) { die($mail->ErrorInfo); return false; } else { return true; } } function inputSanitize($str){ return strip_tags(htmlentities($str)); } <file_sep><?php include('._._inc_header._._.php'); if(isset($_GET['id'])){ $validated = false; if(is_numeric($_GET['id'])){ $validateUserID = $odb->prepare("SELECT * FROM `users` WHERE `id` = ?"); $validateUserID->BindValue(1, $_GET['id']); $validateUserID->execute(); if($validateUserID->rowCount() == 1){ $validateReputationID = $odb->prepare("SELECT * FROM `users` WHERE `id` = ?"); $validateReputationID->BindValue(1, $_GET['id']); $validateReputationID->execute(); $array = $validateReputationID->fetch(PDO::FETCH_ASSOC); $modifiedUsername = $array['username']; }else{ $TibiaMarket->redirect("index"); } }else{ $TibiaMarket->redirect("index"); } }else{ $TibiaMarket->redirect("index"); } //Taken $getRecipientReputations = $odb->prepare("SELECT * FROM `reputation` WHERE `recipient_id` = ?"); $getRecipientReputations->BindValue(1, $_GET['id']); $getRecipientReputations->execute(); //Given $getGiverReputations = $odb->prepare("SELECT * FROM `reputation` WHERE `giver_id` = ?"); $getGiverReputations->BindValue(1, $_GET['id']); $getGiverReputations->execute(); $user = $TibiaMarket->userData(); if($user['id'] == $_GET['id']){ $self_rep = true; }else{ $self_rep = false; } ?> <div id="content"> <div id="content-header"> </div> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">Reputation <?php echo(" - ".$modifiedUsername); ?> </a> </div> <div class="row"> <div class="col-sm-12"> <?php if($TibiaMarket->isLogged()){ ?> <a class="btn btn-primary btn-xs" onclick="window.open('rep/<?php echo ($_GET['id']); ?>','MsgWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=250');">Add/Modify Reputation</a> <?php } ?> <table class="table table-bordered table-striped table-hover data-table"> <thead> <tr> <th>Name</th> <th>Amount</th> <th>Description</th> <th>Time</th> <?php if($self_rep){ ?> <th>Report</th> <?php } ?> </tr> </thead> <tbody> <?php while($record = $getRecipientReputations->fetch(PDO::FETCH_ASSOC)){ $query = $odb->prepare("SELECT * FROM `users` WHERE `id` = ?"); $query->BindValue(1, $record['giver_id']); $query->execute(); $userinfo = $query->fetch(PDO::FETCH_ASSOC); $reputation = $userinfo['reputation']; $VIP = $userinfo['VIP']; $access = $userinfo['access_level']; $id = $userinfo['id']; $username = $userinfo['username']; $description = inputSanitize($record['description']); //Positive reputation if($record['amount'] > 0){ $rep_color = "color: #32CD32;"; $formatted = "+".$record['amount']; } //Neutral reputation if($record['amount'] == 0){ $rep_color = "color: #000000;"; $formatted = $record['amount']; } //Negative reputation if($record['amount'] < 0){ $rep_color = "color: #FF0000;"; $formatted = $record['amount']; } //Normal user GREEN $rank = "color: #228B22;"; //VIP OR NOT $vipbold = ""; if($reputation == 0){ $color = "color: #000000;"; }else if($reputation > 0){ $color = "color: #32CD32;"; //Elite users PURPLE if($reputation >= 50 && $reputation < 300){ $rank = "color: #9400D3;"; //Master users ROYAL BLUE }else if($reputation >= 300){ $rank = "color: #436EEE;"; } }else{ $color = "color: #FF0000;"; } //Change if staff //Moderators if($access > 1 && $access < 4){ $rank = "color: #e59400;"; //Administrators }else if($access > 3 && $access < 6){ $rank = "color: #ff0000;"; //Founders }else if($access > 5){ $rank = "color: #dbba08;"; } if($VIP > 0 || $access == 6 || $access == 5){ $vipbold = "font-weight: bold;"; } ?> <tr class="gradeX"> <td><center><span style="<?php _echo($rank); ?> <?php _echo($vipbold); ?>"><?php _echo($username); ?></span> (<a href="<?php _echo("reputation.php?id=".$id);?>"><span style="<?php _echo($color); ?>font-weight: bold;"><?php _echo($reputation); ?></span></a>) </center></td> <td><center><span style="<?php _echo($rep_color); ?> font-weight: bold;" ><?php _echo($formatted);?></span></center></td> <td><center><?php _echo($description);?></center></td> <td><center><?php _echo($record['timestamp']);?></center></td> <?php if($self_rep){ ?> <td><center>REPORT BUTTON HERE</center></td> <?php } ?> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <?php include('._._inc_footer._._.php'); ?><file_sep><?php include('../._._inc_header._._.php'); //Founder $getFounders = $odb->prepare("SELECT * FROM `users` WHERE `access_level` = ?"); $getFounders->BindValue(1, "6"); $getFounders->execute(); //Super Administrators $getSuperAdmins = $odb->prepare("SELECT * FROM `users` WHERE `access_level` = ?"); $getSuperAdmins->BindValue(1, "5"); $getSuperAdmins->execute(); //Administrators $getAdmins = $odb->prepare("SELECT * FROM `users` WHERE `access_level` = ?"); $getAdmins->BindValue(1, "4"); $getAdmins->execute(); //Super Moderators $getSuperMods = $odb->prepare("SELECT * FROM `users` WHERE `access_level` = ?"); $getSuperMods->BindValue(1, "3"); $getSuperMods->execute(); //Moderators $getMods = $odb->prepare("SELECT * FROM `users` WHERE `access_level` = ?"); $getMods->BindValue(1, "2"); $getMods->execute(); ?> <div id="content"> <div id="content-header"> <h1>Staff</h1> </div> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">Staff</a> </div> <div class="row"> <div class="col-xs-8"> <?php if($getFounders->rowCount() > 0){ echo ("<p><h4>Founders:</h4></p>"); while($result = $getFounders->fetch(PDO::FETCH_ASSOC)){ $formatted = preg_replace("/ /","+",$result['username']); echo("<p><a href='https://secure.tibia.com/community/?subtopic=characters&name=".$formatted."'>".$result['username']."</a></p>"); } } if($getSuperAdmins->rowCount() > 0){ echo ("<p><h4>Super Administrators:</h4></p>"); while($result = $getSuperAdmins->fetch(PDO::FETCH_ASSOC)){ $formatted = preg_replace("/ /","+",$result['username']); echo("<p><a href='https://secure.tibia.com/community/?subtopic=characters&name=".$formatted."'>".$result['username']."</a></p>"); } } if($getAdmins->rowCount() > 0){ echo ("<p><h4>Admins:</h4></p>"); while($result = $getAdmins->fetch(PDO::FETCH_ASSOC)){ $formatted = preg_replace("/ /","+",$result['username']); echo("<p><a href='https://secure.tibia.com/community/?subtopic=characters&name=".$formatted."'>".$result['username']."</a></p>"); } } if($getSuperMods->rowCount() > 0){ echo ("<p><h4>Super Moderators:</h4></p>"); while($result = $getSuperMods->fetch(PDO::FETCH_ASSOC)){ $formatted = preg_replace("/ /","+",$result['username']); echo("<p><a href='https://secure.tibia.com/community/?subtopic=characters&name=".$formatted."'>".$result['username']."</a></p>"); } } if($getMods->rowCount() > 0){ echo ("<p><h4>Moderators:</h4></p>"); while($result = $getMods->fetch(PDO::FETCH_ASSOC)){ $formatted = preg_replace("/ /","+",$result['username']); echo("<p><a href='https://secure.tibia.com/community/?subtopic=characters&name=".$formatted."'>".$result['username']."</a></p>"); } } ?> </div> </div> </div> <?php include('../._._inc_footer._._.php'); ?><file_sep><?php include('._._inc_header._._.php'); if($TibiaMarket->isLogged() == false){ $TibiaMarket->redirect("login"); } if(isset($_POST['newpw'])){ $errors = array(); if( (empty($_POST['newpw'])) || (empty($_POST['newpw2'])) || (empty($_POST['oldpw']))){ $errors[] = "Fill in all the fields!"; }else{ $changed = false; $pw = $_POST['newpw']; $pw2 = $_POST['newpw2']; if (strlen($pw) < 6){ $errors[] = 'Your password must be atleast 6 characters'; } else if (strlen($pw) > 18){ $errors[] = 'Your password cannot be more than 18 characters long'; } else if (strcmp($pw, $pw2) != 0) { $errors[] = 'Both new passwords does not match.'; } if(!$TibiaMarket->hashVerify($_POST['oldpw'], $userData['password'])){ $errors[] = 'Your current password does not match.'; } if(empty($errors)){ $hashPW = $TibiaMarket->hashPW($pw); $updatePW = $odb->prepare("UPDATE `users` SET `password` = ? WHERE `id` = ?"); $updatePW->BindValue(1, $hashPW); $updatePW->BindValue(2, $userData['id']); $updatePW->execute(); $changed = true; } } } ?> <div id="content"> <div id="content-header"> <h1>Settings</h1> </div> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">Settings - <?php $access = $TibiaMarket->userTable($userData['id'], "access_level"); if($access == 6){ echo "Founder"; } if($access == 5){ echo "Super Administrator"; } if($access == 4){ echo "Administrator"; } if($access == 3){ echo "Super Moderator"; } if($access == 2){ echo "Moderator"; } if($access == 1){ echo "VIP Member"; } if($access == 0){ echo "Member"; } ?> </a> </div> <div class="row"> <div class="col-xs-4"></div> <div class="col-xs-5"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-cog"></i> </span> <h5>Change Password </h5> </div> <div class="widget-content nopadding"> <form action="" method="post" class="form-horizontal"> <?php if(isset($_POST['newpw2'])){ if(!empty($errors)){ echo '<div class="alert alert-danger">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; foreach($errors as $error){ echo ''.$error.'<br />'; } echo '</div>'; }else{ if($changed){ echo '<div class="alert alert-success">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; echo 'Your password has been changed.'; echo '</div>'; } } } ?> <div class="form-group"> <label class="col-sm-4 control-label">Current Password</label> <div class="col-sm-8"> <input type="password" class="form-control input-sm" name="oldpw"> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">New Password</label> <div class="col-sm-8"> <input type="password" class="form-control input-sm" name="newpw"> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">Retype New Password</label> <div class="col-sm-8"> <input type="password" class="form-control input-sm" name="<PASSWORD>"> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary btn-sm">Submit</button> </div> </form> </div> </div> </div> </div> </div> <?php include('._._inc_footer._._.php'); ?><file_sep><?php include('._-configurations._-/loader.php'); $token = $_GET['token']; $query1 = $odb->prepare("SELECT * FROM `users` WHERE `status` = ?"); $query1->BindValue(1, $token); $query1->execute(); if($query1->rowCount() == 1){ $query2 = $odb->prepare("UPDATE `users` SET `status` = ? WHERE `status` = ?"); $query2->BindValue(1, "ACTIVE"); $query2->BindValue(2, $token); $query2->execute(); } Header("Location: {$siteURL}login"); die(); ?><file_sep><?php $access = $TibiaMarket->userTable($userData['id'], "access_level"); $rank; if($link = 'nope'){ if($access == 6){ $rank = "Founder"; } if($access == 5){ $rank = "Super Administrator"; } if($access == 4){ $rank = "Administrator"; } if($access == 3){ $rank = "Super Moderator"; } if($access == 2){ $rank = "Moderator"; } if($access < 2){ $rank = "User"; } ?> <?php echo $rank ?> <?php } else { echo "Someone is where they're not suppose to be..."; } ?><file_sep><?php include('._._inc_header._._.php'); $getItemInfo = $odb->prepare("SELECT * FROM `items`"); $getItemInfo->execute(); ?> <div id="content"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-th"></i> </span> <h5>Open Auctions</h5> </div> <div id="specialdiv" style ="position:fixed; z-index:100; bottom:0%; left: 0%; padding:20px; background-color:black; color:white; text-align: center; border: none; display:none;"><b><u>Item Information</u></b></div> <div class="widget-content nopadding"> <table class="table table-bordered table-striped table-hover data-table"> <thead> <tr> <th>Item Name</th> <th>Item Description</th> <th>Rarity</th> <th>Highest Winning Bid</th> <th>Lowest Bid</th> <th>Average Bid</th> <th>Successful Auctions</th> </tr> </thead> <tbody> <?php while($record = $getItemInfo->fetch(PDO::FETCH_ASSOC)){ if($record['rarity'] == 0){ $rarity = '<KEY>ues<KEY>'; }else if ($record['rarity'] == 1){ $rarity = 'iVBORw0KGgoAAAANSUhEUgAAAJYAAAAZCAYAAADT59fv<KEY>'; }else if ($record['rarity'] == 2){ $rarity = '<KEY>'; }else if ($record['rarity'] == 3){ $rarity = '<KEY>'; }else if ($record['rarity'] == 4){ $rarity = '<KEY>UIe<KEY>//<KEY>'; }else{ $rarity = '<KEY>'; } ?> <tr class="gradeX"> <td><center><?php echo("<img alt=\"\" src=\"data:image/gif;base64,".$record['image']."\" /> "); echo($record['name']);?></center></td> <td><center><?php echo($record['description']);?></center></td> <td><center><?php echo("<span style='display:none'>".$record['rarity']."</span><img alt=\"\" src=\"data:image/gif;base64,".$rarity."\" /> "); ?></center></td> <td><center><?php _echo($record['name']);?></center></td> <td><center><?php echo($record['name']);?></center></td> <td><center><?php echo($record['name']);?></center></td> <td><center><?php echo($record['name']);?></center></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <?php include('._._inc_footer._._.php'); ?><file_sep><?php class TibiaMarket{ private $db; public function __construct($database) { $this->db = $database; } public function date(){ return date('Y-m-d'); } public function time(){ return date('H:i:s'); } public function dateTime(){ return date('Y-m-d H:i:s'); } public function userIP(){ return $_SERVER['REMOTE_ADDR']; } public function hashPW($pw){ return password_hash($pw, PASSWORD_BCRYPT, array("cost" => 11)); } public function hashVerify($pw, $hash){ return password_verify($pw, $hash); } public function token(){ return md5(uniqid('auth', true)); } public function addLog($log){ $query = $this->db->prepare("INSERT INTO `logs` (`id`, `log`) VALUES(NULL, ?)"); $query->BindValue(1, $log); $query->execute(); } public function sessionName(){ return "tibiamarketnet"; } public function isLogged(){ $sess = $this->getSession(); if(!$sess){ return false; }else{ $query = $this->db->prepare("SELECT * FROM `users` WHERE `lghash` = ?"); $query->BindValue(1, $sess); $query->execute(); if($query->rowCount() == 1){ return true; }else{ return false; } } } public function addhttp($url) { if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { $url = "http://" . $url; } return $url; } public function setSession($hash, $check){ if($check == "1"){ session_destroy(); ini_set('session.cookie_lifetime', 86400); ini_set('session.gc_maxlifetime', 86400); session_start(); $_SESSION[$this->sessionName()] = $hash; }else{ $_SESSION[$this->sessionName()] = $hash; } return true; } public function getSession(){ if(isset($_SESSION[$this->sessionName()])){ if(empty($_SESSION[$this->sessionName()])){ return false; }else{ return $_SESSION[$this->sessionName()]; } }else{ return false; } } public function userData(){ $sess = $this->getSession(); $query = $this->db->prepare("SELECT * FROM `users` WHERE `lghash` = ?"); $query->BindValue(1, $sess); $query->execute(); return $query->fetch(PDO::FETCH_ASSOC); } public function userTable($uid, $table){ $query = $this->db->prepare("SELECT * FROM `users` WHERE `id` = ?"); $query->BindValue(1, $uid); $query->execute(); $qf = $query->fetch(PDO::FETCH_ASSOC); return $qf[$table]; } public function itemTable($id, $table){ $query = $this->db->prepare("SELECT * FROM `items` WHERE `id` = ?"); $query->BindValue(1, $id); $query->execute(); $qf = $query->fetch(PDO::FETCH_ASSOC); return $qf[$table]; } public function itemImageTable($id, $table){ $query = $this->db->prepare("SELECT * FROM `items` WHERE `id` = ?"); $query->BindValue(1, $id); $query->execute(); $qf = $query->fetch(PDO::FETCH_ASSOC); return $qf[$table]; } public function worldTable($id, $table){ $query = $this->db->prepare("SELECT * FROM `worlds` WHERE `id` = ?"); $query->BindValue(1, $id); $query->execute(); $qf = $query->fetch(PDO::FETCH_ASSOC); return $qf[$table]; } public function newsTable($author){ $query = $this->db->prepare("SELECT * FROM `news` WHERE `author` = ? ORDER BY ABS(DATEDIFF('timestamp', NOW())) LIMIT 5"); $query->BindValue(1, $author); $query->execute(); $result = $query->fetch(PDO::FETCH_ASSOC); return $result; } public function characterTable($id, $table){ $query = $this->db->prepare("SELECT * FROM `characters` WHERE `id` = ?"); $query->BindValue(1, $id); $query->execute(); $qf = $query->fetch(PDO::FETCH_ASSOC); return $qf[$table]; } public function auctionTable($id, $table){ $query = $this->db->prepare("SELECT * FROM `auctions` WHERE `id` = ?"); $query->BindValue(1, $id); $query->execute(); $qf = $query->fetch(PDO::FETCH_ASSOC); return $qf[$table]; } public function getAvgItemPrice($id){ $query = $this->db->prepare("SELECT * FROM `auctions` WHERE `item` = ? && `status` >= ?"); $query->BindValue(1, $id); $query->BindValue(2, 1); $query->execute(); $totals = array(); if($query->rowCount() > 0){ while($result = $query->fetch(PDO::FETCH_ASSOC)){ $getLastBid = $odb->prepare("SELECT * FROM `bids` WHERE `auctionid` = ? ORDER BY `id` DESC LIMIT 1"); $getLastBid->BindValue(1, $result['id']); $getLastBid->execute(); $totals[] = $getLastBid['bid']; } $average = array_sum($totals)/count($totals); return $average; }else{ return "Not enough information."; } } public function getTotAucforItem($id){ $query = $this->db->prepare("SELECT * FROM `auctions` WHERE `item` = ? && `status` = ?"); $query->BindValue(1, $id); $query->BindValue(2, '0'); $query->execute(); return $query->rowCount(); } public function redirect($url, $written){ if($written){ die('<meta http-equiv="Refresh" content="0.1; url=' . $url . '"">'); }else{ Header("Location:" . $url); exit(); } } public function email_exists($email){ $query = $this->db->prepare("SELECT * FROM `users` WHERE `email` = ?"); $query->BindValue(1, $email); $query->execute(); $count = $query->rowCount(); if($count > 0){ return true; }else{ return false; } } public function username_exists($email){ $query = $this->db->prepare("SELECT * FROM `users` WHERE `username` = ?"); $query->BindValue(1, $email); $query->execute(); $count = $query->rowCount(); if($count > 0){ return true; }else{ return false; } } public function userIDByUsername($username){ $query = $this->db->prepare("SELECT * FROM `users` WHERE `username` = ?"); $query->BindValue(1, $username); $query->execute(); $qf = $query->fetch(PDO::FETCH_ASSOC); return $qf['id']; } public function characterPage($name){ $namereplace = str_replace(" ", "+", $name); $url = "https://secure.tibia.com/community/?subtopic=characters&name=" . $namereplace; return $this->downloadString($url); } public function downloadString($url){ // last version of chrome $userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_TIMEOUT, 5); curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); $response = curl_exec($curl); curl_close($curl); return $response; } }<file_sep><?php include('._._inc_header._._.php'); if($TibiaMarket->isLogged() == false){ $TibiaMarket->redirect("login"); } if(isset($_POST['item'])){ $errors = array(); if( empty($_POST['item']) || empty($_POST['world']) || empty($_POST['character']) || empty($_POST['minbid']) || empty($_POST['length'])){ $errors[] = "Please fill in all the fields"; } if(!is_numeric($_POST['item']) || !is_numeric($_POST['world']) || !is_numeric($_POST['character']) || !is_numeric($_POST['minbid']) || !is_numeric($_POST['length'])){ $errors[] = "Verify your inputs."; } if($TibiaMarket->characterTable($_POST['character'], "userid") != $userData['id']){ $errors[] = "Character not found"; } if(empty($TibiaMarket->itemTable($_POST['item'], "name"))){ $errors[] = "Item not found"; } if(empty($TibiaMarket->worldTable($_POST['world'], "name"))){ $errors[] = "World not found"; } if($_POST['minbid'] < 0){ $errors[] = "Minimum bid cannot be lower than zero."; } if(isset($_POST['buyout'])){ if(empty($_POST['buyout'])){ $buyout = "0"; }else{ if($_POST['buyout'] < 0){ $errors[] = "Buyout cannot be lower than zero"; } } }else{ $buyout = "0"; } if($_POST['length'] == "1"){ $length = "3 Days"; }elseif($_POST['length'] == "2"){ $length = "5 Days"; }elseif($_POST['length'] == "3"){ $length = "7 Days"; }elseif($_POST['length'] == "4"){ $length = "14 Days"; }else{ $errors[] = "Length is not valid"; } $getVerifiedCharCount = $odb->prepare("SELECT * FROM `characters` WHERE `userid` = ? AND `status` = ?"); $getVerifiedCharCount->BindValue(1, $userData['id']); $getVerifiedCharCount->BindValue(2, "1"); $getVerifiedCharCount->execute(); if($getVerifiedCharCount->rowCount() == 0){ $errors[] = "You do not have a verified character."; } $item = inputSanitize($_POST['item']); $world = inputSanitize($_POST['world']); $char = inputSanitize($_POST['character']); $minbid = inputSanitize($_POST['minbid']); $buyout = inputSanitize($_POST['buyout']); $ctnt = inputSanitize($_POST['message']); if(empty($errors)){ //count the expire $nowUnix = time(); $lengthToAdd = strtotime('+' . $length); $insertAuction = $odb->prepare("INSERT INTO `auctions` (`userid`, `item`, `world`, `charid`, `minbid`, `buyout`, `length`, `addedunix`, `expire`, `comment`) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $insertAuction->BindValue(1, $userData['id']); $insertAuction->BindValue(2, $item); $insertAuction->BindValue(3, $world); $insertAuction->BindValue(4, $char); $insertAuction->BindValue(5, $minbid); $insertAuction->BindValue(6, $buyout); $insertAuction->BindValue(7, $length); $insertAuction->BindValue(8, $nowUnix); $insertAuction->BindValue(9, $lengthToAdd); $insertAuction->BindValue(10, $ctnt); $insertAuction->execute(); } } ?> <div id="content"> <div id="content-header"> <h1>My Auctions</h1> </div> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">My Auctions</a> </div> <div class="row"> <div class="col-xs-12"> <?php if(isset($errors)){ if(!empty($errors)){ echo '<div class="alert alert-danger">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; foreach($errors as $error){ echo ''.$error.'<br />'; } echo '</div>'; } } ?> </div> <div class="col-xs-8"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-trophy"></i> </span> <h5>My Auctions</h5> </div> <div class="widget-content nopadding"> <table class="table table-bordered table-striped table-hover data-table"> <thead> <tr> <th>Item</th> <th>World</th> <th>Character</th> <th>Buyout</th> <th>Length</th> <th>Auction Ends</th> <th>Current Bid</th> <th>Action</th> </tr> </thead> <tbody> <?php $getMyAuctions = $odb->prepare("SELECT * FROM `auctions` WHERE `userid` = ?"); $getMyAuctions->BindValue(1, $userData['id']); $getMyAuctions->execute(); while($record = $getMyAuctions->fetch(PDO::FETCH_ASSOC)){ ?> <tr> <td><center><?php _echo($TibiaMarket->itemTable($record['item'], "name"));?></center></td> <td><center><?php _echo($TibiaMarket->worldTable($record['world'], "name"));?></center></td> <td><center><?php _echo($TibiaMarket->characterTable($record['charid'], "name"));?></center></td> <td> <center> <?php if($record['buyout'] == 0){ echo '<span class="label label-info">Disabled</span>'; }else{ _echo($record['buyout']); } ?> </center> </td> <td><center><?php _echo($record['length']);?></center></td> <td><center><?php _echo(date('Y-m-d H:i', $record['expire']));?></center></td> <td> <center> <?php $getLastBid = $odb->prepare("SELECT * FROM `bids` WHERE `auctionid` = ? ORDER BY `id` DESC LIMIT 1"); $getLastBid->BindValue(1, $record['id']); $getLastBid->execute(); $getLastBidF = $getLastBid->fetch(PDO::FETCH_ASSOC); if(empty($getLastBidF['bid'])){ _echo("0"); }else{ _echo(($getLastBidF['bid'])); } ?> </center> </td> <td style="width:65;"> <center> <a href="auction/<?php _echo($record['id']);?>" class="btn btn-primary btn-xs">View Auction</a> </center> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <div class="col-xs-4"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-trophy"></i> </span> <h5>Create Auction</h5> </div> <div class="widget-content nopadding"> <?php $getVerifiedCharCount = $odb->prepare("SELECT * FROM `characters` WHERE `userid` = ? AND `status` = ?"); $getVerifiedCharCount->BindValue(1, $userData['id']); $getVerifiedCharCount->BindValue(2, "1"); $getVerifiedCharCount->execute(); if($getVerifiedCharCount->rowCount() == 0){ ?> <div class="alert alert-danger"> <button type="button" class="close" data-dismiss="alert">×</button> You must have a verified character to create an auction. </div> <?php }else{ ?> <form action="" method="post" class="form-horizontal"> <div class="form-group"> <label class="col-sm-4 control-label">Item</label> <div class="col-sm-8"> <select name="item"> <?php $getAllItems = $odb->prepare("SELECT * FROM `items`"); $getAllItems->execute(); while($record = $getAllItems->fetch(PDO::FETCH_ASSOC)){ ?> <option value="<?php _echo($record['id']);?>"> <?php _echo($record['name']);?> </option> <?php } ?> </select> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">World</label> <div class="col-sm-8"> <select name="world"> <?php $getAllWorlds = $odb->prepare("SELECT * FROM `worlds`"); $getAllWorlds->execute(); while($record = $getAllWorlds->fetch(PDO::FETCH_ASSOC)){ ?> <option value="<?php _echo($record['id']);?>"> <?php _echo($record['name']);?> </option> <?php } ?> </select> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">Character</label> <div class="col-sm-8"> <select name="character"> <?php $getAllChars = $odb->prepare("SELECT * FROM `characters` WHERE `userid` = ?"); $getAllChars->BindValue(1, $userData['id']); $getAllChars->execute(); while($record = $getAllChars->fetch(PDO::FETCH_ASSOC)){ ?> <option value="<?php _echo($record['id']);?>"> <?php _echo($record['name']);?> </option> <?php } ?> </select> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">Minimum Bid</label> <div class="col-sm-8"> <input type="text" class="form-control input-sm" name="minbid"> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">Buyout</label> <div class="col-sm-8"> <input type="text" class="form-control input-sm" name="buyout"> <span class="help-block text-left">Leave empty to disable</span> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">Length</label> <div class="col-sm-8"> <select name="length"> <option value="1">3 Days</option> <option value="2">5 Days</option> <option value="3">7 Days</option> <option value="4">14 Days</option> </select> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">Comment / Message</label> <div class="col-sm-8"> <textarea class="form-control input-sm" name="message"></textarea> <span class="help-block text-left">You can leave a message or comment that all bidders can see.</span> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary btn-sm">Submit</button> </div> </form> <?php } ?> </div> </div> </div> </div> </div> <?php include('._._inc_footer._._.php'); ?><file_sep><?php include('._._inc_header._._.php'); if($TibiaMarket->isLogged() == false){ $TibiaMarket->redirect("login"); } $user = $TibiaMarket->userData(); ?> <script> function submitChat(){ <?php if($TibiaMarket->isLogged() == false){ $TibiaMarket->redirect("login"); } $user = $TibiaMarket->userData(); ?> if(chat_form.msgbox.value == ''){ return; } var username = "<?php echo $user['username']; ?>"; var access_level = "<?php echo $user['access_level']; ?>"; var message = chat_form.msgbox.value; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200){ var mydiv = document.getElementById("chat-messages-inner"); mydiv.innerHTML = xmlhttp.responseText; } } xmlhttp.open('GET', 'php/insertchat.php?username='+username+'&access_level='+access_level+'&message='+message, true) xmlhttp.send(); } //$(document).ready(function(e){}); </script> <div id="content"> <div class="widget-box widget-chat"> <div class="widget-title"> <span class="icon"> <i class="fa fa-comment"></i> </span> <h5>Open Chat</h5> <div class="buttons"> <a class="btn go-full-screen"><i class="fa fa-resize-full"></i></a> </div> </div> <div class="widget-content nopadding"> <div class="chat-content"> <div class="chat-messages" id="chat-messages" style="overflow: hidden; outline: none;" tabindex="5000"> <div id="chat-messages-inner" class="chat-messages-inner"> <p id="msg-1" class="user-neytiri show" style="display: none;"><img src="img/chat/staff_icon.png" alt=""><span class="msg-block"><strong>Sheepyy</strong> <span class="msg">This is an admin test.</span></span></p> <p id="msg-2" class="user-cartoon-man show" style="display: none;"><img src="img/chat/user_icon.png" alt=""><span class="msg-block"><strong>Ceori</strong> <span class="time">- 18:46</span><span class="msg">This is a user test.</span></span></p> </div> </div> <div class="chat-message well"> <form action="javascript:submitChat()" method="post" name="chat_form" class="form-horizontal"> <span class="input-box input-group"> <input placeholder="Enter message here..." type="text" class="form-control input-small" name="msgbox" id="msg-box" onkeydown = "if (event.keyCode == 13) document.getElementById('chatbutton').click()" > <span class="input-group-btn"> <button id='chatbutton' class="btn btn-success btn-small" type="button" onclick="submitChat()">Send</button> </span> </span> </form> </div> </div> </div> </div> </div> <?php include('._._inc_footer._._.php'); ?><file_sep><?php include('._-configurations._-/loader.php'); if(isset($_POST['submit'])){ if(strlen($_POST['description']) > 0){ if(strlen($_POST['description']) <= 210){ if($_POST['action'] == "update"){ $user = $TibiaMarket->userData(); $id = $user['id']; //Get the amount of the reputation $squery = $odb->prepare("SELECT * FROM `reputation` WHERE `giver_id` = ? && `recipient_id` = ?"); $squery->BindValue(1, $id); $squery->BindValue(2, $_GET['id']); $squery->execute(); $q = $squery->fetch(PDO::FETCH_ASSOC); $amount = $q['amount']; //Get the total amount of reputation this user has. $dquery = $odb->prepare("SELECT * FROM `users` WHERE `id` = ?"); $dquery->BindValue(1, $_GET['id']); $dquery->execute(); $q2 = $dquery->fetch(PDO::FETCH_ASSOC); $totalrep = $q2['reputation']; //Remove the amount temporarily. $altered = $totalrep - $amount; $added = $altered + $_POST['repamount']; //Update the description $updatedesc = $odb->prepare("UPDATE `reputation` SET `description` = ? WHERE `giver_id` = ? && `recipient_id` = ?"); $updatedesc->BindValue(1, $_POST['description']); $updatedesc->BindValue(2, $id); $updatedesc->BindValue(3, $_GET['id']); $updatedesc->execute(); //Update the amount $updateamt = $odb->prepare("UPDATE `reputation` SET `amount` = ? WHERE `giver_id` = ? && `recipient_id` = ?"); $updateamt->BindValue(1, $_POST['repamount']); $updateamt->BindValue(2, $id); $updateamt->BindValue(3, $_GET['id']); $updateamt->execute(); //Update the reputation $updaterep = $odb->prepare("UPDATE `users` SET `reputation` = ? WHERE `id` = ?"); $updaterep->BindValue(1, $added); $updaterep->BindValue(2, $_GET['id']); $updaterep->execute(); }elseif($_POST['action'] == "add"){ $user = $TibiaMarket->userData(); $id = $user['id']; $addrep = $odb->prepare("INSERT INTO `reputation` (`id`, `recipient_id`, `giver_id`, `amount`, `description`, `timestamp`) VALUES (NULL, ? , ? , ? , ? , CURRENT_TIMESTAMP)"); $addrep->BindValue(1, $_GET['id']); $addrep->BindValue(2, $id); $addrep->BindValue(3, $_POST['repamount']); $addrep->BindValue(4, $_POST['description']); $addrep->execute(); $dquery = $odb->prepare("SELECT * FROM `users` WHERE `id` = ?"); $dquery->BindValue(1, $_GET['id']); $dquery->execute(); $q2 = $dquery->fetch(PDO::FETCH_ASSOC); $totalrep = $q2['reputation']; $rep = $_POST['repamount']; $added = $totalrep + $rep; //Update the reputation $updaterep = $odb->prepare("UPDATE `users` SET `reputation` = ? WHERE `id` = ?"); $updaterep->BindValue(1, $added); $updaterep->BindValue(2, $_GET['id']); $updaterep->execute(); }else{ echo("There's an error! :("); } }else{ echo("Your reputation can only be a maximum of 210."); } }else{ echo("You need to provide a description!"); } } ?> <script> window.onunload = refreshParent; function refreshParent() { window.opener.location.reload(); } </script> <html lang="en"> <head> <title><?php _echo($siteName);?></title> <base href="<?php _echo($siteURL);?>"> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="css/bootstrap.min.css" /> <link rel="stylesheet" href="css/font-awesome.css" /> <link rel="stylesheet" href="css/fullcalendar.css" /> <link rel="stylesheet" href="css/jquery.jscrollpane.css" /> <link rel="stylesheet" href="css/select2.css" /> <link rel="stylesheet" href="css/jquery-ui.css"> <link rel="stylesheet" href="css/jquery.gritter.css"> <link href="/img/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <!--[if lt IE 9]> <script type="text/javascript" src="js/respond.min.js"></script> <![endif]--> </head> <div style="text-align: center; padding-top: 10px;"> <div class="col-sm-12"> <?php if($TibiaMarket->isLogged()){ if(isset($_GET['id'])){ $user = $TibiaMarket->userData(); $access = $user['access_level']; $id = $user['id']; $reputation = $user['reputation']; $VIP = $user['VIP']; // $query = $odb->prepare("SELECT * FROM `reputation` WHERE `giver_id` = ? && `recipient_id` = ?"); $query->BindValue(1, $id); $query->BindValue(2, $_GET['id']); $query->execute(); $recipientquery = $odb->prepare("SELECT * FROM `users` WHERE `id` = ?"); $recipientquery->BindValue(1, $_GET['id']); $recipientquery->execute(); $recipientinfo = $recipientquery->fetch(PDO::FETCH_ASSOC); $recipientaccess = $recipientinfo['access_level']; $recipientid = $recipientinfo['id']; $recipientusername = $recipientinfo['username']; $recipientreputation = $recipientinfo['reputation']; $recipientVIP = $recipientinfo['VIP']; $totalrep = 1; if($access < 1){ if($reputation >= 50 && $reputation < 300){ $totalrep = 2; } if($reputation >= 300){ $totalrep = 3; } } if($VIP > 0){ $totalrep += 2; } if($access > 1 && $access < 4){ $totalrep = 5; } if($access > 3 && $access < 6){ $totalrep = 8; } if($access > 5){ $totalrep = 15; } $totalrep *=2; $startrep = $totalrep/2; $timesadded = 0; if($_GET['id'] != $user['id']){ //new rep ?> <form action="" method="post" class="form-horizontal"> <div class="form-group"> <div class="col-sm-8"> <select name="repamount"> <?php //Add new Reputation if($query->rowCount() == 0){ while($timesadded < $totalrep + 1){ if($startrep > 0){ $color = "color:green;"; $message = "Positive: (+"; }elseif($startrep == 0){ $color = "color:grey;"; $message = "Neutral: "; }elseif($startrep < 0){ $color = "color:red;"; $message = "Negative: ("; } echo("<option style=".$color." font-weight: bold; value=".$startrep.">".$message.$startrep.")</option>"); $startrep -= 1; $timesadded += 1; } $action = "add"; //Update the rep }else{ while($timesadded < $totalrep + 1){ if($startrep > 0){ $color = "color:green;"; $message = "Positive: (+"; }elseif($startrep == 0){ $color = "color:grey;"; $message = "Neutral: ("; }elseif($startrep < 0){ $color = "color:red;"; $message = "Negative: ("; } echo("<option style=".$color." font-weight: bold; value=".$startrep.">".$message.$startrep.")</option>"); $startrep -= 1; $timesadded += 1; } $action = "update"; } ?> </select> </div> </div> <!-- Action to take depending on whether it exists already. --> <input type="hidden" name="action" id="hiddenField" value="<?php echo($action); ?>" /> <div class="form-group"> <label class="col-sm-4 control-label">Description</label> <div class="col-sm-8"> <input id="desc1" type="text" class="form-control input-sm" name="description"> <span class="help-block text-left">IMPORTANT: Abusing the reputation system may lead to <u><b>losing</b></u> ALL of your reputation, and being temporarily banned. </span> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary btn-sm" name="submit">Submit</button> </div> </form> <?php }else{ echo("<span style='color:red;'>Error: You can't rep yourself silly! </span>"); } }else{ echo("<span style='color:red;'>Error: You don't have an ID! </span>"); } }else{ echo("<span style='color:red;'> You're not logged in! </span>"); } ?> </div> </div> </html><file_sep><?php include('._._inc_header._._.php'); ?> <div id="content"> <div id="content-header"> <h1>My Bids</h1> </div> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">My Bids</a> </div> <div class="row"> <div class="col-xs-12"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-star"></i> </span> <h5>My Winning Bids</h5> </div> <div class="widget-content nopadding"> <table class="table table-bordered table-striped table-hover data-table"> <thead> <tr> <th>Item Name</th> <th>World</th> <th>My Bid</th> <th>Current Bid</th> <th>Auction End Date</th> <th>Auction Status</th> <th>Action</th> </tr> </thead> <tbody> <?php $getMyBids = $odb->prepare("SELECT m1.* FROM `bids` m1 LEFT JOIN `bids` m2 ON (m1.`auctionid` = m2.`auctionid` AND m1.`id` < m2.`id`) WHERE m1.`userid` = ? AND m2.`id` IS NULL"); $getMyBids->BindValue(1, $userData['id']); $getMyBids->execute(); while($record = $getMyBids->fetch(PDO::FETCH_ASSOC)){ ?> <tr class="gradeX"> <td><center><?php _echo($TibiaMarket->itemTable($TibiaMarket->auctionTable($record['auctionid'],"item"), "name"));?></center></td> <td><center><?php _echo($TibiaMarket->worldTable($TibiaMarket->auctionTable($record['auctionid'],"item"), "name"));?></center></td> <td><center><?php _echo($record['bid']);?></center></td> <td> <center> <?php $getLastBid = $odb->prepare("SELECT * FROM `bids` WHERE `auctionid` = ? ORDER BY `id` DESC LIMIT 1"); $getLastBid->BindValue(1, $record['auctionid']); $getLastBid->execute(); $getLastBidF = $getLastBid->fetch(PDO::FETCH_ASSOC); if(empty($getLastBidF['bid'])){ _echo("0"); }else{ _echo(($getLastBidF['bid'])); } ?> </center> </td> <td><center><?php _echo(date('Y-m-d H:i', $TibiaMarket->auctionTable($record['auctionid'], "expire")));?></center></td> <td> <center> <?php if($TibiaMarket->auctionTable($record['auctionid'], "status") == 0){ echo '<span class="label label-success">Open</span>'; }else{ echo '<span class="label label-warning">Closed</span>'; } ?> </center> </td> <td> <center> <a href="auction/<?php _echo($record['auctionid']);?>" class="btn btn-primary btn-xs">View</a> </center> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> <div class="row"> <div class="col-xs-12"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-star"></i> </span> <h5>All of My Bids</h5> </div> <div class="widget-content nopadding"> <table class="table table-bordered table-striped table-hover data-table"> <thead> <tr> <th>Item Name</th> <th>World</th> <th>My Bid</th> <th>Current Bid</th> <th>Auction End Date</th> <th>Auction Status</th> <th>Action</th> </tr> </thead> <tbody> <?php $getMyBids = $odb->prepare("SELECT * FROM `bids` WHERE `userid` = ?"); $getMyBids->BindValue(1, $userData['id']); $getMyBids->execute(); while($record = $getMyBids->fetch(PDO::FETCH_ASSOC)){ ?> <tr class="gradeX"> <td><center><?php _echo($TibiaMarket->itemTable($TibiaMarket->auctionTable($record['auctionid'],"item"), "name"));?></center></td> <td><center><?php _echo($TibiaMarket->worldTable($TibiaMarket->auctionTable($record['auctionid'],"item"), "name"));?></center></td> <td><center><?php _echo($record['bid']);?></center></td> <td> <center> <?php $getLastBid = $odb->prepare("SELECT * FROM `bids` WHERE `auctionid` = ? ORDER BY `id` DESC LIMIT 1"); $getLastBid->BindValue(1, $record['auctionid']); $getLastBid->execute(); $getLastBidF = $getLastBid->fetch(PDO::FETCH_ASSOC); if(empty($getLastBidF['bid'])){ _echo("0"); }else{ _echo(($getLastBidF['bid'])); } ?> </center> </td> <td><center><?php _echo(date('Y-m-d H:i', $TibiaMarket->auctionTable($record['auctionid'], "expire")));?></center></td> <td> <center> <?php if($TibiaMarket->auctionTable($record['auctionid'], "status") == 0){ echo '<span class="label label-success">Open</span>'; }else{ echo '<span class="label label-warning">Closed</span>'; } ?> </center> </td> <td> <center> <a href="auction/<?php _echo($record['auctionid']);?>" class="btn btn-primary btn-xs">View</a> </center> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> </div> <?php include('._._inc_footer._._.php'); ?><file_sep><?php include('._._inc_header._._.php'); ?> <div id="content"> <?php include ('./php/newsticker.php'); ?> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-th"></i> </span> <h5>Open Auctions</h5> </div> <div id="specialdiv" style ="position:fixed; z-index:100; bottom:0%; left: 0%; padding:20px; background-color:black; color:white; text-align: center; border: none; display:none;"><b><u>Item Information</u></b></div> <div class="widget-content nopadding"> <table class="table table-bordered table-striped table-hover data-table"> <thead> <tr> <th>Action</th> <th>Item</th> <th>Character</th> <th>Current Bid</th> <th>World</th> <th>Auction End Date</th> <th>Status</th> </tr> </thead> <tbody> <?php //STATUS 0 = Normal accepted $getOpenMarkets = $odb->prepare("SELECT * FROM `auctions` WHERE `status` = ?"); $getOpenMarkets->BindValue(1, "0"); $getOpenMarkets->execute(); while($record = $getOpenMarkets->fetch(PDO::FETCH_ASSOC)){ //Item information $itemid = $TibiaMarket->itemTable($record['item'], "id"); $getItemInfo = $odb->prepare("SELECT * FROM `items` WHERE `id` = ?"); $getItemInfo->BindValue(1, $itemid); $getItemInfo->execute(); $iteminfo = $getItemInfo->fetch(PDO::FETCH_ASSOC); $char_name = $TibiaMarket->characterTable($record['charid'], "name"); $getUserReputation = $odb->prepare("SELECT * FROM `users` WHERE `id` = ?"); $getUserReputation->BindValue(1, $record['userid']); $getUserReputation->execute(); $array = $getUserReputation->fetch(PDO::FETCH_ASSOC); $reputation = $array['reputation']; $VIP = $array['VIP']; $access = $array['access_level']; //Normal user GREEN $rank = "color: #228B22;"; //VIP OR NOT $vipbold = ""; if($reputation == 0){ $color = "color: #000000;"; }else if($reputation > 0){ $color = "color: #32CD32;"; //Elite users PURPLE if($reputation >= 50 && $reputation < 300){ $rank = "color: #9400D3;"; //Master users ROYAL BLUE }else if($reputation >= 300){ $rank = "color: #436EEE;"; } }else{ $color = "color: #FF0000;"; } //Change if staff //Moderators if($access > 1 && $access < 4){ $rank = "color: #e59400;"; //Administrators }else if($access > 3 && $access < 6){ $rank = "color: #ff0000;"; //Founders }else if($access > 5){ $rank = "color: #dbba08;"; } if($VIP > 0 || $access == 6 || $access == 5){ $vipbold = "font-weight: bold;"; } ?> <tr class="gradeX"> <td> <center> <?php if($TibiaMarket->isLogged()){ echo '<a href="auction/' . $record['id'] . '" class="btn btn-primary btn-xs">Make a bid</a>'; }else{ echo '<a href="login" class="btn btn-primary btn-xs">Make a bid</a>'; } ?> </center> </td> <td><center><?php echo("<img alt=\"\" src=\"data:image/gif;base64," . $TibiaMarket->itemTable($record['item'], "image") . "\" /> ");echo($TibiaMarket->itemTable($record['item'], "name"));?></center></td> <td><center><span style="<?php _echo($rank); ?> <?php _echo($vipbold); ?>"><?php _echo($char_name); ?></span> (<a href="<?php _echo("reputation.php?id=".$record['userid']);?>"><span style="<?php _echo($color); ?> font-weight: bold;"><?php _echo($reputation); ?></span></a>) </center></td> <td> <center> <?php $getLastBid = $odb->prepare("SELECT * FROM `bids` WHERE `auctionid` = ? ORDER BY `id` DESC LIMIT 1"); $getLastBid->BindValue(1, $record['id']); $getLastBid->execute(); $getLastBidF = $getLastBid->fetch(PDO::FETCH_ASSOC); if(empty($getLastBidF['bid'])){ _echo("0"); }else{ _echo(($getLastBidF['bid'])); } ?> </center> </td> <td><center><?php _echo($TibiaMarket->worldTable($record['world'], "name"));?></center></td> <td><center><?php _echo(date('Y-m-d H:i', $TibiaMarket->auctionTable($record['id'], "expire")));?></center></td> <td><center><span class="label label-success">Open</span></center></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <?php include('._._inc_footer._._.php'); ?><file_sep><?php include('._._inc_header._._.php'); if($TibiaMarket->isLogged()){ Header("Location: index"); exit(); } if(isset($_POST['username'])){ $errors = array(); $secret = "nope"; $response = $_POST['g-recaptcha-response']; $uIP = $TibiaMarket->userIP(); $data = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$uIP"); $decoded = json_decode($data); if(isset($_POST['g-recaptcha-response'])){ $captcha = $_POST['g-recaptcha-response']; } if( empty($_POST['username']) || empty($_POST['email']) || empty($_POST['password1']) || empty($_POST['password2'])){ $errors[] = "Please fill in all the fields"; } $uIP = $TibiaMarket->userIP(); $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['<PASSWORD>']; $password2 = $_POST['<PASSWORD>']; if(strlen($username) < 5){ $errors[] = 'Your username must be atleast 5 characters'; } if(!$decoded->success){ $errors[] = 'Captcha was not entered.'; } if (strlen($password) < 6){ $errors[] = 'Your password must be atleast 6 characters'; } else if (strlen($password) > 18){ $errors[] = 'Your password cannot be more than 18 characters long'; } else if (strcmp($password, $password2) != 0) { $errors[] = 'Password does not match.'; } if($TibiaMarket->email_exists($email)){ $errors[] = 'Your email already exists in our records'; } if($TibiaMarket->username_exists($username)){ $errors[] = 'Username is already in use.'; } if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Email is not valid"; } if(empty($errors)){ $token = $TibiaMarket->token(); $insertUser = $odb->prepare("INSERT INTO `users` (`username`, `email`, `password`, `registrationip`, `registrationdate`, `lastlogin`, `status`, `lghash`) VALUES(?, ?, ?, ?, ?, ?, ?, ?)"); $insertUser->BindValue(1, $username); $insertUser->BindValue(2, $email); $insertUser->BindValue(3, $TibiaMarket->hashPW($password)); $insertUser->BindValue(4, $uIP); $insertUser->BindValue(5, $TibiaMarket->dateTime()); $insertUser->BindValue(6, "0000-00-00 00:00:00"); $insertUser->BindValue(7, $token); $insertUser->BindValue(8, ""); $insertUser->execute(); $message = "Greetings {$username}, Please activate your account by clicking or by copying and pasting in your browser. {$siteURL}activate/{$token} Kind regards, TibiaMarket"; $sendMail = SendEmail($email, "Activate your " . $siteName . " account!", $message); $success = true; } } ?> <div id="content"> <div id="content-header"> <h1>Register</h1> </div> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">Register</a> </div> <div class="row"> <div class="col-xs-3"></div> <div class="col-xs-6"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-unlock-alt"></i> </span> <h5>Register</h5> </div> <div class="widget-content nopadding"> <form action="" method="post" class="form-horizontal"> <?php if(isset($errors)){ if(empty($errors)){ if($success){ echo '<div class="alert alert-success">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; echo '<strong>You have successfully been registered. Verify your email to activate your account.</strong><br>'; echo '</div>'; } }else{ echo '<div class="alert alert-danger">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; echo '<strong>Oh snap!</strong><br>'; foreach($errors as $error){ echo '-'.$error.'<br />'; } echo '</div>'; } } ?> <div class="form-group"> <label class="col-sm-4 control-label">Username</label> <div class="col-sm-8"> <input type="text" class="form-control input-sm" name="username"> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">Email</label> <div class="col-sm-8"> <input type="text" class="form-control input-sm" name="email"> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">Password</label> <div class="col-sm-8"> <input type="<PASSWORD>" class="form-control input-sm" name="<PASSWORD>"> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">Re-Type Password</label> <div class="col-sm-8"> <input type="<PASSWORD>" class="form-control input-sm" name="<PASSWORD>"> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary btn-sm">Submit</button> </div> <div class="g-recaptcha form-actions" data-theme="dark" data-sitekey="NOPE"></div> </form> </div> </div> </div> </div> </div> <?php include('._._inc_footer._._.php'); ?><file_sep><?php include('../._._inc_header._._.php'); ?> <?php $access = $TibiaMarket->userTable($userData['id'], "access_level"); $username = $TibiaMarket->userTable($userData['id'], "username"); if($access == 4 && $owner == $username || $access >= 5 && $access <=6){ $query = $odb->prepare("SELECT * FROM `news` WHERE `id` = ?"); $query->BindValue(1, $_GET['id']); $query->execute(); $result = $query->fetch(PDO::FETCH_ASSOC); $author = $result['author']; $description = $result['description']; $time = $result['timestamp']; $header = $result['header']; $owner = $result['owner']; $url = $result['url']; if(isset($_GET['confirmation'])){ $TibiaMarket->addLog($username." deleted the news: \"".$description."\""); $del = $odb->prepare("DELETE FROM `news` WHERE `id` = ?"); $del->BindValue(1, $_GET['id']); $del->execute(); Header("Location:http://www.tibiamarket.net/"); } } ?> <div id="content"> <?php if($access == 4 && $owner == $username || $access >= 5 && $access <=6){ ?> <div id="content-header"> <h1>Delete News</h1> </div> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">Delete</a> </div> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-comment"></i> </span> <h5>Are you sure you want to delete this news?</h5> </div> <div class="widget-content" id="gritter-notify"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-th"></i> </span> <h5>News information</h5> </div> <div class="widget-content nopadding"> <table class="table table-bordered table-striped table-hover"> <thead> <tr> <th>Author</th> <th>Header</th> <th>Description</th> <th>URL</th> <th>Timestamp</th> <th>Owner</th> </tr> </thead> <tbody> <tr> <td><?php echo($author); ?></td> <td><?php echo($header); ?></td> <td><?php echo($description); ?></td> <td><?php echo($url); ?> </td> <td><?php echo($time); ?></td> <td><?php echo($owner); ?></td> </tr> </tbody> </table> </div> </div> <form method="post"> <a href="<?php echo('./staff/delete/'.$_GET["id"].'&&confirmation=1')?>" class="sticky btn btn-block btn-dark-green">Yes, delete this news.</a> </form> <a href="http://www.tibiamarket.net/index" class="normal btn btn-block btn-dark-red">No, do not delete this news.</a> </div> </div> <?php }else{ echo("You do not have permission to be here."); include('../php/rank.php'); } ?> </div> <?php include('../._._inc_footer._._.php'); ?><file_sep><?php include('keen_header.php'); ?> <div id="content"> </div> <?php include('keen_footer.php'); ?><file_sep><?php if(isset($_POST["imageuploader"])){ $check = getimagesize($_FILES["image"]["tmp_name"]); if ($check!== false){ $data = file_get_contents($_FILES['image']['tmp_name']); $base64 = base64_encode($data); $updateImage = $odb->prepare("UPDATE `items` SET `image` = ? WHERE `id` = ?"); $updateImage->BindValue(1, $base64); $updateImage->BindValue(2, $_POST['item']); $updateImage->execute(); $success = true; }else{ $errors[] = "Please add an image."; } } if ($link == 'nope'){ if(isset($errors)){ if(empty($errors)){ if($success){ echo '<div class="alert alert-success">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; echo '<strong>You have successfully posted a news article. Visit <a href="http://www.tibiamarket.net">the index page </a> to view it!</strong><br>'; echo '</div>'; } }else{ echo '<div class="alert alert-danger">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; echo '<strong>Oh snap!</strong><br>'; foreach($errors as $error){ echo '-'.$error.'<br />'; } echo '</div>'; } } ?> <div class="widget-box"> <div class="widget-title"> <h5>Update Images - Working</h5> </div> <div class="widget-content"> <form action="" method="post" class="form-horizontal" enctype="multipart/form-data"> <div class="form-group"> <label class="col-sm-4 control-label">Image</label> <div class="col-sm-8"> <select name="item"> <?php $getAllItems = $odb->prepare("SELECT * FROM `items`"); $getAllItems->execute(); while($record = $getAllItems->fetch(PDO::FETCH_ASSOC)){ ?> <option value="<?php _echo($record['id']);?>"> <?php _echo($record['name']);?> </option> <?php } ?> </select> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">Upload</label> <div class="col-sm-8"> <input type="file" name="image"> <span class="help-block text-left">Uploading anything but accurate images will result in a demotion.</span> </div> </div> <div class="form-actions"> <button type="submit" name="imageuploader" class="btn btn-primary btn-sm">Update Image</button> </div> </form> </div> </div> <?php } else { echo "Someone is where they're not suppose to be..."; } ?> <file_sep><?php include('._._inc_header._._.php'); ?> <div id="content"> <div id="content-header"> <h1>Terms of Services</h1> </div> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">TOS</a> </div> <div class="row"> <div class="col-xs-8"> <p><b>Introduction</b></p> <p>These terms and conditions govern your use of this website; by using this website, you accept these terms and conditions in full. If you disagree with these terms and conditions or any part of these terms and conditions, you must not use this website. </p> <p>This website uses cookies. By using this website and agreeing to these terms and conditions, you consent to our TIBIAMARKET's use of cookies in accordance with the terms of TIBIAMARKET's privacy policy / cookies policy.</p> <p><b>Tibia</b></p> <p>Needless to say, as a fansite of Tibia we follow and enforce the Tibia Rules in all aspects of our website. This means that you cannot, for example, support the use of illegal softwares; make forbidden advertising; add illegal pictures to our website or talk about Open Tibia servers. Doing so we will be mad at you, disagree with your actions, then probably ban you off of our website (depending on the severity of your actions). </p> <p>All of our content is in relation to Tibia, however we do not own Tibia. Tibia is Copyright by CipSoft GmbH. Any and all images, content, and information provided by Cipsoft are not ours. We will do our best to provide sources, however in any case if Cipsoft requests the removal of something that belongs to them, we will obide by their wishes without hesitation. That includes by but not limited to, changes to this terms and conditions. </p> <p>We are a fansite to facilitate to the needs and desires to progress Tibia as a community based fansite. </p> <p><b>License to use website</b></p> <p>Unless otherwise stated, TIBIAMARKET and/or its licensors own the intellectual property rights in the website and material on the website. Subject to the license below, all these intellectual property rights are reserved.</p> <p>You may view, download for caching purposes only, and print pages from the website for your own personal use, subject to the restrictions set out below and elsewhere in these terms and conditions. </p> <p>You must not:</p> <p>• republish material from this website (including republication on another website);</p> <p>• sell, rent or sub-license material from the website;</p> <p>• show any material from the website in public, without giving express permission to do so;</p> <p>• reproduce, duplicate, copy or otherwise exploit material on this website for a commercial purpose;</p> <p>• edit or otherwise modify any material on the website unless given express permission to do so; or</p> <p>• redistribute material from this website except for content specifically and expressly made available for redistribution.</p> <p><b>Acceptable use</b></p> <p>You must not use this website in any way that causes, or may cause, damage to the website or impairment of the availability or accessibility of the website; or in any way which is unlawful, illegal, fraudulent or harmful, or in connection with any unlawful, illegal, fraudulent or harmful purpose or activity.</p> <p>You must not use this website to copy, store, host, transmit, send, use, publish or distribute any material which consists of (or is linked to) any spyware, computer virus, Trojan horse, worm, keystroke logger, rootkit or other malicious computer software.</p> <p>You must not conduct any systematic or automated data collection activities (including without limitation scraping, data mining, data extraction and data harvesting) on or in relation to this website without TIBIAMARKET’s express written consent.</p> <p>You must not use this website to transmit or send unsolicited commercial communications.</p> <p>You must not use this website for any purposes related to marketing without TIBIAMARKET’s express written consent.</p> <p><b>Restricted access</b></p> <p>Access to certain areas of this website is restricted. TIBIAMARKET reserves the right to restrict access to areas of this website, or indeed this entire website, at TIBIAMARKET’s discretion.</p> <p>If TIBIAMARKET provides you with a user ID and password to enable you to access restricted areas of this website or other content or services, you must ensure that the user ID and password are kept confidential. </p> <p>TIBIAMARKET may disable your user ID and password in TIBIAMARKET’s sole discretion without notice or explanation.</p> <p><b>User content</b></p> <p>In these terms and conditions, “your user content” means material (including without limitation text, images, audio material, video material and audio-visual material) that you submit to this website, for whatever purpose.</p> <p>You grant to TIBIAMARKET a worldwide, irrevocable, non-exclusive, royalty-free license to use, reproduce, adapt, publish, translate and distribute your user content in any existing or future media. You also grant to TIBIAMARKET the right to sub-license these rights, and the right to bring an action for infringement of these rights.</p> <p>Your user content must not be illegal or unlawful, must not infringe any third party's legal rights, and must not be capable of giving rise to legal action whether against you or TIBIAMARKET or a third party (in each case under any applicable law). </p> <p>You must not submit any user content to the website that is or has ever been the subject of any threatened or actual legal proceedings or other similar complaint.</p> <p>TIBIAMARKET reserves the right to edit or remove any material submitted to this website, or stored on TIBIAMARKET’s servers, or hosted or published upon this website.</p> <p><b>No warranties</b></p> <p>This website is provided “as is” without any representations or warranties, express or implied. TIBIAMARKET makes no representations or warranties in relation to this website or the information and materials provided on this website. </p> <p>Without prejudice to the generality of the foregoing paragraph, TIBIAMARKET does not warrant that:</p> <p>• this website will be constantly available, or available at all; or</p> <p>• the information on this website is complete, true, accurate or non-misleading.</p> <p>Nothing on this website constitutes, or is meant to constitute, advice of any kind. </p> <p><b>Limitations of liability</b></p> <p>TIBIAMARKET will not be liable to you (whether under the law of contact, the law of torts or otherwise) in relation to the contents of, or use of, or otherwise in connection with, this website:</p> <p>• for any indirect, special or consequential loss; or</p> <p>• for any business losses, loss of revenue, income, profits or anticipated savings, loss of contracts or business relationships, loss of reputation or goodwill, or loss or corruption of information or data.</p> <p>These limitations of liability apply even if TIBIAMARKET has been expressly advised of the potential loss.</p> <p><b>Exceptions</b></p> <p>Nothing in this website disclaimer will exclude or limit any warranty implied by law that it would be unlawful to exclude or limit; and nothing in this website disclaimer will exclude or limit TIBIAMARKET’s liability in respect of any:</p> <p>• death or personal injury caused by TIBIAMARKET’s negligence;</p> <p>• fraud or fraudulent misrepresentation on the part of TIBIAMARKET; or</p> <p>• matter which it would be illegal or unlawful for TIBIAMARKET to exclude or limit, or to attempt or purport to exclude or limit, its liability. </p> <p><b>Reasonableness</b></p> <p>By using this website, you agree that the exclusions and limitations of liability set out in this website disclaimer are reasonable. </p> <p>If you do not think they are reasonable, you must not use this website. <p><b>Other parties</b></p> <p>You accept that, as a limited liability entity, TIBIAMARKET has an interest in limiting the personal liability of its officers and employees. You agree that you will not bring any claim personally against TIBIAMARKET’s officers or employees in respect of any losses you suffer in connection with the website.</p> <p>Without prejudice to the foregoing paragraph, you agree that the limitations of warranties and liability set out in this website disclaimer will protect TIBIAMARKET’s officers, employees, agents, subsidiaries, successors, assigns and sub-contractors as well as TIBIAMARKET. </p> <p><b>Unenforceable provisions</b></p> <p>If any provision of this website disclaimer is, or is found to be, unenforceable under applicable law, that will not affect the enforceability of the other provisions of this website disclaimer.</p> <p><b>Indemnity</b></p> <p>You hereby indemnify TIBIAMARKET and undertake to keep TIBIAMARKET indemnified against any losses, damages, costs, liabilities and expenses (including without limitation legal expenses and any amounts paid by TIBIAMARKET to a third party in settlement of a claim or dispute on the advice of TIBIAMARKET’s legal advisers) incurred or suffered by TIBIAMARKET arising out of any breach by you of any provision of these terms and conditions, or arising out of any claim that you have breached any provision of these terms and conditions.</p> <p><b>Breaches of these terms and conditions</b></p> <p>Without prejudice to TIBIAMARKET’s other rights under these terms and conditions, if you breach these terms and conditions in any way, TIBIAMARKET may take such action as TIBIAMARKET deems appropriate to deal with the breach, including suspending your access to the website, prohibiting you from accessing the website, blocking computers using your IP address from accessing the website, contacting your internet service provider to request that they block your access to the website and/or bringing court proceedings against you.</p> <p><b>Variation</b></p> <p>TIBIAMARKET may revise these terms and conditions from time-to-time. Revised terms and conditions will apply to the use of this website from the date of the publication of the revised terms and conditions on this website. Please check this page regularly to ensure you are familiar with the current version.</p> <p><b>Assignment</b></p> <p>TIBIAMARKET may transfer, sub-contract or otherwise deal with TIBIAMARKET’s rights and/or obligations under these terms and conditions without notifying you or obtaining your consent.</p> <p>You may not transfer, sub-contract or otherwise deal with your rights and/or obligations under these terms and conditions. </p> <p><b>Severability</b></p> <p>If a provision of these terms and conditions is determined by any court or other competent authority to be unlawful and/or unenforceable, the other provisions will continue in effect. If any unlawful and/or unenforceable provision would be lawful or enforceable if part of it were deleted, that part will be deemed to be deleted, and the rest of the provision will continue in effect. </p> <p><b>Entire agreement</b></p> <p>These terms and conditions constitute the entire agreement between you and TIBIAMARKET in relation to your use of this website, and supersede all previous agreements in respect of your use of this website.</p> <p><b>Law and jurisdiction</b></p> <p>These terms and conditions will be governed by and construed in accordance with Federal Law, and any disputes relating to these terms and conditions will be subject to the exclusive jurisdiction of the courts of Vermont.</p> <p><b>TIBIAMARKET’s details:</b></p> <p>You can contact TIBIAMARKET by email to <EMAIL>, using our contact form, or submitting a support ticket. </p> </div> </div> </div> <?php include('._._inc_footer._._.php'); ?><file_sep><?php if(isset($_POST['author'])){ $errors = array(); if( empty($_POST['author']) || empty($_POST['message']) || empty($_POST['url'])){ $errors[] = "Please fill in all the fields"; } if(empty($errors)){ $author = $_POST['author']; $message = $_POST['message']; $url = $_POST['url']; $username = $TibiaMarket->userTable($userData['id'], "username"); $access = $TibiaMarket->userTable($userData['id'], "access_level"); $insertNews = $odb->prepare("INSERT INTO `news` (`id`, `author`, `header`, `description`, `url`, `timestamp`, `owner`) VALUES (NULL, ? , ? , ? , ?, CURRENT_TIMESTAMP, ?);"); // Author $insertNews->BindValue(1, $author); //Header $insertNews->BindValue(2, 'TibiaMarket Staff'); //Message $insertNews->BindValue(3, $message); //URL $insertNews->BindValue(4, $url); //Owner $insertNews->BindValue(5, $username); $insertNews->execute(); $success = true; $TibiaMarket->addLog($username." added the news: \"".$message."\""); } } if ($link == 'nope'){ if(isset($errors)){ if(empty($errors)){ if($success){ echo '<div class="alert alert-success">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; echo '<strong>You have successfully posted a news article. Visit <a href="http://www.tibiamarket.net">the index page </a> to view it!</strong><br>'; echo '</div>'; } }else{ echo '<div class="alert alert-danger">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; echo '<strong>Oh snap!</strong><br>'; foreach($errors as $error){ echo '-'.$error.'<br />'; } echo '</div>'; } } ?> <div class="widget-box"> <div class="widget-title"> <h5>News Adder</h5> </div> <div class="widget-content"> <form action="" method="post" class="form-horizontal"> <div class="form-group"> <label class="col-sm-4 control-label">Author</label> <div class="col-sm-8"> <select name="author"> <option>Staff</option> <option>TibiaMarket</option> <option>Cipsoft</option> <option>TibiaRoyal</option> <option>GuildStats.eu</option> <option>Portal Tibia</option> <option>Tibia-Stats</option> <option>TibiaBr</option> <option>TibiaEvents</option> <option>TibiaLatina.Wikia</option> <option>TibiaWiki</option> <option>TibiaWiki.com.br</option> <option>FunTibia</option> <option>Lootpic</option> <option>MrThomsen</option> <option>Rookie.com.pl</option> <option>TibiaBrasileiros</option> <option>TibiaCubix</option> <option>TibiaGuias</option> <option>TibiaHof</option> <option>TibiaLibrary</option> <option>TibiaLottery</option> <option>TibiaML</option> <option>TibiaMagazine</option> <option>TibiaMisterios</option> <option>TibiaWars</option> <option>World of Rookgaard</option> </select> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">Information</label> <div class="col-sm-8"> <textarea class="form-control input-sm" name="message"></textarea> <span class="help-block text-left">Here is the body of the news.</span> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">URL</label> <div class="col-sm-8"> <input type="text" class="form-control input-sm" name="url"> <span class="help-block text-left">Provide a URL so people can navigate to for more information. EX. https://www.tibiamarket.net</span> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary btn-sm">Add News</button> </div> </form> </div> </div> <?php } else { echo "Someone is where they're not suppose to be..."; } ?> <file_sep><?php if ($link == 'nope'){ ?> <table class="table table-bordered table-striped table-hover data-table"> <thead> <tr> <th>ID</th> <th>LOGS</th> <th>Time</th> </tr> </thead> <tbody> <?php $getLogs = $odb->prepare("SELECT * FROM `logs` ORDER BY id DESC"); $getLogs->execute(); while($record = $getLogs->fetch(PDO::FETCH_ASSOC)){ ?> <tr class="gradeX"> <td><center><?php echo($record['id']); ?></center></td> <td><center><?php echo($record['log']); ?></center></td> <td><center><?php echo($record['timestamp']); ?> </center></td> </tr> <?php } ?> </tbody> </table> <?php } else { echo "Someone is where they're not suppose to be..."; } ?><file_sep><?php include('._._inc_header._._.php'); if(isset($_POST['chname'])){ $errors = array(); $charName = inputSanitize($_POST['chname']); $getAllContent = $TibiaMarket->characterPage($charName); preg_match("/Level:<\/td><td>(.*)<\/td><\/tr><tr bgcolor=#F1E0C6><td><nobr>Achievement Points/", $getAllContent, $matches); array_shift($matches); $level = $matches[0]; if($level < 80){ $errors[] = "Your character must be higher than level 80."; }else{ $token = $TibiaMarket->token() . $TibiaMarket->token(); $insertChar = $odb->prepare("INSERT INTO `characters` (`userid`, `name`, `hash`, `status`) VALUES(?, ?, ?, ?)"); $insertChar->BindValue(1, $userData['id']); $insertChar->BindValue(2, $charName); $insertChar->BindValue(3, $token); $insertChar->BindValue(4, "0"); $insertChar->execute(); } } if(isset($_GET['deleteCharacter'])){ if(is_numeric($_GET['deleteCharacter'])){ $deleteCharacter = $odb->prepare("DELETE FROM `characters` WHERE `id` = ? AND `userid` = ?"); $deleteCharacter->BindValue(1, $_GET['deleteCharacter']); $deleteCharacter->BindValue(2, $userData['id']); $deleteCharacter->execute(); $deleteAllBids = $odb->prepare("DELETE FROM `bids` WHERE `charid` = ? AND `userid` = ?"); $deleteAllBids->BindValue(1, $_GET['deleteCharacter']); $deleteAllBids->BindValue(2, $userData['id']); $deleteAllBids->execute(); $TibiaMarket->redirect("characters"); } } if(isset($_GET['verify'])){ if(is_numeric($_GET['verify'])){ $errors = array(); $getCharName = $odb->prepare("SELECT * FROM `characters` WHERE `id` = ? AND `userid` = ?"); $getCharName->BindValue(1, $_GET['verify']); $getCharName->BindValue(2, $userData['id']); $getCharName->execute(); $getCharNameF = $getCharName->fetch(PDO::FETCH_ASSOC); $charName = $getCharNameF['name']; $verifyHash = $getCharNameF['hash']; $getAllContent = $TibiaMarket->characterPage($charName); preg_match("/Comment:<\/td><td>(.*)<\/td><\/tr><tr bgcolor/s", $getAllContent, $matches); array_shift($matches); $comment = $matches[0]; if (strpos($comment, $verifyHash) !== false) { $updateChar = $odb->prepare("UPDATE `characters` SET `status` = ? WHERE `id` = ? AND `hash` = ?"); $updateChar->BindValue(1, "1"); $updateChar->BindValue(2, $_GET['verify']); $updateChar->BindValue(3, $verifyHash); $updateChar->execute(); $TibiaMarket->redirect("characters"); }else{ $errors[] = "The Verify Hash was not found in the Comment section of your profile on Tibia."; } // Comment:</td><td>Special Canadian Archer! </td></tr><tr bgcolor=#D4C0A1><td> } } ?> <div id="content"> <div id="content-header"> <h1>My Characters</h1> </div> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">My Characters</a> </div> <div class="row"> <div class="col-xs-12"> <div class="alert alert-info alert-block"> <a class="close" data-dismiss="alert" href="#">×</a> <center>To verify a character, you must put the verify hash in your comments on Tibia. Then click on Verify to finish the verifying process.</center> </div> </div> <div class="col-xs-12"> <?php if(isset($errors)){ if(!empty($errors)){ echo '<div class="alert alert-danger">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; foreach($errors as $error){ echo ''.$error.'<br />'; } echo '</div>'; } } ?> </div> <div class="col-xs-8"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-user"></i> </span> <h5>My Characters</h5> </div> <div class="widget-content nopadding"> <table class="table table-bordered table-striped table-hover data-table"> <thead> <tr> <th>Name</th> <th>Verify Hash</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> <?php $getMyCharacters = $odb->prepare("SELECT * FROM `characters` WHERE `userid` = ?"); $getMyCharacters->BindValue(1, $userData['id']); $getMyCharacters->execute(); while($record = $getMyCharacters->fetch(PDO::FETCH_ASSOC)){ ?> <tr> <td><?php _echo($record['name']);?></td> <td><?php _echo($record['hash']);?></td> <td> <center> <?php if($record['status'] == 0){ ?> <span class="label label-danger">Unverified</span> <?php }else{ ?> <span class="label label-success">Verified</span> <?php } ?> </center> </td> <td style="width:130px;"> <center> <?php if($record['status'] == 0){ ?> <a href="characters?verify=<?php _echo($record['id']);?>" class="btn btn-primary btn-xs">Verify</a> <?php } ?> <a href="characters?deleteCharacter=<?php _echo($record['id']);?>" class="btn btn-danger btn-xs">Remove</a> </center> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <div class="col-xs-4"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-user"></i> </span> <h5>Add Character</h5> </div> <div class="widget-content nopadding"> <form action="" method="post" class="form-horizontal"> <div class="form-group"> <label class="col-sm-4 control-label">Character Name</label> <div class="col-sm-8"> <input type="text" class="form-control input-sm" name="chname"> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary btn-sm">Submit</button> </div> </form> </div> </div> </div> </div> </div> <?php include('._._inc_footer._._.php'); ?><file_sep><?php include('._._inc_header._._.php'); if(isset($_POST['username'])){ $errors = array(); if( empty($_POST['username']) || empty($_POST['password'])){ $errors[] = "Please fill in all the fields."; } $username = inputSanitize($_POST['username']); $password = inputSanitize($_POST['password']); if(!$TibiaMarket->username_exists($username)){ $errors[] = 'Wrong username/password combination.'; }else{ $dbPassword = $TibiaMarket->userTable($TibiaMarket->userIDByUsername($username), "password"); if($TibiaMarket->hashVerify($password, $dbPassword)){ $userStatus = $TibiaMarket->userTable($TibiaMarket->userIDByUsername($username), "status"); if($userStatus == "ACTIVE"){ //update the token $token = $TibiaMarket->token(); $updateUserInfo = $odb->prepare("UPDATE `users` SET `lastlogin` = ?, `lghash` = ? WHERE `username` = ?"); $updateUserInfo->BindValue(1, $TibiaMarket->dateTime()); $updateUserInfo->BindValue(2, $token); $updateUserInfo->BindValue(3, $username); $updateUserInfo->execute(); $set = $TibiaMarket->setSession($token, "0"); //see if the IP exists for username. $id = $TibiaMarket->userTable($TibiaMarket->userIDByUsername($username), "id"); $getIPs = $odb->prepare("SELECT * FROM `internetprotocols` WHERE `userid` = ? && `ip` = ?"); $getIPs->BindValue(1, $id); $getIPs->BindValue(2, $TibiaMarket->userIP()); $getIPs->execute(); if($getIPs->rowCount() == 0){ $addip = $odb->prepare("INSERT INTO `internetprotocols` (`id`, `userid`, `ip`, `first_time`) VALUES (NULL, ? , ? , CURRENT_TIMESTAMP)"); $addip->BindValue(1, $id); $addip->BindValue(2, $TibiaMarket->userIP()); $addip->execute(); } Header("Location: index"); exit(); $success = true; }else{ $errors[] = "You must activate your account first."; } }else{ $errors[] = 'Wrong username/password combination.'; } } } ?> <div id="content"> <div id="content-header"> <h1>Login</h1> </div> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">Login</a> </div> <div class="row"> <div class="col-xs-4"></div> <div class="col-xs-4"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-lock"></i> </span> <h5>Login</h5> </div> <div class="widget-content nopadding"> <form action="" method="post" class="form-horizontal"> <?php if(isset($_POST['username'])){ if(!empty($errors)){ echo '<div class="alert alert-danger">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; foreach($errors as $error){ echo ''.$error.'<br />'; } echo '</div>'; } } ?> <div class="form-group"> <label class="col-sm-3 control-label">Username</label> <div class="col-sm-9"> <input type="text" class="form-control input-sm" name="username"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Password</label> <div class="col-sm-9"> <input type="password" class="form-control input-sm" name="password"> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary btn-sm">Submit</button> </div> </form> </div> </div> </div> </div> </div> <?php include('._._inc_footer._._.php'); ?><file_sep><?php include('._._inc_header._._.php'); if(isset($_POST['subject'])){ $errors = array(); if( empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['message'])){ $errors[] = "Please fill in all the fields."; } $email = inputSanitize($_POST['email']); $subject = inputSanitize($_POST['subject']); $message = inputSanitize($_POST['message']); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Email is not valid"; } if(empty($errors)){ $userIP = $TibiaMarket->userIP(); $message = "<center><b>You have received a new message from a user on {$siteName}</b></center> Email: {$email} Subject: {$subject} Message: {$message} User Ip Address: {$userIP}"; $sendMail = SendEmail($contactEmail, "New Message on {$siteName}", $message); $success = true; } } ?> <div id="content"> <div id="content-header"> <h1>Contact</h1> </div> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a> <a href="#" class="current">Contact</a> </div> <div class="row"> <div class="col-xs-3"></div> <div class="col-xs-6"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-envelope"></i> </span> <h5>Contact Us</h5> </div> <div class="widget-content nopadding"> <form action="" method="post" class="form-horizontal"> <?php if(isset($errors)){ if(empty($errors)){ if($success){ echo '<div class="alert alert-success">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; echo '<strong>We have received your email. We should reply within 48 hours.</strong><br>'; echo '</div>'; } }else{ echo '<div class="alert alert-danger">'; echo '<button type="button" class="close" data-dismiss="alert">×</button>'; echo '<strong>Oh snap!</strong><br>'; foreach($errors as $error){ echo '-'.$error.'<br />'; } echo '</div>'; } } ?> <div class="form-group"> <label class="col-sm-3 control-label">Email</label> <div class="col-sm-9"> <input type="text" class="form-control input-sm" name="email"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Subject</label> <div class="col-sm-9"> <input type="text" class="form-control input-sm" name="subject"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Message</label> <div class="col-sm-9"> <textarea class="form-control input-sm" rows="4" name="message"></textarea> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary btn-sm">Submit</button> </div> </form> </div> </div> </div> </div> </div> <?php include('._._inc_footer._._.php'); ?>
9b36a9d53d9beddaeaabc3bb3c164a74a5803336
[ "JavaScript", "PHP" ]
29
PHP
sheepiiHD/TibiaMarket
b451c17f1efcab98f16a6e865a37434eb5e2df2b
809aba92cfe7599654af0a13ec7066ed369e8eae
refs/heads/main
<file_sep>require("../../../model/pet"); require("../../../model/pet_transaction"); require("../../../model/ring_record"); const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); module.exports = async (req, res) => { let address = req.query.address; let petId = req.query.petId; //查询恐龙信息 let pet = await sequelizer.models.Pet.findByPk(petId); if(pet == null){ return null; } //查询 恐龙的出售记录 let list = await sequelizer.models.PetTransaction.findAll({ where:{pet_id:petId} }) // 查询恐龙的 战绩 let ringRecord = []; if(pet.type != 255){ ringRecord = await sequelizer.models.RingRecord.findAll({ where:{challenger_pet_id:petId} }) }else{ ringRecord = await sequelizer.models.RingRecord.findAll({ where:{ring_pet_id:petId} }) } let data = { pet:pet, sellRecord:list, ringRecord:ringRecord } res.status(200).json(result.success(data)); } <file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); const { QueryTypes,Op } = require('sequelize'); require("../../../model/pet_transaction"); module.exports = async (req, res) => { const param = req.query; let offer = 0; let limit = 10; if(param.pageSize != undefined && param.current != undefined){ offer = Number((param.current-1)*param.pageSize); limit = Number(param.pageSize) } let opention = { offset:offer, limit:limit, where:{ [Op.or]: [{ buy_user_address: param.address }, { sell_user_address: param.address }], } } let data = await sequelizer.models.PetTransaction.findAndCountAll(opention); res.status(200).json(result.success(data)); } <file_sep>/* indent size: 2 */ const {DataTypes} = require('sequelize'); const sequelize = require("../config/mysql2") const Model = sequelize.define('Config', { id: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true }, config_key: { type: DataTypes.STRING(100), allowNull: true }, config_value: { type: DataTypes.BIGINT, allowNull: true } }, { tableName: 'config', timestamps: false }); module.exports = Model;<file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); require("../../../model/egg_transaction"); module.exports = async (req, res) => { let param = { address : req.query.address, pageSize : req.query.pageSize, current : req.query.current, } let where = {}; if(param.address!=undefined){ where.to_address = param.address; } let offset = 0; let limit = 10; if(param.pageSize != undefined && param != undefined){ offset = Number((param.current-1)*param.pageSize); limit = Number(param.pageSize) } let data = await sequelizer.models.EggTransaction.findAndCountAll({ limit: limit, offset:offset, where:where, order:[["create_time","desc"]] }); res.status(200).json(result.success(data)); } <file_sep>/* indent size: 2 */ const {DataTypes} = require('sequelize'); const sequelize = require("../config/mysql2") const Model = sequelize.define('Pet', { pet_id: { type: DataTypes.BIGINT, allowNull: false, primaryKey: true }, status: { type: DataTypes.INTEGER(1), allowNull: true }, owner_address: { type: DataTypes.STRING(255), allowNull: true }, type: { type: DataTypes.INTEGER(3), allowNull: true }, image: { type: DataTypes.INTEGER(255), allowNull: true }, create_time: { type: DataTypes.BIGINT, allowNull: true }, tx_hash: { type: DataTypes.STRING(255), allowNull: true }, uuid: { type: DataTypes.STRING(255), allowNull: true } }, { tableName: 'pet', timestamps: false }); module.exports = Model;<file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); require("../../../model/token_info"); module.exports = async (req, res) => { const param = ctx.query; const { token, chainid} = param let data= sequelizer.models.TokenInfo.findOne({where:{token_address:token,chainid:chainid}}); res.status(200).json(result.success(data)); } <file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); require("../../../model/egg_hatch"); require("../../../model/pet"); module.exports = async (req, res) => { let tx_hash = req.query.tx_hash; let hatch = await sequelizer.models.findOne({ where:{tx_hash:tx_hash,status:2} }) let data = null; if(hatch !=null){ data = await sequelizer.models.Pet.findAll({ where:{hatch_tx_hash:tx_hash} }); } res.status(200).json(result.success(data)); }<file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); const { QueryTypes } = require('sequelize'); module.exports = async (req, res) => { let param = req.query; let startTime; let endTime = new Date().getTime() ; if(param.type == 1){ startTime = endTime - 24*60*60*1000; } if(param.type == 2){ startTime = endTime - 7*24*60*60*1000; } if(param.type == 3){ startTime = endTime - 30*24*60*60*1000; } let max_jackpot = await sequelizer.query( 'select if(max(jackpot) is null,0,max(jackpot)) as total from ring where createTime > ? and createTime < ? and status in (1,2) ;',{ replacements: [startTime,endTime], type: QueryTypes.SELECT }) console.log(max_jackpot); let sum_jackpot = await sequelizer.query( 'select if(sum(jackpot) is null,0,sum(jackpot)) as total from ring where createTime > ? and createTime < ? and status in (1,2) ;',{ replacements: [startTime,endTime], type: QueryTypes.SELECT }) console.log(sum_jackpot); let history_max_jackpot = await sequelizer.query( 'select if(sum(max_jackpot) is null,0,sum(max_jackpot))as total from ring where createTime > ? and createTime < ?;',{ replacements: [startTime,endTime], type: QueryTypes.SELECT }) let data = { max_jackpot: max_jackpot[0]['total'], sum_jackpot: sum_jackpot[0]['total'], history_max_jackpot: history_max_jackpot[0]['total'] } res.status(200).json(result.success(data)); } <file_sep>// Require and initialize outside of your main handler const {Sequelize} = require("sequelize"); const sequelize = new Sequelize('test2_nulls_world', process.env.USER, process.env.PASSWORD, { host: process.env.HOST, port: 3306, dialect: 'mysql', dialectModule: require('mysql2'), pool: { max: 15, min: 5, idle: 20000, evict: 15000, acquire: 30000 }, }); module.exports = sequelize <file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); require("../../../model/egg_hatch"); module.exports = async (req, res) => { let address = req.query.address; let data = sequelizer.models.EggHatch.findAll({ where:{owner_address:address,status:1} }) res.status(200).json(result.success(data)); }<file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); require("../../../model/ring_record"); module.exports = async (req, res) => { let uuid = req.query.uuid; if(uuid =='' || uuid==undefined ||uuid==null){ res.status(200).json(result.error("uuid is empty")); return } let param = { where:{uuid:uuid} } let data = await sequelizer.models.RingRecord.findOne(param); res.status(200).json(result.success(data)); } <file_sep> const result = {} result.success = function(data){ return {code:200,message:"执行成功",data:data} } result.error = function(message){ return {code:500,message:message} } module.exports = result;<file_sep>/* indent size: 2 */ const {DataTypes} = require('sequelize'); const sequelize = require("../config/mysql2") const Model = sequelize.define('Ring', { item_id: { type: DataTypes.BIGINT, allowNull: false, primaryKey: true }, owner_address: { type: DataTypes.STRING(255), allowNull: true }, pet_id: { type: DataTypes.BIGINT, allowNull: true }, initialCapital: { type: DataTypes.BIGINT, allowNull: true }, token: { type: DataTypes.STRING(255), allowNull: true }, multipe: { type: DataTypes.INTEGER(255), allowNull: true }, max_jackpot: { type: DataTypes.BIGINT, allowNull: true }, jackpot: { type: DataTypes.BIGINT, allowNull: true }, count: { type: DataTypes.INTEGER(11), allowNull: true }, backage_image: { type: DataTypes.INTEGER(255), allowNull: true }, tickets: { type: DataTypes.INTEGER(255), allowNull: true }, createTime: { type: DataTypes.BIGINT, allowNull: true }, status: { type: DataTypes.INTEGER(1), allowNull: true }, max_multipe: { type: DataTypes.INTEGER(1), allowNull: true }, token_name: { type: DataTypes.STRING(50), allowNull: true }, token_precision: { type: DataTypes.INTEGER(1), allowNull: true } }, { tableName: 'ring', timestamps: false }); module.exports = Model;<file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); const { QueryTypes,Op } = require('sequelize'); require("../../../model/pet"); module.exports = async (req, res) => { let where = { owner_address:req.query.address } if(req.query.status != 0){ where.status = req.query.status } let offer = 0; let limit = 10; if(req.query.pageSize != undefined && req.query != undefined){ offer = Number((req.query.current-1)*req.query.pageSize); limit = Number(req.query.pageSize) } let type = req.query.type; if(type == 1){ where.type = 255 } if(type == 2){ where.type = { [Op.ne]: 255} } let option = { where:where, offset:offer, limit:limit, order:[["type",'desc'],["create_time","desc"]] } let data = await sequelizer.models.Pet.findAndCountAll(option); res.status(200).json(result.success(data)); } <file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); require("../../../model/item"); module.exports = async (req, res) => { let param = { where:{'model':1,'status':1}, order:[["count",'asc']] } let item = await sequelizer.models.Item.findOne(param); if(item == undefined){ res.status(200).json(result.error("no found item")); return } let data = { item_id:item.contract_item_id } res.status(200).json(result.success(data)); }<file_sep>/* indent size: 2 */ const {DataTypes} = require('sequelize'); const sequelize = require("../config/mysql2") const Model = sequelize.define('TokenInfo', { id: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true }, chainid: { type: DataTypes.INTEGER(11), allowNull: true }, token_address: { type: DataTypes.STRING(255), allowNull: true }, token_name: { type: DataTypes.STRING(255), allowNull: true }, cretae_time: { type: DataTypes.DATE, allowNull: true }, precision: { type: DataTypes.INTEGER(5), allowNull: true } }, { tableName: 'token_info', timestamps: false }); module.exports = Model;<file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); const { QueryTypes } = require('sequelize'); module.exports = async (req, res) => { let param = req.query; let offer = 0; let limit = 10; if(param.pageSize != undefined && param != undefined){ offer = Number((param.current-1)*param.pageSize); limit = Number(param.pageSize) } let sql = "select ps.id,ps.pet_id,ps.current,ps.current_contract,ps.price,p.type,p.image from pet_sell ps left join pet p on ps.pet_id = p.pet_id where ps.status = 1 "; let count_sql = "select count(ps.pet_id) from pet_sell ps left join pet p on ps.pet_id = p.pet_id where ps.status = 1 "; if(param.type == 1){ sql+= " and p.type = 255 "; count_sql+= " and p.type = 255 "; } if(param.type == 2){ sql+= " and p.type <> 255 "; count_sql+= " and p.type <> 255 "; } sql+= ' order by ps.create_time limit ?,?' let list = await sequelizer.query(sql,{ replacements: [offer,limit], type: QueryTypes.SELECT }) let count = await sequelizer.query(count_sql,{ type: QueryTypes.SELECT }) let data = { count:count[0]['count(ps.pet_id)'], row:list } res.status(200).json(result.success(data)); } <file_sep>/* indent size: 2 */ const {DataTypes} = require('sequelize'); const sequelize = require("../config/mysql2") const Model = sequelize.define('PetSell', { id: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true, autoIncrement: true }, pet_id: { type: DataTypes.BIGINT, allowNull: true }, pet_image: { type: DataTypes.INTEGER(2), allowNull: true }, current: { type: DataTypes.STRING(10), allowNull: true }, current_contract: { type: DataTypes.STRING(255), allowNull: true }, price: { type: DataTypes.BIGINT, allowNull: true }, sell_account: { type: DataTypes.STRING(50), allowNull: true }, create_time: { type: DataTypes.BIGINT, allowNull: true }, status: { type: DataTypes.INTEGER(11), allowNull: true }, tx_hash: { type: DataTypes.STRING(255), allowNull: true }, current_precision: { type: DataTypes.INTEGER(255), allowNull: true } }, { tableName: 'pet_sell', timestamps: false }); module.exports = Model;<file_sep>/* indent size: 2 */ const {DataTypes} = require('sequelize'); const sequelize = require("../config/mysql2") const Model = sequelize.define('Message', { id: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true }, type: { type: DataTypes.INTEGER(1), allowNull: true }, is_read: { type: DataTypes.INTEGER(1), allowNull: true }, message: { type: DataTypes.STRING(255), allowNull: true }, create_time: { type: DataTypes.DATE, allowNull: true }, address: { type: DataTypes.STRING(255), allowNull: true }, event_id: { type: DataTypes.STRING(255), allowNull: true } }, { tableName: 'message', timestamps: false }); module.exports = Model; <file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); const { QueryTypes,Op } = require('sequelize'); require("../../../model/ring"); require("../../../model/item_commit_log"); module.exports = async (req, res) => { const { status, current, pageSize, sort, number } = req.query; let offer = 0; let limit = 10; if(pageSize != undefined && current != undefined){ offer = Number((current-1)*pageSize); limit = Number(pageSize) } let order = [["createTime", 'desc']]; if(sort == 0){ order = [["jackpot", 'desc']]; }else if(sort == 1){ order = [["jackpot", 'asc']]; }else if(sort == 2){ order =[["createTime", 'desc']]; }else if(sort == 3){ order =[["max_multipe", 'desc']]; } const where = {}; if (status != 0) where.status = status if (number?.length > 0) where.item_id = number const list = await this.ctx.model.Ring.findAndCountAll({ offset: offer, limit: limit, where, order: order, }) list.rows.every(async function(ring){ let list = await sequelizer.models.ItemCommitLog.findAll({ where:{ item_id:ring.item_id, nonce:{ [Op.gte]: ring.nonce}, status:0 } }); ring.dataValues.list = list }) res.status(200).json(result.success(list)); } <file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); const { QueryTypes } = require('sequelize'); module.exports = async (req, res) => { let address = req.query.address; let sql = "select * from pet where owner_address = ? and type <> 255 and status = 4"; let data = await sequelizer.query(sql,{ replacements: [address], type: QueryTypes.SELECT }) res.status(200).json(result.success(data)); } <file_sep>const sequelizer = require("../../../config/mysql2"); const result = require("../../../utils/Result"); require("../../../model/ring_record"); module.exports = async (req, res) => { let id = req.query.id; if (id == undefined && id.length == 0) { res.status(200).json(result.errot("id is empty")); return } let param = { where: { item_id: id } } let data = await sequelizer.models.RingRecord.findAll(param); res.status(200).json(result.success(data)); }
3b9bc1821096cc43389e57e9dae08e14ff4ea1ed
[ "JavaScript" ]
22
JavaScript
slightly-null/nulls_world_api
801873051e74e8778b4db954e3c3d8b593d07661
01ea7d0f816a67d853609865fdc1a5f20b162517
refs/heads/master
<repo_name>LogisticsCompany/LogisticsManagementSystem<file_sep>/src/com/biyeseng/action/AddMsgAction.java package com.biyeseng.action; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.biyeseng.db.DBManager; import com.biyeseng.util.CommonUtil; /** * 添加留言信息 * * @author biyeseng * @company www.biyeseng.cn * */ public class AddMsgAction extends HttpServlet { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); DBManager dbm = new DBManager(); //留言内容 String msg = request.getParameter("msg"); if (msg != null) { msg = CommonUtil.TextToHtml(msg); } String date = CommonUtil.getDate(); //发布人 Object user = request.getSession().getAttribute("user"); String appuser = ""; if (user != null && appuser.toString() != null) { appuser = (String) user; } String sql = "insert into message(msg,appuser,date,reply) values('" + msg + "','" + appuser + "','" + date + "','')"; Statement stat = null; Connection conn = null; try { conn = dbm.getConnection(); stat = conn.createStatement(); stat.execute(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (stat != null) stat.close(); if (conn != null) conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } out.println("<script>alert('留言发布成功,我们会尽快给您回复!');window.location.href='message.jsp'</script>"); out.flush(); out.close(); } } <file_sep>/src/com/biyeseng/action/UserLogAction.java package com.biyeseng.action; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.biyeseng.db.DBManager; /** * 会员登录 * @author biyeseng * @company www.biyeseng.cn * */ public class UserLogAction extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String username=request.getParameter("name"); String userpwd=request.getParameter("pwd"); DBManager dbm=new DBManager(); boolean login=dbm.loginUser(username, userpwd); if(login){ request.getSession().setAttribute("user", username); out.println("<script>alert('登陆成功!');window.location.href='index.jsp'</script>"); }else{ out.println("<script>alert('用户名或密码有误!');window.location.href='index.jsp'</script>"); } out.flush(); out.close(); } } <file_sep>/src/com/biyeseng/action/ModAdminAction.java package com.biyeseng.action; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.biyeseng.db.DBManager; import java.sql.*; /** * 修改员工 * @author biyeseng * @company www.biyeseng.cn * */ public class ModAdminAction extends HttpServlet { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String id = request.getParameter("id"); String name = request.getParameter("name"); String pwd = request.getParameter("pwd"); String rname=request.getParameter("rname"); String zhi=request.getParameter("zhi"); String tel=request.getParameter("tel"); String age=request.getParameter("age"); DBManager dbm = new DBManager(); String sql = "update admin set userName='"+name+"',userPw='"+pwd+"' ,rname='"+rname+"',zhi='"+zhi+"',tel='"+tel+"',age='"+age+"' where id="+id; Statement stat = null; Connection conn=null; try { conn=dbm.getConnection(); stat = conn.createStatement(); stat.execute(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if(stat!=null) stat.close(); if(conn!=null) conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } response.sendRedirect("admin/admin/list.jsp"); out.flush(); out.close(); } } <file_sep>/readme.md #### 命令行连接数据库 `mysql -u root -p -h 172.16.31.10 -P 3306` ##### password `<PASSWORD>` <file_sep>/src/com/biyeseng/action/AddCarAction.java package com.biyeseng.action; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.biyeseng.db.DBManager; /** * 添加车辆信息 * * @author biyeseng * @company www.biyeseng.cn * */ public class AddCarAction extends HttpServlet { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); //车牌信息 String pai = request.getParameter("pai"); //车型 String size = request.getParameter("size"); //长短途 String type = request.getParameter("type"); //状态 String state = request.getParameter("state"); //备注 String info = request.getParameter("info"); DBManager dbm = new DBManager(); // 添加车辆信息 String sql = "insert into car(pai,size,type,state,info) values('" + pai + "','" + size + "','" + type + "','" + state + "','" + info + "')"; Statement stat = null; Connection conn = null; try { conn = dbm.getConnection(); stat = conn.createStatement(); stat.execute(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (stat != null) stat.close(); if (conn != null) conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } response.sendRedirect("admin/car/list.jsp"); out.flush(); out.close(); } }
7727869eb2d523288503d8aca45bb11e1a9a3744
[ "Markdown", "Java" ]
5
Java
LogisticsCompany/LogisticsManagementSystem
554fa6950b42048fe69fafa84fdea649bc7af026
dd64c3c1ebd339d1770a33853897efa73089b04e
refs/heads/master
<repo_name>zjy243352154/gdx-pandas<file_sep>/requirements.txt enum34; python_version < '3.4' future gdxcc pandas>=0.20.1 numpy>=1.7 <file_sep>/gdxpds/special.py # [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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. # # 3. Neither the name of the copyright holder nor 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 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. # [/LICENSE] import copy import logging import gdxcc import numpy as np # List of numpy special values in gdxGetSpecialValues order # 1E300, 2E300, 3E300, 4E300, 5E300 NUMPY_SPECIAL_VALUES = [None, np.nan, np.inf, -np.inf, np.finfo(float).eps] logger = logging.getLogger(__name__) def convert_gdx_to_np_svs(df, num_dims): """ Converts GDX special values to the corresponding numpy versions. Parmeters --------- df : pandas.DataFrame a GdxSymbol DataFrame as it was read directly from GDX num_dims : int the number of columns in df that list the dimension values for which the symbol value is non-zero / non-default Returns ------- pandas.DataFrame copy of df for which all GDX special values have been converted to their numpy equivalents """ # create clean copy of df try: tmp = copy.deepcopy(df) except: logger.warning("Unable to deepcopy:\n{}".format(df)) tmp = copy.copy(df) # apply the map to the value columns and merge with the dimensional information tmp = (tmp.iloc[:, :num_dims]).merge(tmp.iloc[:, num_dims:].replace(GDX_TO_NP_SVS, value=None), left_index=True, right_index=True) return tmp def is_np_eps(val): """ Parameters ---------- val : numeric value to test Returns ------- bool True if val is equal to eps (np.finfo(float).eps), False otherwise """ return np.abs(val - NUMPY_SPECIAL_VALUES[-1]) < NUMPY_SPECIAL_VALUES[-1] def is_np_sv(val): """ Parameters ---------- val : numeric value to test Returns ------- bool True if val is NaN, eps, or is in NUMPY_SPECIAL_VALUES; False otherwise """ return np.isnan(val) or (val in NUMPY_SPECIAL_VALUES) or is_np_eps(val) def convert_np_to_gdx_svs(df, num_dims): """ Converts numpy special values to the corresponding GDX versions. Parmeters --------- df : pandas.DataFrame a GdxSymbol DataFrame in pandas/numpy form num_dims : int the number of columns in df that list the dimension values for which the symbol value is non-zero / non-default Returns ------- pandas.DataFrame copy of df for which all numpy special values have been converted to their GDX equivalents """ # converts a single value; NANs are assumed already handled def convert_approx_eps(value): # eps values are not always caught by ==, use is_np_eps which applies # a tolerance if is_np_eps(value): return SPECIAL_VALUES[4] return value # get a clean copy of df try: tmp = copy.deepcopy(df) except: logger.warning("Unable to deepcopy:\n{}".format(df)) tmp = copy.copy(df) # fillna and apply map to value columns, then merge with dimensional columns try: values = tmp.iloc[:, num_dims:].replace(NP_TO_GDX_SVS, value=None).applymap(convert_approx_eps) tmp = (tmp.iloc[:, :num_dims]).merge(values, left_index=True, right_index=True) except: logger.error("Unable to convert numpy special values to GDX special values." + \ "num_dims: {}, dataframe:\n{}".format(num_dims, df)) raise return tmp def pd_isnan(val): """ Utility function for identifying None or NaN (which are indistinguishable in pandas). Parameters ---------- val : numeric value to test Returns ------- bool True if val is a GDX encoded special value that maps to None or numpy.nan; False otherwise """ return val is None or val != val def pd_val_equal(val1, val2): """ Utility function used to test special value conversions. Parameters ---------- val1 : float or None first value to compare val2 : float or None second value to compare Returns ------- bool True if val1 and val2 are equal in the sense of == or they are both NaN/None. The values that map to None and np.nan are assumed to be equal because pandas cannot be relied upon to make the distinction. """ return pd_isnan(val1) and pd_isnan(val2) or val1 == val2 def gdx_isnan(val,gdxf): """ Utility function for equating the GDX special values that map to None or NaN (which are indistinguishable in pandas). Parameters ---------- val : numeric value to test gdxf : GdxFile GDX file containing the value. Provides np_to_gdx_svs map. Returns ------- bool True if val is a GDX encoded special value that maps to None or numpy.nan; False otherwise """ return val in [SPECIAL_VALUES[0], SPECIAL_VALUES[1]] def gdx_val_equal(val1,val2,gdxf): """ Utility function used to test special value conversions. Parameters ---------- val1 : float or GDX special value first value to compare val2 : float or GDX special value second value to compare gdxf : GdxFile GDX file containing val1 and val2 Returns ------- bool True if val1 and val2 are equal in the sense of == or they are equivalent GDX-format special values. The values that map to None and np.nan are assumed to be equal because pandas cannot be relied upon to make the distinction. """ if gdx_isnan(val1, gdxf) and gdx_isnan(val2, gdxf): return True return val1 == val2 def load_specials(gams_dir_finder): """ Load special values Needs to be called after gdxcc is loaded. Populates the module attributes SPECIAL_VALUES, GDX_TO_NP_SVS, and NP_TO_GDX_SVS. Parameters ---------- gams_dir_finder : :class:`gdxpds.tools.GamsDirFinder` """ global SPECIAL_VALUES global GDX_TO_NP_SVS global NP_TO_GDX_SVS H = gdxcc.new_gdxHandle_tp() rc = gdxcc.gdxCreateD(H, gams_dir_finder.gams_dir, gdxcc.GMS_SSSIZE) if not rc: raise Exception(rc[1]) # get special values special_values = gdxcc.doubleArray(gdxcc.GMS_SVIDX_MAX) gdxcc.gdxGetSpecialValues(H, special_values) SPECIAL_VALUES = [] GDX_TO_NP_SVS = {} NP_TO_GDX_SVS = {} for i in range(gdxcc.GMS_SVIDX_MAX): if i >= len(NUMPY_SPECIAL_VALUES): break SPECIAL_VALUES.append(special_values[i]) gdx_val = special_values[i] GDX_TO_NP_SVS[gdx_val] = NUMPY_SPECIAL_VALUES[i] NP_TO_GDX_SVS[NUMPY_SPECIAL_VALUES[i]] = gdx_val gdxcc.gdxFree(H) # These values are populated by load_specials, called in load_gdxcc SPECIAL_VALUES = [] GDX_TO_NP_SVS = {} NP_TO_GDX_SVS = {} <file_sep>/gdxpds/write_gdx.py # [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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. # # 3. Neither the name of the copyright holder nor 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 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. # [/LICENSE] import logging from numbers import Number # gdxpds needs to be imported before pandas to try to avoid library conflict on # Linux that causes a segmentation fault. from gdxpds.tools import Error from gdxpds.gdx import GdxFile, GdxSymbol, GAMS_VALUE_COLS_MAP, GamsDataType import pandas as pds logger = logging.getLogger(__name__) class Translator(object): def __init__(self,dataframes,gams_dir=None): self.dataframes = dataframes self.__gams_dir=None def __exit__(self, *args): if self.__gdx is not None: self.__gdx.__exit__(self, *args) def __del__(self): if self.__gdx is not None: self.__gdx.__del__() @property def dataframes(self): return self.__dataframes @dataframes.setter def dataframes(self,value): err_msg = "Expecting map of name, pandas.DataFrame pairs." try: for symbol_name, df in value.items(): if not isinstance(symbol_name, str): raise Error(err_msg) if not isinstance(df, pds.DataFrame): raise Error(err_msg) except AttributeError: raise Error(err_msg) self.__dataframes = value self.__gdx = None @property def gams_dir(self): return self.__gams_dir @gams_dir.setter def gams_dir(self, value): self.__gams_dir = value @property def gdx(self): if self.__gdx is None: self.__gdx = GdxFile(gams_dir=self.__gams_dir) for symbol_name, df in self.dataframes.items(): self.__add_symbol_to_gdx(symbol_name, df) return self.__gdx def save_gdx(self,path,gams_dir=None): if gams_dir is not None: self.__gams_dir=gams_dir self.gdx.write(path) def __add_symbol_to_gdx(self, symbol_name, df): data_type, num_dims = self.__infer_data_type(symbol_name,df) logger.info("Inferred data type of {} to be {}.".format(symbol_name,data_type.name)) self.__gdx.append(GdxSymbol(symbol_name,data_type,dims=num_dims)) self.__gdx[symbol_name].dataframe = df return def __infer_data_type(self,symbol_name,df): """ Returns ------- (gdxpds.GamsDataType, int) symbol type and number of dimensions implied by df """ # See if structure implies that symbol_name may be a Variable or an Equation # If so, break tie based on naming convention--Variables start with upper case, # equations start with lower case var_or_eqn = False df_col_names = df.columns var_eqn_col_names = [col_name for col_name, col_ind in GAMS_VALUE_COLS_MAP[GamsDataType.Variable]] if len(df_col_names) >= len(var_eqn_col_names): # might be variable or equation var_or_eqn = True trunc_df_col_names = df_col_names[len(df_col_names) - len(var_eqn_col_names):] for i, df_col in enumerate(trunc_df_col_names): if df_col and (df_col.lower() != var_eqn_col_names[i].lower()): var_or_eqn = False break if var_or_eqn: num_dims = len(df_col_names) - len(var_eqn_col_names) if symbol_name[0].upper() == symbol_name[0]: return GamsDataType.Variable, num_dims else: return GamsDataType.Equation, num_dims # Parameter or set num_dims = len(df_col_names) - 1 if len(df.index) > 0: if isinstance(df.loc[df.index[0],df.columns[-1]],Number): return GamsDataType.Parameter, num_dims return GamsDataType.Set, num_dims def to_gdx(dataframes,path=None,gams_dir=None): """ Parameters: - dataframes (map of pandas.DataFrame): symbol name to pandas.DataFrame dict to be compiled into a single gdx file. Each DataFrame is assumed to represent a single set or parameter. The last column must be the parameter's value, or the set's listing of True/False, and must be labeled as (case insensitive) 'value'. - path (optional string): if provided, the gdx file will be written to this path Returns a gdxdict.gdxdict, which is defined in [py-gdx](https://github.com/geoffleyland/py-gdx). """ translator = Translator(dataframes,gams_dir=gams_dir) if path is not None: translator.save_gdx(path) return translator.gdx <file_sep>/gdxpds/test/test_conversions.py # [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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. # # 3. Neither the name of the copyright holder nor 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 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. # [/LICENSE] import os import subprocess as subp import gdxpds.gdx from gdxpds.test import base_dir, run_dir from gdxpds.test.test_session import manage_rundir import pandas as pds def roundtrip_one_gdx(filename,dirname): # load gdx, make map of symbols and number of records gdx_file = os.path.join(base_dir,filename) with gdxpds.gdx.GdxFile() as gdx: gdx.read(gdx_file) num_records = {} total_records = 0 for symbol in gdx: num_records[symbol.name] = symbol.num_records total_records += num_records[symbol.name] assert total_records > 0 # call command-line interface to transform gdx to csv out_dir = os.path.join(run_dir, dirname, os.path.splitext(filename)[0]) if not os.path.exists(os.path.dirname(out_dir)): os.mkdir(os.path.dirname(out_dir)) cmds = ['python', os.path.join(gdxpds.test.bin_prefix,'gdx_to_csv.py'), '-i', gdx_file, '-o', out_dir] subp.call(cmds) # call command-line interface to transform csv to gdx txt_file = os.path.join(out_dir, 'csvs.txt') f = open(txt_file, 'w') for p, _dirs, files in os.walk(out_dir): for file in files: if os.path.splitext(file)[1] == '.csv': f.write("{}\n".format(os.path.join(p,file))) break f.close() roundtripped_gdx = os.path.join(out_dir, 'output.gdx') cmds = ['python', os.path.join(gdxpds.test.bin_prefix,'csv_to_gdx.py'), '-i', txt_file, '-o', roundtripped_gdx] subp.call(cmds) # load gdx and check symbols and records against original map... # ... first without full load with gdxpds.gdx.GdxFile(lazy_load=True) as gdx: gdx.read(roundtripped_gdx) for symbol_name, records in num_records.items(): if records > 0: assert symbol_name in gdx, "Expected {} in {}.".format(symbol_name,roundtripped_gdx) assert gdx[symbol_name].num_records == records, "Expected {} in {} to have {} records, but has {}.".format(symbol_name,roundtripped_gdx,records,gdx[symbol_name].num_records) # ... then with a full load with gdxpds.gdx.GdxFile(lazy_load=False) as gdx: gdx.read(roundtripped_gdx) for symbol_name, records in num_records.items(): if records > 0: assert symbol_name in gdx, "Expected {} in {}.".format(symbol_name,roundtripped_gdx) assert gdx[symbol_name].num_records == records, "Expected {} in {} to have {} records, but has {}.".format(symbol_name,roundtripped_gdx,records,gdx[symbol_name].num_records) return roundtripped_gdx def test_gdx_roundtrip(manage_rundir): filenames = ['CONVqn.gdx','OptimalCSPConfig_In.gdx','OptimalCSPConfig_Out.gdx'] for filename in filenames: roundtrip_one_gdx(filename,'gdx_roundtrip') return def test_csv_roundtrip(manage_rundir): # load csvs into pandas and make map of filenames to number of rows csvs = [os.path.join(base_dir, 'installed_capacity.csv'), os.path.join(base_dir, 'annual_generation.csv')] n = len(csvs) num_records = {} total_records = 0 for csv in csvs: df = pds.read_csv(csv, index_col = None) num_records[os.path.splitext(os.path.basename(csv))[0]] = len(df.index) total_records += len(df.index) assert total_records > 0 # call command-line interface to transform csv to gdx out_dir = os.path.join(run_dir, 'csv_roundtrip') if not os.path.exists(out_dir): os.mkdir(out_dir) gdx_file = os.path.join(out_dir, 'intermediate.gdx') cmds = ['python', os.path.join(gdxpds.test.bin_prefix,'csv_to_gdx.py'), '-i', csvs[0], csvs[1], '-o', gdx_file] subp.call(cmds) # call command-line interface to transform gdx to csv cmds = ['python', os.path.join(gdxpds.test.bin_prefix,'gdx_to_csv.py'), '-i', gdx_file, '-o', out_dir] subp.call(cmds) # load csvs into pandas and check filenames and number of rows against original map for csv_name, records in num_records.items(): csv_file = os.path.join(out_dir, csv_name + '.csv') assert os.path.isfile(csv_file) df = pds.read_csv(csv_file, index_col = None) assert len(df.index) == records cnt = 0 for _p, _dirs, files in os.walk(out_dir): for file in files: if os.path.splitext(file)[1] == '.csv': cnt += 1 break assert cnt == n <file_sep>/gdxpds/read_gdx.py # [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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. # # 3. Neither the name of the copyright holder nor 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 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. # [/LICENSE] from collections import OrderedDict import logging # gdxpds needs to be imported before pandas to try to avoid library conflict on # Linux that causes a segmentation fault. from gdxpds.tools import Error from gdxpds.gdx import GdxFile logger = logging.getLogger(__name__) class Translator(object): def __init__(self,gdx_file,gams_dir=None,lazy_load=False): self.__gdx = GdxFile(gams_dir=gams_dir,lazy_load=lazy_load) self.__gdx.read(gdx_file) self.__dataframes = None def __exit__(self, *args): self.__gdx.__exit__(self, *args) def __del__(self): self.__gdx.__del__() @property def gams_dir(self): return self.gdx.gams_dir @gams_dir.setter def gams_dir(self, value): self.gdx.gams_dir = value @property def gdx_file(self): return self.gdx.filename @gdx_file.setter def gdx_file(self,value): self.__gdx.__del__() self.__gdx = GdxFile(gams_dir=self.gdx.gams_dir,lazy_load=self.gdx.lazy_load) self.__gdx.read(value) self.__dataframes = None @property def gdx(self): return self.__gdx @property def dataframes(self): if self.__dataframes is None: self.__dataframes = OrderedDict() for symbol in self.__gdx: if not symbol.loaded: symbol.load() self.__dataframes[symbol.name] = symbol.dataframe.copy() return self.__dataframes @property def symbols(self): return [symbol_name for symbol_name in self.gdx] def dataframe(self, symbol_name): if not symbol_name in self.gdx: raise Error("No symbol named '{}' in '{}'.".format(symbol_name, self.gdx_file)) if not self.gdx[symbol_name].loaded: self.gdx[symbol_name].load() # This was returning { symbol_name: dataframe }, which seems intuitively off. return self.gdx[symbol_name].dataframe.copy() def to_dataframes(gdx_file,gams_dir=None): """ Primary interface for converting a GAMS GDX file to pandas DataFrames. Parameters: - gdx_file (string): path to a GDX file - gams_dir (string): optional path to GAMS directory Returns a dict of Pandas DataFrames, one item for each symbol in the GDX file, keyed with the symbol name. """ dfs = Translator(gdx_file,gams_dir=gams_dir).dataframes return dfs def list_symbols(gdx_file,gams_dir=None): """ Returns the list of symbols available in gdx_file. Parameters: - gdx_file (string): path to a GDX file - gams_dir (string): optional path to GAMS directory """ symbols = Translator(gdx_file,gams_dir=gams_dir,lazy_load=True).symbols return symbols def to_dataframe(gdx_file,symbol_name,gams_dir=None,old_interface=True): """ Interface for getting the { symbol_name: pandas.DataFrame } dict for a single symbol. Parameters: - gdx_file (string): path to a GDX file - symbol_name (string): symbol whose pandas.DataFrame is being requested - gams_dir (string): optional path to GAMS directory Returns a dict with a single entry, where the key is symbol_name and the value is the corresponding pandas.DataFrame. """ df = Translator(gdx_file,gams_dir=gams_dir,lazy_load=True).dataframe(symbol_name) return {symbol_name: df} if old_interface else df <file_sep>/gdxpds/__init__.py # [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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. # # 3. Neither the name of the copyright holder nor 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 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. # [/LICENSE] __author__ = "<NAME>" __email__ = "<EMAIL>" from ._version import __version__ import logging import sys logger = logging.getLogger(__name__) from gdxpds.tools import Error from gdxpds.special import load_specials from ._version import __version__ def load_gdxcc(gams_dir=None): """ Method to initialize GAMS, especially to load required libraries that can sometimes conflict with other packages. Parameters ---------- gams_dir : None or str if not None, directory containing the GAMS executable """ if 'pandas' in sys.modules: logger.warning("Especially on Linux, gdxpds should be imported before " + \ "pandas to avoid a library conflict. Also make sure your " + \ "GAMS directory is listed in LD_LIBRARY_PATH.") import gdxcc from gdxpds.tools import GamsDirFinder finder = GamsDirFinder(gams_dir=gams_dir) H = gdxcc.new_gdxHandle_tp() _rc = gdxcc.gdxCreateD(H,finder.gams_dir,gdxcc.GMS_SSSIZE) gdxcc.gdxFree(H) load_specials(finder) return try: load_gdxcc() except: from gdxpds.tools import GamsDirFinder gams_dir = None try: gams_dir = GamsDirFinder().gams_dir except: pass logger.warning(f"Unable to load gdxcc with default GAMS directory '{gams_dir}'. " "You may need to explicitly call gdxpds.load_gdxcc(gams_dir) " "before importing pandas to avoid a library conflict.") from gdxpds.read_gdx import to_dataframes, list_symbols, to_dataframe from gdxpds.write_gdx import to_gdx <file_sep>/gdxpds/gdx.py # [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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. # # 3. Neither the name of the copyright holder nor 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 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. # [/LICENSE] ''' Backend functionality for reading and writing GDX files. The GdxFile and GdxSymbol classes are full-featured interfaces for going between the GDX format and pandas DataFrames, including translation between GDX and numpy special values. ''' from __future__ import absolute_import, print_function from builtins import super import atexit from collections import defaultdict, OrderedDict try: from collections.abc import MutableSequence except ImportError: from collections import MutableSequence import copy from ctypes import c_bool from enum import Enum import logging from numbers import Number # try to import gdx loading utility HAVE_GDX2PY = False try: # special Windows dll for optimized loading of GAMS parameters import gdx2py HAVE_GDX2PY = True except ImportError: pass # gdxpds needs to be imported before pandas to try to avoid library conflict on # Linux that causes a segmentation fault. from gdxpds import Error from gdxpds.tools import NeedsGamsDir import gdxcc import numpy as np import pandas as pds import gdxpds.special as special # Import some things for backward compatibility from gdxpds.special import ( convert_gdx_to_np_svs, convert_np_to_gdx_svs, gdx_isnan, gdx_val_equal, NUMPY_SPECIAL_VALUES, is_np_eps, is_np_sv, ) logger = logging.getLogger(__name__) def replace_df_column(df,colname,new_col): """ Utility function that replaces df[colname] with new_col. Special care is taken for the case when df has multiple columns named '*', since this causes pandas to crash. Parameters ---------- df : pandas.DataFrame edited in place by this function colname : str name of column in df whose data is to be replaced new_col : vector, list, pandas.Series new column data for df[colname] """ cols = df.columns tmpcols = [col if col != '*' else 'aaa' for col in cols ] df.columns = tmpcols df[colname] = new_col df.columns = cols return class GdxError(Error): def __init__(self, H, msg): """ Pulls information from gdxcc about the last encountered error and appends it to msg. Parameters ---------- H : pointer or None SWIG binding pointer to a GDX object msg : str gdxpds error message Attributes ---------- msg : str msg that is passed in with a gdxErrorStr appended """ if H: msg += ". " + gdxcc.gdxErrorStr(H, gdxcc.gdxGetLastError(H))[1] + "." super().__init__(msg) class GdxFile(MutableSequence, NeedsGamsDir): def __init__(self,gams_dir=None,lazy_load=True): """ Initializes a GdxFile object by connecting to GAMS and creating a pointer. Throws a GdxError if either of those operations fail. """ self.lazy_load = lazy_load self._version = None self._producer = None self._filename = None self._symbols = OrderedDict() NeedsGamsDir.__init__(self,gams_dir=gams_dir) self._H = self._create_gdx_object() self.universal_set = GdxSymbol('*',GamsDataType.Set,dims=1,file=None,index=0) self.universal_set._file = self atexit.register(gdxcc.gdxFree, self.H) return def cleanup(self): gdxcc.gdxFree(self.H) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.cleanup() def __del__(self): self.cleanup() def clone(self): """ Returns a new GdxFile containing clones of the GdxSymbols in this GdxFile. The clone will not be associated with a filename. The clone's GdxSymbols will not have indexes. The clone will be ready to write to a new file. """ result = GdxFile(gams_dir=self.gams_dir,lazy_load=False) for symbol in self: result.append(symbol.clone()) result[-1]._file = result return result @property def empty(self): """ Returns True if this GdxFile object contains any symbols. """ return len(self) == 0 @property def H(self): """ GDX object handle """ return self._H @property def filename(self): return self._filename @property def version(self): """ GDX file version """ return self._version @property def producer(self): """ What program wrote the GDX file """ return self._producer @property def num_elements(self): return sum([symbol.num_records for symbol in self]) def read(self,filename): """ Opens gdx file at filename and reads meta-data. If not self.lazy_load, also loads all symbols. Throws an Error if not self.empty. Throws a GdxError if any calls to gdxcc fail. """ if not self.empty: raise Error("GdxFile.read can only be used if the GdxFile is .empty") # open the file rc = gdxcc.gdxOpenRead(self.H,str(filename)) if not rc[0]: raise GdxError(self.H,f"Could not open {filename!r}") self._filename = filename # read in meta-data ... # ... for the file ret, self._version, self._producer = gdxcc.gdxFileVersion(self.H) if ret != 1: raise GdxError(self.H,"Could not get file version") ret, symbol_count, element_count = gdxcc.gdxSystemInfo(self.H) logger.debug("Opening '{}' with {} symbols and {} elements with lazy_load = {}.".format(filename,symbol_count,element_count,self.lazy_load)) # ... for the symbols ret, name, dims, data_type = gdxcc.gdxSymbolInfo(self.H,0) if ret != 1: raise GdxError(self.H,"Could not get symbol info for the universal set") self.universal_set = GdxSymbol(name,data_type,dims=dims,file=self,index=0) for i in range(symbol_count): index = i + 1 ret, name, dims, data_type = gdxcc.gdxSymbolInfo(self.H,index) if ret != 1: raise GdxError(self.H,"Could not get symbol info for symbol {}".format(index)) self.append(GdxSymbol(name,data_type,dims=dims,file=self,index=index)) # read all symbols if not lazy_load if not self.lazy_load: for symbol in self: symbol.load() return def write(self,filename): # only write if all symbols loaded for symbol in self: if not symbol.loaded: raise Error("All symbols must be loaded before this file can be written.") ret = gdxcc.gdxOpenWrite(self.H,str(filename),"gdxpds") if not ret: raise GdxError(self.H, f"Could not open {filename!r} for writing. " "Consider cloning this file (.clone()) before trying to write.") self._filename = filename # write the universal set self.universal_set.write() for i, symbol in enumerate(self,start=1): try: symbol.write(index=i) except: logger.error("Unable to write {} to {}".format(symbol,filename)) raise gdxcc.gdxClose(self.H) def __repr__(self): return "GdxFile(self,gams_dir={},lazy_load={})".format( repr(self.gams_dir), repr(self.lazy_load)) def __str__(self): s = "GdxFile containing {} symbols and {} elements.".format(len(self),self.num_elements) sep = " Symbols:\n " for symbol in self: s += sep + str(symbol) sep = "\n " return s def __getitem__(self,key): """ Supports list-like indexing and symbol-based indexing """ return self._symbols[self._name_key(key)] def __setitem__(self,key,value): self._check_insert_setitem(key, value) value._file = self if key < len(self): self._symbols[self._name_key(key)] = value self._fixup_name_keys() return assert key == len(self) self._symbols[value.name] = value return def __delitem__(self,key): del self._symbols[self._name_key(key)] return def __len__(self): return len(self._symbols) def insert(self,key,value): self._check_insert_setitem(key, value) value._file = self if key == len(self) and value.name not in self._symbols: # We can safely append the symbol. This is fast (O(log(n)) complexity) self._symbols[value.name] = value else: # Need to insert inside the sequence. This is slow (O(n) complexity) data = [(symbol.name, symbol) for symbol in self] data.insert(key,(value.name,value)) self._symbols = OrderedDict(data) return def __contains__(self,key): """ Returns True if __getitem__ works with key. """ try: self.__getitem__(key) return True except: return False def keys(self): return [symbol.name for symbol in self] def _name_key(self,key): name_key = key if isinstance(key,int): name_key = list(self._symbols.keys())[key] return name_key def _check_insert_setitem(self,key,value): if not isinstance(value,GdxSymbol): raise Error("GdxFiles only contain GdxSymbols. GdxFile was given a {}.".format(type(value))) if not isinstance(key,int): raise Error("When adding or replacing GdxSymbols in GdxFiles, only integer, not name indices, may be used.") if key > len(self): raise Error("Invalid key, {}".format(key)) return def _fixup_name_keys(self): self._symbols = OrderedDict([(symbol.name, symbol) for cur_key, symbol in self._symbols]) return def _create_gdx_object(self): H = gdxcc.new_gdxHandle_tp() rc = gdxcc.gdxCreateD(H,self.gams_dir,gdxcc.GMS_SSSIZE) if not rc: raise GdxError(H,rc[1]) return H class GamsDataType(Enum): Set = gdxcc.GMS_DT_SET Parameter = gdxcc.GMS_DT_PAR Variable = gdxcc.GMS_DT_VAR Equation = gdxcc.GMS_DT_EQU Alias = gdxcc.GMS_DT_ALIAS class GamsVariableType(Enum): Unknown = gdxcc.GMS_VARTYPE_UNKNOWN Binary = gdxcc.GMS_VARTYPE_BINARY Integer = gdxcc.GMS_VARTYPE_INTEGER Positive = gdxcc.GMS_VARTYPE_POSITIVE Negative = gdxcc.GMS_VARTYPE_NEGATIVE Free = gdxcc.GMS_VARTYPE_FREE SOS1 = gdxcc.GMS_VARTYPE_SOS1 SOS2 = gdxcc.GMS_VARTYPE_SOS2 Semicont = gdxcc.GMS_VARTYPE_SEMICONT Semiint = gdxcc.GMS_VARTYPE_SEMIINT class GamsEquationType(Enum): Equality = 53 + gdxcc.GMS_EQUTYPE_E GreaterThan = 53 + gdxcc.GMS_EQUTYPE_G LessThan = 53 + gdxcc.GMS_EQUTYPE_L NothingEnforced = 53 + gdxcc.GMS_EQUTYPE_N External = 53 + gdxcc.GMS_EQUTYPE_X Conic = 53 + gdxcc.GMS_EQUTYPE_C class GamsValueType(Enum): Level = gdxcc.GMS_VAL_LEVEL # .l Marginal = gdxcc.GMS_VAL_MARGINAL # .m Lower = gdxcc.GMS_VAL_LOWER # .lo Upper = gdxcc.GMS_VAL_UPPER # .ub Scale = gdxcc.GMS_VAL_SCALE # .scale @classmethod def _missing_(cls, value): if isinstance(value,str): for value_type in cls: if value_type.name == value: return value_type if value == 'Value': return GamsValueType(GamsValueType.Level) super()._missing_(value) GAMS_VALUE_COLS_MAP = defaultdict(lambda : [('Value',GamsValueType.Level.value)]) GAMS_VALUE_COLS_MAP[GamsDataType.Variable] = [(value_type.name, value_type.value) for value_type in GamsValueType] GAMS_VALUE_COLS_MAP[GamsDataType.Equation] = GAMS_VALUE_COLS_MAP[GamsDataType.Variable] GAMS_VALUE_DEFAULTS = { GamsValueType.Level: 0.0, GamsValueType.Marginal: 0.0, GamsValueType.Lower: -np.inf, GamsValueType.Upper: np.inf, GamsValueType.Scale: 1.0 } GAMS_VARIABLE_DEFAULT_LOWER_UPPER_BOUNDS = { GamsVariableType.Unknown: (-np.inf,np.inf), GamsVariableType.Binary: (0.0,1.0), GamsVariableType.Integer: (0.0,np.inf), GamsVariableType.Positive: (0.0,np.inf), GamsVariableType.Negative: (-np.inf,0.0), GamsVariableType.Free : (-np.inf,np.inf), GamsVariableType.SOS1: (0.0,np.inf), GamsVariableType.SOS2: (0.0,np.inf), GamsVariableType.Semicont: (1.0,np.inf), GamsVariableType.Semiint: (1.0,np.inf) } class GdxSymbol(object): def __init__(self,name,data_type,dims=0,file=None,index=None, description='',variable_type=None,equation_type=None): self._name = name self.description = description self._loaded = False self._data_type = GamsDataType(data_type) self._variable_type = None; self.variable_type = variable_type self._equation_type = None; self.equation_type = equation_type self._dataframe = None; self._dims = None self.dims = dims assert self._dataframe is not None self._file = file self._index = index if self.file is not None: # reading from file # get additional meta-data ret, records, userinfo, description = gdxcc.gdxSymbolInfoX(self.file.H,self.index) if ret != 1: raise GdxError(self.file.H,"Unable to get extended symbol information for {}".format(self.name)) self._num_records = records if self.data_type == GamsDataType.Variable: self.variable_type = GamsVariableType(userinfo) elif self.data_type == GamsDataType.Equation: self.equation_type = GamsEquationType(userinfo) self.description = description if self.index > 0: ret, gdx_domain = gdxcc.gdxSymbolGetDomainX(self.file.H,self.index) if ret == 0: raise GdxError(self.file.H,"Unable to get domain information for {}".format(self.name)) assert len(gdx_domain) == len(self.dims), "Dimensional information read in from GDX should be consistent." self.dims = gdx_domain else: # universal set assert self.index == 0 self._loaded = True return # writing new symbol self._loaded = True return def clone(self): if not self.loaded: raise Error("Symbol {} cannot be cloned because it is not yet loaded.".format(repr(self.name))) assert self.loaded result = GdxSymbol(self.name,self.data_type, dims=self.dims, description=self.description, variable_type=self.variable_type, equation_type=self.equation_type) result.dataframe = copy.deepcopy(self.dataframe) assert result.loaded return result @property def name(self): return self._name @name.setter def name(self,value): self._name = value if self.file is not None: self.file._fixup_name_keys() return @property def data_type(self): return self._data_type @data_type.setter def data_type(self, value): if not self.loaded or self.num_records > 0: raise Error("Cannot change the data_type of a GdxSymbol that is yet to be read for file or contains records.") self._data_type = GamsDataType(value) self.variable_type = None self.equation_type = None self._init_dataframe() return @property def variable_type(self): return self._variable_type @variable_type.setter def variable_type(self,value): if self.data_type == GamsDataType.Variable: if value is None: # default to Free self._variable_type = GamsVariableType.Free else: try: self._variable_type = GamsVariableType(value) except: if isinstance(self._variable_type,GamsVariableType): logger.warning("Ignoring invalid GamsVariableType request '{}'.".format(value)) return logger.debug("Setting variable_type to {}.".format(GamsVariableType.Free)) self._variable_type = GamsVariableType.Free return assert self.data_type != GamsDataType.Variable if value is not None: logger.warning("GdxSymbol is not a Variable, so setting variable_type to None") self._variable_type = None @property def equation_type(self): return self._equation_type @equation_type.setter def equation_type(self,value): if self.data_type == GamsDataType.Equation: if value is None: # default to Equality self._equation_type = GamsEquationType.Equality else: try: self._equation_type = GamsEquationType(value) except: if isinstance(self._equation_type,GamsEquationType): logger.warning("Ignoring invalid GamsEquationType request '{}'.".format(value)) return logger.debug("Setting equation_type to {}.".format(GamsEquationType.Equality)) self._equation_type = GamsEquationType.Equality return assert self.data_type != GamsDataType.Equation if value is not None: logger.warning("GdxSymbol is not an Equation, so setting equation_type to None") self._equation_type = None @property def value_cols(self): """ Returns list of (name, GamsValueType.value) tuples that describe the value columns in the dataframe, that is, those columns that follow the self.dims. """ return GAMS_VALUE_COLS_MAP[self.data_type] @property def value_col_names(self): return [col_name for col_name, col_ind in self.value_cols] def get_value_col_default(self,value_col_name): if not value_col_name in self.value_col_names: raise Error(f"{value_col_name} is not one of the value columns for " f"this GdxSymbol, which is a {self.data_type}") value_col = GamsValueType(value_col_name) if self.data_type == GamsDataType.Set: assert value_col == GamsValueType.Level return c_bool(True) if (self.data_type == GamsDataType.Variable) and ( (value_col == GamsValueType.Lower) or (value_col == GamsValueType.Upper)): lb_default, ub_default = GAMS_VARIABLE_DEFAULT_LOWER_UPPER_BOUNDS[self.variable_type] if value_col == GamsValueType.Lower: return lb_default else: assert value_col == GamsValueType.Upper return ub_default return GAMS_VALUE_DEFAULTS[value_col] @property def file(self): return self._file @property def index(self): return self._index @property def loaded(self): return self._loaded @property def full_typename(self): if self.data_type == GamsDataType.Parameter and self.dims == 0: return 'Scalar' elif self.data_type == GamsDataType.Variable: return self.variable_type.name + " " + self.data_type.name return self.data_type.name @property def dims(self): return self._dims @dims.setter def dims(self, value): if (self._dims is not None) and (self.loaded and ((self.num_dims > 0) or (self.num_records > 0))): if not isinstance(value,list) or len(value) != self.num_dims: raise Error(f"Cannot set dims to {value}, because the number of " "dimensions has already been set to {self.num_dims}.") if isinstance(value, int): self._dims = ['*'] * value self._init_dataframe() return if not isinstance(value, list): raise Error('dims must be an int or a list. Was passed {} of type {}.'.format(value, type(value))) for dim in value: if not isinstance(dim, str): raise Error('Individual dimensions must be denoted by strings. Was passed {} as element of {}.'.format(dim, value)) assert (self._dims is None) or (self.loaded and (self.num_dims == 0) and (self.num_records == 0)) or (len(value) == self.num_dims) self._dims = value if self.loaded and self.num_records > 0: self._dataframe.columns = self.dims + self.value_col_names return self._init_dataframe() @property def num_dims(self): return len(self.dims) @property def dataframe(self): return self._dataframe @dataframe.setter def dataframe(self, data): try: # get data in common format and start dealing with dimensions if isinstance(data, pds.DataFrame): df = data.copy() has_col_names = True else: df = pds.DataFrame(data) has_col_names = False if df.empty: # clarify dimensionality, as needed for loading empty GdxSymbols df = pds.DataFrame(data,columns=self.dims + self.value_cols) # finish handling dimensions n = len(df.columns) if (self.num_dims > 0) or (self.num_records > 0): if not ((n == self.num_dims) or (n == self.num_dims + len(self.value_cols))): raise Error("Cannot set dataframe to {} because the number ".format(df.head()) + \ "of dimensions would change. This symbol has {} ".format(self.num_dims) + \ "dimensions, currently represented by {}.".format(self.dims)) num_dims = self.num_dims else: # num_dims not explicitly established yet. in this case we must # assume value columns have been provided or dimensionality is 0 num_dims = max(n - len(self.value_cols),0) if (num_dims == 0) and (n < len(self.value_cols)): raise Error("Cannot set dataframe to {} because the number ".format(df.head()) + \ "of dimensions cannot be established consistent with {}.".format(self)) if self.loaded and (num_dims > 0): logger.warning('Inferring {} to have {} dimensions. '.format(self.name,num_dims) + 'Recommended practice is to explicitly set gdxpds.gdx.GdxSymbol dims in the constructor.') replace_dims = True if has_col_names: dim_cols = list(df.columns)[:num_dims] elif self.num_dims == num_dims: dim_cols = self.dims replace_dims = False else: dim_cols = ['*'] * num_dims for col in dim_cols: if not isinstance(col, str): replace_dims = False logger.info("Not using dataframe column names to set dimensions because {} is not a string.".format(col)) if num_dims != self.num_dims: self.dims = num_dims break if replace_dims: self.dims = dim_cols # all done establishing dimensions assert self.num_dims == num_dims # finalize the dataframe if n == self.num_dims: self._append_default_values(df) df.columns = self.dims + self.value_col_names self._dataframe = df except Exception: logger.error("Unable to set dataframe for {} to\n{}\n\nIn process dataframe: {}".format(self,data,self._dataframe)) raise if self.data_type == GamsDataType.Set: self._fixup_set_value() return def _init_dataframe(self): self._dataframe = pds.DataFrame([],columns=self.dims + self.value_col_names) if self.data_type == GamsDataType.Set: colname = self._dataframe.columns[-1] replace_df_column(self._dataframe,colname,self._dataframe[colname].astype(c_bool)) return def _append_default_values(self,df): assert len(df.columns) == self.num_dims logger.debug("Applying default values to create valid dataframe for '{self.name}'.") for value_col_name in self.value_col_names: df[value_col_name] = self.get_value_col_default(value_col_name) def _fixup_set_value(self): """ Tricky to get boolean set values to come through right. isinstance(True,Number) == True and float(True) = 1, but isinstance(c_bool(True),Number) == False, and this keeps the default value of 0.0. Could just test for isinstance(,bool), but this fix has the added advantage of speaking the GDX bindings data type language, and also fills in any missing values, so users no longer need to actually specify self.dataframe['Value'] = True. """ assert self.data_type == GamsDataType.Set colname = self._dataframe.columns[-1] assert colname == self.value_col_names[0], f"Unexpected final column {colname!r} in Set dataframe" if self._dataframe[colname].isnull().values.any(): logger.warning(f"Filling null values in {self} with True. To be " "filled:\n{self._dataframe[self._dataframe[colname].isnull()]}") replace_df_column(self._dataframe, colname, self._dataframe[colname].fillna(value=True)) replace_df_column(self._dataframe,colname,self._dataframe[colname].apply(lambda x: c_bool(x))) return @property def num_records(self): if self.loaded: return len(self.dataframe.index) return self._num_records def __repr__(self): return "GdxSymbol({},{},{},file={},index={},description={},variable_type={},equation_type={})".format( repr(self.name), repr(self.data_type), repr(self.dims), repr(self.file), repr(self.index), repr(self.description), repr(self.variable_type), repr(self.equation_type)) def __str__(self): s = self.name s += ", " + self.description s += ", " + self.full_typename s += ", {} records".format(self.num_records) s += ", {} dims {}".format(self.num_dims, self.dims) s += ", loaded" if self.loaded else ", not loaded" return s def load(self): if self.loaded: logger.info("Nothing to do. Symbol already loaded.") return if not self.file: raise Error("Cannot load {} because there is no file pointer".format(repr(self))) if not self.index: raise Error("Cannot load {} because there is no symbol index".format(repr(self))) if self.data_type == GamsDataType.Parameter and HAVE_GDX2PY: self.dataframe = gdx2py.par2list(self.file.filename,self.name) self._loaded = True return _ret, records = gdxcc.gdxDataReadStrStart(self.file.H,self.index) def reader(): handle = self.file.H for i in range(records): yield gdxcc.gdxDataReadStr(handle) vc = self.value_cols # do this for speed in the next line data = [elements + [values[col_ind] for col_name, col_ind in vc] for ret, elements, values, afdim in reader()] # gdxdict called gdxGetElemText here, but I do not currently see value in doing that self.dataframe = data if not self.data_type == GamsDataType.Set: self.dataframe = special.convert_gdx_to_np_svs(self.dataframe, self.num_dims) self._loaded = True return def unload(self): self.dataframe = None self._loaded = False def write(self,index=None): if not self.loaded: raise Error("Cannot write unloaded symbol {}.".format(repr(self.name))) if self.data_type == GamsDataType.Set: self._fixup_set_value() if index is not None: self._index = index if self.index == 0: # universal set gdxcc.gdxUELRegisterRawStart(self.file.H) gdxcc.gdxUELRegisterRaw(self.file.H,self.name) gdxcc.gdxUELRegisterDone(self.file.H) return # write the data userinfo = 0 if self.variable_type is not None: userinfo = self.variable_type.value elif self.equation_type is not None: userinfo = self.equation_type.value if not gdxcc.gdxDataWriteStrStart(self.file.H, self.name, self.description, self.num_dims, self.data_type.value, userinfo): raise GdxError(self.file.H,"Could not start writing data for symbol {}".format(repr(self.name))) # set domain information if self.num_dims > 0: if self.index: if not gdxcc.gdxSymbolSetDomainX(self.file.H,self.index,self.dims): raise GdxError(self.file.H,"Could not set domain information for {}. Domains are {}".format(repr(self.name),repr(self.dims))) else: logger.info("Not writing domain information because symbol index is unknown.") values = gdxcc.doubleArray(gdxcc.GMS_VAL_MAX) # make sure index is clean -- needed for merging in convert_np_to_gdx_svs self.dataframe = self.dataframe.reset_index(drop=True) for row in special.convert_np_to_gdx_svs(self.dataframe, self.num_dims).itertuples(index=False, name=None): dims = [str(x) for x in row[:self.num_dims]] vals = row[self.num_dims:] for _col_name, col_ind in self.value_cols: values[col_ind] = float(0.0) try: if isinstance(vals[col_ind],Number): values[col_ind] = float(vals[col_ind]) except: raise Error("Unable to set element {} from {}.".format(col_ind,vals)) gdxcc.gdxDataWriteStr(self.file.H,dims,values) gdxcc.gdxDataWriteDone(self.file.H) return # ------------------------------------------------------------------------------ # Helper functions # ------------------------------------------------------------------------------ def append_set(gdx_file, set_name, df, cols=None, dim_names=None, description=None): """ Convenience function that appends set_name to gdx_file as a :class:`GamsDataType.Set <GamsDataType>` :class:`GdxSymbol` using data in df. Parameters ---------- gdx_file : :class:`GdxFile` file to which new :class:`GdxSymbol` is to be added set_name : str name of the :class:`GdxSymbol` to be added df : pandas.DataFrame dataframe or data that can be used to construct a dataframe containing the set data. assumes that all columns define dimensions (there is no 'Value' column) cols : None or list of str if not None, these are the columns in df to be used for the set definition dim_names : None or list of str if provided, the columns of a copy of df (or of df[cols]) will be renamed to these names, because the dimension names are taken from the final dataframe, these will also be the dimension names description : None or str passed directly to :class:`GdxSymbol` """ # ensure df is DataFrame and not Series logger.debug(f"Defining set {set_name!r} based on:\n{df!r}") tmp = pds.DataFrame(df) # select down to data we actually want if cols is not None: tmp = tmp[cols] if dim_names is not None: if tmp.empty: tmp = pds.DataFrame([], columns = dim_names) else: tmp.columns = dim_names # define the symbol gdx_file.append(GdxSymbol(set_name, GamsDataType.Set, dims = list(tmp.columns), description = description)) # define the data for the symbol gdx_file[-1].dataframe = tmp # debug description of what happened logger.debug(f"Added set {set_name!r} to {gdx_file!r} using processed data:\n{tmp!r}") return def append_parameter(gdx_file, param_name, df, cols=None, dim_names=None, description=None): """ Convenience function that appends param_name to gdx_file as a :class:`GamsDataType.Parameter <GamsDataType>` :class:`GdxSymbol` using data in df. Parameters ---------- gdx_file : :class:`GdxFile` file to which new :class:`GdxSymbol` is to be added param_name : str name of the :class:`GdxSymbol` to be added df : pandas.DataFrame dataframe or data that can be used to construct a dataframe containing the parameter data. assumes that the last selected column is the 'Value' column cols : None or list of str if not None, these are the columns in df to be used for the parameter definition dim_names : None or list of str if provided, the columns of a copy of df (or of df[cols]) will be renamed to these names + ['Value']. because the dimension names are taken from the final dataframe, these will also be the dimension names description : None or str passed directly to :class:`GdxSymbol` """ # pre-process the data logger.debug(f"Defining parameter {param_name!r} based on:\n{df!r}") tmp = pds.DataFrame(df) if cols is not None: tmp = tmp[cols] if dim_names is not None: if tmp.empty: tmp = pds.DataFrame([], columns = dim_names + ['Value']) else: tmp.columns = dim_names + ['Value'] # define the symbol gdx_file.append(GdxSymbol(param_name, GamsDataType.Parameter, dims = list(tmp.columns)[:-1], description = description)) # define the data for the symbol gdx_file[-1].dataframe = tmp # debug descripton of what happened logger.debug(f"Added parameter {param_name!r} to {gdx_file!r} using processed data:\n{tmp!r}") return <file_sep>/gdxpds/test/test_specials.py # [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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. # # 3. Neither the name of the copyright holder nor 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 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. # [/LICENSE] import logging import os import subprocess as subp import gdxpds.gdx import gdxpds.special from gdxpds.test import base_dir, run_dir from gdxpds.test.test_session import manage_rundir from gdxpds.test.test_conversions import roundtrip_one_gdx import gdxcc import numpy as np import pandas as pds import pytest logger = logging.getLogger(__name__) def value_column_index(sym,gams_value_type): for i, val in enumerate(sym.value_cols): if val[1] == gams_value_type.value: break return len(sym.dims) + i def test_roundtrip_just_special_values(manage_rundir): outdir = os.path.join(run_dir,'special_values') if not os.path.exists(outdir): os.mkdir(outdir) # create gdx file containing all special values with gdxpds.gdx.GdxFile() as f: df = pds.DataFrame([['sv' + str(i+1), gdxpds.special.SPECIAL_VALUES[i]] for i in range(gdxcc.GMS_SVIDX_MAX-2)], columns=['sv','Value']) logger.info("Special values are:\n{}".format(df)) # save this directly as a GdxSymbol filename = os.path.join(outdir,'direct_write_special_values.gdx') ret = gdxcc.gdxOpenWrite(f.H,filename,"gdxpds") if not ret: raise gdxpds.gdx.GdxError(f.H,"Could not open {} for writing. Consider cloning this file (.clone()) before trying to write".format(repr(filename))) # write the universal set f.universal_set.write() if not gdxcc.gdxDataWriteStrStart(f.H, 'special_values', '', 1, gdxpds.gdx.GamsDataType.Parameter.value, 0): raise gdxpds.gdx.GdxError(f.H,"Could not start writing data for symbol special_values") # set domain information if not gdxcc.gdxSymbolSetDomainX(f.H,1,[df.columns[0]]): raise gdxpds.gdx.GdxError(f.H,"Could not set domain information for special_values.") values = gdxcc.doubleArray(gdxcc.GMS_VAL_MAX) for row in df.itertuples(index=False,name=None): dims = [str(x) for x in row[:1]] vals = row[1:] for _col_name, col_ind in gdxpds.gdx.GAMS_VALUE_COLS_MAP[gdxpds.gdx.GamsDataType.Parameter]: values[col_ind] = float(vals[col_ind]) gdxcc.gdxDataWriteStr(f.H,dims,values) gdxcc.gdxDataWriteDone(f.H) gdxcc.gdxClose(f.H) # general test for expected values def check_special_values(gdx_file): df = gdx_file['special_values'].dataframe for i, val in enumerate(df['Value'].values): assert gdxpds.special.pd_val_equal(val, gdxpds.special.NUMPY_SPECIAL_VALUES[i]) # now roundtrip it gdx-only with gdxpds.gdx.GdxFile(lazy_load=False) as f: f.read(filename) check_special_values(f) with f.clone() as g: rt_filename = os.path.join(outdir,'roundtripped.gdx') g.write(rt_filename) with gdxpds.gdx.GdxFile(lazy_load=False) as g: g.read(filename) check_special_values(g) # now roundtrip it through csv roundtripped_gdx = roundtrip_one_gdx(filename,'roundtrip_just_special_values') with gdxpds.gdx.GdxFile(lazy_load=False) as h: h.read(roundtripped_gdx) check_special_values(h) def test_roundtrip_special_values(manage_rundir): filename = 'OptimalCSPConfig_Out.gdx' original_gdx = os.path.join(base_dir,filename) roundtripped_gdx = roundtrip_one_gdx(filename,'roundtrip_special_values') data = [] for gdx_file in [original_gdx, roundtripped_gdx]: with gdxpds.gdx.GdxFile(lazy_load=False) as gdx: data.append([]) gdx.read(gdx_file) sym = gdx['calculate_capacity_value'] assert sym.data_type == gdxpds.gdx.GamsDataType.Equation val = sym.dataframe.iloc[0,value_column_index(sym,gdxpds.gdx.GamsValueType.Marginal)] assert gdxpds.special.is_np_sv(val) data[-1].append(val) sym = gdx['CapacityValue'] assert sym.data_type == gdxpds.gdx.GamsDataType.Variable val = sym.dataframe.iloc[0,value_column_index(sym,gdxpds.gdx.GamsValueType.Upper)] assert gdxpds.special.is_np_sv(val) data[-1].append(val) data = list(zip(*data)) for pt in data: for i in range(1,len(pt)): assert (pt[i] == pt[0]) or (np.isnan(pt[i]) and np.isnan(pt[0])) def test_special_integrity(): """ Check that the special values line up """ assert all(sv in gdxpds.special.GDX_TO_NP_SVS for sv in gdxpds.special.SPECIAL_VALUES) assert all(sv in gdxpds.special.NP_TO_GDX_SVS for sv in gdxpds.special.NUMPY_SPECIAL_VALUES) for val in gdxpds.special.SPECIAL_VALUES: assert gdxpds.special.NP_TO_GDX_SVS[gdxpds.special.GDX_TO_NP_SVS[val]] == val for val in gdxpds.special.NUMPY_SPECIAL_VALUES: # Can't use "==", as None != NaN assert gdxpds.special.pd_val_equal(gdxpds.special.GDX_TO_NP_SVS[gdxpds.special.NP_TO_GDX_SVS[val]], val) def test_numpy_eps(): assert(gdxpds.special.is_np_eps(np.finfo(float).eps)) assert(not gdxpds.special.is_np_eps(float(0.0))) assert(not gdxpds.special.is_np_eps(2.0 * np.finfo(float).eps)) <file_sep>/gdxpds/tools.py # [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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. # # 3. Neither the name of the copyright holder nor 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 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. # [/LICENSE] import logging import os import subprocess as subp import re logger = logging.getLogger(__name__) class Error(Exception): """ Base class for all Exceptions raised by this package. """ class GamsDirFinder(object): """ Class for finding and accessing the system's GAMS directory. The find function first looks for the 'GAMS_DIR' environment variable. If that is unsuccessful, it next uses 'which gams' for POSIX systems, and the default install location, 'C:/GAMS', for Windows systems. In the latter case it prefers the largest version number. You can always specify the GAMS directory directly, and this class will attempt to clean up your input. (Even on Windows, the GAMS path must use '/' rather than '\'.) """ gams_dir_cache = None def __init__(self,gams_dir=None): self.gams_dir = gams_dir @property def gams_dir(self): """The GAMS directory on this system.""" if self.__gams_dir is None: raise RuntimeError("Unable to locate your GAMS directory.") return self.__gams_dir @gams_dir.setter def gams_dir(self, value): self.__gams_dir = None if isinstance(value, str): self.__gams_dir = self.__clean_gams_dir(value) elif value is not None: logger.warning(f"Unexpected gams_dir type {type(value)}. Ignoring " f"input {value!r} because it is not a str.") if self.__gams_dir is None: self.__gams_dir = self.__find_gams() def __clean_gams_dir(self,value): """ Cleans up the path string. """ if value is None: return None assert(isinstance(value, str)) ret = os.path.realpath(value) if not os.path.exists(ret): return None ret = re.sub('\\\\','/',ret) return ret def __find_gams(self): """ For all systems, the first place we examine is the GAMS_DIR environment variable, and the second is GAMSDIR. For Windows, the next step is to try 'where gams'. Then we look in the default install location (C:/GAMS), preferring win64 to win32 and the most recent version. For all others, the next step is 'which gams'. Returns ------- str or None If not None, the return value is the found gams_dir """ # check for environment variable ret = os.environ.get('GAMS_DIR') ret = self.__clean_gams_dir(ret) if ret is None: ret = os.environ.get('GAMSDIR') ret = self.__clean_gams_dir(ret) if ret is None and os.name == 'nt': # windows systems try: ret = os.path.dirname(subp.check_output(['where', 'gams']).decode().split("\n")[0]) except: ret = None ret = self.__clean_gams_dir(ret) if ret is None and os.name == 'nt': # search in default installation location cur_dir = r'C:\GAMS' if os.path.exists(cur_dir): # level 1 - prefer win64 to win32 for _p, dirs, _files in os.walk(cur_dir): if 'win64' in dirs: cur_dir = os.path.join(cur_dir, 'win64') elif len(dirs) > 0: cur_dir = os.path.join(cur_dir, dirs[0]) else: return ret break if os.path.exists(cur_dir): # level 2 - prefer biggest number (most recent version) for _p, dirs, _files in os.walk(cur_dir): if len(dirs) > 1: try: versions = [float(x) for x in dirs] ret = os.path.join(cur_dir, "{}".format(max(versions))) except: ret = os.path.join(cur_dir, dirs[0]) elif len(dirs) > 0: ret = os.path.join(cur_dir, dirs[0]) break ret = self.__clean_gams_dir(ret) if ret is None and os.name != 'nt': # posix systems try: ret = os.path.dirname(subp.check_output(['which', 'gams'])).decode() except: ret = None ret = self.__clean_gams_dir(ret) if ret is not None: GamsDirFinder.gams_dir_cache = ret if ret is None: logger.debug(f"Did not find GAMS directory. Using cached value {self.gams_dir_cache}.") ret = GamsDirFinder.gams_dir_cache return ret class NeedsGamsDir(object): """ Mix-in class that asserts that a GAMS directory is needed and provides the methods required to find and access it. Attributes ---------- gams_dir : str The GAMS directory whose value has either been directly set or has been found using the GamsDirFinder class. """ def __init__(self,gams_dir=None): self.gams_dir = gams_dir @property def gams_dir(self): return self.__gams_dir @gams_dir.setter def gams_dir(self, value): self.__gams_dir = GamsDirFinder(value).gams_dir <file_sep>/gdxpds/test/__init__.py # [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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. # # 3. Neither the name of the copyright holder nor 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 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. # [/LICENSE] import os # if True, test products will be deleted on tear down clean_up = True base_dir = os.path.dirname(__file__) run_dir = os.path.join(base_dir, 'output') def apply_dirname(f, num_times): ret = f for _i in range(num_times): ret = os.path.dirname(ret) return ret bin_prefix = '' # git repo (development) candidate = os.path.join(apply_dirname(__file__,3), 'bin') if os.path.isdir(candidate) and os.path.isfile(os.path.join(candidate,'gdx_to_csv.py')): bin_prefix = candidate # anaconda set-up candidate = os.path.join(apply_dirname(__file__,6), 'bin') if os.path.isdir(candidate) and os.path.isfile(os.path.join(candidate,'gdx_to_csv.py')): bin_prefix = candidate # install location for Windows candidate = os.path.join(apply_dirname(__file__,5), 'Scripts') if bin_prefix == '' and os.path.isdir(candidate) and os.path.isfile(os.path.join(candidate,'gdx_to_csv.py')): bin_prefix = candidate # install location for Linux candidate = os.path.join('/','usr','local','bin') if bin_prefix == '' and os.path.isdir(candidate) and os.path.isfile(os.path.join(candidate,'gdx_to_csv.py')): bin_prefix = candidate <file_sep>/gdxpds/test/test_session.py # [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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. # # 3. Neither the name of the copyright holder nor 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 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. # [/LICENSE] import os import shutil import pytest from gdxpds.test import run_dir STARTUP = True @pytest.fixture(scope="session",autouse=True) def manage_rundir(request, clean_up): """ At the beginning of the session, creates the test run_dir. If test.clean_up, deletes this folder after the tests have finished running. Arguments - request contains the pytest session, including collected tests """ global STARTUP if STARTUP: if os.path.exists(run_dir): # create clean space for running tests shutil.rmtree(run_dir) STARTUP = False os.mkdir(run_dir) def finalize_rundir(): if os.path.exists(run_dir) and clean_up: shutil.rmtree(run_dir) request.addfinalizer(finalize_rundir) <file_sep>/gdxpds/test/test_read.py # [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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. # # 3. Neither the name of the copyright holder nor 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 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. # [/LICENSE] import logging import os import pytest import gdxpds.gdx from gdxpds import to_dataframes from gdxpds.test import base_dir logger = logging.getLogger(__name__) def test_read(): filename = 'all_generator_properties_input.gdx' gdx_file = os.path.join(base_dir,filename) with gdxpds.gdx.GdxFile() as f: f.read(gdx_file) for symbol in f: symbol.load() def test_read_none(): with pytest.raises(gdxpds.gdx.GdxError) as excinfo: to_dataframes(None) assert "Could not open None" in str(excinfo.value) def test_read_path(): filename = 'all_generator_properties_input.gdx' from pathlib import Path gdx_file = Path(base_dir) / filename to_dataframes(gdx_file) def test_unload(): filename = 'all_generator_properties_input.gdx' gdx_file = os.path.join(base_dir,filename) with gdxpds.gdx.GdxFile() as f: f.read(gdx_file) assert not f['startupfuel'].loaded assert f['startupfuel'].dataframe.empty f['startupfuel'].load() assert f['startupfuel'].loaded assert not f['startupfuel'].dataframe.empty assert 'CC' in f['startupfuel'].dataframe['*'].tolist() f['startupfuel'].unload() assert not f['startupfuel'].loaded assert f['startupfuel'].dataframe.empty f['startupfuel'].load() assert f['startupfuel'].loaded assert not f['startupfuel'].dataframe.empty assert 'CC' in f['startupfuel'].dataframe['*'].tolist() <file_sep>/README.txt gdx-pandas: Python package to translate between gdx (GAMS data) and pandas. There are two main ways to use gdxpds. The first use case is the one that was initially supported: direct conversion between GDX files on disk and pandas DataFrames or a csv version thereof. Starting with the Version 1.0.0 rewrite, there is now a second style of use which involves interfacing with GDX files and symbols via the `gdxpds.gdx.GdxFile` and `gdxpds.gdx.GdxSymbol` classes. Please visit https://nrel.github.io/gdx-pandas for the latest documentation. DEPENDENCIES - Python 3.4 or 3.6 (gdx-pandas support for Python 2.X has been discontinued; GAMS does not yet support Python 3.7) - pandas (In general you will want the SciPy stack. Anaconda comes with it, or see [my notes for Windows](https://elainethale.wordpress.com/programming-notes/python-environment-set-up/).) - For Python versions < 3.4, enum34. Also **uninstall the enum package** if it is installed. - Install [GAMS](https://www.gams.com/download/) - Put the GAMS directory in your `PATH` and/or assign it to the `GAMS_DIR` environment variable - GAMS Python bindings - See GAMS/win64/XX.X/apifiles/readme.txt on Windows, GAMS/gamsXX.X_osx_x64_64_sfx/apifiles/readme.txt on Mac, or /opt/gams/gamsXX.X_linux_x64_64_sfx/apifiles/readme.txt on Linux - Run the following for the correct version of the Python bindings ```bash python setup.py install ``` or ```bash python setup.py build --build-base=/path/to/somwhere/you/have/write/access install ``` with the latter being for the case when you can install packages into Python but don't have GAMS directory write access. - For Python 3.X, use .../apifiles/Python/api_XX/setup.py. For Python 3.X in particular you will need GAMS version >= 24.5.1 (Python 3.4, Windows and Linux), 24.7.4 (Python 3.4, Mac OS X), or >= 24.8.4 (Python 3.6) TESTING After installation, you can test the package using pytest: pytest --pyargs gdxpds If the tests fail due to permission IOErrors, apply `chmod g+x` and `chmod a+x` to the `gdx-pandas/gdxpds/test` folder. <file_sep>/README.md # gdx-pandas [![PyPI](https://img.shields.io/pypi/v/gdxpds.svg)](https://pypi.python.org/pypi/gdxpds/) [![Documentation](https://img.shields.io/badge/docs-ready-blue.svg)](https://nrel.github.io/gdx-pandas) gdx-pandas is a python package to translate between gdx (GAMS data) and pandas. [Install](#install) | [Documentation](https://nrel.github.io/gdx-pandas) | [Uninstall](#uninstall) ## Install ### Preliminaries - Python 3.4 or 3.6 (gdx-pandas support for Python 2.X has been discontinued; GAMS does not yet support Python 3.7) - pandas (In general you will want the SciPy stack. Anaconda comes with it, or see [my notes for Windows](https://elainethale.wordpress.com/programming-notes/python-environment-set-up/).) - For Python versions < 3.4, enum34. Also **uninstall the enum package** if it is installed. - Install [GAMS](https://www.gams.com/download/) - Put the GAMS directory in your `PATH` and/or assign it to the `GAMS_DIR` environment variable - GAMS Python bindings - See GAMS/win64/XX.X/apifiles/readme.txt on Windows, GAMS/gamsXX.X_osx_x64_64_sfx/apifiles/readme.txt on Mac, or /opt/gams/gamsXX.X_linux_x64_64_sfx/apifiles/readme.txt on Linux - Run the following for the correct version of the Python bindings ```bash python setup.py install ``` or ```bash python setup.py build --build-base=/path/to/somwhere/you/have/write/access install ``` with the latter being for the case when you can install packages into Python but don't have GAMS directory write access. - For Python 3.X, use .../apifiles/Python/api_XX/setup.py. For Python 3.X in particular you will need GAMS version >= 24.5.1 (Python 3.4, Windows and Linux), 24.7.4 (Python 3.4, Mac OS X), or >= 24.8.4 (Python 3.6) ### Get the Latest Package ```bash pip install gdxpds ``` or ```bash pip install git+https://github.com/NREL/gdx-pandas.git@v1.2.0 ``` or ```bash pip install git+https://github.com/NREL/gdx-pandas.git@master ``` Versions are listed at [pypi](https://pypi.python.org/pypi/gdxpds/) and https://github.com/NREL/gdx-pandas/releases. After installation, you can test the package using pytest: ```bash pytest --pyargs gdxpds ``` If the tests fail due to permission IOErrors, apply `chmod g+x` and `chmod a+x` to the `gdx-pandas/gdxpds/test` folder. ## Uninstall ``` pip uninstall gdxpds ``` <file_sep>/setup.py # [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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. # # 3. Neither the name of the copyright holder nor 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 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. # [/LICENSE] from distutils.core import setup import os here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'gdxpds', '_version.py'), encoding='utf-8') as f: version = f.read() version = version.split()[2].strip('"').strip("'") setup( name = 'gdxpds', version = version, author = '<NAME>', author_email = '<EMAIL>.gov', packages = ['gdxpds', 'gdxpds.test'], scripts = ['bin/csv_to_gdx.py', 'bin/gdx_to_csv.py'], url = 'https://github.com/NREL/gdx-pandas', description = 'Python package to translate between gdx (GAMS data) and pandas.', long_description=open('README.txt').read(), package_data={ 'gdxpds.test': ['*.csv','*.gdx'] }, install_requires=open('requirements.txt').read() )
36b31ba0d79ff5559df92e52b711bdfa6cdd42d1
[ "Markdown", "Python", "Text" ]
15
Text
zjy243352154/gdx-pandas
24dae4f17e53d29fbac76bbff4b9febff19dae04
958574dd8bebb4ebc515704ef433e09559e6186a
refs/heads/master
<repo_name>nibalizer/inaugust.com<file_sep>/src/js/task-report.js $.fn.graphite.defaults.url = "http://graphite.openstack.org/render/"; tasks = [ 'CreateServer', 'DeleteServer', 'ListServers' ]; float_tasks = [ 'AddFloatingIP', 'CreateFloatingIP', 'DeleteFloatingIP', 'GetFloatingIP', 'ListFloatingIPs' ] big_providers = [ 'hpcloud', 'rax', ] small_providers = [ 'bluebox', 'ovh' ] jobs = [ 'gate-tempest-dsvm-full', 'gate-tempest-dsvm-neutron-full' ] for(i=0; i<tasks.length; ++i) { $("#graph-container").append($(new Image()).addClass('graph').graphite({ from: "-72hours", width: 885, height: 495, bgcolor: 'ffffff', fgcolor: '000000', lineMode: 'connected', vtitle: 'Time in Seconds', title: tasks[i], target: [ "alias(scale(averageSeries(stats.timers.nodepool.task.hpcloud-b*." + tasks[i] + "Task.mean), '0.001'), 'HP')", "alias(scale(averageSeries(stats.timers.nodepool.task.bluebox-sjc1." + tasks[i] + "Task.mean), '0.001'), 'BB')", "alias(scale(averageSeries(stats.timers.nodepool.task.ovh-gra1." + tasks[i] + "Task.mean), '0.001'), 'OVH')", "alias(scale(averageSeries(stats.timers.nodepool.task.rax-*." + tasks[i] + "Task.mean), '0.001'), 'RAX')", ] })); } for(i=0; i<float_tasks.length; ++i) { $("#graph-container").append($(new Image()).addClass('graph').graphite({ from: "-72hours", width: 885, height: 495, bgcolor: 'ffffff', fgcolor: '000000', lineMode: 'connected', vtitle: 'Time in Seconds', yMax: '10', title: float_tasks[i], target: [ "alias(scale(averageSeries(stats.timers.nodepool.task.hpcloud-b*." + float_tasks[i] + "Task.mean), '0.001'), 'HP')", "alias(scale(averageSeries(stats.timers.nodepool.task.bluebox-sjc1." + float_tasks[i] + "Task.mean), '0.001'), 'BB')", ] })); } for(i=0; i<big_providers.length; ++i) { $("#graph-container").append($(new Image()).addClass('graph').graphite({ from: "-72hours", width: 885, height: 495, bgcolor: 'ffffff', fgcolor: '000000', areaMode: 'stacked', yMax: '800', title: big_providers[i] + " nodes launched", target: [ "color(alias(summarize(sumSeries(stats_counts.nodepool.launch.provider." + big_providers[i] + "*.ready), '1h'), 'Ready'), '00ff22')", "color(alias(summarize(sumSeries(stats_counts.nodepool.launch.provider." + big_providers[i] + "*.error.*), '1h'), 'Error'), 'ff0000')" ] })); } for(i=0; i<small_providers.length; ++i) { $("#graph-container").append($(new Image()).addClass('graph').graphite({ from: "-72hours", width: 885, height: 495, bgcolor: 'ffffff', fgcolor: '000000', areaMode: 'stacked', yMax: '60', title: small_providers[i] + " nodes launched", target: [ "color(alias(summarize(sumSeries(stats_counts.nodepool.launch.provider." + small_providers[i] + "*.ready), '1h'), 'Ready'), '00ff22')", "color(alias(summarize(sumSeries(stats_counts.nodepool.launch.provider." + small_providers[i] + "*.error.*), '1h'), 'Error'), 'ff0000')" ] })); } for(i=0; i<jobs.length; ++i) { $("#graph-container").append($(new Image()).addClass('graph').graphite({ from: "-72hours", width: 885, height: 495, bgcolor: 'ffffff', fgcolor: '000000', lineMode: 'connected', vtitle: 'Time in Minute', yMax: '90', title: jobs[i] + ' job runtime', target: [ "alias(scale(averageSeries(stats.timers.nodepool.job." + jobs[i] + ".master.*.hpcloud-b*.runtime.mean), '0.000016'), 'HP')", "alias(scale(averageSeries(stats.timers.nodepool.job." + jobs[i] + ".master.*.bluebox-sjc1.runtime.mean), '0.000016'), 'BB')", "alias(scale(averageSeries(stats.timers.nodepool.job." + jobs[i] + ".master.*.ovh-gra1.runtime.mean), '0.000016'), 'OVH')", "alias(scale(averageSeries(stats.timers.nodepool.job." + jobs[i] + ".master.*.rax-*.runtime.mean), '0.000016'), 'RAX')", ] })); } $("#graph-container").append($(new Image()).addClass('graph').graphite({ from: "-72hours", width: 885, height: 495, bgcolor: 'ffffff', fgcolor: '000000', lineMode: 'connected', vtitle: 'Time in Minutes', title: 'Time to SSH Ready', target: [ "alias(scale(averageSeries(stats.timers.nodepool.launch.provider.hpcloud-b*.ready.mean), '0.000016'), 'HP')", "alias(scale(averageSeries(stats.timers.nodepool.launch.provider.bluebox-sjc1.ready.mean), '0.000016'), 'BB')", "alias(scale(averageSeries(stats.timers.nodepool.launch.provider.ovh-gra1.ready.mean), '0.000016'), 'OVH')", "alias(scale(averageSeries(stats.timers.nodepool.launch.provider.rax-*.ready.mean), '0.000016'), 'RAX')", ] }));
014f8e8e470a4373919f9a73aefeef1b70147552
[ "JavaScript" ]
1
JavaScript
nibalizer/inaugust.com
1b482f692a7a0c0a9d8fc5f17eafff501f11ab32
8c4fb251b5def1e673a87e331387f5bb37a012ab
refs/heads/master
<repo_name>MGUltra/CS290<file_sep>/Assignment4/script.js /*************************************************************** * Name: <NAME> * Date: 10/30/2016 * Class: CS290 - Web Development * HW Assignment: DOM and Events * Description: ****************************************************************/ /****************** TABLE AND BUTTON CONSTRUCTORS *************************/ /****************************************************************** * Function name: createTable * paremeters: none * description: This function creates a 4x4 table with 1 header row * and three additional rows. A nested loop is used to apply text to the * cells in the table. * ****************************************************************/ function createTable() { var docB = document.body; // create table var table = document.createElement('table'); // create table body var tableB = document.createElement('tbody'); // create header row var tRow = document.createElement('tr'); for(var i = 0; i < 4; i++) { var headerCell = document.createElement('th'); var headerText = document.createTextNode("Header " + (i + 1)); // append text node to cell headerCell.appendChild(headerText); // append cell to table row tRow.appendChild(headerCell); } // append header row to table body tableB.appendChild(tRow); // create additional rows for(var x = 0; x < 3; x++) { var nextRow = document.createElement('tr'); for(var y = 0; y < 4; y++) { var nextCell = document.createElement('td'); var cellText = document.createTextNode((y+1) + ', ' + (x+1)); // give each cell a unique ID based on coordinates var cellTextId = (y+1) + ', ' + (x+1); // set attribute id nextCell.setAttribute('id', cellTextId); // append text node to cell nextCell.appendChild(cellText); // append cell to table row nextRow.appendChild(nextCell); } // append row to table body tableB.appendChild(nextRow); } // apend table body to table table.appendChild(tableB); // apend table to document body docB.appendChild(table); // set table border attribute table.setAttribute("border", "1px"); } /****************************************************************** * Function name: createButtons * paremeters: none * description: This function creates elements for each directional * as well as mark cell button. The elements are created, assigned ids, * given text nodes for labels, and then appended to the document body. * ****************************************************************/ function createButtons() { // create elemenets var moveCellUp = document.createElement("button"); var moveCellDown = document.createElement("button"); var moveCellLeft = document.createElement("button"); var moveCellRight = document.createElement("button"); var markCell = document.createElement("button"); // assign ids moveCellUp.id = "moveUp"; moveCellDown.id = "moveDown"; moveCellLeft.id = "moveLeft"; moveCellRight.id = "moveRight"; markCell.id = "markCell"; // create text nodes var moveCellUpText = document.createTextNode("Up"); var moveCellDownText = document.createTextNode("Down"); var moveCellLeftText = document.createTextNode("Left"); var moveCellRightText = document.createTextNode("Right"); var markCellText = document.createTextNode("Mark Cell"); // append text nodes moveCellUp.appendChild(moveCellUpText); moveCellDown.appendChild(moveCellDownText); moveCellLeft.appendChild(moveCellLeftText); moveCellRight.appendChild(moveCellRightText); markCell.appendChild(markCellText); // append button elements to document body document.body.appendChild(moveCellUp); document.body.appendChild(moveCellDown); document.body.appendChild(moveCellLeft); document.body.appendChild(moveCellRight); document.body.appendChild(markCell); } /************** MOVEMENT AND TABLE INTERACTION FUNCTIONS ************/ /****************************************************************** * Function name: moveCellUp * paremeters: none * description: This function is used to move up one cell. The current * location is retrieved using the element id and the global variables * for the current column and rows. A call to edgeCheck is made to verify * if a move up is possible. the border style of the current cell is reverted * to match the others and the border style of the new cell is widened. The * global variable is updated accordingly. * ****************************************************************/ function moveCellUp() { var curLoc = document.getElementById(currentColumn +", " + currentRow); if(edgeCheck("up") == false) { return; } else { curLoc.style.borderWidth = "1px"; currentRow -= 1; var newLoc = document.getElementById(currentColumn +", " + currentRow); newLoc.style.borderWidth = "3px"; } } /****************************************************************** * Function name: moveCellDown * paremeters: * description: This function is used to move down one cell. The current * location is retrieved using the element id and the global variables * for the current column and rows. A call to edgeCheck is made to verify * if a move up is possible. the border style of the current cell is reverted * to match the others and the border style of the new cell is widened. The * global variable is updated accordingly. * ****************************************************************/ function moveCellDown() { var curLoc = document.getElementById(currentColumn +", " + currentRow); if(edgeCheck("down") == false) { return; } else { curLoc.style.borderWidth = "1px"; currentRow += 1; var newLoc = document.getElementById(currentColumn +", " + currentRow); newLoc.style.borderWidth = "3px"; } } /****************************************************************** * Function name: moveCellLeft * paremeters: none * description: This function is used to move left one cell. The current * location is retrieved using the element id and the global variables * for the current column and rows. A call to edgeCheck is made to verify * if a move up is possible. the border style of the current cell is reverted * to match the others and the border style of the new cell is widened. The * global variable is updated accordingly. * ****************************************************************/ function moveCellLeft() { var curLoc = document.getElementById(currentColumn +", " + currentRow); if(edgeCheck("left") == false) { return; } else { curLoc.style.borderWidth = "1px"; currentColumn -= 1; var newLoc = document.getElementById(currentColumn +", " + currentRow); newLoc.style.borderWidth = "3px"; } } /****************************************************************** * Function name: moveCellRight * paremeters: none * description: This function is used to move right one cell. The current * location is retrieved using the element id and the global variables * for the current column and rows. A call to edgeCheck is made to verify * if a move up is possible. the border style of the current cell is reverted * to match the others and the border style of the new cell is widened. The * global variable is updated accordingly. * ****************************************************************/ function moveCellRight() { var curLoc = document.getElementById(currentColumn +", " + currentRow); if(edgeCheck("right") == false) { return; } else { curLoc.style.borderWidth = "1px"; currentColumn += 1; var newLoc = document.getElementById(currentColumn +", " + currentRow); newLoc.style.borderWidth = "3px"; } } /****************************************************************** * Function name: markCell * paremeters: none * description: The current cell is retrieved through its id. The * background color is then changed to yellow. * ****************************************************************/ function markCell() { var curLoc = document.getElementById(currentColumn +", " + currentRow); curLoc.style.backgroundColor = "yellow"; } /****************************************************************** * Function name: edgeCheck * paremeters: direction * description: * ****************************************************************/ function edgeCheck(direction) { if(direction == "up") { if(currentRow == 1) { return false; } else { return true; } } else if(direction == "down") { if(currentRow == 3) { return false; } else { return true; } } else if(direction == "left") { if(currentColumn == 1) { return false; } else { return true; } } else if(direction == "right") { if(currentColumn == 4) { return false; } else { return true; } } } // global location Variables var currentRow = 1; var currentColumn = 1; // Call Constructors createTable(); createButtons(); // Initialize a current cell var startingLocation = document.getElementById("1, 1"); startingLocation.style.borderWidth = "3px"; // initialize buttons document.getElementById("moveUp").addEventListener("click", moveCellUp); document.getElementById("moveDown").addEventListener("click", moveCellDown); document.getElementById("moveLeft").addEventListener("click", moveCellLeft); document.getElementById("moveRight").addEventListener("click", moveCellRight); document.getElementById("markCell").addEventListener("click", markCell); <file_sep>/README.md # CS290 CS290 - Web Development <file_sep>/Assignment2/objects.js // Name: <NAME> // Date: 10/16/16 // Description: CS290 - Activity: JS Objects function deepEqual(objectA, objectB) { // test if both parameters are objects and not null values if((typeof(objectA) == "object") && (typeof(objectB) == "object") && (objectA != null) && (objectB != null)) { // if they are both objects, test each property of the objects // create variables for the amount of properties in each object var sizeObjectA = 0; var sizeObjectB = 0; // count the amount of properties in each object, increment sizes for properties in object // if property count differs, return false. for(var propA in objectA) { sizeObjectA++; } for(var propB in objectB) { sizeObjectB++; } if(sizeObjectA != sizeObjectB) { return false; } // get property names in arrays utilizing object.keys() var namesObjectA = object.keys(objectA); var namesObjectB = object.keys(objectB); // compare property names, return false is mismatch for(var i = 0, i < sizeObjectA; i++) { if(namesObjectA[i] != namesObjectB[i]) { return false; } } // compare properties with recursive call if names match for(var propA in objectA) { if(deepEqual(objectA[propA], objectA[propA]) == false) { return false; } } // if all tests are passed, return true return true; } else { // if parameters are not both objects and not both null, return result applying === return objectA === objectB; } }<file_sep>/Assignment3/automobile.js /*************************************************************** * Name: <NAME> * Date: 10/23/2016 * Class: CS290 - Web Development * HW Assignment: Higher-Order Functions and Objects * Description: This program sorts the objects of the Automobile * class by their year, make, and type. That task is accomplished with * a sort function which takes an array of objects and a comparator * function as parameters. ****************************************************************/ function Automobile( year, make, model, type ){ this.year = year; //integer (ex. 2001, 1995) this.make = make; //string (ex. Honda, Ford) this.model = model; //string (ex. Accord, Focus) this.type = type; //string (ex. Pickup, SUV) Automobile.prototype.logMe = function(typeBool) { if(typeBool == true) { console.log(this.year + " " + this.make + " " + this.model + " " + this.type); } else { console.log(this.year + " " + this.make + " " + this.model); } } } var automobiles = [ new Automobile(1995, "Honda", "Accord", "Sedan"), new Automobile(1990, "Ford", "F-150", "Pickup"), new Automobile(2000, "GMC", "Tahoe", "SUV"), new Automobile(2010, "Toyota", "Tacoma", "Pickup"), new Automobile(2005, "Lotus", "Elise", "Roadster"), new Automobile(2008, "Subaru", "Outback", "Wagon") ]; /*This function sorts arrays using an arbitrary comparator. You pass it a comparator and an array of objects appropriate for that comparator and it will return a new array which is sorted with the largest object in index 0 and the smallest in the last index*/ function sortArr( comparator, array ){ /*your code here*/ var swapFlag = false; do{ swapFlag = false; for (var i = 0; i < array.length - 1; i++) { if(comparator(array[i], array[i+1]) == false) { var tempAuto = array[i]; array[i] = array[i + 1]; array[i + 1] = tempAuto; swapFlag = true; } } }while(swapFlag == true); } /*A comparator takes two arguments and uses some algorithm to compare them. If the first argument is larger or greater than the 2nd it returns true, otherwise it returns false. Here is an example that works on integers*/ function exComparator( int1, int2){ if (int1 > int2){ return true; } else { return false; } } /*For all comparators if cars are 'tied' according to the comparison rules then the order of those 'tied' cars is not specified and either can come first*/ /*This compares two automobiles based on their year. Newer cars are "greater" than older cars.*/ function yearComparator( auto1, auto2){ /* your code here*/ if(auto1.year > auto2.year) { return true; } else { return false; } } /*This compares two automobiles based on their make. It should be case insensitive and makes which are alphabetically earlier in the alphabet are "greater" than ones that come later.*/ function makeComparator( auto1, auto2){ /* your code here*/ if(auto1.make.toLowerCase() > auto2.make.toLowerCase()) { return false; } else { return true; } } /*This compares two automobiles based on their type. The ordering from "greatest" to "least" is as follows: roadster, pickup, suv, wagon, (types not otherwise listed). It should be case insensitive. If two cars are of equal type then the newest one by model year should be considered "greater".*/ function typeComparator( auto1, auto2){ /* your code here*/ // define function to get type of Automobile function getType(automobileType) { var typeFlag = 5; if(automobileType == "wagon") { typeFlag = 4; } else if(automobileType == "suv") { typeFlag = 3; } else if(automobileType == "pickup") { typeFlag = 2; } else if(automobileType == "roadster") { typeFlag = 1; } return typeFlag; } // Test for matching types, call exComparitor if match if(auto1.type.toLowerCase() == auto2.type.toLowerCase()) { return exComparator(auto1.year, auto2.year); } // Compare types of auto1 and auto2 var type1 = getType(auto1.type.toLowerCase()); var type2 = getType(auto2.type.toLowerCase()); if(type1 > type2) { return false; } else { return true; } } /*Your program should output the following to the console.log, including the opening and closing 5 stars. All values in parenthesis should be replaced with appropriate values. Each line is a seperate call to console.log. Each line representing a car should be produced via a logMe function. This function should be added to the Automobile class and accept a single boolean argument. If the argument is 'true' then it prints "year make model type" with the year, make, model and type being the values appropriate for the automobile. If the argument is 'false' then the type is ommited and just the "year make model" is logged. ***** The cars sorted by year are: (year make model of the 'greatest' car) (...) (year make model of the 'least' car) The cars sorted by make are: (year make model of the 'greatest' car) (...) (year make model of the 'least' car) The cars sorted by type are: (year make model type of the 'greatest' car) (...) (year make model type of the 'least' car) ***** As an example of the content in the parenthesis: 1990 Ford F-150 */ function printArray(sortedArray, typeBool) { for(var i = 0; i < sortedArray.length; i++) { sortedArray[i].logMe(typeBool); } } console.log('*****'); sortArr(yearComparator, automobiles); console.log('The cars sorted by year are:'); printArray(automobiles, false); console.log(''); sortArr(makeComparator, automobiles); console.log('The cars sorted by make are:'); printArray(automobiles, false); console.log(''); sortArr(typeComparator, automobiles); console.log('The cars sorted by type are:'); printArray(automobiles, true); console.log('*****'); <file_sep>/Assignment2/functions.js // Name: <NAME> // Date: 10/16/16 // Description: CS290 - Activity: JS Functions console.log(sayHi()); function sayHi() { return "Hi!"; } //console.log(sayGoodbye()); // Does not work var sayGoodbye = function(){ return "Goodbye!"; } console.log(sayGoodbye()); // Does Work
315258181d5503d5b7af004905019871230ed1e7
[ "JavaScript", "Markdown" ]
5
JavaScript
MGUltra/CS290
8f6276641a216cac37802642bd4ebbe5651b0ad5
011a4855baad8a073c9214ef8deb326b08b1dd66
refs/heads/master
<repo_name>maxithub/reactive-app<file_sep>/src/main/resources/schema.sql drop table if exists app_user; create table app_user ( id varchar (20) not null, first_name varchar (200) not null, last_name varchar (200) not null, middle_name varchar (200), gender varchar (50) not null, age smallint not null, province varchar (200) not null, city varchar (200), primary key (id) ); -- drop index idx_app_user ; create index idx_app_user on app_user (province, city, age);<file_sep>/src/main/resources/util.sql select * from app_user; select count(1) from app_user; <file_sep>/src/main/java/max/lab/r2app/reactiveapp/ReactiveAppApplication.java package max.lab.r2app.reactiveapp; import lombok.extern.slf4j.Slf4j; import max.lab.r2app.reactiveapp.repository.AppUserRepository; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @Slf4j @SpringBootApplication public class ReactiveAppApplication { public static void main(String[] args) { SpringApplication.run(ReactiveAppApplication.class, args); } // @Bean public CommandLineRunner commandLineRunner(AppUserRepository repository) { return (args -> repository.deleteAll().subscribe((v) -> log.info("Deleted all appusers"))); } } <file_sep>/src/main/java/max/lab/r2app/reactiveapp/controller/AppUserController.java package max.lab.r2app.reactiveapp.controller; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import max.lab.r2app.reactiveapp.domain.AppUser; import max.lab.r2app.reactiveapp.repository.AppUserRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.validation.Validator; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; import static max.lab.r2app.reactiveapp.controller.ControllerHelper.*; import static org.springframework.web.reactive.function.server.RouterFunctions.route; import static org.springframework.web.reactive.function.server.ServerResponse.notFound; import static org.springframework.web.reactive.function.server.ServerResponse.ok; @RequiredArgsConstructor @Configuration @Slf4j public class AppUserController { private final AppUserRepository appUserRepo; private final Validator validator; private final ObjectMapper objectMapper; @Bean public RouterFunction<ServerResponse> routes() { return route() .POST("/appuser", this::create) .PUT("/appuser/{id}", this::update) .GET("/appusers", this::findMany) .GET("/appuser/{id}", this::findOne) .build(); } private Mono<ServerResponse> findOne(ServerRequest request) { var id = request.pathVariable("id"); return appUserRepo.findById(id) .flatMap(ok()::bodyValue) .switchIfEmpty(notFound().build()) .onErrorResume(t -> handleException(t, log, "Failed to find AppUsers: " + id)); } private Mono<ServerResponse> update(ServerRequest request) { var id = request.pathVariable("id"); return appUserRepo.findById(id) .then(request.bodyToMono(AppUser.class)) .doOnNext(appUser -> validate(validator, appUser)) .flatMap(appUserRepo::update) .then(ok().build()) .switchIfEmpty(notFound().build()) .onErrorResume(t -> handleException(t, log, "Failed to update AppUser")); } private Mono<ServerResponse> findMany(ServerRequest request) { return queryParamsToMono(request, objectMapper, PageHolder.class, validator) .flatMap(page -> ok() .body(appUserRepo.find( request.queryParam("province"), request.queryParam("city"), request.queryParam("age").map(s -> { Integer i = null; try { i = Integer.valueOf(s); } catch (Exception e) { } return i; }), page.toPageable()), AppUser.class)) .onErrorResume(t -> handleException(t, log, "Failed to find AppUsers")); } private Mono<ServerResponse> create(ServerRequest request) { return request.bodyToMono(AppUser.class) .flatMap(appUser -> validateAsync(validator, (theAppUser, errors) -> { String id = appUser.getId(); return appUserRepo.findById(id).hasElement().doOnNext(b -> { if (b.booleanValue()) { errors.reject("AppUser.alreadyExists", new Object[] { id }, "AppUser: {0} already exists"); } }).then(Mono.just(errors)); }, appUser)) .flatMap(appUserRepo::insert) .then(ok().build()) .onErrorResume(t -> handleException(t, log, "Failed to create AppUser")); } } <file_sep>/src/main/java/max/lab/r2app/reactiveapp/repository/AppUserRepository.java package max.lab.r2app.reactiveapp.repository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import max.lab.r2app.reactiveapp.domain.AppUser; import org.springframework.data.domain.Pageable; import org.springframework.data.r2dbc.core.DatabaseClient; import org.springframework.data.r2dbc.query.Criteria; import org.springframework.stereotype.Repository; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.Optional; import static org.springframework.data.r2dbc.query.Criteria.where; import static org.springframework.util.StringUtils.isEmpty; @RequiredArgsConstructor @Repository @Slf4j public class AppUserRepository { private final DatabaseClient databaseClient; public Mono<Void> insert(AppUser appUser) { return databaseClient.insert().into(AppUser.class).using(appUser).then(); } public Mono<Void> update(AppUser appUser) { return databaseClient.update().table(AppUser.class).using(appUser).then(); } public Mono<AppUser> findById(String id) { return databaseClient.select().from(AppUser.class).matching(where("id").is(id)).fetch().one(); } public Flux<AppUser> findAll(Pageable page) { return find(Optional.empty(), Optional.empty(), Optional.empty(), page); } public Flux<AppUser> find(Optional<String> province, Optional<String> city, Optional<Integer> age, Pageable page) { Criteria where = null; if (province.isPresent() && !isEmpty(province.get())) { where = (where == null ? where("province").is(province.get()) : where.and("province").is(province.get())); } if (city.isPresent() && !isEmpty(city.get())) { where = (where == null ? where("city").is(city.get()) : where.and("city").is(city.get())); } if (age.isPresent()) { where = (where == null ? where("age").is(age.get()) : where.and("age").is(age.get())); } var query = databaseClient.select().from(AppUser.class).page(page); if (where != null) { query = query.matching(where); } return query.fetch().all(); } public Mono<Void> deleteAll() { return databaseClient.delete().from(AppUser.class).then(); } } <file_sep>/src/main/resources/application.properties spring.r2dbc.url=r2dbc:postgresql://max-pc:5432/r2app spring.r2dbc.username=r2appuser spring.r2dbc.password=<PASSWORD> management.endpoint.metrics.enabled=true management.endpoints.web.exposure.include=* management.endpoint.prometheus.enabled=true management.metrics.export.prometheus.enabled=true<file_sep>/src/main/resources/database.sql CREATE USER r2appuser WITH PASSWORD '<PASSWORD>'; CREATE DATABASE r2app OWNER r2appuser; GRANT ALL PRIVILEGES ON DATABASE r2app to r2appuser;
f4a20d23d6245c782a1d813f68df9e806980ec85
[ "Java", "SQL", "INI" ]
7
SQL
maxithub/reactive-app
803ee09006eee0772fa8b30d5990efd4ce1a4686
221c6c120e371974f5a228cf56423e52e3fa97fe
refs/heads/master
<file_sep>package com.cmeb.cnm.firstassignment; import android.graphics.drawable.Icon; /** * Created by User on 14/11/2017. */ public class Currency { public String name; private int flag; public double rate; Currency(String n, int f, double r) { name = n; flag = f; rate = r; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } public double getRate() { return rate; } public void setTaxe(double rate) { this.rate = rate; } } <file_sep>package com.cmeb.cnm.firstassignment; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.media.Image; import android.os.AsyncTask; import android.os.Bundle; import android.support.constraint.ConstraintLayout; import android.text.Editable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.SimpleAdapter; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import static android.content.ContentValues.TAG; public class CurrencyConversionApp extends Activity { private ArrayList<Spinner> spinners = new ArrayList<>(); private ArrayList<EditText> editTexts = new ArrayList<>(); private int[] selections; private Integer lastChanged = -1; private boolean initialized = false; // private ListView lv; // private ProgressBar pBar; ArrayList<Currency> currencies_global = new ArrayList<>(); LayoutInflater inflator; // URL to get contacts JSON private static String url = "https://api.fixer.io/latest"; // @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.convert_layout); selections = new int[] {0, 29, 8, 3}; GetCurrencies getCurrencies = new GetCurrencies(); getCurrencies.execute(); // initializeCurrencies(); inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); } private void initializeRows(int[] selection) { for (int i=0; i<4; i++){ if(i==0) { spinners.add((Spinner) findViewById(R.id.countrySpinner1)); editTexts.add((EditText) findViewById(R.id.editValue1)); editTexts.get(0).setText("1"); } else if (i==1) { spinners.add(i, (Spinner) findViewById(R.id.countrySpinner2)); editTexts.add((EditText) findViewById(R.id.editValue2)); } else if (i==2) { spinners.add(i, (Spinner) findViewById(R.id.countrySpinner3)); editTexts.add((EditText) findViewById(R.id.editValue3)); } else if (i==3) { spinners.add(i, (Spinner) findViewById(R.id.countrySpinner4)); editTexts.add((EditText) findViewById(R.id.editValue4)); } spinners.get(i).setAdapter(new NewAdapter()); spinners.get(i).setSelection(selection[i]); spinners.get(i).setOnItemSelectedListener( new NewItemSelectedListener(i)); editTexts.get(i).addTextChangedListener(new NewTextWatcher(i)); } } public class NewItemSelectedListener implements AdapterView.OnItemSelectedListener { private int j; public NewItemSelectedListener(int j) { this.j = j; } public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { selections[j]=pos; lastChanged=j; if (!initialized){ if (j==3){ initialized=true; lastChanged = 0; } } } public void onNothingSelected(AdapterView parent) {} } class NewTextWatcher implements android.text.TextWatcher { private int position; public NewTextWatcher(int i) { this.position = i; } @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { lastChanged = position; } } // CASO NAO HAJA NET: private void initializeCurrencies() { /* currencies_global.add(new Currency("Euro", R.drawable.europe, 1)); for (int i = 0; i<currencies_global.size(); i++) switch (currencies_global.get(i).getName()) { case ("BGN"): { currencies_global.get(i).setName("Bulgarian Lev"); currencies_global.get(i).setFlag(R.drawable.bulgaria); } case ("BRL"): { currencies_global.get(i).setName("Brazilian Real"); currencies_global.get(i).setFlag(R.drawable.brazil); } case ("CAD"): { currencies_global.get(i).setName("Canadian Dollar"); currencies_global.get(i).setFlag(R.drawable.canada); } case("CHF"):{ currencies_global.get(i).setName("Swiss Franc"); currencies_global.get(i).setFlag(R.drawable.switzerland); } case("CNY"):{ currencies_global.get(i).setName("Chinese Yuan"); currencies_global.get(i).setFlag(R.drawable.china); } case("CZK"):{ currencies_global.get(i).setName("Czech Koruna"); currencies_global.get(i).setFlag(R.drawable.czech); } case("GBP"):{ currencies_global.get(i).setName("British Pound"); currencies_global.get(i).setFlag(R.drawable.unitedkingdom); } case("HKD"):{ currencies_global.get(i).setName("Hong Kong Dollar"); currencies_global.get(i).setFlag(R.drawable.hongkong); } case("HRK"):{ currencies_global.get(i).setName("Croatian Kuna"); currencies_global.get(i).setFlag(R.drawable.croatia); } case("HUF"):{ currencies_global.get(i).setName("Hungarian Forint"); currencies_global.get(i).setFlag(R.drawable.hungary); } case("IDR"):{ currencies_global.get(i).setName("Indesian Rupiah"); currencies_global.get(i).setFlag(R.drawable.indonesia); } case("ILS"):{ currencies_global.get(i).setName("Isreali New Shekel"); currencies_global.get(i).setFlag(R.drawable.israel); } case("INR"):{ currencies_global.get(i).setName("Indian Rupee"); currencies_global.get(i).setFlag(R.drawable.india); } case("JPY"):{ currencies_global.get(i).setName("Japanese Yen"); currencies_global.get(i).setFlag(R.drawable.japan); } case("KRW"):{ currencies_global.get(i).setName("South Korean Won"); currencies_global.get(i).setFlag(R.drawable.southkorea); } case("MXN"):{ currencies_global.get(i).setName("Mexican Peso"); currencies_global.get(i).setFlag(R.drawable.mexico); } case("MYR"):{ currencies_global.get(i).setName("Malaysian Ringgit"); currencies_global.get(i).setFlag(R.drawable.malaysia); } case("NOK"):{ currencies_global.get(i).setName("Norwegian Krone"); currencies_global.get(i).setFlag(R.drawable.norway); } case("NZD"):{ currencies_global.get(i).setName("New Zeeland Dollar"); currencies_global.get(i).setFlag(R.drawable.newzealand); } case("PHP"):{ currencies_global.get(i).setName("Philippine Piso"); currencies_global.get(i).setFlag(R.drawable.philippines); } case("PLN"):{ currencies_global.get(i).setName("Philippine Piso"); currencies_global.get(i).setFlag(R.drawable.philippines); } case("RON"):{ currencies_global.get(i).setName("Romanian Leu"); currencies_global.get(i).setFlag(R.drawable.romania); } case("RUB"):{ currencies_global.get(i).setName("Russian Rubble"); currencies_global.get(i).setFlag(R.drawable.russia); } case("SEK"):{ currencies_global.get(i).setName("Swedish Krona"); currencies_global.get(i).setFlag(R.drawable.sweden); } case("SGD"):{ currencies_global.get(i).setName(""); currencies_global.get(i).setFlag(R.drawable.philippines); } case("THB"):{ currencies_global.get(i).setName("Singapore Dollar"); currencies_global.get(i).setFlag(R.drawable.singapore); } case("TRY"):{ currencies_global.get(i).setName("Turkish Lira"); currencies_global.get(i).setFlag(R.drawable.turkey); } case("USD"):{ currencies_global.get(i).setName("USA Dollar"); currencies_global.get(i).setFlag(R.drawable.usa); } case("ZAR"): { currencies_global.get(i).setName("South African Rand"); currencies_global.get(i).setFlag(R.drawable.southafrica); } case("AUD"):{ currencies_global.get(i).setName("Australian Dollar"); currencies_global.get(i).setFlag(R.drawable.australia); } */ currencies_global.add(new Currency("USA dollar", R.drawable.usa, 1)); currencies_global.add(new Currency("Euro", R.drawable.europe, 2)); currencies_global.add(new Currency("Japanese yen", R.drawable.japan, 3)); currencies_global.add(new Currency("Pound sterling", R.drawable.unitedkingdom, 4)); currencies_global.add(new Currency("Australian dollar", R.drawable.australia, 5)); currencies_global.add(new Currency("Canadian dollar", R.drawable.canada, 6)); currencies_global.add(new Currency("Swiss fran", R.drawable.switzerland, 2)); currencies_global.add(new Currency("Renminbi", R.drawable.china, 2)); currencies_global.add(new Currency("Swedish krona", R.drawable.sweden, 2)); currencies_global.add(new Currency("New Zealand dollar", R.drawable.newzealand, 2)); currencies_global.add(new Currency("Mexican pesa", R.drawable.mexico, 2)); currencies_global.add(new Currency("Singapore dollar", R.drawable.singapore, 2)); currencies_global.add(new Currency("Hong Kong dollar", R.drawable.hongkong, 2)); currencies_global.add(new Currency("Norwegian krone", R.drawable.norway, 2)); currencies_global.add(new Currency("Turkish lira", R.drawable.turkey, 2)); currencies_global.add(new Currency("South Korean won", R.drawable.southkorea, 2)); currencies_global.add(new Currency("Russian ruble", R.drawable.russia, 2)); currencies_global.add(new Currency("Indian rupee", R.drawable.india, 2)); currencies_global.add(new Currency("Brazilian real", R.drawable.brazil, 2)); currencies_global.add(new Currency("South African rand", R.drawable.southafrica, 2)); // } } public void onConvert(View v) { Double taxeProportion; Double newValue; Double referenceTaxe = currencies_global.get(selections[lastChanged]).getRate(); Double insertedValue = Double.parseDouble(editTexts.get(lastChanged).getText().toString()); for (int j = 0; j < 4; j++) { if (j != lastChanged) { taxeProportion = currencies_global.get(selections[j]).getRate() / referenceTaxe; newValue = insertedValue * taxeProportion; editTexts.get(j).setText(newValue.toString()); } } } class NewAdapter extends BaseAdapter { @Override public int getCount() { return currencies_global.size(); } @Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int i, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflator.inflate(R.layout.dropdown_layout, null); ImageView icon = convertView.findViewById(R.id.flag); icon.setImageResource(currencies_global.get(i).getFlag()); TextView currencyName = convertView.findViewById(R.id.countryNameLabel); currencyName.setText(currencies_global.get(i).getName()); } else{ ImageView icon = convertView.findViewById(R.id.flag); icon.setImageResource(currencies_global.get(i).getFlag()); TextView currencyName = convertView.findViewById(R.id.countryNameLabel); currencyName.setText(currencies_global.get(i).getName()); } return convertView; } } public void onViewTaxes(View v) { setContentView(R.layout.taxes_layout); } private class GetCurrencies extends AsyncTask<Void, Void, Void> { // @Override // protected void onPreExecute(){ //shoing progress bar // ProgressBar pBar = new ProgressBar(this, null, android.R.attr.progressBarStyleSmall); // } @Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Object node JSONObject currencies = jsonObj.getJSONObject("rates"); JSONArray names = currencies.names(); currencies_global.add(new Currency("Euro", (R.drawable.europe), 1)); for (int k = 0; k < names.length(); k++) { switch (names.getString(k)) { case ("BGN"): { Currency cur = new Currency("Bulgarian Lev", (R.drawable.bulgaria), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case ("BRL"): { Currency cur = new Currency("Brazilian Real", (R.drawable.brazil), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case ("CAD"): { Currency cur = new Currency("Canadian Dollar", (R.drawable.canada), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("CHF"):{ Currency cur = new Currency("Swiss Franc", (R.drawable.switzerland), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("CNY"):{ Currency cur = new Currency("Chinese Yuan", (R.drawable.china), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("CZK"):{ Currency cur = new Currency("Czech Koruna", (R.drawable.czech), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("GBP"):{ Currency cur = new Currency("British Pound", (R.drawable.unitedkingdom), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("HKD"):{ Currency cur = new Currency("Hong Kong Dollar", (R.drawable.hongkong), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("HRK"):{ Currency cur = new Currency("Croatian Kuna", (R.drawable.croatia), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("HUF"):{ Currency cur = new Currency("Hungarian Forint", (R.drawable.hungary), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("IDR"):{ Currency cur = new Currency("Indesian Rupiah", (R.drawable.indonesia), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("ILS"):{ Currency cur = new Currency("Isreali New Shekel", (R.drawable.israel), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("INR"):{ Currency cur = new Currency("Indian Rupee", (R.drawable.india), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("JPY"):{ Currency cur = new Currency("Japanese Yen", (R.drawable.japan), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("KRW"):{ Currency cur = new Currency("South Korean Won", (R.drawable.southkorea), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("MXN"):{ Currency cur = new Currency("Mexican Peso", (R.drawable.mexico), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("MYR"):{ Currency cur = new Currency("Malaysian Ringgit", (R.drawable.malaysia), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("NOK"):{ Currency cur = new Currency("Norwegian Krone", (R.drawable.norway), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("NZD"):{ Currency cur = new Currency("New Zeeland Dollar", (R.drawable.newzealand), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("PHP"):{ Currency cur = new Currency("Philippine Piso", (R.drawable.philippines), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("PLN"):{ Currency cur = new Currency("Philippine Piso", (R.drawable.philippines), currencies.getDouble(names.getString(k))); currencies_global.add(cur); ///////////////////////////////////////////////// // currencies_global.get(i).setName("Philippine Piso"); // currencies_global.get(i).setFlag(R.drawable.philippines); ////////////////////////////// break; } case("RON"):{ Currency cur = new Currency("Romanian Leu", (R.drawable.romania), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("RUB"):{ Currency cur = new Currency("Russian Rubble", (R.drawable.russia), currencies.getDouble(names.getString(k))); currencies_global.add(cur); break; } case("SEK"):{ currencies_global.add(new Currency("Swedish Krona", (R.drawable.sweden), currencies.getDouble(names.getString(k)))); break; } case("SGD"):{ currencies_global.add(new Currency("Singapore Dollar", (R.drawable.singapore), currencies.getDouble(names.getString(k)))); break; } case("THB"):{ currencies_global.add(new Currency("Thai Baht", (R.drawable.thailand), currencies.getDouble(names.getString(k)))); break; } case("TRY"):{ currencies_global.add(new Currency("Turkish Lira", (R.drawable.turkey), currencies.getDouble(names.getString(k)))); break; } case("USD"):{ currencies_global.add(new Currency("USA Dollar", (R.drawable.usa), currencies.getDouble(names.getString(k)))); break; } case("ZAR"): { currencies_global.add(new Currency("South African Rand", (R.drawable.southafrica), currencies.getDouble(names.getString(k)))); break; } case("AUD"):{ currencies_global.add(new Currency("Australian Dollar", (R.drawable.australia), currencies.getDouble(names.getString(k)))); break; } } } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG) .show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG) .show(); } }); } runOnUiThread(new Runnable() { @Override public void run() { initializeRows(selections); } }); return null; } } // @Override // protected void onPostExecute(Void result) { // super.onPostExecute(result); // // Dismiss the progress dialog //// if (pDialog.isShowing()) //// pDialog.dismiss(); // /** // * Updating parsed JSON data into ListView // * */ // ListAdapter adapter = new SimpleAdapter( // CurrencyConversionApp.this, currencies_global, // R.layout.taxes_layout, new String[]{"currency_name", "currency_rate"}, // new int[]{R.id.currency_name, R.id.currency_rate}); // // lv.setAdapter(adapter); // } // } }
476f4d2b790f8c9347d3e8780c1cf5086e8c0731
[ "Java" ]
2
Java
carlamota/currency_assignment
91f82262093c52b8848f27143b658284bda2673d
242164e7d0cfa7bad975652a34e5db9208d8dd7a
refs/heads/master
<repo_name>federikos/hooks-context-use-json-fetch<file_sep>/src/Component3.js import React, {useState, useEffect} from 'react'; import useJsonFetch from './useJsonFetch'; import { store } from 'react-notifications-component'; import Loader from 'react-loader-spinner'; const Component1 = () => { const [switcher, setSwitcher] = useState(false); const [url, setUrl] = useState(''); const handleClick = e => { setSwitcher(true); setUrl(`${process.env.REACT_APP_BASE_URL}${e.target.name}`); }; const [{data, loading, error}] = useJsonFetch(url, {switcher, setSwitcher}); //обработка успешных запросов (data) useEffect(() => { if(data) { const type = data.status === 'ok' ? "success" : "danger"; store.addNotification({ title: "Компонент 3", message: data.status, type, insert: "top", container: "bottom-center", animationIn: ["animated", "fadeIn"], animationOut: ["animated", "fadeOut"], dismiss: { duration: 4000, onScreen: true } }); } }, [data]); //обработка запросов с ошибкой (error) useEffect(() => { if(error) { store.addNotification({ title: "Компонент 3", message: error, type: "danger", insert: "top", container: "bottom-center", animationIn: ["animated", "fadeIn"], animationOut: ["animated", "fadeOut"], dismiss: { duration: 4000, onScreen: true } }); } }, [error]); return ( <div> <h2>Компонент №3</h2> <button name="data" onClick={handleClick}>Отправить успешный запрос</button> <button name="error" onClick={handleClick}>Отправить неудачный запрос</button> <button name="loading" onClick={handleClick}>Отправить удачный медленный запрос</button> { //обработка состояния загрузки loading && <Loader type="Puff" color="#00BFFF" height={100} width={100} /> } </div> ); }; export default Component1;<file_sep>/src/useJsonFetch.js import {useState, useEffect} from 'react'; export default function useJsonFetch(url, opts) { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); useEffect(() => { if (opts.switcher) { setLoading(true); fetch(url) .then(res => res.json()) .then(res => setData(res)) .catch(err => setError(err)) .finally(() => { setLoading(false); opts.setSwitcher(false) }) } }, [url, opts.switcher]); return [{data, loading, error}]; };
a5844b00737f73f14926154f46ce727353cc8af6
[ "JavaScript" ]
2
JavaScript
federikos/hooks-context-use-json-fetch
8dc4c2867fa24a1dfa923e901b248f43ad4c4fe0
bc452b47a16543804992eeb313a4e534f42f2e74
refs/heads/main
<repo_name>hkid/goWebBubbleV2<file_sep>/main.go package main import ( "awesomeProject2/models" "awesomeProject2/dao" "awesomeProject2/routers" ) func main() { // 0 创建数据库 // 1 连接数据库 ->封装为函数 err:=dao.InitMysql() if err!=nil{ panic(err) } //模型绑定 dao.DB.AutoMigrate(&models.Todo{}) r:=routers.SetupRouter() r.Run(":80") } <file_sep>/dao/mysql.go package dao import "gorm.io/gorm" import "gorm.io/driver/mysql" var ( DB *gorm.DB ) func InitMysql() (err error){ dsn:="root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local" DB,err =gorm.Open(mysql.Open(dsn),&gorm.Config{}) //这不要 := if err!=nil{ return err } return nil }
75a139c17607d2bef7cbb349f2d178c6b2bf43f2
[ "Go" ]
2
Go
hkid/goWebBubbleV2
19d5809484d3d4e52431d860253fc2c3d22dc4af
bd2e76acd878b9debd79278e4dc8799a514f3f3d
refs/heads/master
<repo_name>artemsen/xvi<file_sep>/src/ui/insert.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::dialog::{Dialog, DialogHandler, DialogType, ItemId}; use super::widget::{InputFormat, InputLine, StandardButton, WidgetType}; /// "Insert bytes" dialog. pub struct InsertDialog { length: ItemId, offset: ItemId, pattern: ItemId, btn_ok: ItemId, btn_cancel: ItemId, } impl InsertDialog { /// Width of the dialog. const WIDTH: usize = 42; /// Show the "Insert bytes" configuration dialog. /// /// # Arguments /// /// * `offset` - default start offset (current position) /// * `pattern` - default pattern /// /// # Return value /// /// Start offset, number of bytes to insert and pattern to fill. pub fn show(offset: u64, pattern: &[u8]) -> Option<(u64, u64, Vec<u8>)> { // create dialog let mut dlg = Dialog::new(InsertDialog::WIDTH, 7, DialogType::Normal, "Insert bytes"); dlg.add_line(WidgetType::StaticText( "Insert bytes at offset".to_string(), )); // length let widget = InputLine::new("1".to_string(), InputFormat::DecUnsigned, Vec::new(), 6); let length = dlg.add( Dialog::PADDING_X + 7, Dialog::PADDING_Y, 6, WidgetType::Edit(widget), ); // start offset let widget = InputLine::new( format!("{:x}", offset), InputFormat::HexUnsigned, Vec::new(), 12, ); let offset = dlg.add( Dialog::PADDING_X + 30, Dialog::PADDING_Y, 12, WidgetType::Edit(widget), ); // pattern dlg.add_separator(); dlg.add_line(WidgetType::StaticText("Fill with pattern:".to_string())); let text = pattern.iter().map(|b| format!("{:02x}", b)).collect(); let widget = InputLine::new( text, InputFormat::HexStream, Vec::new(), InsertDialog::WIDTH, ); let pattern = dlg.add_line(WidgetType::Edit(widget)); // warning message dlg.add_separator(); dlg.add_center("WARNING!".to_string()); dlg.add_center("This operation cannot be undone!".to_string()); // buttons let btn_ok = dlg.add_button(StandardButton::OK, true); let btn_cancel = dlg.add_button(StandardButton::Cancel, false); // construct dialog handler let mut handler = Self { length, offset, pattern, btn_ok, btn_cancel, }; // show dialog if let Some(id) = dlg.show(&mut handler) { if id != handler.btn_cancel { let length = if let WidgetType::Edit(widget) = dlg.get_widget(handler.length) { widget.get_value().parse::<u64>().unwrap_or(0) } else { 0 }; debug_assert_ne!(length, 0); let offset = if let WidgetType::Edit(widget) = dlg.get_widget(handler.offset) { u64::from_str_radix(widget.get_value(), 16).unwrap_or(0) } else { 0 }; let pattern = handler.get_pattern(&dlg); return Some((offset, length, pattern)); } } None } /// Get current sequence from the pattern field. fn get_pattern(&self, dialog: &Dialog) -> Vec<u8> { if let WidgetType::Edit(widget) = dialog.get_widget(self.pattern) { let mut value = widget.get_value().to_string(); if !value.is_empty() { if value.len() % 2 != 0 { value.push('0'); } return (0..value.len()) .step_by(2) .map(|i| u8::from_str_radix(&value[i..i + 2], 16).unwrap()) .collect(); } } vec![0] } } impl DialogHandler for InsertDialog { fn on_close(&mut self, dialog: &mut Dialog, item: ItemId) -> bool { item == self.btn_cancel || dialog.get_context(self.btn_ok).enabled } fn on_item_change(&mut self, dialog: &mut Dialog, item: ItemId) { if item == self.length { if let WidgetType::Edit(widget) = dialog.get_widget(self.length) { let is_valid = widget.get_value().parse::<u64>().unwrap_or(0) != 0; dialog.set_enabled(self.btn_ok, is_valid); } } } fn on_focus_lost(&mut self, dialog: &mut Dialog, item: ItemId) { if item == self.length || item == self.offset { if let WidgetType::Edit(widget) = dialog.get_widget_mut(item) { if widget.get_value().is_empty() { widget.set_value("0".to_string()); } } } else if item == self.pattern { if let WidgetType::Edit(widget) = dialog.get_widget_mut(self.pattern) { let mut value = widget.get_value().to_string(); if value.is_empty() { widget.set_value("00".to_string()); } else if value.len() % 2 != 0 { value.push('0'); widget.set_value(value); } } } } } <file_sep>/src/file.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use std::collections::BTreeMap; use std::fs::OpenOptions; use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom, Write}; use std::ops::Range; use std::path::Path; /// Editable file. pub struct File { /// File handle file: std::fs::File, /// Absolute path to the file. pub path: String, /// File size. pub size: u64, /// Cached map of real changes (offset -> new byte value). pub changes: BTreeMap<u64, u8>, /// Data cache. cache: Cache, } impl File { /// Size of the block for read/write operations. const BLOCK_SIZE: usize = Cache::SIZE; /// Open file. /// /// # Arguments /// /// * `file` - file to open /// /// # Return value /// /// Self instance. pub fn open(file: &Path) -> Result<Self> { let path = std::fs::canonicalize(file)?; if !path.is_file() { return Err(Error::new(ErrorKind::InvalidData, "Not a file")); } // open file in read only mode let file = OpenOptions::new().read(true).open(&path)?; let meta = file.metadata()?; if meta.len() == 0 { return Err(Error::new(ErrorKind::UnexpectedEof, "File is empty")); } Ok(Self { file, path: path.into_os_string().into_string().unwrap(), size: meta.len(), changes: BTreeMap::new(), cache: Cache::new(), }) } /// Check if file is modofied. pub fn is_modified(&self) -> bool { !self.changes.is_empty() } /// Read up to `size` bytes from file. /// /// # Arguments /// /// * `offset` - start offset /// * `size` - number of bytes to read /// /// # Return value /// /// File data. pub fn read(&mut self, offset: u64, size: usize) -> Result<Vec<u8>> { debug_assert!(offset < self.size); // read up to the end of file #[allow(clippy::cast_possible_truncation)] let max_size = (self.size - offset) as usize; let size = size.min(max_size); // update cache if needed if !self.cache.has(offset, size) { let cache_size = Cache::SIZE.min(max_size).max(size); self.cache.data.resize(cache_size, 0); self.cache.start = offset; self.file.seek(SeekFrom::Start(offset))?; self.file.read_exact(&mut self.cache.data)?; } // get file data #[allow(clippy::cast_possible_truncation)] let start = (offset - self.cache.start) as usize; let end = start + size; let mut data = self.cache.data[start..end].to_vec(); // apply changes for (&addr, &value) in self.changes.range(offset..offset + size as u64) { #[allow(clippy::cast_possible_truncation)] let index = (addr - offset) as usize; data[index] = value; } Ok(data) } /// Write changes to the current file. pub fn save(&mut self) -> Result<()> { // reopen file with the write permission let mut file = OpenOptions::new().write(true).open(self.path.clone())?; // write changes for (&offset, &value) in &self.changes { file.seek(SeekFrom::Start(offset))?; file.write_all(&[value])?; } // reset self.cache.data.clear(); self.changes.clear(); Ok(()) } /// Create copy of the file and write the current changes to it (save as). /// /// # Arguments /// /// * `file` - path to the new file /// * `progress` - long time operation handler pub fn save_as(&mut self, file: &Path, progress: &mut dyn ProgressHandler) -> Result<()> { // create new file let mut new_file = OpenOptions::new() .read(true) .write(true) .create(true) .open(&file)?; new_file.set_len(0)?; let mut offset = 0; loop { // update progress info let percent = (100.0 / self.size as f64) * offset as f64; if !progress.update(percent as u8) { return Err(Error::new(ErrorKind::Interrupted, "Aborted by user")); } // read and write let data = self.read(offset, File::BLOCK_SIZE)?; new_file.write_all(&data)?; offset += data.len() as u64; if offset >= self.size { break; //eof } } self.file = new_file; let path = std::fs::canonicalize(file)?; self.path = path.into_os_string().into_string().unwrap(); // reset self.cache.data.clear(); self.changes.clear(); Ok(()) } /// Find sequence inside the current file from the specified position. /// /// # Arguments /// /// * `start` - start address /// * `sequence` - sequence to find /// * `backward` - search direction /// * `progress` - long time operation handler /// /// # Return value /// /// Offset of the next sequence entry. pub fn find( &mut self, start: u64, sequence: &[u8], backward: bool, progress: &mut dyn ProgressHandler, ) -> Result<u64> { debug_assert!(start <= self.size); debug_assert!(!sequence.is_empty()); debug_assert!(File::BLOCK_SIZE > sequence.len()); let mut offset = start; if backward { if offset == 0 { offset = self.size; } offset -= 1; } else { offset += 1; } let mut round = false; let mut handled = 0; loop { // update progress info let percent = (100.0 / self.size as f64) * handled as f64; if !progress.update(percent as u8) { return Err(Error::new(ErrorKind::Interrupted, "Aborted by user")); } if backward { // backward search if round && offset < start { break; } if offset >= File::BLOCK_SIZE as u64 { offset -= File::BLOCK_SIZE as u64; } else { if self.size < File::BLOCK_SIZE as u64 { offset = 0; } else { offset = self.size - File::BLOCK_SIZE as u64; } round = true; } } else { // forward search if offset as u64 >= self.size { offset = 0; round = true; } } let file_data = self.read(offset as u64, File::BLOCK_SIZE)?; let mut window = file_data.windows(sequence.len()); if !backward { if let Some(pos) = window.position(|wnd| wnd == sequence) { return Ok(offset as u64 + pos as u64); } } else if let Some(pos) = window.rposition(|wnd| wnd == sequence) { return Ok(offset as u64 + pos as u64); } if !backward { offset += File::BLOCK_SIZE as u64; if round && offset as u64 >= start { break; } } handled += file_data.len() as u64; } Err(Error::new(ErrorKind::NotFound, "Sequence not found")) } /// Insert bytes at the specified position in the file. /// /// # Arguments /// /// * `offset` - start position of bytes to insert /// * `length` - number of bytes to insert /// * `pattern` - pattern to fill the added range /// * `progress` - long time operation handler pub fn insert( &mut self, offset: u64, length: u64, pattern: &[u8], progress: &mut dyn ProgressHandler, ) -> Result<()> { debug_assert!(self.changes.is_empty()); debug_assert!(offset <= self.size); debug_assert!(length > 0); debug_assert!(!pattern.is_empty()); // reopen file with the write permission let mut file = OpenOptions::new().read(true).write(true).open(&self.path)?; // extend the file file.set_len(self.size + length)?; let mut handled = 0; let mut buffer = vec![0; File::BLOCK_SIZE]; // move (copy) data to the end of file let mut back_offset = self.size; while back_offset > offset { // update progress info let percent = (100.0 / (self.size - offset + length) as f64) * handled as f64; if !progress.update(percent as u8) { return Err(Error::new(ErrorKind::Interrupted, "Aborted by user")); } // calculate size and position of the next block let mut size = buffer.len(); #[allow(clippy::cast_possible_truncation)] if back_offset - (size as u64).min(back_offset) <= offset { size = (back_offset - offset) as usize; } let read_offset = back_offset - size as u64; let write_offset = back_offset + length - size as u64; // read data file.seek(SeekFrom::Start(read_offset))?; file.read_exact(&mut buffer[..size])?; // write data file.seek(SeekFrom::Start(write_offset))?; file.write_all(&buffer[..size])?; //dst_end -= size as u64; back_offset -= size as u64; handled += size as u64; } // fill with pattern let max_offset = offset + length; let mut fill_offset = offset; let mut pattern_pos = 0; while fill_offset < max_offset { // update progress info let percent = (100.0 / (self.size - offset + length) as f64) * handled as f64; if !progress.update(percent as u8) { return Err(Error::new(ErrorKind::Interrupted, "Aborted by user")); } // calculate size of the next block let mut size = buffer.len(); #[allow(clippy::cast_possible_truncation)] if fill_offset + (size as u64) > max_offset { size = (max_offset - fill_offset) as usize; } // apply pattern for byte in buffer.iter_mut().take(size) { *byte = pattern[pattern_pos]; pattern_pos += 1; if pattern_pos == pattern.len() { pattern_pos = 0; } } // write data file.seek(SeekFrom::Start(fill_offset))?; file.write_all(&buffer[..size])?; fill_offset += size as u64; handled += size as u64; } file.sync_all()?; self.size += length; // reset cache self.cache.data.clear(); Ok(()) } /// Cut out the specified range from the file. /// /// # Arguments /// /// * `range` - range to cut out /// * `progress` - long time operation handler pub fn cut(&mut self, range: &Range<u64>, progress: &mut dyn ProgressHandler) -> Result<()> { debug_assert!(self.changes.is_empty()); debug_assert!(!range.is_empty()); debug_assert!(range.end <= self.size); let range_len = range.end - range.start; // reopen file with the write permission let mut file = OpenOptions::new().read(true).write(true).open(&self.path)?; let mut offset = range.start; let mut buffer = vec![0; File::BLOCK_SIZE]; loop { // update progress info let percent = (100.0 / (self.size - range.end) as f64) * (offset - range.start) as f64; if !progress.update(percent as u8) { return Err(Error::new(ErrorKind::Interrupted, "Aborted by user")); } // read data file.seek(SeekFrom::Start(offset + range_len))?; let size = file.read(&mut buffer)?; if size == 0 { break; //end of file } // write data file.seek(SeekFrom::Start(offset))?; file.write_all(&buffer[..size])?; offset += size as u64; } self.size -= range_len; // truncate the file file.set_len(self.size)?; file.sync_all()?; // reset cache self.cache.data.clear(); Ok(()) } } /// Data cache. struct Cache { /// Cache buffer. data: Vec<u8>, /// Start address of the cache. start: u64, } impl Cache { /// Size of the cache. const SIZE: usize = 4096; /// Create new cache instance. fn new() -> Self { Self { data: Vec::with_capacity(Cache::SIZE), start: 0, } } /// Check if cache contains specified range. fn has(&self, offset: u64, size: usize) -> bool { offset >= self.start && offset + (size as u64) < self.start + self.data.len() as u64 } } /// Progress handler interface for long time operations. pub trait ProgressHandler { /// Update progress and check for interrupt. /// /// # Arguments /// /// * `percent` - current percent of completion /// /// # Return value /// /// `false` if operation aborted by user. fn update(&mut self, percent: u8) -> bool; } #[cfg(test)] struct ProgressTest {} #[cfg(test)] impl ProgressHandler for ProgressTest { fn update(&mut self, percent: u8) -> bool { assert!(percent <= 100); true } } #[test] fn test_find() { let path = std::env::temp_dir().join("xvi_test_file.find"); let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .open(&path) .unwrap(); file.set_len(0).unwrap(); file.write_all(&vec![11; 4]).unwrap(); file.write_all(&vec![22, 33, 33, 33, 44]).unwrap(); file.write_all(&vec![55, 5]).unwrap(); let mut progress = ProgressTest {}; let mut file = File::open(&path).unwrap(); assert_eq!( file.find(0, &vec![42], false, &mut progress) .unwrap_err() .kind(), ErrorKind::NotFound ); assert_eq!( file.find(0, &vec![33, 33], false, &mut progress).unwrap(), 5 ); assert_eq!( file.find(5, &vec![33, 33], false, &mut progress).unwrap(), 6 ); assert_eq!( file.find(file.size, &vec![33, 33], true, &mut progress) .unwrap(), 6 ); std::fs::remove_file(path).unwrap(); } #[test] fn test_cut() { let path = std::env::temp_dir().join("xvi_test_file.cut"); let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .open(&path) .unwrap(); file.set_len(0).unwrap(); file.write_all(&vec![11; 4]).unwrap(); file.write_all(&vec![22, 33, 44, 55]).unwrap(); file.write_all(&vec![66; 4]).unwrap(); let mut progress = ProgressTest {}; let mut file = File::open(&path).unwrap(); file.cut(&(2..5), &mut progress).unwrap(); assert_eq!( file.read(0, 255).unwrap(), vec![11, 11, 33, 44, 55, 66, 66, 66, 66] ); std::fs::remove_file(path).unwrap(); } #[test] fn test_insert() { let path = std::env::temp_dir().join("xvi_test_file.insert"); let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .open(&path) .unwrap(); file.set_len(0).unwrap(); file.write_all(&vec![11, 22, 33, 44, 55, 66, 77]).unwrap(); let mut progress = ProgressTest {}; let mut file = File::open(&path).unwrap(); file.insert(1, 4, &vec![88, 99], &mut progress).unwrap(); assert_eq!( file.read(0, 255).unwrap(), vec![11, 88, 99, 88, 99, 22, 33, 44, 55, 66, 77] ); std::fs::remove_file(path).unwrap(); } <file_sep>/src/ui/saveas.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::dialog::{Dialog, DialogHandler, DialogType, ItemId}; use super::widget::{InputFormat, InputLine, StandardButton, WidgetType}; /// "Save as" dialog. pub struct SaveAsDialog { path: ItemId, btn_ok: ItemId, btn_cancel: ItemId, } impl SaveAsDialog { /// Width of the dialog. const WIDTH: usize = 40; /// Show the "Save As" dialog. /// /// # Arguments /// /// * `default` - default file name /// /// # Return value /// /// New file name. pub fn show(default: String) -> Option<String> { // create dialog let mut dlg = Dialog::new(SaveAsDialog::WIDTH, 2, DialogType::Normal, "Save as"); // file path input dlg.add_line(WidgetType::StaticText("File name:".to_string())); let edit = InputLine::new(default, InputFormat::Any, Vec::new(), SaveAsDialog::WIDTH); let path = dlg.add_line(WidgetType::Edit(edit)); // buttons let btn_ok = dlg.add_button(StandardButton::OK, true); let btn_cancel = dlg.add_button(StandardButton::Cancel, false); // construct dialog handler let mut handler = Self { path, btn_ok, btn_cancel, }; handler.on_item_change(&mut dlg, handler.path); // show dialog if let Some(id) = dlg.show(&mut handler) { if id != handler.btn_cancel { if let WidgetType::Edit(widget) = dlg.get_widget(handler.path) { return Some(widget.get_value().to_string()); } } } None } } impl DialogHandler for SaveAsDialog { fn on_close(&mut self, dialog: &mut Dialog, item: ItemId) -> bool { item == self.btn_cancel || dialog.get_context(self.btn_ok).enabled } fn on_item_change(&mut self, dialog: &mut Dialog, item: ItemId) { if item == self.path { let is_ok = match dialog.get_widget(self.path) { WidgetType::Edit(widget) => !widget.get_value().is_empty(), _ => true, }; dialog.set_enabled(self.btn_ok, is_ok); } } } <file_sep>/src/editor.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::changes::ChangeList; use super::config::Config; use super::cursor::{Cursor, Direction, HalfByte, Place}; use super::file::{File, ProgressHandler}; use super::view::View; use std::collections::BTreeSet; use std::io; use std::ops::Range; use std::path::Path; /// Holder of editable documents, implements editor business logic. pub struct Editor { /// Editable documents. documents: Vec<Document>, /// Index of currently selected document. current: usize, } impl Editor { /// Create group of documents. /// /// # Arguments /// /// * `files` - files to open /// * `config` - app configuration /// /// # Return value /// /// Group instance. pub fn new(files: &[String], config: &Config) -> io::Result<Self> { debug_assert!(!files.is_empty()); // open documents let mut documents = Vec::with_capacity(files.len()); for file in files { documents.push(Document::new(Path::new(file), config)?); } Ok(Self { documents, current: 0, }) } /// Get currently focused document. pub fn current(&self) -> &Document { &self.documents[self.current] } /// Get number of opened documents. /// /// # Return value /// /// Number of opened documents. pub fn len(&self) -> usize { self.documents.len() } /// Get current cursor offset and list of opened files. /// Used for history saving. /// /// # Return value /// /// Cursor offset and list with absolute path of currently edited files. pub fn get_files(&self) -> (u64, Vec<String>) { ( self.documents[self.current].cursor.offset, self.documents .iter() .map(|doc| doc.file.path.to_string()) .collect(), ) } /// Resize the current workspace. /// /// # Arguments /// /// * `width` - new width of workspace /// * `height` - new height of workspace /// /// # Return value /// /// `false` if screen space is not enough pub fn resize(&mut self, width: usize, height: usize) -> bool { // height of a single view (lines per document) let lpd = height / self.documents.len(); let last = self.documents.len() - 1; if width < View::MIN_WIDTH || lpd < View::MIN_HEIGHT { return false; } // resize views for (index, doc) in self.documents.iter_mut().enumerate() { let y = index * lpd; // enlarge last window to fit the entire workspace let height = if index == last { height - lpd * index } else { lpd }; doc.view.resize(y, width, height); } self.refresh(); let current = &self.documents[self.current]; let view_offset = current.view.offset; let cursor_offset = current.cursor.offset; self.move_cursor(&Direction::Absolute(cursor_offset, view_offset)); true } /// Draw documents in current workspace. pub fn draw(&self) { self.documents.iter().for_each(|doc| doc.view.draw(doc)); // show cursor let current = &self.documents[self.current]; if let Some((mut x, y)) = current .view .get_position(current.cursor.offset, current.cursor.place == Place::Hex) { if current.cursor.half == HalfByte::Right { x += 1; } current.view.workspace.show_cursor(x, y); } } /// Move cursor. /// /// # Arguments /// /// * `dir` - move direction pub fn move_cursor(&mut self, dir: &Direction) { // move cursor in the current document let current = &mut self.documents[self.current]; let mut update = current.move_cursor(dir); let view_offset = current.view.offset; let cursor_offset = current.cursor.offset; // move cursor in other documents let index = self.current; for (_, doc) in self .documents .iter_mut() .enumerate() .filter(|(i, _)| *i != index) { update |= doc.move_cursor(&Direction::Absolute(cursor_offset, view_offset)); } // refresh view data if update { self.refresh(); } } /// Switch focus between documents and fields: /// current hex -> current ascii -> next hex -> next ascii /// /// # Arguments /// /// * `dir` - switch direction pub fn switch_focus(&mut self, dir: &Focus) { let current = &self.documents[self.current]; let has_ascii = current.view.ascii_table.is_some(); match dir { Focus::NextField => { if current.cursor.place == Place::Hex && has_ascii { self.documents .iter_mut() .for_each(|doc| doc.cursor.set_place(Place::Ascii)); } else { self.current += 1; if self.current == self.documents.len() { self.current = 0; } if current.cursor.place == Place::Ascii { self.documents .iter_mut() .for_each(|doc| doc.cursor.set_place(Place::Hex)); } } } Focus::PreviousField => { if current.cursor.place == Place::Ascii { self.documents .iter_mut() .for_each(|doc| doc.cursor.set_place(Place::Hex)); } else { if self.current > 0 { self.current -= 1; } else { self.current = self.documents.len() - 1; } if current.cursor.place == Place::Hex && has_ascii { self.documents .iter_mut() .for_each(|doc| doc.cursor.set_place(Place::Ascii)); } } } Focus::NextDocument => { if self.current + 1 < self.documents.len() { self.current += 1; } } Focus::PreviousDocument => { if self.current > 0 { self.current -= 1; } } Focus::DocumentIndex(index) => { debug_assert!(*index < self.documents.len()); self.current = *index; } } } /// Change data in the currently focused document. /// /// # Arguments /// /// * `offset` - offset of the byte value to change /// * `value` - new value /// * `mask` - mask of the new value pub fn change(&mut self, offset: u64, value: u8, mask: u8) { self.documents[self.current].change(offset, value, mask); self.refresh(); } /// Undo last change in the currently focused document. pub fn undo(&mut self) { if let Some(change) = self.documents[self.current].changes.undo() { let offset = self.documents[self.current].view.offset; self.move_cursor(&Direction::Absolute(change.offset, offset)); self.refresh(); } } /// Redo (opposite to Undo) for the currently focused document. pub fn redo(&mut self) { if let Some(change) = self.documents[self.current].changes.redo() { let offset = self.documents[self.current].view.offset; self.move_cursor(&Direction::Absolute(change.offset, offset)); self.refresh(); } } /// Jump to the closest change. /// /// # Arguments /// /// * `forward` - search direction pub fn closest_change(&mut self, forward: bool) { let current = &self.documents[self.current]; // offset of the closest changed byte let changed = if forward { if let Some((offset, _)) = current .file .changes .range((current.cursor.offset + 1)..u64::MAX) .min() { Some(offset) } else { None } } else if let Some((offset, _)) = current.file.changes.range(0..current.cursor.offset).max() { Some(offset) } else { None }; if let Some(&offset) = changed { let base_offset = current.view.offset; self.move_cursor(&Direction::Absolute(offset, base_offset)); } } /// Save currently focused document. pub fn save(&mut self) -> io::Result<()> { let current = &mut self.documents[self.current]; current.file.save()?; current.changes.reset(); self.refresh(); Ok(()) } /// Save currently focused document with the new name. /// /// # Arguments /// /// * `file` - path to the new file /// * `progress` - long time operation handler pub fn save_as(&mut self, file: &Path, progress: &mut dyn ProgressHandler) -> io::Result<()> { let current = &mut self.documents[self.current]; current.file.save_as(file, progress)?; current.changes.reset(); self.refresh(); Ok(()) } /// Find sequence inside the currently focused document. /// /// # Arguments /// /// * `start` - start address /// * `sequence` - sequence to find /// * `backward` - search direction /// * `progress` - long time operation handler /// /// # Return value /// /// Operation status. pub fn find( &mut self, start: u64, sequence: &[u8], backward: bool, progress: &mut dyn ProgressHandler, ) -> io::Result<()> { let current = &mut self.documents[self.current]; match current.file.find(start, sequence, backward, progress) { Ok(offset) => { if offset != u64::MAX { let view_offset = current.view.offset; self.move_cursor(&Direction::Absolute(offset, view_offset)); self.refresh(); } Ok(()) } Err(err) => Err(err), } } /// Fill range in the currently focused document. /// /// # Arguments /// /// * `range` - range to fill /// * `pattern` - pattern to use pub fn fill(&mut self, range: &Range<u64>, pattern: &[u8]) { debug_assert!(!range.is_empty()); debug_assert!(!pattern.is_empty()); let current = &mut self.documents[self.current]; let mut pattern_pos = 0; for offset in range.start..range.end { current.change(offset, pattern[pattern_pos], 0xff); pattern_pos += 1; if pattern_pos == pattern.len() { pattern_pos = 0; } } let offset = current.view.offset; self.move_cursor(&Direction::Absolute(range.end, offset)); self.refresh(); } /// Insert bytes at specified offset. /// /// # Arguments /// /// * `offset` - start offset /// * `size` - number of bytes to insert /// * `pattern` - pattern to fill /// * `progress` - long time operation handler /// /// # Return value /// /// Operation status. pub fn insert( &mut self, offset: u64, size: u64, pattern: &[u8], progress: &mut dyn ProgressHandler, ) -> io::Result<()> { let current = &mut self.documents[self.current]; debug_assert!(!current.file.is_modified()); debug_assert!(offset <= current.file.size); current.file.insert(offset, size, pattern, progress)?; current.view.max_offset = current.file.size; let view_offset = current.view.offset; self.move_cursor(&Direction::Absolute(offset + size, view_offset)); self.refresh(); Ok(()) } /// Cut out the specified range. /// /// # Arguments /// /// * `range` - range to cut out /// * `progress` - long time operation handler pub fn cut( &mut self, range: &Range<u64>, progress: &mut dyn ProgressHandler, ) -> io::Result<()> { let current = &mut self.documents[self.current]; debug_assert!(!current.file.is_modified()); current.file.cut(range, progress)?; current.view.max_offset = current.file.size; let offset = current.view.offset; self.move_cursor(&Direction::Absolute(range.start, offset)); self.refresh(); Ok(()) } /// Setup via GUI. pub fn config_changed(&mut self, config: &Config) { for doc in &mut self.documents { doc.view.fixed_width = config.fixed_width; doc.view.ascii_table = config.ascii_table; if doc.view.ascii_table.is_none() { doc.cursor.set_place(Place::Hex); } doc.view.reinit(); } let cursor = self.documents[self.current].cursor.offset; let base = self.documents[self.current].view.offset; self.move_cursor(&Direction::Absolute(cursor, base)); self.refresh(); } /// Refresh documents buffers: data cache, changed set, diff etc. fn refresh(&mut self) { // refresh buffer for all documents self.documents.iter_mut().for_each(Document::refresh); // update diff markers if self.documents.len() > 1 { for index in 0..self.documents.len() { let mut diff = BTreeSet::new(); let doc = &mut self.documents[index]; let offset = doc.view.offset; let size = doc.view.lines * doc.view.columns; let data_l = doc.file.read(offset, size).unwrap(); for (_, doc_r) in self .documents .iter_mut() .enumerate() .filter(|(i, _)| *i != index) { let data_r = if offset >= doc_r.file.size { vec![] } else { doc_r.file.read(offset, size).unwrap() }; for (index, byte_l) in data_l.iter().enumerate() { let mut equal = false; if let Some(byte_r) = data_r.get(index) { equal = byte_l == byte_r; } if !equal { diff.insert(offset + index as u64); } } } self.documents[index].view.differs = diff; } } } } /// Editable document. pub struct Document { /// Editable file. pub file: File, /// Change list. pub changes: ChangeList, /// Cursor position within a page. pub cursor: Cursor, /// View of the document. pub view: View, } impl Document { /// Create new document instance. /// /// # Arguments /// /// * `path` - path to the file to open /// * `config` - app configuration /// /// # Return value /// /// Document instance. fn new(path: &Path, config: &Config) -> io::Result<Self> { let file = File::open(path)?; let file_size = file.size; Ok(Self { file, changes: ChangeList::default(), cursor: Cursor::default(), view: View::new(config, file_size), }) } /// Move cursor. /// /// # Arguments /// /// * `dir` - move direction /// /// # Return value /// /// `true` if new base address was set fn move_cursor(&mut self, dir: &Direction) -> bool { let new_base = self.cursor.move_to(dir, &self.view); let base_changed = new_base != self.view.offset; if base_changed { self.view.offset = new_base; self.refresh(); } base_changed } /// Update currently displayed page. fn refresh(&mut self) { self.file.changes = self.changes.get(); self.view.data = self .file .read(self.view.offset, self.view.lines * self.view.columns) .unwrap(); self.view.changes = self .file .changes .keys() .filter(|&o| { (self.view.offset..self.view.offset + (self.view.lines * self.view.columns) as u64) .contains(o) }) .copied() .collect(); } /// Change data in the document. /// /// # Arguments /// /// * `offset` - offset of the byte value to change /// * `value` - new value /// * `mask` - mask of the new value fn change(&mut self, offset: u64, value: u8, mask: u8) { debug_assert!(mask == 0x0f || mask == 0xf0 || mask == 0xff); // get currently set value let old = if let Some(val) = self.changes.last(offset) { val } else { self.file.read(offset, 1).unwrap()[0] }; // set new value let new = (old & !mask) | (value & mask); if old != value { self.changes.set(offset, old, new); } } } /// Focus switch direction. pub enum Focus { NextField, PreviousField, NextDocument, PreviousDocument, DocumentIndex(usize), } <file_sep>/src/ui/dialog.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::super::curses::{Color, Curses, Event, Key, KeyPress, Window}; use super::widget::{Button, StandardButton, WidgetContext, WidgetType}; use unicode_segmentation::UnicodeSegmentation; /// Dialog window. pub struct Dialog { /// Dialog window. window: Window, /// Dialog items. items: Vec<DialogItem>, /// Last used line number used by constructor. lcline: usize, /// Currently focused item. focus: ItemId, /// Title. title: String, /// Resize flag. resized: bool, } impl Dialog { // Size of the field between window edge and border const BORDER_X: usize = 3; const BORDER_Y: usize = 1; // Size of the padding pub const PADDING_X: usize = Dialog::BORDER_X + 2; pub const PADDING_Y: usize = Dialog::BORDER_Y + 1; /// Create new dialog. /// /// # Arguments /// /// * `width` - width of the useful area /// * `height` - height of the useful area /// * `dt` - dialog type, used for setting background color /// * `title` - dialog title /// /// # Return value /// /// Dialog instance. pub fn new(width: usize, height: usize, dt: DialogType, title: &str) -> Self { // dialog size with borders let width = width + Dialog::PADDING_X * 2; let height = height + Dialog::PADDING_Y * 2 + 2 /* buttons with separator */; // dialog color from type let color = if dt == DialogType::Normal { Color::Dialog } else { Color::Error }; // separator above buttons block let separator = DialogItem { widget: WidgetType::Separator {}, context: WidgetContext { x: Dialog::BORDER_X, y: height - Dialog::PADDING_Y - 2, width: width - Dialog::BORDER_X * 2, ..WidgetContext::default() }, }; Self { window: Window::new_centered(width, height, color), items: vec![separator], lcline: Dialog::PADDING_Y, focus: ItemId::MAX, title: format!(" {} ", title), resized: false, } } /// Get size of the dialog exclude borders and padding. /// /// # Return value /// /// Size of the useful area. pub fn get_size(&self) -> (usize, usize) { let (mut width, mut height) = self.window.get_size(); width -= Dialog::PADDING_X * 2; height -= Dialog::PADDING_Y * 2; (width, height) } /// Run dialog: show window and handle input events. /// /// # Arguments /// /// * `handler` - dialog custom handlers /// /// # Return value /// /// Last focused item Id or None if Esc pressed. pub fn show(&mut self, handler: &mut dyn DialogHandler) -> Option<ItemId> { let mut last_focus = None; if self.focus == ItemId::MAX { self.initialize_focus(); } // main event handler loop loop { // redraw self.draw(); // handle next event match Curses::wait_event() { Event::TerminalResize => { self.resized = true; } Event::KeyPress(event) => { match event.key { Key::Tab => { if let Some(previous) = self.move_focus(event.modifier != KeyPress::SHIFT) { handler.on_focus_lost(self, previous); } } Key::Esc => { break; } Key::Enter => { if handler.on_close(self, self.focus) { last_focus = Some(self.focus); break; } } _ => { if self.focus != ItemId::MAX { let item = &mut self.items[self.focus]; if item.widget.key_press(&event) { handler.on_item_change(self, self.focus); } else if event.key == Key::Left || event.key == Key::Up { if let Some(previous) = self.move_focus(false) { handler.on_focus_lost(self, previous); } } else if event.key == Key::Right || event.key == Key::Down { if let Some(previous) = self.move_focus(true) { handler.on_focus_lost(self, previous); } } } } }; } } } if self.resized { Curses::screen_resize(); } last_focus } /// Show simple dialog without external handlers. pub fn show_unmanaged(&mut self) -> Option<ItemId> { let mut dummy = DialogEmptyHandler {}; self.show(&mut dummy) } /// Hide dialog window. pub fn hide(&self) { self.window.hide(); } /// Get item widget instance. /// /// # Arguments /// /// * `item` - item Id /// /// # Return value /// /// Widget instance. pub fn get_widget(&self, item: ItemId) -> &WidgetType { &self.items[item].widget } /// Get mutable item widget instance. /// /// # Arguments /// /// * `item` - item Id /// /// # Return value /// /// Mutable widget instance. pub fn get_widget_mut(&mut self, item: ItemId) -> &mut WidgetType { &mut self.items[item].widget } /// Get item context. /// /// # Arguments /// /// * `item` - item Id /// /// # Return value /// /// Context of the item. pub fn get_context(&self, item: ItemId) -> &WidgetContext { &self.items[item].context } /// Enable or disable item. /// /// # Arguments /// /// * `item` - item Id /// * `state` - new state to set pub fn set_enabled(&mut self, item: ItemId, state: bool) { self.items[item].context.enabled = state; } /// Add new widget onto dialog window. /// /// # Arguments /// /// * `x` - widget position /// * `y` - widget position /// * `width` - widget width /// * `widget` - widget to add /// /// # Return value /// /// Item Id of added widget. pub fn add(&mut self, x: usize, y: usize, width: usize, widget: WidgetType) -> ItemId { let context = WidgetContext { x, y, width, ..WidgetContext::default() }; self.items.push(DialogItem { widget, context }); self.items.len() as ItemId - 1 } /// Add new widget on the next line on dialog window. /// /// # Arguments /// /// * `widget` - widget to add /// /// # Return value /// /// Item Id of added widget. pub fn add_line(&mut self, widget: WidgetType) -> ItemId { let (width, _) = self.get_size(); let line = self.lcline; self.lcline += 1; self.add(Dialog::PADDING_X, line, width, widget) } /// Add centered text on the next line on dialog window. /// /// # Arguments /// /// * `text` - static text to add pub fn add_center(&mut self, text: String) { debug_assert!(!text.is_empty()); let (width, _) = self.get_size(); let len = text.graphemes(true).count(); debug_assert!(len <= width); let x = Dialog::PADDING_X + width / 2 - len / 2; let line = self.lcline; self.lcline += 1; self.add(x, line, len, WidgetType::StaticText(text)); } /// Add standart button on dialog. /// /// # Arguments /// /// * `button` - button to add /// * `default` - default button flag /// /// # Return value /// /// Item Id of added widget. pub fn add_button(&mut self, button: StandardButton, default: bool) -> ItemId { let text = button.text(default); let (width, height) = self.get_size(); let btn_width = text.len(); let btn_y = height + Dialog::PADDING_Y - 1; let mut btn_x = Dialog::PADDING_X; // total width of buttons on the same line let mut total_width = btn_width; for item in self.items.iter().filter(|i| i.context.y == btn_y) { total_width += item.context.width + 1 /* space */; } debug_assert!(total_width <= width); // calculate position of the button let center = width / 2 - total_width / 2; if total_width == btn_width { btn_x += center; } else { // move items on the same line to the left let mut move_x = center; for item in self.items.iter_mut().filter(|i| i.context.y == btn_y) { item.context.x = Dialog::PADDING_X + move_x; move_x += item.context.width + 1 /* space */; } btn_x += move_x; } let widget = WidgetType::Button(Button { text, default }); self.add(btn_x, btn_y, btn_width, widget) } /// Add separator in the nect line on dialog window. pub fn add_separator(&mut self) { let (mut width, _) = self.window.get_size(); width -= Dialog::BORDER_X * 2; let line = self.lcline; self.lcline += 1; self.add(Dialog::BORDER_X, line, width, WidgetType::Separator {}); } /// Draw dialog window. pub fn draw(&self) { self.window.clear(); // draw border let (mut width, mut height) = self.window.get_size(); width -= Dialog::BORDER_X * 2; height -= Dialog::BORDER_Y * 2; // top line with title let line = "\u{2554}".to_string() + &"\u{2550}".repeat(width - 2) + "\u{2557}"; self.window.print(Dialog::BORDER_X, Dialog::BORDER_Y, &line); let length = self.title.len(); let center = Dialog::BORDER_X + width / 2 - length / 2; self.window.print(center, Dialog::BORDER_Y, &self.title); self.window .set_style(center, Dialog::BORDER_Y, length, Window::BOLD); // bottom line let line = "\u{255a}".to_string() + &"\u{2550}".repeat(width - 2) + "\u{255d}"; self.window .print(Dialog::BORDER_X, Dialog::BORDER_Y + height - 1, &line); // left and right lines for y in Dialog::BORDER_Y + 1..Dialog::BORDER_Y + height - 1 { self.window.print(Dialog::BORDER_X, y, "\u{2551}"); self.window .print(Dialog::BORDER_X + width - 1, y, "\u{2551}"); } // dialog items let mut cursor: Option<(usize, usize)> = None; for item in &self.items { if let Some((x, y)) = item.widget.draw(&self.window, &item.context) { cursor = Some((x, y)); } } if let Some((x, y)) = cursor { self.window.show_cursor(x, y); } else { Window::hide_cursor(); } self.window.refresh(); } /// Set focus to the next windget. /// /// # Arguments /// /// * `forward` - focus movement direction /// /// # Return value /// /// Previously focus (item that lost the focus). fn move_focus(&mut self, forward: bool) -> Option<ItemId> { debug_assert_ne!(self.focus, ItemId::MAX); let mut focus = self.focus; loop { if forward { focus += 1; if focus == self.items.len() as ItemId { focus = 0; } } else { if focus == 0 { focus = self.items.len() as ItemId; } focus -= 1; } let item = &self.items[focus]; if item.context.enabled && item.widget.focusable() { break; } } if focus != self.focus { let previous = self.focus; let item = &mut self.items[self.focus]; item.context.focused = false; self.focus = focus; let item = &mut self.items[self.focus]; item.context.focused = true; item.widget.focus_set(); return Some(previous); } None } /// Set initial focus. fn initialize_focus(&mut self) { debug_assert_eq!(self.focus, ItemId::MAX); // find the first focusable widget for (index, item) in self.items.iter().enumerate() { if item.context.enabled && item.widget.focusable() { self.focus = index; break; } } debug_assert_ne!(self.focus, ItemId::MAX); // no one focusable item? // if focus is inside the buttons block then set it to default button if let WidgetType::Button(_) = &self.items[self.focus].widget { for (index, item) in self.items.iter().skip(self.focus).enumerate() { if let WidgetType::Button(widget) = &item.widget { if widget.default { self.focus += index; break; } } } } let item = &mut self.items[self.focus]; item.context.focused = true; item.widget.focus_set(); } /// Get max width of the dialog. /// /// # Return value /// /// Max width of useful area (exclude borders). pub fn max_width() -> usize { let (width, _) = Curses::screen_size(); let padding = Dialog::PADDING_X * 2; if width < padding { 0 } else { width - padding } } } /// Dialog type. #[derive(Copy, Clone, PartialEq)] pub enum DialogType { Normal, Error, } /// Type of dialog item ID. pub type ItemId = usize; /// Single dialog item. pub struct DialogItem { widget: WidgetType, context: WidgetContext, } /// Dialog handlers. pub trait DialogHandler { /// Check if dialog can be closed (not canceled). /// /// # Arguments /// /// * `dialog` - dialog instance /// * `item` - currently focused item Id /// /// # Return value /// /// true if dialog can be closed. fn on_close(&mut self, _dialog: &mut Dialog, _item: ItemId) -> bool { true } /// Item change callback. /// /// # Arguments /// /// * `dialog` - dialog instance /// * `item` - Id of the item that was changed fn on_item_change(&mut self, _dialog: &mut Dialog, _item: ItemId) {} /// Focus lost callback. /// /// # Arguments /// /// * `dialog` - dialog instance /// * `item` - Id of the item that lost focus fn on_focus_lost(&mut self, _dialog: &mut Dialog, _item: ItemId) {} } /// Empty dialog handler, used for simple dialogs. struct DialogEmptyHandler; impl DialogHandler for DialogEmptyHandler {} <file_sep>/src/ui/widget.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::super::curses::{Color, Key, KeyPress, Window}; use unicode_segmentation::UnicodeSegmentation; /// Typed widget. #[derive(PartialEq)] pub enum WidgetType { Separator, StaticText(String), CheckBox(CheckBox), ListBox(ListBox), ProgressBar(u8), Button(Button), Edit(InputLine), } impl WidgetType { /// Draw widget. /// /// # Arguments /// /// * `wnd` - window (canvas) /// * `ctx` - widget context /// /// # Return value /// /// Cursor coordinates on the window. pub fn draw(&self, wnd: &Window, ctx: &WidgetContext) -> Option<(usize, usize)> { match self { WidgetType::Separator => { let text = format!("\u{255f}{:\u{2500}^1$}\u{2562}", "", ctx.width - 2); wnd.print(ctx.x, ctx.y, &text); } WidgetType::StaticText(text) => { wnd.print(ctx.x, ctx.y, text); } WidgetType::CheckBox(widget) => { widget.draw(wnd, ctx); } WidgetType::ListBox(widget) => { widget.draw(wnd, ctx); } WidgetType::ProgressBar(percent) => { debug_assert!(*percent <= 100); let text = format!(" {:>3}%", percent); let barsz = ctx.width - text.len(); let fill = *percent as usize * barsz / 100; let bar = "\u{2588}".repeat(fill) + &"\u{2591}".repeat(barsz - fill) + &text; wnd.print(ctx.x, ctx.y, &bar); } WidgetType::Button(widget) => { widget.draw(wnd, ctx); } WidgetType::Edit(widget) => { return widget.draw(wnd, ctx); } }; None } /// Keyboard input handler. /// /// # Arguments /// /// * `key` - pressed key /// /// # Return value /// /// `true` if key was handled. pub fn key_press(&mut self, key: &KeyPress) -> bool { match self { WidgetType::Edit(widget) => widget.key_press(key), WidgetType::CheckBox(widget) => widget.key_press(key), WidgetType::ListBox(widget) => widget.key_press(key), _ => false, } } /// Check if widget is focusable. /// /// # Return value /// /// `true` if widget can take focus pub fn focusable(&self) -> bool { matches!( self, WidgetType::CheckBox(_) | WidgetType::Button(_) | WidgetType::ListBox(_) | WidgetType::Edit(_) ) } /// Set focus handler. pub fn focus_set(&mut self) { if let WidgetType::Edit(edit) = self { edit.on_focus_set(); } } } /// Widget context: linkage with a dialog. pub struct WidgetContext { /// Focus flag. pub focused: bool, /// State. pub enabled: bool, /// Start column on the dialog window. pub x: usize, /// Line number on the dialog window. pub y: usize, /// Size of the widget. pub width: usize, } impl Default for WidgetContext { fn default() -> Self { Self { focused: false, enabled: true, x: 0, y: 0, width: 0, } } } /// Check box control. #[derive(PartialEq)] pub struct CheckBox { pub state: bool, pub title: String, } impl CheckBox { /// Draw widget. /// /// # Arguments /// /// * `wnd` - window (canvas) /// * `ctx` - widget context pub fn draw(&self, wnd: &Window, ctx: &WidgetContext) { let text = &format!("[{}] {}", if self.state { 'x' } else { ' ' }, self.title); wnd.print(ctx.x, ctx.y, text); if ctx.focused || !ctx.enabled { let color = if ctx.focused { Color::Focused } else { Color::Disabled }; wnd.set_color(ctx.x, ctx.y, 3, color); } } /// Keyboard input handler. /// /// # Arguments /// /// * `key` - pressed key /// /// # Return value /// /// `true` if key was handled. pub fn key_press(&mut self, key: &KeyPress) -> bool { if key.key == Key::Char(' ') { self.state = !self.state; true } else { false } } } /// List box control. #[derive(PartialEq)] pub struct ListBox { pub list: Vec<String>, pub current: usize, } impl ListBox { /// Draw widget. /// /// # Arguments /// /// * `wnd` - window (canvas) /// * `ctx` - widget context pub fn draw(&self, wnd: &Window, ctx: &WidgetContext) { debug_assert!(self.current < self.list.len()); let text = format!( "{: ^width$}", self.list[self.current], width = ctx.width - 2 ); wnd.print(ctx.x, ctx.y, "\u{25c4}"); wnd.print(ctx.x + ctx.width - 1, ctx.y, "\u{25ba}"); wnd.print(ctx.x + 1, ctx.y, &text); if ctx.focused || !ctx.enabled { let color = if ctx.focused { Color::Focused } else { Color::Disabled }; wnd.set_color(ctx.x, ctx.y, ctx.width, color); } } /// Keyboard input handler. /// /// # Arguments /// /// * `key` - pressed key /// /// # Return value /// /// `true` if key was handled. pub fn key_press(&mut self, key: &KeyPress) -> bool { match key.key { Key::Left => { if self.current > 0 { self.current -= 1; } } Key::Right => { if self.current < self.list.len() - 1 { self.current += 1; } } _ => { return false; } }; true } } /// Button. #[derive(PartialEq)] pub struct Button { /// Text representation. pub text: String, /// Default button in group. pub default: bool, } impl Button { /// Draw widget. /// /// # Arguments /// /// * `wnd` - window (canvas) /// * `ctx` - widget context pub fn draw(&self, wnd: &Window, ctx: &WidgetContext) { wnd.print(ctx.x, ctx.y, &self.text); if ctx.focused || !ctx.enabled { let color = if ctx.focused { Color::Focused } else { Color::Disabled }; wnd.set_color(ctx.x, ctx.y, ctx.width, color); } } } /// Standard buttons. #[derive(Clone, Copy, PartialEq)] pub enum StandardButton { OK, Cancel, Retry, Yes, No, } impl StandardButton { /// Get text representation of the button. /// /// # Arguments /// /// * `default` - default button in group /// /// # Return value /// /// Button text. pub fn text(self, default: bool) -> String { let title = match self { StandardButton::OK => "OK", StandardButton::Cancel => "Cancel", StandardButton::Retry => "Retry", StandardButton::Yes => "Yes", StandardButton::No => "No", }; format!( "{} {} {}", if default { '{' } else { '[' }, title, if default { '}' } else { ']' } ) } } /// Single line input widget. #[derive(PartialEq)] pub struct InputLine { /// Editing value. value: String, /// Value format. format: InputFormat, /// Size of the input field. width: usize, /// Selection flag. selection: bool, /// Cursor position in value string. cursor: usize, /// First visible character of value string. start: usize, /// Input history. history: Vec<String>, /// Current index in history. current: usize, } impl InputLine { /// Create new widget instance. /// /// # Arguments /// /// * `value` - default value /// * `format` - value format /// * `history` - input history /// * `width` - size of the input field /// /// # Return value /// /// Widget instance. pub fn new(value: String, format: InputFormat, history: Vec<String>, width: usize) -> Self { Self { value, format, width, selection: false, cursor: 0, start: 0, history, current: 0, } } /// Set new value. /// /// # Arguments /// /// * `value` - new value pub fn set_value(&mut self, value: String) { self.value = value; self.move_cursor(isize::MIN); } /// Get the current value. /// /// # Return value /// /// Current value. pub fn get_value(&self) -> &str { &self.value } /// Draw widget. /// /// # Arguments /// /// * `wnd` - window (canvas) /// * `ctx` - widget context pub fn draw(&self, wnd: &Window, ctx: &WidgetContext) -> Option<(usize, usize)> { // get substring to display let visible_end = self.start + ctx.width.min(self.length() - self.start); let start = self.char2byte(self.start); let end = self.char2byte(visible_end); let substr = self.value[start..end].to_string(); // draw wnd.print(ctx.x, ctx.y, &substr); if !self.history.is_empty() { wnd.print(ctx.x + ctx.width - 1, ctx.y, "\u{25bc}"); } let color = if ctx.focused { Color::Focused } else { Color::Input }; wnd.set_color(ctx.x, ctx.y, ctx.width, color); if ctx.focused { if self.selection { wnd.set_color(ctx.x, ctx.y, self.cursor - self.start, Color::Select); } Some((ctx.x + self.cursor - self.start, ctx.y)) } else { None } } /// Keyboard input handler. /// /// # Arguments /// /// * `key` - pressed key /// /// # Return value /// /// `true` if key was handled. pub fn key_press(&mut self, key: &KeyPress) -> bool { match key.key { Key::Up => { if key.modifier & KeyPress::CTRL != 0 { self.from_history(false); return true; } return false; } Key::Down => { if key.modifier & KeyPress::CTRL != 0 { self.from_history(true); return true; } return false; } Key::Home => { self.move_cursor(isize::MIN); } Key::End => { self.move_cursor(isize::MAX); } Key::Left => { self.move_cursor(-1); } Key::Right => { self.move_cursor(1); } Key::Delete => { self.delete_char(1); } Key::Backspace => { self.delete_char(-1); } Key::Char(ch) => { self.insert_char(ch); } _ => { return false; } }; true } /// Focus set handler. pub fn on_focus_set(&mut self) { self.move_cursor(isize::max_value()); self.selection = true; } /// Move cursor inside the edit string. fn move_cursor(&mut self, step: isize) { debug_assert!(step != 0); self.selection = false; // change cursor position let length = self.length() as isize; self.cursor = if step > length || self.cursor as isize + step > length { length as usize } else if step < 0 && self.cursor as isize + step < 0 { 0 } else { (self.cursor as isize + step) as usize }; // change start position (first visible character) if self.cursor < self.start { self.start = self.cursor; } else if self.cursor >= self.start + self.width { self.start = self.cursor - self.width + 1; } } /// Insert character to current cursor position. fn insert_char(&mut self, ch: char) { let max_hex = 16; let max_dec = 20; let max_stream = 256 * 2; let allow = match self.format { InputFormat::Any => true, InputFormat::HexStream => self.value.len() < max_stream && ch.is_ascii_hexdigit(), InputFormat::HexSigned => { (self.value.len() < max_hex && ch.is_ascii_hexdigit()) || ((self.cursor == 0 || self.selection) && (ch == '-' || ch == '+')) } InputFormat::HexUnsigned => self.value.len() <= max_hex && ch.is_ascii_hexdigit(), InputFormat::DecSigned => { (self.value.len() < max_dec && ch.is_ascii_digit()) || ((self.cursor == 0 || self.selection) && (ch == '-' || ch == '+')) } InputFormat::DecUnsigned => self.value.len() <= max_dec && ch.is_ascii_digit(), }; if allow { if self.selection { // delete the entire selection self.selection = false; self.value.clear(); self.move_cursor(isize::min_value()); } let byte_pos = self.char2byte(self.cursor); self.value.insert(byte_pos, ch); self.move_cursor(1); } } /// Delete character from current cursor position. fn delete_char(&mut self, count: isize) { debug_assert!(count != 0); if self.selection { // delete the entire selection self.selection = false; self.value.clear(); self.move_cursor(isize::min_value()); } let length = self.length(); if count > 0 && self.cursor < length { // delete to the right let remove = std::cmp::min(length - self.cursor, count as usize); let byte_start = self.char2byte(self.cursor); let byte_end = self.char2byte(self.cursor + remove); self.value.drain(byte_start..byte_end); } else if count < 0 && self.cursor > 0 { // delete to the left (backspace) let remove = std::cmp::min(self.cursor, count.abs() as usize); let byte_start = self.char2byte(self.cursor - remove); let byte_end = self.char2byte(self.cursor); self.value.drain(byte_start..byte_end); self.move_cursor(count); } } /// Move through history. fn from_history(&mut self, forward: bool) { if forward && self.current + 1 < self.history.len() { self.current += 1; } else if !forward && self.current > 0 { self.current -= 1; } else { return; } self.value = self.history[self.current].clone(); self.move_cursor(isize::MAX); self.selection = true; } /// Get length of the string in visual characters (grapheme). fn length(&self) -> usize { self.value.graphemes(true).count() } /// Convert char (grapheme) position to byte offset inside the value. fn char2byte(&self, char_pos: usize) -> usize { let mut byte_pos = 0; if char_pos > 0 { let (i, gr) = self .value .grapheme_indices(true) .nth(char_pos - 1) .expect("Invalid position"); byte_pos = i + gr.len(); } byte_pos } } /// Value formats. #[derive(Clone, PartialEq)] pub enum InputFormat { Any, HexStream, HexSigned, HexUnsigned, DecSigned, DecUnsigned, } <file_sep>/src/history.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::inifile::IniFile; use std::env; use std::path::PathBuf; /// History: loads, holds and saves editor history (offsets, searches, etc). pub struct History { /// Last position in files. pub file_pos: Vec<(String, u64)>, /// Search history. pub search: Vec<Vec<u8>>, /// Last used search direction (volatile). pub search_backward: bool, /// Goto address history. pub goto: Vec<u64>, /// Last used pattern to fill (volatile). pub pattern: Vec<u8>, } impl History { // Max number of stored entries const MAX_FILE: usize = 10; const MAX_SEARCH: usize = 10; const MAX_GOTO: usize = 10; // INI sections names const SEC_FILE: &'static str = "file"; const SEC_SEARCH: &'static str = "search"; const SEC_GOTO: &'static str = "goto"; /// Load history from the ini file. /// /// # Arguments /// /// * `ini` - ini file to process fn load(&mut self, ini: &IniFile) { // read recent file position history if let Some(section) = ini.sections.get(History::SEC_FILE) { self.file_pos.reserve(section.len().max(History::MAX_FILE)); for line in section.iter().take(History::MAX_FILE) { // stored as `file:offset` let split: Vec<&str> = line.rsplitn(2, ':').collect(); if split.len() == 2 { if let Ok(offset) = u64::from_str_radix(split[0], 16) { self.file_pos.push((split[1].to_string(), offset)); } } } } // read search history if let Some(section) = ini.sections.get(History::SEC_SEARCH) { self.search.reserve(section.len().max(History::MAX_SEARCH)); for line in section.iter().take(History::MAX_SEARCH) { if line.len() % 2 == 0 { let mut seq = Vec::with_capacity(line.len() / 2); for i in (0..line.len()).step_by(2) { if let Ok(n) = u8::from_str_radix(&line[i..i + 2], 16) { seq.push(n); } else { break; } } if !seq.is_empty() { self.search.push(seq); } } } } // read "goto" history if let Some(section) = ini.sections.get(History::SEC_GOTO) { self.goto.reserve(section.len().max(History::MAX_GOTO)); for line in section.iter().take(History::MAX_GOTO) { if let Ok(offset) = u64::from_str_radix(line, 16) { self.goto.push(offset); } } } } /// Save history to the ini file. pub fn save(&self) { if let Some(file) = History::ini_file() { let mut ini = IniFile::new(); // recent file position history ini.sections.insert( History::SEC_FILE.to_string(), self.file_pos .iter() .take(History::MAX_FILE) .map(|(f, o)| format!("{}:{:x}", f, o)) .collect(), ); // search history ini.sections.insert( History::SEC_SEARCH.to_string(), self.search .iter() .take(History::MAX_SEARCH) .map(|s| s.iter().map(|b| format!("{:02x}", b)).collect()) .collect(), ); // "goto" history ini.sections.insert( History::SEC_GOTO.to_string(), self.goto .iter() .take(History::MAX_GOTO) .map(|o| format!("{:x}", o)) .collect(), ); ini.save(&file).ok(); } } /// Get last position for the specified file. pub fn get_filepos(&self, file: &str) -> Option<u64> { // get absolute path let path = if let Ok(path) = std::fs::canonicalize(file) { path.into_os_string().into_string().unwrap() } else { file.to_string() }; // search in history if let Some((_, offset)) = self.file_pos.iter().find(|(f, _)| *f == path) { return Some(*offset); } None } /// Add last position for the specified file. pub fn add_filepos(&mut self, file: &str, offset: u64) { // get absolute path let path = if let Ok(path) = std::fs::canonicalize(file) { path.into_os_string().into_string().unwrap() } else { file.to_string() }; // remove previous records and new one self.file_pos.retain(|(f, _)| *f != path); self.file_pos.insert(0, (path, offset)); self.file_pos.truncate(History::MAX_FILE); } /// Add search sequence to history. pub fn add_search(&mut self, sequence: &[u8]) { self.search.retain(|s| s != sequence); self.search.insert(0, sequence.to_vec()); self.search.truncate(History::MAX_SEARCH); } /// Add "goto" address to history. pub fn add_goto(&mut self, offset: u64) { self.goto.retain(|o| o != &offset); self.goto.insert(0, offset); self.goto.truncate(History::MAX_GOTO); } /// Get path to the history file. fn ini_file() -> Option<PathBuf> { let dir; match env::var("XDG_DATA_HOME") { Ok(val) => dir = PathBuf::from(val), Err(_) => match env::var("HOME") { Ok(val) => dir = PathBuf::from(val).join(".local").join("share"), Err(_) => return None, }, }; Some(dir.join("xvi").join("history")) } } impl Default for History { fn default() -> Self { let mut instance = Self { file_pos: Vec::new(), search: Vec::new(), search_backward: false, goto: Vec::new(), pattern: vec![0], }; if let Some(file) = History::ini_file() { if let Ok(ini) = IniFile::load(&file) { instance.load(&ini); } } instance } } #[test] fn test_load() { let mut ini = IniFile::new(); ini.sections.insert( History::SEC_FILE.to_string(), vec![ "/path/to/file:1234abc".to_string(), "/path/to/file:invalid".to_string(), ], ); ini.sections.insert( History::SEC_SEARCH.to_string(), vec![ "abcdef1234567890".to_string(), "1234abc".to_string(), // not even "invalid".to_string(), ], ); ini.sections.insert( History::SEC_GOTO.to_string(), vec!["abc".to_string(), "-1".to_string()], ); let mut history = History { file_pos: Vec::new(), search: Vec::new(), search_backward: false, goto: Vec::new(), pattern: Vec::new(), }; history.load(&ini); assert_eq!( history.file_pos, vec![("/path/to/file".to_string(), 0x1234abc_u64)] ); assert_eq!( history.search, vec![vec![0xab, 0xcd, 0xef, 0x12, 0x34, 0x56, 0x78, 0x90]] ); assert_eq!(history.goto, vec![0xabc]); } #[test] fn test_set_goto() { let mut history = History { file_pos: Vec::new(), search: Vec::new(), search_backward: false, goto: vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], pattern: Vec::new(), }; history.add_goto(55); assert_eq!(history.goto, vec![55, 0, 1, 2, 3, 4, 5, 6, 7, 8],); history.add_goto(3); assert_eq!(history.goto, vec![3, 55, 0, 1, 2, 4, 5, 6, 7, 8],); } #[test] fn test_filepos() { let mut history = History { file_pos: Vec::new(), search: Vec::new(), search_backward: false, goto: Vec::new(), pattern: Vec::new(), }; history.add_filepos("file1", 1); history.add_filepos("/path/file2", 2); history.add_filepos("file1", 3); assert_eq!(history.file_pos.len(), 2); assert_eq!(history.file_pos[0], ("file1".to_string(), 3)); assert_eq!(history.file_pos[1], ("/path/file2".to_string(), 2)); assert_eq!(history.get_filepos("file1"), Some(3)); assert_eq!(history.get_filepos("/path/file2"), Some(2)); assert_eq!(history.get_filepos("file3"), None); } <file_sep>/src/ui/goto.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::dialog::{Dialog, DialogHandler, DialogType, ItemId}; use super::widget::{InputFormat, InputLine, StandardButton, WidgetType}; /// "Goto" dialog. pub struct GotoDialog { // Current offet (cursor position) current: u64, // Items of the dialog. abs_hex: ItemId, abs_dec: ItemId, rel_hex: ItemId, rel_dec: ItemId, } impl GotoDialog { /// Width of the input fields. const INP_WIDTH: usize = 17; /// Show the "Goto" configuration dialog. /// /// # Arguments /// /// * `history` - address history /// * `current` - current offset /// /// # Return value /// /// Absolute offset to jump. pub fn show(history: &[u64], current: u64) -> Option<u64> { // create dialog let mut dlg = Dialog::new(44, 5, DialogType::Normal, "Goto"); dlg.add_line(WidgetType::StaticText("Absolute offset".to_string())); // absolute offset in dec dlg.add_line(WidgetType::StaticText("hex:".to_string())); let history: Vec<String> = history.iter().map(|o| format!("{:x}", o)).collect(); let init = if history.is_empty() { String::new() } else { history[0].clone() }; let widget = InputLine::new( init, InputFormat::HexUnsigned, history, GotoDialog::INP_WIDTH, ); let abs_hex = dlg.add( Dialog::PADDING_X + 4, Dialog::PADDING_Y + 1, GotoDialog::INP_WIDTH, WidgetType::Edit(widget), ); // absolute offset in dec dlg.add( Dialog::PADDING_X + 23, Dialog::PADDING_Y + 1, 4, WidgetType::StaticText("dec:".to_string()), ); let widget = InputLine::new( String::new(), InputFormat::DecUnsigned, Vec::new(), GotoDialog::INP_WIDTH, ); let abs_dec = dlg.add( Dialog::PADDING_X + 27, Dialog::PADDING_Y + 1, GotoDialog::INP_WIDTH, WidgetType::Edit(widget), ); dlg.add_separator(); dlg.add_line(WidgetType::StaticText("Relative offset".to_string())); // relative offset in hex dlg.add_line(WidgetType::StaticText("hex:".to_string())); let widget = InputLine::new( String::new(), InputFormat::HexSigned, Vec::new(), GotoDialog::INP_WIDTH, ); let rel_hex = dlg.add( Dialog::PADDING_X + 4, Dialog::PADDING_Y + 4, GotoDialog::INP_WIDTH, WidgetType::Edit(widget), ); // relative offset in dec dlg.add( Dialog::PADDING_X + 23, Dialog::PADDING_Y + 4, 4, WidgetType::StaticText("dec:".to_string()), ); let widget = InputLine::new( String::new(), InputFormat::DecSigned, Vec::new(), GotoDialog::INP_WIDTH, ); let rel_dec = dlg.add( Dialog::PADDING_X + 27, Dialog::PADDING_Y + 4, GotoDialog::INP_WIDTH, WidgetType::Edit(widget), ); // buttons dlg.add_button(StandardButton::OK, true); let btn_cancel = dlg.add_button(StandardButton::Cancel, false); // construct dialog handler let mut handler = Self { current, abs_hex, abs_dec, rel_hex, rel_dec, }; handler.on_item_change(&mut dlg, handler.abs_hex); // show dialog if let Some(id) = dlg.show(&mut handler) { if id != btn_cancel { if let WidgetType::Edit(widget) = dlg.get_widget(handler.abs_hex) { return Some(u64::from_str_radix(widget.get_value(), 16).unwrap_or(0)); } } } None } /// Update fields. /// /// # Arguments /// /// * `dialog` - dialog instance /// * `source` - id of item that is the source of the changes fn update(&mut self, dialog: &mut Dialog, source: ItemId) { // calculate offset let mut offset = 0; if let WidgetType::Edit(widget) = dialog.get_widget(source) { let value = widget.get_value(); if source == self.abs_hex { offset = u64::from_str_radix(value, 16).unwrap_or(0); } else if source == self.abs_dec { offset = value.parse::<u64>().unwrap_or(0); } else if source == self.rel_hex || source == self.rel_dec { let relative = if source == self.rel_hex { i64::from_str_radix(value, 16).unwrap_or(0) } else { value.parse::<i64>().unwrap_or(0) }; if relative >= 0 || relative.unsigned_abs() < self.current { offset = self.current; if relative >= 0 { offset += relative.unsigned_abs(); } else { offset -= relative.unsigned_abs(); } } } else { unreachable!(); } } // update other fields if source != self.abs_hex { if let WidgetType::Edit(widget) = dialog.get_widget_mut(self.abs_hex) { widget.set_value(format!("{:x}", offset)); } } if source != self.abs_dec { if let WidgetType::Edit(widget) = dialog.get_widget_mut(self.abs_dec) { widget.set_value(format!("{}", offset)); } } if source != self.rel_hex { if let WidgetType::Edit(widget) = dialog.get_widget_mut(self.rel_hex) { let offset = offset as i64 - self.current as i64; let sign = if offset < 0 { "-" } else { "" }; let text = format!("{}{:x}", sign, i64::abs(offset)); widget.set_value(text); } } if source != self.rel_dec { let offset = offset as i64 - self.current as i64; if let WidgetType::Edit(widget) = dialog.get_widget_mut(self.rel_dec) { widget.set_value(format!("{}", offset)); } } } } impl DialogHandler for GotoDialog { fn on_item_change(&mut self, dialog: &mut Dialog, item: ItemId) { self.update(dialog, item); } fn on_focus_lost(&mut self, dialog: &mut Dialog, item: ItemId) { if let WidgetType::Edit(widget) = dialog.get_widget_mut(item) { if widget.get_value().is_empty() { widget.set_value("0".to_string()); self.update(dialog, item); } } } } <file_sep>/src/cursor.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::view::View; /// Cursor position and movement. pub struct Cursor { /// Absolute offset (current position) of the cursor. pub offset: u64, /// Position inside a hex byte (left/right half byte). pub half: HalfByte, /// Edit mode (hex/ascii). pub place: Place, } impl Cursor { const WORD_SIZE: u64 = 4; /// Set current place (ascii/hex). pub fn set_place(&mut self, place: Place) { self.place = place; self.half = HalfByte::Left; } /// Move cursor. /// /// # Arguments /// /// * `dir` - move direction /// * `view` - view instance /// /// # Return value /// /// New page offset. #[allow(clippy::too_many_lines)] pub fn move_to(&mut self, dir: &Direction, view: &View) -> u64 { let page_size = (view.lines * view.columns) as u64; let mut new_base = view.offset; match dir { Direction::PrevHalf => { if self.place == Place::Hex { if self.half == HalfByte::Right { self.half = HalfByte::Left; } else if self.offset != 0 { self.half = HalfByte::Right; self.offset -= 1; } } else if self.offset != 0 { self.half = HalfByte::Left; self.offset -= 1; } if self.offset < new_base { new_base -= view.columns as u64; } } Direction::NextHalf => { if self.offset == view.max_offset - 1 || (self.place == Place::Hex && self.half == HalfByte::Left) { self.half = HalfByte::Right; } else { self.half = HalfByte::Left; self.offset += 1; if self.offset >= new_base + page_size { new_base += view.columns as u64; } } } Direction::PrevByte => { self.half = HalfByte::Left; if self.offset != 0 { self.offset -= 1; if self.offset < new_base { new_base -= view.columns as u64; } } } Direction::NextByte => { self.half = HalfByte::Left; if self.offset < view.max_offset - 1 { self.offset += 1; if self.offset >= new_base + page_size { new_base += view.columns as u64; } } } Direction::PrevWord => { if self.offset != 0 { self.offset -= Cursor::WORD_SIZE - self.offset % Cursor::WORD_SIZE; if self.offset < new_base { new_base -= view.columns as u64; } } self.half = HalfByte::Left; } Direction::NextWord => { self.offset += Cursor::WORD_SIZE - self.offset % Cursor::WORD_SIZE; if self.offset > view.max_offset - 1 { self.offset = view.max_offset - 1; } if self.offset >= new_base + page_size { new_base += view.columns as u64; } self.half = HalfByte::Left; } Direction::LineBegin => { self.offset -= self.offset % (view.columns as u64); self.half = HalfByte::Left; } Direction::LineEnd => { self.offset += view.columns as u64 - self.offset % (view.columns as u64) - 1; if self.offset > view.max_offset - 1 { self.offset = view.max_offset - 1; } self.half = HalfByte::Left; } Direction::LineUp => { if self.offset >= view.columns as u64 { self.offset -= view.columns as u64; if self.offset < new_base { new_base -= view.columns as u64; } } } Direction::LineDown => { if self.offset + (view.columns as u64) < view.max_offset { self.offset += view.columns as u64; } else if self.offset + (view.columns as u64) - self.offset % (view.columns as u64) < view.max_offset { self.offset = view.max_offset - 1; self.half = HalfByte::Left; } if self.offset >= new_base + page_size { new_base += view.columns as u64; } } Direction::ScrollUp => { if new_base != 0 { new_base -= view.columns as u64; self.offset -= view.columns as u64; } } Direction::ScrollDown => { if new_base + page_size + 1 < view.max_offset { new_base += view.columns as u64; self.offset += view.columns as u64; } } Direction::PageUp => { if new_base >= page_size { new_base -= page_size; self.offset -= page_size; } else { new_base = 0; self.offset = 0; self.half = HalfByte::Left; } } Direction::PageDown => { if new_base + page_size * 2 < view.max_offset { new_base += page_size; self.offset += page_size; } else { if page_size > view.max_offset { new_base = 0; } else { new_base = view.max_offset - page_size; let align = view.max_offset % view.columns as u64; new_base -= align; if align != 0 { new_base += view.columns as u64; } } self.offset = view.max_offset - 1; self.half = HalfByte::Left; } } Direction::FileBegin => { new_base = 0; self.offset = 0; self.half = HalfByte::Left; } Direction::FileEnd => { self.offset = view.max_offset - 1; self.half = HalfByte::Left; if page_size > view.max_offset { new_base = 0; } else { new_base = view.max_offset - page_size; let align = view.max_offset % view.columns as u64; new_base -= align; if align != 0 { new_base += view.columns as u64; } } } Direction::Absolute(offset, base) => { self.offset = if offset < &view.max_offset { *offset } else { view.max_offset - 1 }; self.half = HalfByte::Left; // try to use desirable base offset new_base = *base; if self.offset < new_base || self.offset > new_base + page_size { if self.offset > page_size / 3 { new_base = self.offset - page_size / 3; } else { new_base = self.offset; } new_base -= new_base % view.columns as u64; } if new_base + page_size > view.max_offset { if page_size > view.max_offset { new_base = 0; } else { new_base = view.max_offset - page_size; let align = view.max_offset % view.columns as u64; new_base -= align; if align != 0 { new_base += view.columns as u64; } } } } }; new_base - new_base % view.columns as u64 } } impl Default for Cursor { fn default() -> Self { Self { offset: 0, half: HalfByte::Left, place: Place::Hex, } } } /// Position inside a hex byte (left/right half byte). #[derive(PartialEq)] pub enum HalfByte { Left, Right, } /// Edit mode (hex/ascii). #[derive(PartialEq, Clone)] pub enum Place { Hex, Ascii, } /// Cursor direction to move. pub enum Direction { /// Previous half of byte (hex mode only). PrevHalf, /// Next half of byte (hex mode only). NextHalf, /// Previous byte. PrevByte, /// Next byte. NextByte, /// Previous word (4 bytes). PrevWord, /// Next word (4 bytes). NextWord, /// First byte of current line. LineBegin, /// Last byte of current line. LineEnd, /// Previous line. LineUp, /// Next line. LineDown, /// Scroll one line up. ScrollUp, /// Scroll one line down. ScrollDown, /// Page up. PageUp, /// Page down. PageDown, /// File beginning. FileBegin, /// End of file. FileEnd, /// Absolute offset (offset, desirable base offset). Absolute(u64, u64), } <file_sep>/build.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use std::process::Command; fn main() { // set version from git if let Ok(output) = Command::new("git") .args(&["describe", "--tags", "--long", "--always", "--dirty"]) .output() { if output.status.success() { let mut ver = std::str::from_utf8(&output.stdout) .unwrap() .trim() .to_string(); if ver.starts_with('v') { ver.remove(0); } let components: Vec<&str> = ver.split('-').collect(); if components.len() > 2 { ver = format!( "{}.{}-{}", components[0], components[1], components[2..].join("-") ); } println!("cargo:rustc-env=CARGO_PKG_VERSION={}", ver); } } } <file_sep>/src/ui/cut.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::dialog::{Dialog, DialogHandler, DialogType, ItemId}; use super::range::RangeControl; use super::widget::StandardButton; use std::ops::Range; /// "Cut out range" dialog. pub struct CutDialog { rctl: RangeControl, btn_ok: ItemId, btn_cancel: ItemId, } impl CutDialog { /// Show the "Cut out" configuration dialog. /// /// # Arguments /// /// * `offset` - defualt start offset (current position) /// * `max` - max offset (file size) /// /// # Return value /// /// Range to cut out. pub fn show(offset: u64, max: u64) -> Option<Range<u64>> { // create dialog let mut dlg = Dialog::new( RangeControl::DIALOG_WIDTH, 6, DialogType::Normal, "Cut out range", ); // place range control on dialog let rctl = RangeControl::create(&mut dlg, offset..offset + 1, max); // warning message dlg.add_separator(); dlg.add_center("WARNING!".to_string()); dlg.add_center("This operation cannot be undone!".to_string()); // buttons let btn_ok = dlg.add_button(StandardButton::OK, true); let btn_cancel = dlg.add_button(StandardButton::Cancel, false); // construct dialog handler let mut handler = Self { rctl, btn_ok, btn_cancel, }; // show dialog if let Some(id) = dlg.show(&mut handler) { if id != handler.btn_cancel { let range = handler.rctl.get(&dlg); debug_assert!(range.is_some()); return range; } } None } } impl DialogHandler for CutDialog { fn on_close(&mut self, dialog: &mut Dialog, item: ItemId) -> bool { item == self.btn_cancel || dialog.get_context(self.btn_ok).enabled } fn on_item_change(&mut self, dialog: &mut Dialog, item: ItemId) { self.rctl.on_item_change(dialog, item); dialog.set_enabled(self.btn_ok, self.rctl.get(dialog).is_some()); } fn on_focus_lost(&mut self, dialog: &mut Dialog, item: ItemId) { self.rctl.on_focus_lost(dialog, item); } } <file_sep>/src/main.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> mod ascii; mod changes; mod config; mod controller; mod curses; mod cursor; mod editor; mod file; mod history; mod inifile; mod ui; mod view; use config::Config; use controller::Controller; use curses::Curses; // Exit codes const EFAULT: i32 = 14; const EINVAL: i32 = 22; /// Main entry point. fn main() { // handle command line arguments let args = CmdLineArgs::new().unwrap_or_else(|err| { eprintln!("{}", err); std::process::exit(EINVAL); }); if args.help { print_help(); return; } if args.version { print_version(); return; } if args.files.is_empty() { eprintln!("Input files not specified"); std::process::exit(EINVAL); } // install custom panic hook to close curses before printing error info let default_panic = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { Curses::close(); default_panic(info); })); // set window title println!("\x1b]0;XVI: {}\x07", args.files.join(", ")); let config = Config::load(); Curses::initialize(&config.colors); if let Err(err) = Controller::run(&args.files, args.offset, config) { Curses::close(); eprintln!("{}: {}", err, args.files.join(", ")); let mut exit_code = EFAULT; if let Some(errno) = err.raw_os_error() { if errno != 0 { exit_code = errno; } } std::process::exit(exit_code); }; Curses::close(); } /// Print program version. fn print_version() { println!( "XVI - hexadecimal editor ver.{}.", env!("CARGO_PKG_VERSION") ); println!("Homepage: {}", env!("CARGO_PKG_HOMEPAGE")); } /// Print usage info. fn print_help() { print_version(); println!("Usage: xvi [OPTION...] FILE..."); println!(" -o, --offset ADDRESS Set initial cursor offset"); println!(" -v, --version Print version info and exit"); println!(" -h, --help Print this help and exit"); } /// Command line arguments. struct CmdLineArgs { /// Initial cursor offset. offset: Option<u64>, /// Flag to print version info. version: bool, /// Flag to print help. help: bool, /// List of files to open. files: Vec<String>, } impl CmdLineArgs { /// Create new instance from current command line arguments. fn new() -> Result<Self, String> { // get command line args and skip self executable file name let args: Vec<String> = std::env::args().skip(1).collect(); CmdLineArgs::parse(args) } /// Parse command line arguments. /// /// # Arguments /// /// * `args` - command line arguments without self file name fn parse(args: Vec<String>) -> Result<Self, String> { let mut instance = Self { files: Vec::new(), offset: None, version: false, help: false, }; let mut last_index = args.len(); let mut it = args.iter().enumerate(); while let Some((index, arg)) = it.next() { if !arg.starts_with('-') { last_index = index; break; } match arg.as_ref() { "-o" | "--offset" => { if let Some((_, text)) = it.next() { let (start, radix) = if text.starts_with("0x") { (2 /* skip 0x */, 16) } else if text.to_lowercase().chars().any(|c| matches!(c, 'a'..='f')) { (0, 16) } else { (0, 10) }; if let Ok(offset) = u64::from_str_radix(&text[start..], radix) { instance.offset = Some(offset); } else { return Err(format!("Invalid offset value: {}", text)); } } else { return Err("Offset not specified".to_string()); } } "-v" | "--version" => { instance.version = true; } "-h" | "--help" => { instance.help = true; } "--" => { last_index = index + 1; break; } _ => { return Err(format!("Invalid argument: {}", arg)); } }; } if last_index < args.len() { instance.files = args.into_iter().skip(last_index).collect(); } Ok(instance) } } #[test] fn test_simple() { let args = ["--help".to_string()]; let args = CmdLineArgs::parse(args.to_vec()).unwrap(); assert!(args.help); assert!(!args.version); assert!(args.offset.is_none()); assert!(args.files.is_empty()); let args = ["-v".to_string()]; let args = CmdLineArgs::parse(args.to_vec()).unwrap(); assert!(!args.help); assert!(args.version); assert!(args.offset.is_none()); assert!(args.files.is_empty()); let args = ["--version".to_string(), "-h".to_string()]; let args = CmdLineArgs::parse(args.to_vec()).unwrap(); assert!(args.help); assert!(args.version); assert!(args.offset.is_none()); assert!(args.files.is_empty()); } #[test] fn test_offset() { let args = ["--offset".to_string(), "0x12345678".to_string()]; let args = CmdLineArgs::parse(args.to_vec()).unwrap(); assert!(!args.help); assert!(!args.version); assert!(args.files.is_empty()); assert_eq!(args.offset, Some(0x12345678)); let args = ["--offset".to_string(), "1234567a".to_string()]; let args = CmdLineArgs::parse(args.to_vec()).unwrap(); assert!(!args.help); assert!(!args.version); assert!(args.files.is_empty()); assert_eq!(args.offset, Some(0x1234567a)); let args = ["-o".to_string(), "12345678".to_string()]; let args = CmdLineArgs::parse(args.to_vec()).unwrap(); assert!(!args.help); assert!(!args.version); assert!(args.files.is_empty()); assert_eq!(args.offset, Some(12345678)); let args = ["-o".to_string()]; assert!(CmdLineArgs::parse(args.to_vec()).is_err()); let args = ["-o".to_string(), "test".to_string()]; assert!(CmdLineArgs::parse(args.to_vec()).is_err()); } #[test] fn test_files() { let args = ["file".to_string()]; let args = CmdLineArgs::parse(args.to_vec()).unwrap(); assert!(!args.help); assert!(!args.version); assert_eq!(args.files.len(), 1); assert_eq!(args.files.get(0), Some(&"file".to_string())); let args = [ "-v".to_string(), "--".to_string(), "--file1".to_string(), "file2".to_string(), ]; let args = CmdLineArgs::parse(args.to_vec()).unwrap(); assert_eq!(args.files.len(), 2); assert_eq!(args.files.get(0), Some(&"--file1".to_string())); assert_eq!(args.files.get(1), Some(&"file2".to_string())); } <file_sep>/src/inifile.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use std::collections::BTreeMap; use std::fs::{create_dir_all, File}; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::path::Path; /// INI file (DOS-like, very simple). pub struct IniFile { pub sections: BTreeMap<String, Vec<String>>, } impl IniFile { /// Create instance. pub fn new() -> Self { Self { sections: BTreeMap::new(), } } /// Load configuration from the file. pub fn load(file: &Path) -> io::Result<Self> { let ini_file = File::open(file)?; let mut instance = IniFile::new(); let mut last_section = String::new(); for line in BufReader::new(ini_file).lines().flatten() { let line = line.trim(); // skip comments and empty lines if line.is_empty() || line.starts_with('#') { continue; } // section name if line.starts_with('[') && line.ends_with(']') { last_section = String::from(&line[1..line.len() - 1]).to_lowercase(); continue; } // section line instance .sections .entry(last_section.clone()) .or_insert_with(Vec::new) .push(line.to_string()); } Ok(instance) } /// Save configuration to the file. pub fn save(&self, file: &Path) -> io::Result<()> { create_dir_all(file.parent().unwrap())?; let mut ini = File::create(file)?; for (name, params) in &self.sections { ini.write_all(format!("[{}]\n", name).as_bytes())?; for line in params.iter() { ini.write_all(format!("{}\n", line).as_bytes())?; } } Ok(()) } /// Set value for specified key in the named section. #[cfg(test)] pub fn set_keyval(&mut self, section: &str, key: &str, value: &str) { let lc_key = key.to_lowercase(); let new_line = format!("{} = {}", lc_key, value); let section = section.to_lowercase(); let section = self.sections.entry(section).or_insert_with(Vec::new); for (index, line) in section.iter().enumerate() { if let Some((ck_key, _)) = IniFile::keyval(line) { if ck_key == lc_key { section[index] = new_line; return; } } } section.push(new_line); } /// Get string value for specified key in the named section. pub fn get_strval(&self, section: &str, key: &str) -> Option<String> { if let Some(section) = self.sections.get(&section.to_lowercase()) { let key = key.to_lowercase(); for line in section.iter() { if let Some((ckey, val)) = IniFile::keyval(line) { if ckey == key { return Some(val); } } } } None } /// Get numeric value for specified key in the named section. pub fn get_numval(&self, section: &str, key: &str) -> Option<usize> { if let Some(val) = self.get_strval(section, key) { if let Ok(val) = val.parse::<usize>() { return Some(val); } } None } /// Get boolean value for specified key in the named section. pub fn get_boolval(&self, section: &str, key: &str) -> Option<bool> { if let Some(val) = self.get_numval(section, key) { return Some(val != 0); } None } /// Parse and convert line to the Key/Value pair. pub fn keyval(line: &str) -> Option<(String, String)> { let split: Vec<&str> = line.splitn(2, '=').collect(); return if split.len() == 2 { let key = String::from(split[0].trim()).to_lowercase(); let value = String::from(split[1].trim()); Some((key, value)) } else { None }; } } #[test] fn test_load() { let tmp_file = std::env::temp_dir().join("xvi_test_ini.load"); let ini_data = r#"#comment [section1] [Section2] # c o m m e n t Section_line Section_line [seCTIon3] sectionLine1 sectionLine2 sectionLine3"#; std::fs::write(&tmp_file, ini_data).unwrap(); let ini = IniFile::load(&tmp_file).unwrap(); assert_eq!(ini.sections.len(), 2); assert!(ini.sections.contains_key("section2")); assert_eq!( ini.sections["section2"], vec!["Section_line", "Section_line"] ); assert!(ini.sections.contains_key("section3")); assert_eq!( ini.sections["section3"], vec!["sectionLine1", "sectionLine2", "sectionLine3"] ); std::fs::remove_file(tmp_file).unwrap(); } #[test] fn test_save() { let mut ini = IniFile::new(); ini.sections.insert( "section1".to_string(), vec!["line".to_string(), "line".to_string()], ); ini.sections.insert( "section2".to_string(), vec![ "line1".to_string(), "line2".to_string(), "line3".to_string(), ], ); let tmp_file = std::env::temp_dir().join("xvi_test_ini.save"); ini.save(&tmp_file).unwrap(); let ini_data = std::fs::read_to_string(&tmp_file).unwrap(); assert_eq!( ini_data, "[section1]\nline\nline\n[section2]\nline1\nline2\nline3\n" ); std::fs::remove_file(tmp_file).unwrap(); } #[test] fn test_str_keyval() { let mut ini = IniFile::new(); ini.set_keyval("Section1", "MyKey", "MyVal"); assert_eq!( ini.get_strval("Section1", "MyKey"), Some("MyVal".to_string()) ); // case ignore assert_eq!( ini.get_strval("section1", "mykey"), Some("MyVal".to_string()) ); // not existing assert_eq!(ini.get_strval("section1", "mykey1"), None); assert_eq!(ini.get_strval("section2", "mykey"), None); // update ini.set_keyval("section1", "Mykey", "MyVal2"); assert_eq!(ini.sections["section1"].len(), 1); assert_eq!( ini.get_strval("section1", "MyKey"), Some("MyVal2".to_string()) ); } #[test] fn test_num_keyval() { let mut ini = IniFile::new(); ini.set_keyval("Section1", "MyKey", "123456789"); assert_eq!(ini.get_numval("Section1", "MyKey"), Some(123456789)); } #[test] fn test_bool_keyval() { let mut ini = IniFile::new(); ini.set_keyval("Section1", "MyKey", "1"); assert_eq!(ini.get_boolval("Section1", "MyKey"), Some(true)); ini.set_keyval("Section1", "MyKey", "0"); assert_eq!(ini.get_boolval("Section1", "MyKey"), Some(false)); } #[test] fn test_keyval() { assert_eq!( IniFile::keyval("mykey=myvalue"), Some(("mykey".to_string(), "myvalue".to_string())) ); assert_eq!( IniFile::keyval("MyKey=MyValue"), Some(("mykey".to_string(), "MyValue".to_string())) ); assert_eq!( IniFile::keyval(" mykey\t =\tmyvalue\n\n"), Some(("mykey".to_string(), "myvalue".to_string())) ); assert_eq!( IniFile::keyval("mykey = myva=lue"), Some(("mykey".to_string(), "myva=lue".to_string())) ); assert_eq!(IniFile::keyval("mykeymyvalue"), None); } <file_sep>/src/ui/progress.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::super::curses::{Curses, Event, Key}; use super::super::file::ProgressHandler; use super::dialog::{Dialog, DialogType, ItemId}; use super::messagebox::MessageBox; use super::widget::{StandardButton, WidgetType}; /// Progress dialog. pub struct ProgressDialog { dlg: Dialog, bar: ItemId, confirm: bool, } impl ProgressDialog { /// Create new progress window. /// /// # Arguments /// /// * `title` - window title /// * `confirm` - flag to ask confirmation for abort /// /// # Return value /// /// Progress window instance. pub fn new(title: &str, confirm: bool) -> Self { let mut dlg = Dialog::new(50, 1, DialogType::Normal, title); let bar = dlg.add_line(WidgetType::ProgressBar(0)); dlg.add_button(StandardButton::Cancel, true); let mut instance = Self { dlg, bar, confirm }; instance.update(0); instance } /// Hide progress window. pub fn hide(&self) { self.dlg.hide(); } /// Ask user for confirmation to cancel the current operation. /// /// # Return value /// /// `true` if user confirmed abort fn confirm_abort() -> bool { if let Some(button) = MessageBox::show( DialogType::Error, "Abort", &["Are you sure you want to abort the current operation?"], &[(StandardButton::Yes, false), (StandardButton::No, true)], ) { return button == StandardButton::Yes; } false } } impl ProgressHandler for ProgressDialog { fn update(&mut self, percent: u8) -> bool { debug_assert!(percent <= 100); if let WidgetType::ProgressBar(current) = self.dlg.get_widget_mut(self.bar) { *current = percent; self.dlg.draw(); } // check for user interrupt if let Some(Event::KeyPress(key)) = Curses::peek_event() { if matches!(key.key, Key::Esc | Key::Enter | Key::Char(' ')) && (!self.confirm || ProgressDialog::confirm_abort()) { return false; } } true } } <file_sep>/src/ui/fill.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::dialog::{Dialog, DialogHandler, DialogType, ItemId}; use super::range::RangeControl; use super::widget::{InputFormat, InputLine, StandardButton, WidgetType}; use std::ops::Range; /// "Fill fange" dialog. pub struct FillDialog { rctl: RangeControl, pattern: ItemId, btn_ok: ItemId, btn_cancel: ItemId, } impl FillDialog { /// Show the "Fill range" configuration dialog. /// /// # Arguments /// /// * `offset` - default start offset (current position) /// * `max` - max offset (file size) /// * `pattern` - default pattern /// /// # Return value /// /// Range and pattern to fill. pub fn show(offset: u64, max: u64, pattern: &[u8]) -> Option<(Range<u64>, Vec<u8>)> { // create dialog let mut dlg = Dialog::new( RangeControl::DIALOG_WIDTH, 6, DialogType::Normal, "Fill range", ); // place range control on dialog let rctl = RangeControl::create(&mut dlg, offset..offset + 1, max); // pattern dlg.add_separator(); dlg.add_line(WidgetType::StaticText("Fill with pattern:".to_string())); let text = pattern.iter().map(|b| format!("{:02x}", b)).collect(); let widget = InputLine::new( text, InputFormat::HexStream, Vec::new(), RangeControl::DIALOG_WIDTH, ); let pattern = dlg.add_line(WidgetType::Edit(widget)); // buttons let btn_ok = dlg.add_button(StandardButton::OK, true); let btn_cancel = dlg.add_button(StandardButton::Cancel, false); // construct dialog handler let mut handler = Self { rctl, pattern, btn_ok, btn_cancel, }; // show dialog if let Some(id) = dlg.show(&mut handler) { if id != handler.btn_cancel { let range = handler.rctl.get(&dlg).unwrap(); let pattern = handler.get_pattern(&dlg); return Some((range, pattern)); } } None } /// Get current sequence from the pattern field. fn get_pattern(&self, dialog: &Dialog) -> Vec<u8> { if let WidgetType::Edit(widget) = dialog.get_widget(self.pattern) { let mut value = widget.get_value().to_string(); if !value.is_empty() { if value.len() % 2 != 0 { value.push('0'); } return (0..value.len()) .step_by(2) .map(|i| u8::from_str_radix(&value[i..i + 2], 16).unwrap()) .collect(); } } vec![0] } } impl DialogHandler for FillDialog { fn on_close(&mut self, dialog: &mut Dialog, item: ItemId) -> bool { item == self.btn_cancel || dialog.get_context(self.btn_ok).enabled } fn on_item_change(&mut self, dialog: &mut Dialog, item: ItemId) { self.rctl.on_item_change(dialog, item); dialog.set_enabled(self.btn_ok, self.rctl.get(dialog).is_some()); } fn on_focus_lost(&mut self, dialog: &mut Dialog, item: ItemId) { if item == self.pattern { if let WidgetType::Edit(widget) = dialog.get_widget_mut(self.pattern) { let mut value = widget.get_value().to_string(); if value.is_empty() { widget.set_value("00".to_string()); } else if value.len() % 2 != 0 { value.push('0'); widget.set_value(value); } } } else { self.rctl.on_focus_lost(dialog, item); } } } <file_sep>/src/ui/messagebox.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::dialog::{Dialog, DialogType, ItemId}; use super::widget::StandardButton; use std::io::Error; use unicode_segmentation::UnicodeSegmentation; /// Message box dialog. pub struct MessageBox {} impl MessageBox { /// Show message box. /// /// # Arguments /// /// * `dt` - message type (dialog background) /// * `title` - message title /// * `message` - message lines /// * `buttons` - buttons on the dialog /// /// # Return value /// /// Chosen button. pub fn show( dt: DialogType, title: &str, message: &[&str], buttons: &[(StandardButton, bool)], ) -> Option<StandardButton> { debug_assert!(!message.is_empty()); debug_assert!(!buttons.is_empty()); // create dialog let (width, height) = MessageBox::calc_size(message, buttons); let mut dlg = Dialog::new(width, height, dt, title); // add message text to the dialog window for msg in message.iter() { let mut line = (*msg).to_string(); let line_len = line.graphemes(true).count(); if line_len > width { // shrink line let (index, _) = line.grapheme_indices(true).nth(width - 1).unwrap(); line.truncate(index); line.push('\u{2026}'); } dlg.add_center(line); } // buttons let mut first = ItemId::MAX; for (button, default) in buttons.iter() { let item = dlg.add_button(*button, *default); if first == ItemId::MAX { first = item; } } // show dialog dlg.show_unmanaged().map(|id| buttons[id - first].0) } /// Show message about reading errors. /// /// # Arguments /// /// * `file` - path to the file /// * `err` - error description /// * `buttons` - buttons on the dialog /// /// # Return value /// /// Chosen button. pub fn error_read( file: &str, err: &Error, buttons: &[(StandardButton, bool)], ) -> Option<StandardButton> { let error = format!("{}", err); let message = vec!["Error reading file", file, &error]; MessageBox::show(DialogType::Error, "Error", &message, buttons) } /// Show message about writing errors. /// /// # Arguments /// /// * `file` - path to the file /// * `err` - error description /// * `buttons` - buttons on the dialog /// /// # Return value /// /// Chosen button. pub fn error_write( file: &str, err: &Error, buttons: &[(StandardButton, bool)], ) -> Option<StandardButton> { let error = format!("{}", err); let message = vec!["Error writing file", file, &error]; MessageBox::show(DialogType::Error, "Error", &message, buttons) } /// Show message about writing errors and ask user for retry. /// /// # Arguments /// /// * `file` - path to the file /// * `err` - error description /// /// # Return value /// /// `true` if attempt must be repeated pub fn retry_write(file: &str, err: &Error) -> bool { MessageBox::error_write( file, err, &[ (StandardButton::Retry, true), (StandardButton::Cancel, false), ], ) .map_or_else(|| false, |b| b == StandardButton::Retry) } /// Calculate window size. /// /// # Arguments /// /// * `message` - message lines /// * `buttons` - buttons on the dialog /// /// # Return value /// /// Size of the dialog window. fn calc_size(message: &[&str], buttons: &[(StandardButton, bool)]) -> (usize, usize) { let max_width = Dialog::max_width(); let mut width = 0; // size of buttons block for (button, default) in buttons.iter() { width += 1 + button.text(*default).len(); } width -= 1; // remove last space // longest message line for msg in message.iter() { let len = msg.graphemes(true).count(); if width < max_width && width < len { width = len.min(max_width); } } (width, message.len()) } } <file_sep>/src/changes.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use std::collections::BTreeMap; /// Modification of single byte. #[derive(Copy, Clone)] pub struct ByteChange { pub offset: u64, pub old: u8, pub new: u8, } /// List of bytes modifications. pub struct ChangeList { /// List of changes. changes: Vec<ByteChange>, /// Current position in the queue. index: usize, } impl ChangeList { /// Make change: set new value for the byte at specified position. /// /// # Arguments /// /// * `offset` - address of the byte to modify /// * `old` - origin value of the byte /// * `new` - new value of the byte pub fn set(&mut self, offset: u64, old: u8, new: u8) { // try to update the last changed value if it in the same offset if let Some(last) = self.changes.last_mut() { if last.offset == offset { last.new = new; return; } } // reset forward changes by removing the tail if self.index != 0 { self.changes.truncate(self.index); } self.changes.push(ByteChange { offset, old, new }); self.index = self.changes.len(); } /// Get the map of real changes. /// /// Returns map with chages: offset -> value. pub fn get(&self) -> BTreeMap<u64, u8> { let mut real = BTreeMap::new(); let mut origins = BTreeMap::new(); for change in self.changes[0..self.index].iter() { origins.entry(change.offset).or_insert(change.old); real.insert(change.offset, change.new); } // remove changes that restore origin values for (offset, origin) in &origins { if origin == real.get(offset).unwrap() { real.remove(offset); } } real } /// Get value for specified offset. /// /// # Arguments /// /// * `offset` - offset of the value /// /// # Return value /// /// Last value at specified offset pub fn last(&self, offset: u64) -> Option<u8> { for ch in self.changes.iter().rev() { if ch.offset == offset { return Some(ch.new); } } None } /// Undo the last change. /// /// Returns description of the undone change. pub fn undo(&mut self) -> Option<ByteChange> { if self.changes.is_empty() || self.index == 0 { None } else { self.index -= 1; Some(self.changes[self.index]) } } /// Redo the next change. /// /// Returns description of the applied change. pub fn redo(&mut self) -> Option<ByteChange> { if self.changes.is_empty() || self.index == self.changes.len() { None } else { self.index += 1; Some(self.changes[self.index - 1]) } } /// Reset changes. pub fn reset(&mut self) { self.changes.clear(); self.index = 0; } } impl Default for ChangeList { fn default() -> Self { Self { changes: Vec::with_capacity(64), index: 0, } } } #[test] fn test_changesqueue() { let mut ch = ChangeList::default(); ch.set(0x1234, 1, 2); ch.set(0x1235, 3, 4); ch.set(0x1235, 4, 5); ch.set(0x1235, 5, 6); let real = ch.get(); assert_eq!(real.len(), 2); assert_eq!(*real.get(&0x1234).unwrap(), 2); assert_eq!(*real.get(&0x1235).unwrap(), 6); ch.set(0x1234, 2, 1); // restore origin let real = ch.get(); assert_eq!(real.len(), 1); assert_eq!(*real.get(&0x1235).unwrap(), 6); ch.undo(); assert_eq!(ch.get().len(), 2); ch.undo(); assert_eq!(ch.get().len(), 1); ch.undo(); assert_eq!(ch.get().len(), 0); ch.undo(); ch.redo(); assert_eq!(ch.get().len(), 1); ch.reset(); assert_eq!(ch.get().len(), 0); } <file_sep>/src/curses.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use ncurses as nc; /// Wrapper around ncurses. pub struct Curses; impl Curses { /// Initialization. pub fn initialize(colors: &[(Color, i16, i16)]) { // setup locale to get UTF-8 support nc::setlocale(nc::LcCategory::all, ""); // setup ncurses let wnd = nc::initscr(); nc::raw(); nc::noecho(); nc::keypad(wnd, true); nc::set_escdelay(0); // setup colors nc::start_color(); nc::use_default_colors(); for &(color, fg, bg) in colors.iter() { nc::init_pair(color as i16, fg, bg); } nc::bkgdset(nc::COLOR_PAIR(Color::HexNorm as i16)); nc::clear(); } /// Close ncurses. pub fn close() { nc::endwin(); } /// Get screen size. /// /// # Return value /// /// Screen size (width, height). pub fn screen_size() -> (usize, usize) { let window = nc::stdscr(); ( nc::getmaxx(window).unsigned_abs() as usize, nc::getmaxy(window).unsigned_abs() as usize, ) } /// Pass screen resize event. /// Used by dialogs to notify the controller about screen resize. pub fn screen_resize() { let window = nc::stdscr(); let height = nc::getmaxy(window); let width = nc::getmaxx(window); ncurses::resizeterm(height, width); } /// Read next event. /// /// # Return value /// /// Event. fn read_event() -> Option<Event> { match nc::get_wch() { Some(nc::WchResult::Char(chr)) => { if chr == 0x1b { // esc code, read next key - it can be alt+? combination nc::timeout(10); let key = nc::get_wch(); nc::timeout(-1); if let Some(nc::WchResult::Char(chr)) = key { if let Some(mut key) = Curses::key_from_char(chr) { key.modifier |= KeyPress::ALT; return Some(Event::KeyPress(key)); } } return Some(Event::KeyPress(KeyPress::new(Key::Esc, KeyPress::NONE))); } if let Some(key) = Curses::key_from_char(chr) { return Some(Event::KeyPress(key)); } } Some(nc::WchResult::KeyCode(key)) => match key { nc::KEY_RESIZE => { nc::refresh(); return Some(Event::TerminalResize); } _ => { if let Some(key) = Curses::key_from_code(key) { return Some(Event::KeyPress(key)); } } }, None => {} } None } /// Read next event (blocking). /// /// # Return value /// /// Event. pub fn wait_event() -> Event { loop { if let Some(event) = Curses::read_event() { return event; } } } /// Read next event (non blocking). /// /// # Return value /// /// Event. pub fn peek_event() -> Option<Event> { nc::timeout(0); let event = Curses::read_event(); nc::timeout(-1); event } /// Create instance from ncurses code. fn key_from_code(code: i32) -> Option<KeyPress> { match code { nc::KEY_LEFT => Some(KeyPress::new(Key::Left, KeyPress::NONE)), nc::KEY_SLEFT => Some(KeyPress::new(Key::Left, KeyPress::SHIFT)), 0x220 => Some(KeyPress::new(Key::Left, KeyPress::ALT)), 0x221 => Some(KeyPress::new(Key::Left, KeyPress::ALT | KeyPress::SHIFT)), 0x222 => Some(KeyPress::new(Key::Left, KeyPress::CTRL)), 0x223 => Some(KeyPress::new(Key::Left, KeyPress::CTRL | KeyPress::SHIFT)), 0x224 => Some(KeyPress::new(Key::Left, KeyPress::ALT | KeyPress::CTRL)), nc::KEY_RIGHT => Some(KeyPress::new(Key::Right, KeyPress::NONE)), nc::KEY_SRIGHT => Some(KeyPress::new(Key::Right, KeyPress::SHIFT)), 0x22f => Some(KeyPress::new(Key::Right, KeyPress::ALT)), 0x230 => Some(KeyPress::new(Key::Right, KeyPress::ALT | KeyPress::SHIFT)), 0x231 => Some(KeyPress::new(Key::Right, KeyPress::CTRL)), 0x232 => Some(KeyPress::new(Key::Right, KeyPress::CTRL | KeyPress::SHIFT)), 0x233 => Some(KeyPress::new(Key::Right, KeyPress::ALT | KeyPress::CTRL)), nc::KEY_UP => Some(KeyPress::new(Key::Up, KeyPress::NONE)), nc::KEY_SR => Some(KeyPress::new(Key::Up, KeyPress::SHIFT)), 0x235 => Some(KeyPress::new(Key::Up, KeyPress::ALT)), 0x236 => Some(KeyPress::new(Key::Up, KeyPress::ALT | KeyPress::SHIFT)), 0x237 => Some(KeyPress::new(Key::Up, KeyPress::CTRL)), 0x238 => Some(KeyPress::new(Key::Up, KeyPress::CTRL | KeyPress::SHIFT)), 0x239 => Some(KeyPress::new(Key::Up, KeyPress::ALT | KeyPress::CTRL)), nc::KEY_DOWN => Some(KeyPress::new(Key::Down, KeyPress::NONE)), nc::KEY_SF => Some(KeyPress::new(Key::Down, KeyPress::SHIFT)), 0x20c => Some(KeyPress::new(Key::Down, KeyPress::ALT)), 0x20d => Some(KeyPress::new(Key::Down, KeyPress::ALT | KeyPress::SHIFT)), 0x20e => Some(KeyPress::new(Key::Down, KeyPress::CTRL)), 0x20f => Some(KeyPress::new(Key::Down, KeyPress::CTRL | KeyPress::SHIFT)), 0x210 => Some(KeyPress::new(Key::Down, KeyPress::ALT | KeyPress::CTRL)), nc::KEY_PPAGE => Some(KeyPress::new(Key::PageUp, KeyPress::NONE)), nc::KEY_NPAGE => Some(KeyPress::new(Key::PageDown, KeyPress::NONE)), nc::KEY_HOME => Some(KeyPress::new(Key::Home, KeyPress::NONE)), nc::KEY_SHOME => Some(KeyPress::new(Key::Home, KeyPress::SHIFT)), 0x216 => Some(KeyPress::new(Key::Home, KeyPress::ALT)), 0x217 => Some(KeyPress::new(Key::Home, KeyPress::ALT | KeyPress::SHIFT)), 0x218 => Some(KeyPress::new(Key::Home, KeyPress::CTRL)), 0x219 => Some(KeyPress::new(Key::Home, KeyPress::CTRL | KeyPress::SHIFT)), 0x21a => Some(KeyPress::new(Key::Home, KeyPress::ALT | KeyPress::CTRL)), nc::KEY_END => Some(KeyPress::new(Key::End, KeyPress::NONE)), nc::KEY_SEND => Some(KeyPress::new(Key::End, KeyPress::SHIFT)), 0x211 => Some(KeyPress::new(Key::End, KeyPress::ALT)), 0x212 => Some(KeyPress::new(Key::End, KeyPress::ALT | KeyPress::SHIFT)), 0x213 => Some(KeyPress::new(Key::End, KeyPress::CTRL)), 0x214 => Some(KeyPress::new(Key::End, KeyPress::CTRL | KeyPress::SHIFT)), 0x215 => Some(KeyPress::new(Key::End, KeyPress::ALT | KeyPress::CTRL)), nc::KEY_BTAB => Some(KeyPress::new(Key::Tab, KeyPress::SHIFT)), nc::KEY_DC => Some(KeyPress::new(Key::Delete, KeyPress::NONE)), nc::KEY_BACKSPACE => Some(KeyPress::new(Key::Backspace, KeyPress::NONE)), _ => { // check for Fn range if (nc::KEY_F1..nc::KEY_F1 + 64).contains(&code) { let fn_max = 12; let fn_code = code - nc::KEY_F1; #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] let fn_num = 1 + (fn_code % fn_max) as u8; let m = if fn_code >= fn_max * 4 { KeyPress::ALT } else if fn_code >= fn_max * 3 { KeyPress::CTRL | KeyPress::SHIFT } else if fn_code >= fn_max * 2 { KeyPress::CTRL } else if fn_code >= fn_max { KeyPress::SHIFT } else { KeyPress::NONE }; return Some(KeyPress::new(Key::F(fn_num), m)); } None } } } /// Create instance from an ASCII character. fn key_from_char(chr: u32) -> Option<KeyPress> { if let Some(chr) = std::char::from_u32(chr) { if chr.is_ascii() { return match chr as u8 { // check for control codes 0x01 => Some(KeyPress::new(Key::Char('a'), KeyPress::CTRL)), 0x02 => Some(KeyPress::new(Key::Char('b'), KeyPress::CTRL)), 0x03 => Some(KeyPress::new(Key::Char('c'), KeyPress::CTRL)), 0x04 => Some(KeyPress::new(Key::Char('d'), KeyPress::CTRL)), 0x05 => Some(KeyPress::new(Key::Char('e'), KeyPress::CTRL)), 0x06 => Some(KeyPress::new(Key::Char('f'), KeyPress::CTRL)), 0x07 => Some(KeyPress::new(Key::Char('g'), KeyPress::CTRL)), 0x08 => Some(KeyPress::new(Key::Char('h'), KeyPress::CTRL)), 0x09 => Some(KeyPress::new(Key::Tab, KeyPress::NONE)), 0x0a | 0x0d => Some(KeyPress::new(Key::Enter, KeyPress::NONE)), 0x0b => Some(KeyPress::new(Key::Char('k'), KeyPress::CTRL)), 0x0c => Some(KeyPress::new(Key::Char('l'), KeyPress::CTRL)), 0x0e => Some(KeyPress::new(Key::Char('n'), KeyPress::CTRL)), 0x0f => Some(KeyPress::new(Key::Char('o'), KeyPress::CTRL)), 0x10 => Some(KeyPress::new(Key::Char('p'), KeyPress::CTRL)), 0x11 => Some(KeyPress::new(Key::Char('q'), KeyPress::CTRL)), 0x12 => Some(KeyPress::new(Key::Char('r'), KeyPress::CTRL)), 0x13 => Some(KeyPress::new(Key::Char('s'), KeyPress::CTRL)), 0x14 => Some(KeyPress::new(Key::Char('t'), KeyPress::CTRL)), 0x15 => Some(KeyPress::new(Key::Char('u'), KeyPress::CTRL)), 0x16 => Some(KeyPress::new(Key::Char('v'), KeyPress::CTRL)), 0x17 => Some(KeyPress::new(Key::Char('w'), KeyPress::CTRL)), 0x18 => Some(KeyPress::new(Key::Char('x'), KeyPress::CTRL)), 0x19 => Some(KeyPress::new(Key::Char('y'), KeyPress::CTRL)), 0x1a => Some(KeyPress::new(Key::Char('z'), KeyPress::CTRL)), 0x1b => Some(KeyPress::new(Key::Esc, KeyPress::NONE)), 0x1c => Some(KeyPress::new(Key::Char('\\'), KeyPress::CTRL)), 0x1d => Some(KeyPress::new(Key::Char(']'), KeyPress::CTRL)), 0x1e => Some(KeyPress::new(Key::Char('^'), KeyPress::CTRL)), 0x1f => Some(KeyPress::new(Key::Char('_'), KeyPress::CTRL)), 0x7f => Some(KeyPress::new(Key::Backspace, KeyPress::NONE)), // all other is an ascii char _ => Some(KeyPress::new(Key::Char(chr), KeyPress::NONE)), }; } // wide char return Some(KeyPress::new(Key::Char(chr), KeyPress::NONE)); } None } } /// Color identifiers. #[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)] pub enum Color { HexNorm = 1, HexMod, HexDiff, HexNormHi, HexModHi, HexDiffHi, AsciiNorm, AsciiMod, AsciiDiff, AsciiNormHi, AsciiModHi, AsciiDiffHi, Offset, OffsetHi, Bar, Dialog, Error, Disabled, Focused, Input, Select, } /// External event. pub enum Event { /// Terminal window was resized. TerminalResize, /// Key pressed. KeyPress(KeyPress), } /// Key press event data: code with modifiers. pub struct KeyPress { pub key: Key, pub modifier: u8, } impl KeyPress { pub const NONE: u8 = 0b000; pub const SHIFT: u8 = 0b001; pub const CTRL: u8 = 0b010; pub const ALT: u8 = 0b100; pub fn new(key: Key, modifier: u8) -> Self { Self { key, modifier } } } /// Key types. #[derive(PartialEq)] pub enum Key { // alphanumeric Char(char), // functional buttons (F1, F2, ...) F(u8), // special buttons Left, Right, Up, Down, PageUp, PageDown, Home, End, Tab, Backspace, Delete, Enter, Esc, } /// Curses window. pub struct Window { /// Curses window. window: nc::WINDOW, /// Curses panel. panel: nc::PANEL, /// Window width. width: usize, /// Window height. height: usize, } impl Window { // Font styles pub const BOLD: nc::attr_t = nc::A_BOLD(); /// Create new window. /// /// # Arguments /// /// * `x` - window position: column number /// * `y` - window position: line number /// * `width` - window width /// * `height` - window height /// * `color` - background color of the window /// /// # Return value /// /// Window instance. pub fn new(x: usize, y: usize, width: usize, height: usize, color: Color) -> Self { // create curses entities let window = nc::newwin(height as i32, width as i32, y as i32, x as i32); let panel = nc::new_panel(window); nc::update_panels(); // default background nc::wbkgdset(window, nc::COLOR_PAIR(color as i16)); nc::werase(window); Self { window, panel, width, height, } } /// Create new centered window. /// /// # Arguments /// /// * `width` - window width /// * `height` - window height /// * `color` - background color of the window /// /// # Return value /// /// Window instance. pub fn new_centered(width: usize, height: usize, color: Color) -> Self { debug_assert!(width > 0); debug_assert!(height > 0); // get screen size let screen = nc::stdscr(); let screen_width = nc::getmaxx(screen).unsigned_abs() as usize; let screen_height = nc::getmaxy(screen).unsigned_abs() as usize; // calculate window position, center of the screen let x = if width >= screen_width { 0 } else { screen_width / 2 - width / 2 }; let y = if height >= screen_height { 0 } else { (screen_height as f32 / 2.2) as usize - height / 2 }; Window::new(x, y, width, height, color) } /// Hide the window. pub fn hide(&self) { nc::hide_panel(self.panel); } /// Get window size. /// /// # Return value /// /// Size of the window (width, height). pub fn get_size(&self) -> (usize, usize) { (self.width, self.height) } /// Resize the window. /// /// # Arguments /// /// * `width` - window width /// * `height` - window height pub fn resize(&mut self, width: usize, height: usize) { debug_assert!(width > 0); debug_assert!(height > 0); self.width = width; self.height = height; nc::wresize(self.window, height as i32, width as i32); } /// Move window. /// /// # Arguments /// /// * `x` - absolute screen coordinates: column number /// * `y` - absolute screen coordinates: line number pub fn set_pos(&self, x: usize, y: usize) { let status = nc::mvwin(self.window, y as i32, x as i32); debug_assert_eq!(status, nc::OK); } /// Clear the window. pub fn clear(&self) { nc::werase(self.window); } /// Print text on the window. /// /// # Arguments /// /// * `x` - start column of the text /// * `y` - line number /// * `text` - text to print pub fn print(&self, x: usize, y: usize, text: &str) { debug_assert!(x <= self.width); debug_assert!(y <= self.height); nc::mvwaddstr(self.window, y as i32, x as i32, text); } /// Set color for the specified range. /// /// # Arguments /// /// * `x` - start column /// * `y` - line number /// * `width` - number of characters to colorize /// * `color` - color to set pub fn set_color(&self, x: usize, y: usize, width: usize, color: Color) { debug_assert!(x <= self.width); debug_assert!(y <= self.height); debug_assert!(width + x <= self.width); // get current attributes let mut attr = 0; let mut _color = 0; nc::wattr_get(self.window, &mut attr, &mut _color); nc::mvwchgat( self.window, y as i32, x as i32, width as i32, attr, color as i16, ); } /// Set style for the specified range. /// /// # Arguments /// /// * `x` - start column /// * `y` - line number /// * `width` - number of characters to colorize /// * `style` - style to set pub fn set_style(&self, x: usize, y: usize, width: usize, style: nc::attr_t) { debug_assert!(x <= self.width); debug_assert!(y <= self.height); debug_assert!(width + x <= self.width); // get current attributes let mut _attr = 0; let mut color = 0; nc::wattr_get(self.window, &mut _attr, &mut color); nc::mvwchgat( self.window, y as i32, x as i32, width as i32, style, color as i16, ); } /// Set default color for further print operations. /// /// # Arguments /// /// * `color` - color to set pub fn color_on(&self, color: Color) { nc::wattron(self.window, nc::COLOR_PAIR(color as i16)); } /// Refresh the window, flushes all changes to the screen. pub fn refresh(&self) { nc::wrefresh(self.window); } /// Show cursor at specified position. /// /// # Arguments /// /// * `x` - column number /// * `y` - line number pub fn show_cursor(&self, x: usize, y: usize) { // wmove doesn't work, use absolute coordinates let x = nc::getbegx(self.window) + x as i32; let y = nc::getbegy(self.window) + y as i32; nc::mv(y, x); nc::curs_set(nc::CURSOR_VISIBILITY::CURSOR_VISIBLE); } /// Hide cursor. pub fn hide_cursor() { nc::curs_set(nc::CURSOR_VISIBILITY::CURSOR_INVISIBLE); } } impl Drop for Window { fn drop(&mut self) { nc::del_panel(self.panel); nc::update_panels(); nc::delwin(self.window); } } <file_sep>/extra/xvirc # XVI configuration file. # This file contains the default configuration. # The editor searches for a config file in the following locations: # 1. $XDG_CONFIG_HOME/xvi/config # 2. $HOME/.config/xvi/config [View] # Enable/disable fixed width mode (16 bytes per line) FixedWidth = 0 # ASCII field charset (none, 437, 1251, ascii or named) Ascii = 437 [Colors] # Base color theme (Light or Dark) Theme = Dark # Default palette for the Dark theme #General = -1, -1 #Highlight = -1, 235 #Offset = 241, -1 #Ascii = 241, -1 #Modified = 220, -1 #Diff = 124, -1 #Bar = 242, 236 #Dialog = 235, 245 #Error = 250, 88 #Disabled = 239, 245 #Focused = 250, 238 #Input = 235, 243 #Select = 250, 235 # Default palette for the Light theme #General = 7, 4 #Highlight = 0, 12 #Offset = 7, 4 #Ascii = 7, 4 #Modified = 11, 4 #Diff = 1, 4 #Bar = 0, 6 #Dialog = 0, 7 #Error = 15, 1 #Disabled = 8, 7 #Focused = 0, 6 #Input = 0, 6 #Select = 15, 0 # vim: filetype=dosini <file_sep>/src/view.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::ascii::Table; use super::config::Config; use super::curses::{Color, Window}; use super::editor::Document; use std::collections::BTreeSet; use unicode_segmentation::UnicodeSegmentation; /// Document view. pub struct View { /// Line width mode (fixed/dynamic). pub fixed_width: bool, /// ASCII characters table (None hides the field). pub ascii_table: Option<&'static Table>, /// Max offset (file size). pub max_offset: u64, /// Number of lines per page. pub lines: usize, /// Number of bytes per line. pub columns: usize, /// Workspace window (offsets and data). pub workspace: Window, /// Status bar window. statusbar: Window, /// Size of the offset field. pub offset_width: usize, /// Size of the hex field. pub hex_width: usize, /// Start address of currently displayed page. pub offset: u64, /// File data of currently displayed page. pub data: Vec<u8>, /// Addresses of changed values on the current page. pub changes: BTreeSet<u64>, /// Addresses of diff values on the current page. pub differs: BTreeSet<u64>, } impl View { /// Number of words per line in fixed mode. const FIXED_WIDTH: usize = 4; /// Length of a byte in hex representation. const HEX_LEN: usize = 2; /// Margin size between fields offset/hex/ascii. const FIELD_MARGIN: usize = 3; /// Margin between bytes in a word. const BYTE_MARGIN: usize = 1; /// Margin between word. const WORD_MARGIN: usize = 2; /// Number of bytes in a single word. const BYTES_IN_WORD: usize = 4; /// Min width of the screen. pub const MIN_WIDTH: usize = 30; /// Min height of the window (status bar and at least one line of data). pub const MIN_HEIGHT: usize = 2; /// Create new viewer instance. /// /// # Arguments /// /// * `config` - application config /// * `file_size` - file size /// /// # Return value /// /// Viewer instance. pub fn new(config: &Config, file_size: u64) -> Self { Self { fixed_width: config.fixed_width, ascii_table: config.ascii_table, max_offset: file_size, lines: 1, columns: 1, workspace: Window::new(0, 0, 0, 0, Color::HexNorm), statusbar: Window::new(0, 0, 0, 0, Color::Bar), offset_width: 0, hex_width: 0, offset: 0, data: Vec::new(), changes: BTreeSet::new(), differs: BTreeSet::new(), } } /// Reinitialization. pub fn reinit(&mut self) { let (width, height) = self.workspace.get_size(); // define size of the offset field self.offset_width = 4; // minimum 4 digits (u16) for i in (2..8).rev() { if u64::max_value() << (i * 8) & self.max_offset != 0 { self.offset_width = (i + 1) * 2; break; } } // calculate number of words per line let words = if self.fixed_width { View::FIXED_WIDTH } else { // calculate word width (number of chars per word) let hex_width = View::BYTES_IN_WORD * View::HEX_LEN + (View::BYTES_IN_WORD - 1) * View::BYTE_MARGIN + View::WORD_MARGIN; let ascii_width = if self.ascii_table.is_some() { View::BYTES_IN_WORD } else { 0 }; let word_width = hex_width + ascii_width; // available space let mut free_space = width - self.offset_width - View::FIELD_MARGIN; if self.ascii_table.is_some() { free_space -= View::FIELD_MARGIN - View::WORD_MARGIN; } else { free_space += View::WORD_MARGIN; } // number of words per line free_space / word_width }; debug_assert_ne!(words, 0); // window too small? self.lines = height; self.columns = words * View::BYTES_IN_WORD; // calculate hex field size let word_width = View::BYTES_IN_WORD * View::HEX_LEN + (View::BYTES_IN_WORD - 1) * View::BYTE_MARGIN; self.hex_width = words * word_width + (words - 1) * View::WORD_MARGIN; // increase the offset length if possible let data_width = View::FIELD_MARGIN + self.hex_width + self.offset_width + if self.ascii_table.is_some() { View::FIELD_MARGIN + self.columns } else { 0 }; if data_width < width && self.offset_width < 8 { let free_space = width - data_width; let max_offset_len = 8 - self.offset_width; self.offset_width += free_space.min(max_offset_len); } } /// Window resize handler: recalculate the view scheme. /// /// # Arguments /// /// * `y` - start line on the screen /// * `width` - size of the viewer /// * `height` - size of the viewer pub fn resize(&mut self, y: usize, width: usize, height: usize) { debug_assert!(width >= View::MIN_WIDTH); debug_assert!(height >= View::MIN_HEIGHT); self.statusbar.resize(width, 1); self.statusbar.set_pos(0, y); self.workspace.resize(width, height - 1); self.workspace.set_pos(0, y + 1); self.reinit(); } /// Draw the document. /// /// # Arguments /// /// * `doc` - document to render pub fn draw(&self, doc: &Document) { // draw statusbar self.statusbar.clear(); self.draw_statusbar(doc); self.statusbar.refresh(); // draw workspace self.workspace.clear(); self.draw_offset(doc); self.draw_hex(doc); if self.ascii_table.is_some() { self.draw_ascii(doc); } self.highlight(doc); self.workspace.refresh(); } /// Print the status bar. /// /// # Arguments /// /// * `doc` - document to render fn draw_statusbar(&self, doc: &Document) { let (width, _) = self.statusbar.get_size(); // right part: charset, position, etc let mut stat = String::new(); let value = self.data[(doc.cursor.offset - self.offset) as usize]; let percent = (doc.cursor.offset * 100 / if doc.file.size > 1 { doc.file.size - 1 } else { 1 }) as u8; if let Some(table) = self.ascii_table { stat = format!(" \u{2502} {}", table.id); }; stat += &format!( " \u{2502} 0x{offset:04x} = 0x{value:02x} {value:<3} 0{value:<3o} {value:08b} \u{2502} {percent:>3}%", offset = doc.cursor.offset, value = value, percent = percent ); let stat_len = stat.graphemes(true).count(); // left part: path to the file and modification status (at least 5 chars) let path_min = 5; let path_max = if stat_len < width - path_min { width - stat_len } else { path_min }; let mut path = doc.file.path.clone(); if doc.file.is_modified() { path.push('*'); } let path_len = path.graphemes(true).count(); if path_len > path_max { let cut_start = 3; let cut_end = path_len - path_max + cut_start + 1 /*delimiter*/; let (start, _) = path.grapheme_indices(true).nth(cut_start).unwrap(); let (end, _) = path.grapheme_indices(true).nth(cut_end).unwrap(); path.replace_range(start..end, "\u{2026}"); } // compose and print the final status bar line let mut statusbar = format!("{:<width$}{}", path, stat, width = path_max); if let Some((max, _)) = statusbar.grapheme_indices(true).nth(width) { statusbar.truncate(max); } self.statusbar.print(0, 0, &statusbar); } /// Print the offset column. /// /// # Arguments /// /// * `doc` - document to render fn draw_offset(&self, doc: &Document) { self.workspace.color_on(Color::Offset); let cursor_y = (doc.cursor.offset - self.offset) as usize / self.columns; for y in 0..=self.lines { let offset = self.offset + (y * self.columns) as u64; if offset > doc.file.size { break; } if cursor_y == y { self.workspace.color_on(Color::OffsetHi); } let line = format!("{:0width$x}", offset, width = self.offset_width); self.workspace.print(0, y, &line); if cursor_y == y { self.workspace.color_on(Color::Offset); } } } /// Print the hex field. /// /// # Arguments /// /// * `doc` - document to render fn draw_hex(&self, doc: &Document) { self.workspace.color_on(Color::HexNorm); let cursor_x = (doc.cursor.offset % self.columns as u64) as usize; let cursor_y = (doc.cursor.offset - self.offset) as usize / self.columns; let left_pos = self.offset_width + View::FIELD_MARGIN; for y in 0..=self.lines { let offset = self.offset + (y * self.columns) as u64; if offset >= doc.file.size { break; } // fill with hex dump let mut text = String::with_capacity(self.hex_width); for x in 0..self.columns { if !text.is_empty() { text.push(' '); // byte delimiter if x % View::BYTES_IN_WORD == 0 { text.push(' '); // word delimiter } } if let Some(&byte) = self.data.get((offset + x as u64 - self.offset) as usize) { text.push_str(&format!("{:02x}", byte)); } else { text.push_str(" "); // fill with spaces for highlighting } } if cursor_y == y { self.workspace.color_on(Color::HexNormHi); } self.workspace.print(left_pos, y, &text); if cursor_y == y { self.workspace.color_on(Color::HexNorm); } else { // highlight current column let col_x = left_pos + cursor_x * (View::BYTES_IN_WORD - 1) + cursor_x / View::BYTES_IN_WORD; self.workspace .set_color(col_x, y, View::HEX_LEN, Color::HexNormHi); } } } /// Print the ascii field. /// /// # Arguments /// /// * `doc` - document to render fn draw_ascii(&self, doc: &Document) { self.workspace.color_on(Color::AsciiNorm); let cursor_x = (doc.cursor.offset % self.columns as u64) as usize; let cursor_y = (doc.cursor.offset - self.offset) as usize / self.columns; let left_pos = self.offset_width + self.hex_width + View::FIELD_MARGIN * 2; let ascii_table = self.ascii_table.unwrap(); for y in 0..=self.lines { let offset = self.offset + (y * self.columns) as u64; if offset >= doc.file.size { break; } let text = (0..self.columns) .map(|i| { let index = (offset + i as u64 - self.offset) as usize; if let Some(&byte) = self.data.get(index) { ascii_table.charset[byte as usize] } else { ' ' } }) .collect::<String>(); if cursor_y == y { self.workspace.color_on(Color::AsciiNormHi); } self.workspace.print(left_pos, y, &text); if cursor_y == y { self.workspace.color_on(Color::AsciiNorm); } else { // highlight current column let col_x = left_pos + cursor_x; self.workspace.set_color(col_x, y, 1, Color::AsciiNormHi); } } } /// Highlight changes and diffs. /// /// # Arguments /// /// * `doc` - document to render fn highlight(&self, doc: &Document) { // calculate cursor position (indexes within the page data) let cursor_x = (doc.cursor.offset % self.columns as u64) as usize; let cursor_y = (doc.cursor.offset - self.offset) as usize / self.columns; // highlight diff for &offset in &self.differs { let cx = offset as usize % self.columns; let cy = (offset - self.offset) as usize / self.columns; if let Some((x, y)) = self.get_position(offset, true) { let color = if cx == cursor_x || cy == cursor_y { Color::HexDiffHi } else { Color::HexDiff }; self.workspace.set_color(x, y, View::HEX_LEN, color); } if self.ascii_table.is_some() { if let Some((x, y)) = self.get_position(offset, false) { let color = if cx == cursor_x || cy == cursor_y { Color::AsciiDiffHi } else { Color::AsciiDiff }; self.workspace.set_color(x, y, 1, color); } } } // highlight changes for &offset in &self.changes { let cx = offset as usize % self.columns; let cy = (offset - self.offset) as usize / self.columns; if let Some((x, y)) = self.get_position(offset, true) { let color = if cx == cursor_x || cy == cursor_y { Color::HexModHi } else { Color::HexMod }; self.workspace.set_color(x, y, View::HEX_LEN, color); } if self.ascii_table.is_some() { if let Some((x, y)) = self.get_position(offset, false) { let color = if cx == cursor_x || cy == cursor_y { Color::AsciiModHi } else { Color::AsciiMod }; self.workspace.set_color(x, y, 1, color); } } } } /// Get coordinates of specified offset inside the hex or ascii fields. /// /// # Arguments /// /// * `offset` - address of the byte /// * `hex` - field type, `true` for hex, `false` for ascii /// /// # Return value /// /// Coordinates of the byte relative to the view window. pub fn get_position(&self, offset: u64, hex: bool) -> Option<(usize, usize)> { if offset < self.offset { return None; } let y = (offset - self.offset) as usize / self.columns; if y >= self.lines { return None; } let column = (offset % self.columns as u64) as usize; let mut x = self.offset_width + View::FIELD_MARGIN; if hex { x += column * (View::BYTES_IN_WORD - 1) + column / View::BYTES_IN_WORD; } else { x += self.hex_width + View::FIELD_MARGIN + column; } Some((x, y)) } } <file_sep>/src/ui/setup.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::super::ascii; use super::super::config::Config; use super::dialog::{Dialog, DialogType}; use super::widget::{CheckBox, ListBox, StandardButton, WidgetType}; /// Dialog for setting the viewer parameters. pub struct SetupDialog {} impl SetupDialog { /// Show the "Setup" dialog. /// /// # Arguments /// /// * `params` - parameters to set up /// /// # Return value /// /// true if settings were changed pub fn show(config: &mut Config) -> bool { // create dialog let mut dlg = Dialog::new(27, 4, DialogType::Normal, "Setup"); // fixed width setup let checkbox = CheckBox { state: config.fixed_width, title: "Fixed width (16 bytes)".to_string(), }; let fixed = dlg.add_line(WidgetType::CheckBox(checkbox)); dlg.add_separator(); // ASCII encoding dlg.add_line(WidgetType::StaticText("ASCII field:".to_string())); let mut select = 0; let mut tables = Vec::with_capacity(ascii::TABLES.len() + 1 /* None */); tables.push("None (hide)".to_string()); for (index, table) in ascii::TABLES.iter().enumerate() { tables.push(table.name.to_string()); if let Some(current) = config.ascii_table { if current.id == table.id { select = index + 1 /* "None (hide)" */; } } } let listbox = ListBox { list: tables, current: select, }; let ascii = dlg.add_line(WidgetType::ListBox(listbox)); // buttons dlg.add_button(StandardButton::OK, true); let btn_cancel = dlg.add_button(StandardButton::Cancel, false); // show dialog if let Some(id) = dlg.show_unmanaged() { if id != btn_cancel { if let WidgetType::CheckBox(widget) = dlg.get_widget(fixed) { config.fixed_width = widget.state; } if let WidgetType::ListBox(widget) = dlg.get_widget(ascii) { config.ascii_table = if widget.current == 0 { None } else { ascii::TABLES.get(widget.current - 1) } } return true; } } false } } <file_sep>/src/controller.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::config::Config; use super::curses::{Color, Curses, Event, Key, KeyPress, Window}; use super::cursor::{Direction, HalfByte, Place}; use super::editor::{Editor, Focus}; use super::history::History; use super::ui::cut::CutDialog; use super::ui::dialog::{Dialog, DialogType}; use super::ui::fill::FillDialog; use super::ui::goto::GotoDialog; use super::ui::insert::InsertDialog; use super::ui::messagebox::MessageBox; use super::ui::progress::ProgressDialog; use super::ui::saveas::SaveAsDialog; use super::ui::search::SearchDialog; use super::ui::setup::SetupDialog; use super::ui::widget::StandardButton; use std::io::{ErrorKind, Result}; use std::path::Path; /// Controller: accepts input and converts it to commands for editor. pub struct Controller { /// Editor (business logic). editor: Editor, /// History (seach, goto, etc). history: History, /// App configuration. config: Config, /// Keybar window. keybar: Window, } impl Controller { /// Run controller. /// /// # Arguments /// /// * `files` - files to open /// * `offset` - desirable initial offset /// * `config` - configuration pub fn run(files: &[String], offset: Option<u64>, config: Config) -> Result<()> { let history = History::default(); // find initial offset let initial_offset = if let Some(offset) = offset { offset } else { let mut offset = 0; for file in files { if let Some(val) = history.get_filepos(file) { offset = val; break; } } offset }; // create controller instance let mut instance = Self { editor: Editor::new(files, &config)?, keybar: Window::new(0, 0, 0, 0, Color::Bar), history, config, }; if !instance.resize() { return Err(std::io::Error::new( ErrorKind::Other, "Not enough screen space to display", )); } if initial_offset != 0 { instance .editor .move_cursor(&Direction::Absolute(initial_offset, 0)); } instance.main_loop(); Ok(()) } /// Main loop. fn main_loop(&mut self) { loop { // redraw self.draw(); // handle next event match Curses::wait_event() { Event::TerminalResize => { self.resize(); } Event::KeyPress(key) => match key.key { Key::Esc | Key::F(10) => { if self.exit() { return; } } _ => { if !self.key_input_common(&key) { if self.editor.current().cursor.place == Place::Hex { self.key_input_hex(&key); } else { self.key_input_ascii(&key); } } } }, } } } /// Common keyboard input handler. /// /// # Arguments /// /// * `key` - pressed key /// /// # Return value /// /// true if key was handled #[allow(clippy::too_many_lines)] fn key_input_common(&mut self, key: &KeyPress) -> bool { match key.key { Key::F(1) => { Controller::help(); true } Key::F(2) => { if key.modifier == KeyPress::NONE { self.save(); } else if key.modifier == KeyPress::SHIFT { self.save_as(); } true } Key::F(3) => { self.goto(); true } Key::F(5) => { if key.modifier == KeyPress::SHIFT { self.find_closest(self.history.search_backward); } else if key.modifier == KeyPress::ALT { self.find_closest(!self.history.search_backward); } else { self.find(); } true } Key::F(6) => { self.fill(); true } Key::F(7) => { self.insert(); true } Key::F(8) => { self.cut(); true } Key::F(9) => { if SetupDialog::show(&mut self.config) { self.editor.config_changed(&self.config); } true } Key::Tab => { let dir = if key.modifier == KeyPress::SHIFT { Focus::PreviousField } else { Focus::NextField }; self.editor.switch_focus(&dir); true } Key::Left => { if key.modifier == KeyPress::NONE { self.editor.move_cursor(&Direction::PrevByte); } else if key.modifier == KeyPress::SHIFT { self.editor.move_cursor(&Direction::PrevWord); } else if key.modifier == KeyPress::ALT { self.editor.closest_change(false); } else if key.modifier == KeyPress::CTRL { self.editor.switch_focus(&Focus::PreviousField); } true } Key::Right => { if key.modifier == KeyPress::NONE { self.editor.move_cursor(&Direction::NextByte); } else if key.modifier == KeyPress::SHIFT { self.editor.move_cursor(&Direction::NextWord); } else if key.modifier == KeyPress::ALT { self.editor.closest_change(true); } else if key.modifier == KeyPress::CTRL { self.editor.switch_focus(&Focus::NextField); } true } Key::Up => { if key.modifier == KeyPress::NONE { self.editor.move_cursor(&Direction::LineUp); } else if key.modifier == KeyPress::SHIFT { self.editor.move_cursor(&Direction::ScrollUp); } else if key.modifier == KeyPress::ALT { self.editor.closest_change(false); } else if key.modifier == KeyPress::CTRL { self.editor.switch_focus(&Focus::PreviousDocument); } true } Key::Down => { if key.modifier == KeyPress::NONE { self.editor.move_cursor(&Direction::LineDown); } else if key.modifier == KeyPress::SHIFT { self.editor.move_cursor(&Direction::ScrollDown); } else if key.modifier == KeyPress::ALT { self.editor.closest_change(true); } else if key.modifier == KeyPress::CTRL { self.editor.switch_focus(&Focus::NextDocument); } true } Key::Home => { if key.modifier == KeyPress::NONE { self.editor.move_cursor(&Direction::LineBegin); } else if key.modifier == KeyPress::CTRL { self.editor.move_cursor(&Direction::FileBegin); } true } Key::End => { if key.modifier == KeyPress::NONE { self.editor.move_cursor(&Direction::LineEnd); } else if key.modifier == KeyPress::CTRL { self.editor.move_cursor(&Direction::FileEnd); } true } Key::PageUp => { self.editor.move_cursor(&Direction::PageUp); true } Key::PageDown => { self.editor.move_cursor(&Direction::PageDown); true } Key::Char('z') => { if key.modifier == KeyPress::CTRL { self.editor.undo(); true } else { false } } Key::Char('r' | 'y') => { if key.modifier == KeyPress::CTRL { self.editor.redo(); true } else { false } } _ => false, } } /// Keyboard input handler (HEX field focused). /// /// # Arguments /// /// * `key` - pressed key fn key_input_hex(&mut self, key: &KeyPress) { match key.key { Key::Backspace => { self.editor.move_cursor(&Direction::PrevHalf); } Key::Char('G') => { self.editor.move_cursor(&Direction::FileEnd); } Key::Char('g') => { self.editor.move_cursor(&Direction::FileBegin); } Key::Char(':') => { self.goto(); } Key::Char('/') => { self.find(); } Key::Char('n') => { self.find_closest(self.history.search_backward); } Key::Char('N') => { self.find_closest(!self.history.search_backward); } Key::Char('h') => { self.editor.move_cursor(&Direction::PrevByte); } Key::Char('l') => { self.editor.move_cursor(&Direction::NextByte); } Key::Char('k') => { self.editor.move_cursor(&Direction::LineUp); } Key::Char('j') => { self.editor.move_cursor(&Direction::LineDown); } Key::Char('a'..='f' | 'A'..='F' | '0'..='9') => { if key.modifier == KeyPress::NONE { if let Key::Char(chr) = key.key { let half = match chr { 'a'..='f' => chr as u8 - b'a' + 10, 'A'..='F' => chr as u8 - b'A' + 10, '0'..='9' => chr as u8 - b'0', _ => unreachable!(), }; let cursor = &self.editor.current().cursor; let offset = cursor.offset; let (value, mask) = if cursor.half == HalfByte::Left { (half << 4, 0xf0) } else { (half, 0x0f) }; self.editor.change(offset, value, mask); self.editor.move_cursor(&Direction::NextHalf); } } } Key::Char('u') => { self.editor.undo(); } _ => {} } } /// Keyboard input handler (ASCII field focused). /// /// # Arguments /// /// * `key` - pressed key fn key_input_ascii(&mut self, key: &KeyPress) { if let Key::Char(' '..='~') = key.key { if key.modifier == KeyPress::NONE { if let Key::Char(chr) = key.key { let offset = self.editor.current().cursor.offset; self.editor.change(offset, chr as u8, 0xff); self.editor.move_cursor(&Direction::NextByte); } } } } /// Draw editor. fn draw(&self) { Window::hide_cursor(); self.draw_keybar(); self.editor.draw(); } /// Draw key bar (bottom Fn line). fn draw_keybar(&self) { let (width, _) = self.keybar.get_size(); let names = &[ "Help", // F1 "Save", // F2 "Goto", // F3 "", // F4 "Find", // F5 "Fill", // F6 "Insert", // F7 "Cut", // F8 "Setup", // F9 "Exit", // F10 ]; let mut keybar = String::new(); let id_len = 2; // Fn id (decimal number from 1 to 10) let name_min = 1; // at least 1 char for name let keybar_min = names.len() * (id_len + name_min); let key_len = width.max(keybar_min) / names.len(); let name_max = key_len - id_len; for (i, name) in names.iter().enumerate() { let mut name = (*name).to_string(); if i < names.len() - 1 && name.len() > name_max { name.truncate(name_max); } keybar += &format!("{:>2}{:<width$}", i + 1, name, width = name_max); } keybar.truncate(width); self.keybar.clear(); self.keybar.print(0, 0, &keybar); for i in 0..names.len() { let pos = i * key_len; if pos + id_len > width { break; } self.keybar.set_color(pos, 0, id_len, Color::HexNorm); } self.keybar.refresh(); } /// Screen resize handler. /// /// # Return value /// /// `false` if screen space is not enough fn resize(&mut self) -> bool { let (width, height) = Curses::screen_size(); self.keybar.resize(width, 1); self.keybar.set_pos(0, height - 1); self.editor.resize(width, height - 1) } /// Show mini help. fn help() { let mut dlg = Dialog::new(44, 8, DialogType::Normal, "XVI"); dlg.add_center("Use arrows, PgUp, PgDown to move cursor.".to_string()); dlg.add_center("Use Ctrl-z or u for undo,".to_string()); dlg.add_center("Ctrl-r or Ctrl-y for redo.".to_string()); dlg.add_center("Use Tab to switch between fields and files.".to_string()); dlg.add_center("F1-F10 are described in the screen bottom.".to_string()); dlg.add_separator(); dlg.add_center(format!("XVI v.{}", env!("CARGO_PKG_VERSION"))); dlg.add_center(env!("CARGO_PKG_HOMEPAGE").to_string()); dlg.add_button(StandardButton::OK, true); dlg.show_unmanaged(); } /// Save current file, returns false if operation failed. fn save(&mut self) -> bool { if !self.editor.current().file.is_modified() { return true; } loop { match self.editor.save() { Ok(()) => { return true; } Err(err) => { if err.kind() == ErrorKind::Interrupted || !MessageBox::retry_write(&self.editor.current().file.path, &err) { return false; } } } } } /// Save current file with new name. fn save_as(&mut self) { let name = self.editor.current().file.path.to_string(); if let Some(name) = SaveAsDialog::show(name) { loop { let mut progress = ProgressDialog::new("Save as...", true); match self.editor.save_as(Path::new(&name), &mut progress) { Ok(()) => { break; } Err(err) => { progress.hide(); if err.kind() == ErrorKind::Interrupted || !MessageBox::retry_write(&self.editor.current().file.path, &err) { break; } } } } } } /// Goto to specified address. fn goto(&mut self) { if let Some(offset) = GotoDialog::show(&self.history.goto, self.editor.current().cursor.offset) { self.history.add_goto(offset); self.editor.move_cursor(&Direction::Absolute(offset, 0)); } } /// Find position of the sequence. fn find(&mut self) { if let Some((seq, bkg)) = SearchDialog::show(&self.history.search, self.history.search_backward) { self.history.search_backward = bkg; self.history.add_search(&seq); self.find_closest(self.history.search_backward); } } /// Find next/previous position of the sequence. fn find_closest(&mut self, backward: bool) { if self.history.search.is_empty() { self.history.search_backward = backward; self.find(); } else { let mut progress = ProgressDialog::new("Searching...", false); match self.editor.find( self.editor.current().cursor.offset, &self.history.search[0], backward, &mut progress, ) { Ok(()) => {} Err(err) => { progress.hide(); match err.kind() { ErrorKind::Interrupted => { /*skip*/ } ErrorKind::NotFound => { MessageBox::show( DialogType::Error, "Search", &[ "Sequence not found in file", &self.editor.current().file.path, ], &[(StandardButton::OK, true)], ); } _ => { MessageBox::error_read( &self.editor.current().file.path, &err, &[(StandardButton::Cancel, true)], ); } } } } } } /// Fill range. fn fill(&mut self) { let current = self.editor.current(); if let Some((range, pattern)) = FillDialog::show( current.cursor.offset, current.file.size, &self.history.pattern, ) { self.history.pattern = pattern; self.editor.fill(&range, &self.history.pattern); } } /// Insert bytes. fn insert(&mut self) { let file = &self.editor.current().file; if file.is_modified() { MessageBox::show( DialogType::Error, "Insert bytes", &[ &file.path, "was modified.", "Please save or undo your changes first.", ], &[(StandardButton::OK, true)], ); return; } if let Some((mut offset, size, pattern)) = InsertDialog::show(self.editor.current().cursor.offset, &self.history.pattern) { self.history.pattern = pattern; if offset > file.size { offset = file.size; } let mut progress = ProgressDialog::new("Insert bytes...", true); if let Err(err) = self .editor .insert(offset, size, &self.history.pattern, &mut progress) { if err.kind() != ErrorKind::Interrupted { progress.hide(); MessageBox::error_write( &self.editor.current().file.path, &err, &[(StandardButton::Cancel, true)], ); } } } } /// Cut out range. fn cut(&mut self) { let file = &self.editor.current().file; if file.is_modified() { MessageBox::show( DialogType::Error, "Cut range", &[ &file.path, "was modified.", "Please save or undo your changes first.", ], &[(StandardButton::OK, true)], ); return; } if let Some(range) = CutDialog::show(self.editor.current().cursor.offset, file.size) { let mut progress = ProgressDialog::new("Cutting out range...", true); if let Err(err) = self.editor.cut(&range, &mut progress) { if err.kind() != ErrorKind::Interrupted { progress.hide(); MessageBox::error_write( &self.editor.current().file.path, &err, &[(StandardButton::Cancel, true)], ); } } } } /// Exit from editor. fn exit(&mut self) -> bool { for index in 0..self.editor.len() { self.editor.switch_focus(&Focus::DocumentIndex(index)); let current = self.editor.current(); if !current.file.is_modified() { continue; } // ask for save if let Some(button) = MessageBox::show( DialogType::Error, "Exit", &[&current.file.path, "was modified.", "Save before exit?"], &[ (StandardButton::Yes, false), (StandardButton::No, false), (StandardButton::Cancel, true), ], ) { match button { StandardButton::Yes => { // save current document if !self.save() { return false; } } StandardButton::Cancel => { return false; } _ => {} } } else { return false; } } // save history let (offset, files) = self.editor.get_files(); files .iter() .for_each(|f| self.history.add_filepos(f, offset)); self.history.save(); true } } <file_sep>/Makefile # SPDX-License-Identifier: MIT # Copyright (C) 2021 <NAME> <<EMAIL>> THIS_FILE := $(lastword $(MAKEFILE_LIST)) THIS_DIR := $(abspath $(dir $(THIS_FILE))) # default installation prefix PREFIX := /usr # version of the application VERSION := $(shell git describe --tags --long --always | sed 's/-g.*//;s/^v//;s/-/./') # path to extra files (mans, icon, desktop, etc) EXTRA_DIR := $(THIS_DIR)/extra # path to the intermediate dir TARGET_DIR := $(THIS_DIR)/target # path to the application binary TARGET_BIN := $(TARGET_DIR)/release/xvi # app image APPIMG_DIR := $(TARGET_DIR)/appimg APPIMG_TOOL := $(TARGET_DIR)/linuxdeploy-x86_64.AppImage APPIMG_BIN := $(THIS_DIR)/xvi-$(VERSION)-x86_64.AppImage all: $(TARGET_BIN) $(TARGET_BIN): cargo build --release clean: rm -rf $(TARGET_DIR) $(APPIMG_BIN) version: @echo "$(VERSION)" install: $(TARGET_BIN) install -D -m 755 $(TARGET_BIN) $(PREFIX)/bin/$(notdir $(TARGET_BIN)) install -D -m 644 $(EXTRA_DIR)/xvi.1 $(PREFIX)/share/man/man1/xvi.1 install -D -m 644 $(EXTRA_DIR)/xvirc.5 $(PREFIX)/share/man/man5/xvirc.5 uninstall: rm -f "$(PREFIX)/bin/$(notdir $(TARGET_BIN))" rm -f "$(PREFIX)/share/man/man1/xvi.1" rm -f "$(PREFIX)/share/man/man5/xvirc.5" appimage: $(APPIMG_BIN) $(APPIMG_BIN): $(APPIMG_TOOL) rm -rf $(APPIMG_DIR)/* $(MAKE) PREFIX=$(APPIMG_DIR)/$(PREFIX) install install -D -m 644 $(EXTRA_DIR)/xvi.appdata.xml $(APPIMG_DIR)/$(PREFIX)/share/metainfo/xvi.appdata.xml $(APPIMG_TOOL) --appdir $(APPIMG_DIR) \ --desktop-file $(EXTRA_DIR)/xvi.desktop \ --icon-file $(EXTRA_DIR)/xvi.png \ --output appimage mv xvi-*-x86_64.AppImage $@ $(APPIMG_TOOL): mkdir -p $(@D) wget \ https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage \ -O $@ chmod 0755 $@ .PHONY: all clean version install uninstall appimage <file_sep>/README.md # XVI: hex editor for Linux terminal Hex editor with ncurses based user interface: - Low resource utilization, minimum dependencies; - Support for some VIM keyboard shortcuts (`hjkl`, `:`, `/`, etc); - Visual diff between several files; - Highlighting the current position and changed data; - Insert bytes into the middle of the file; - Cutting bytes from the middle of the file; - Filling the range with a pattern; - Undo/redo support; - Search and goto; - Customizable UI colors. ![Screenshot](https://raw.githubusercontent.com/artemsen/xvi/master/.github/screenshot1.png) ![Screenshot](https://raw.githubusercontent.com/artemsen/xvi/master/.github/screenshot2.png) ## Install - Arch users can install the program via [AUR](https://aur.archlinux.org/packages/xvi-git); - AppImage is available in [Releases](https://github.com/artemsen/xvi/releases). ## Configure The editor searches for the configuration file with name `config` in the following directories: - `$XDG_CONFIG_HOME/xvi` - `$HOME/.config/xvi` Sample file is available [here](https://github.com/artemsen/xvi/blob/master/extra/xvirc). See `man xvirc` for details. ## Build The project uses Rust and Cargo: ``` cargo build --release ``` <file_sep>/src/ui/range.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::dialog::{Dialog, DialogHandler, ItemId}; use super::widget::{InputFormat, InputLine, WidgetType}; use std::ops::Range; /// Range control: set of widgets and handlers. pub struct RangeControl { // Max possible value. max: u64, // Items of the dialog. start: ItemId, end: ItemId, length: ItemId, } impl RangeControl { /// Width of the dialog. pub const DIALOG_WIDTH: usize = 43; /// Width of the offset field. const OFFSET_WIDTH: usize = 13; /// Width of the length field. const LENGTH_WIDTH: usize = 9; pub fn create(dlg: &mut Dialog, default: Range<u64>, max: u64) -> Self { debug_assert!(!default.is_empty()); debug_assert!(default.end <= max); dlg.add_line(WidgetType::StaticText( " Start End".to_string(), )); dlg.add_line(WidgetType::StaticText( "Range: \u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}".to_string(), )); // start offset widget let widget = InputLine::new( format!("{:x}", default.start), InputFormat::HexUnsigned, Vec::new(), RangeControl::OFFSET_WIDTH, ); let start = dlg.add( Dialog::PADDING_X + 8, Dialog::PADDING_Y + 1, RangeControl::OFFSET_WIDTH, WidgetType::Edit(widget), ); // end offset widget let widget = InputLine::new( format!("{:x}", default.end - 1), InputFormat::HexUnsigned, Vec::new(), RangeControl::OFFSET_WIDTH, ); let end = dlg.add( Dialog::PADDING_X + 30, Dialog::PADDING_Y + 1, RangeControl::OFFSET_WIDTH, WidgetType::Edit(widget), ); dlg.add_line(WidgetType::StaticText("Length: \u{2514}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500} \u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2518}".to_string())); // range length widget let widget = InputLine::new( format!("{}", default.end - default.start), InputFormat::DecUnsigned, Vec::new(), RangeControl::LENGTH_WIDTH, ); let length = dlg.add( Dialog::PADDING_X + 21, Dialog::PADDING_Y + 2, RangeControl::LENGTH_WIDTH, WidgetType::Edit(widget), ); Self { max, start, end, length, } } /// Get range specified in the control fields. pub fn get(&self, dialog: &Dialog) -> Option<Range<u64>> { let start = self.get_offset(dialog, self.start); let end = self.get_offset(dialog, self.end); if start <= end && start < self.max { Some(start..end + 1) } else { None } } /// Get normalized offset value from the widget. fn get_offset(&self, dialog: &Dialog, item: ItemId) -> u64 { let mut offset = 0; if let WidgetType::Edit(widget) = dialog.get_widget(item) { offset = u64::from_str_radix(widget.get_value(), 16).unwrap_or(0); if offset >= self.max { offset = self.max - 1; } } offset } } impl DialogHandler for RangeControl { fn on_item_change(&mut self, dialog: &mut Dialog, item: ItemId) { if item == self.start || item == self.end { let start = self.get_offset(dialog, self.start); let end = self.get_offset(dialog, self.end); let length = if start > end { 0 } else { end - start + 1 }; if let WidgetType::Edit(widget) = dialog.get_widget_mut(self.length) { widget.set_value(format!("{}", length)); } } else if item == self.length { let mut length = 1; if let WidgetType::Edit(widget) = dialog.get_widget(self.length) { length = widget.get_value().parse::<u64>().unwrap_or(0); if length == 0 { length = 1; } } let mut end = self.get_offset(dialog, self.start) + length - 1; if end >= self.max { end = self.max - 1; } if let WidgetType::Edit(widget) = dialog.get_widget_mut(self.end) { widget.set_value(format!("{:x}", end)); } } } fn on_focus_lost(&mut self, dialog: &mut Dialog, item: ItemId) { if item == self.start || item == self.end { let offset = self.get_offset(dialog, item); if let WidgetType::Edit(widget) = dialog.get_widget_mut(item) { widget.set_value(format!("{:x}", offset)); } } else if item == self.length { let start = self.get_offset(dialog, self.start); let end = self.get_offset(dialog, self.end); let length = if start > end { 0 } else { end - start + 1 }; if let WidgetType::Edit(widget) = dialog.get_widget_mut(self.length) { widget.set_value(format!("{}", length)); } } } } <file_sep>/src/ui/search.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::dialog::{Dialog, DialogHandler, DialogType, ItemId}; use super::widget::{CheckBox, InputFormat, InputLine, StandardButton, WidgetType}; /// "Search sequence" dialog. pub struct SearchDialog { hex: ItemId, ascii: ItemId, btn_ok: ItemId, btn_cancel: ItemId, } impl SearchDialog { /// Width of the dialog. const WIDTH: usize = 40; /// Character used for non-printable values in the ASCII field. const NPCHAR: char = '·'; /// Show the "Search" dialog. /// /// # Arguments /// /// * `sequences` - sequences history /// * `backward` - default search direction /// /// # Return value /// /// Search sequence and direction. pub fn show(sequences: &[Vec<u8>], backward: bool) -> Option<(Vec<u8>, bool)> { // create dialog let mut dlg = Dialog::new(SearchDialog::WIDTH, 6, DialogType::Normal, "Search"); // hex sequence dlg.add_line(WidgetType::StaticText( "Hex sequence to search:".to_string(), )); let history: Vec<String> = sequences .iter() .map(|s| s.iter().map(|b| format!("{:02x}", b)).collect()) .collect(); let init = if history.is_empty() { String::new() } else { history[0].clone() }; let widget = InputLine::new(init, InputFormat::HexStream, history, SearchDialog::WIDTH); let hex = dlg.add_line(WidgetType::Edit(widget)); // ascii sequence dlg.add_line(WidgetType::StaticText("ASCII:".to_string())); let widget = InputLine::new( String::new(), InputFormat::Any, Vec::new(), SearchDialog::WIDTH, ); let ascii = dlg.add_line(WidgetType::Edit(widget)); // search direction dlg.add_separator(); let widget = CheckBox { state: backward, title: "Backward search".to_string(), }; let bkg = dlg.add_line(WidgetType::CheckBox(widget)); // buttons let btn_ok = dlg.add_button(StandardButton::OK, true); let btn_cancel = dlg.add_button(StandardButton::Cancel, false); // construct dialog handler let mut handler = Self { hex, ascii, btn_ok, btn_cancel, }; handler.on_item_change(&mut dlg, handler.hex); // show dialog if let Some(id) = dlg.show(&mut handler) { if id != handler.btn_cancel { let seq = handler.get_sequence(&dlg).unwrap(); debug_assert!(!seq.is_empty()); let dir = if let WidgetType::CheckBox(widget) = dlg.get_widget(bkg) { widget.state } else { backward }; return Some((seq, dir)); } } None } /// Get current sequence from the hex field. fn get_sequence(&self, dialog: &Dialog) -> Option<Vec<u8>> { let mut result = None; if let WidgetType::Edit(widget) = dialog.get_widget(self.hex) { let mut value = widget.get_value().to_string(); if !value.is_empty() { if value.len() % 2 != 0 { value.push('0'); } result = Some( (0..value.len()) .step_by(2) .map(|i| u8::from_str_radix(&value[i..i + 2], 16).unwrap()) .collect(), ); } } result } } impl DialogHandler for SearchDialog { fn on_close(&mut self, dialog: &mut Dialog, item: ItemId) -> bool { item == self.btn_cancel || dialog.get_context(self.btn_ok).enabled } fn on_item_change(&mut self, dialog: &mut Dialog, item: ItemId) { let mut is_ok = false; if item == self.hex { if let Some(hex) = self.get_sequence(dialog) { // set ASCII text from the hex field let ascii = hex .iter() .map(|c| { if *c > 0x20 && *c < 0x7f { *c as char } else { SearchDialog::NPCHAR } }) .collect(); if let WidgetType::Edit(widget) = dialog.get_widget_mut(self.ascii) { widget.set_value(ascii); } is_ok = !hex.is_empty(); } } else if item == self.ascii { // set hex text from the ASCII field if let WidgetType::Edit(widget) = dialog.get_widget(self.ascii) { let hex: String = widget .get_value() .chars() .map(|b| { format!( "{:02x}", if b == SearchDialog::NPCHAR { 0 } else { b as u8 } ) }) .collect(); is_ok = !hex.is_empty(); if let WidgetType::Edit(widget) = dialog.get_widget_mut(self.hex) { widget.set_value(hex); } } } else { is_ok = true; } dialog.set_enabled(self.btn_ok, is_ok); } fn on_focus_lost(&mut self, dialog: &mut Dialog, item: ItemId) { if item == self.hex { if let WidgetType::Edit(widget) = dialog.get_widget_mut(self.hex) { let mut value = widget.get_value().to_string(); if !value.is_empty() && value.len() % 2 != 0 { value.push('0'); widget.set_value(value); } } } } } <file_sep>/src/ui/mod.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> pub mod cut; pub mod dialog; pub mod fill; pub mod goto; pub mod insert; pub mod messagebox; pub mod progress; pub mod range; pub mod saveas; pub mod search; pub mod setup; pub mod widget; <file_sep>/src/config.rs // SPDX-License-Identifier: MIT // Copyright (C) 2021 <NAME> <<EMAIL>> use super::ascii::Table; use super::curses::Color; use super::inifile::IniFile; use std::env; use std::path::PathBuf; /// App configuration. pub struct Config { /// Line width mode (fixed/dynamic). pub fixed_width: bool, /// ASCII table identifier. pub ascii_table: Option<&'static Table>, /// Color scheme. pub colors: Vec<(Color, i16, i16)>, } impl Config { const VIEW: &'static str = "View"; const COLORS: &'static str = "Colors"; /// Load configuration from the default rc file. pub fn load() -> Self { let mut instance = Config::default(); let dir = match env::var("XDG_CONFIG_HOME") { Ok(val) => PathBuf::from(val), Err(_) => match env::var("HOME") { Ok(val) => PathBuf::from(val).join(".config"), Err(_) => PathBuf::new(), }, }; let file = dir.join("xvi").join("config"); if let Ok(ini) = IniFile::load(&file) { if let Some(val) = ini.get_boolval(Config::VIEW, "FixedWidth") { instance.fixed_width = val; } if let Some(val) = ini.get_strval(Config::VIEW, "Ascii") { if val == "none" { instance.ascii_table = None; } else { instance.ascii_table = Table::from_id(&val); } } let mut palette = Palette::DARK.clone(); if let Some(val) = ini.get_strval(Config::COLORS, "Theme") { if val.to_lowercase().as_str() == "light" { palette = Palette::LIGHT.clone(); } } if let Some(section) = ini.sections.get(&Config::COLORS.to_lowercase()) { palette.parse(section); } instance.colors = palette.colors(); } instance } } impl Default for Config { fn default() -> Self { Self { fixed_width: false, ascii_table: Some(Table::default()), colors: Palette::DARK.colors(), } } } /// Color palette. #[derive(Clone)] struct Palette { general: (i16, i16), highlight: (i16, i16), offset: (i16, i16), ascii: (i16, i16), modified: (i16, i16), diff: (i16, i16), bar: (i16, i16), dialog: (i16, i16), error: (i16, i16), disabled: (i16, i16), focused: (i16, i16), input: (i16, i16), select: (i16, i16), } impl Palette { /// Default color palette for the dark theme. const DARK: &'static Palette = &Palette { general: (-1, -1), highlight: (-1, 235), offset: (241, -1), ascii: (241, -1), modified: (220, -1), diff: (124, -1), bar: (242, 236), dialog: (235, 245), error: (250, 88), disabled: (239, 245), focused: (250, 238), input: (235, 243), select: (250, 235), }; /// Default color palette for the light theme. const LIGHT: &'static Palette = &Palette { general: (7, 4), highlight: (0, 12), offset: (7, 4), ascii: (7, 4), modified: (11, 4), diff: (1, 4), bar: (0, 6), dialog: (0, 7), error: (15, 1), disabled: (8, 7), focused: (0, 6), input: (0, 6), select: (15, 0), }; /// Parse ini section with palette setup. /// /// # Arguments /// /// * `section` - ini section yo parse fn parse(&mut self, section: &[String]) { for line in section { if let Some((key, val)) = IniFile::keyval(line) { let split: Vec<&str> = val.splitn(2, ',').collect(); if split.len() == 2 { if let Ok(fg) = split[0].trim().parse::<i16>() { if let Ok(bg) = split[1].trim().parse::<i16>() { match key.as_str() { "general" => { self.general = (fg, bg); } "highlight" => { self.highlight = (fg, bg); } "offset" => { self.offset = (fg, bg); } "ascii" => { self.ascii = (fg, bg); } "modified" => { self.modified = (fg, bg); } "diff" => { self.diff = (fg, bg); } "bar" => { self.bar = (fg, bg); } "dialog" => { self.dialog = (fg, bg); } "error" => { self.error = (fg, bg); } "disabled" => { self.disabled = (fg, bg); } "focused" => { self.focused = (fg, bg); } "input" => { self.input = (fg, bg); } "select" => { self.select = (fg, bg); } _ => {} } } } } } } } /// Compose color table from palette. /// /// # Return value /// /// Color table. pub fn colors(&self) -> Vec<(Color, i16, i16)> { vec![ (Color::HexNorm, self.general.0, self.general.1), (Color::HexMod, self.modified.0, self.modified.1), (Color::HexDiff, self.diff.0, self.diff.1), (Color::HexNormHi, self.highlight.0, self.highlight.1), (Color::HexModHi, self.modified.0, self.highlight.1), (Color::HexDiffHi, self.diff.0, self.highlight.1), (Color::AsciiNorm, self.ascii.0, self.ascii.1), (Color::AsciiMod, self.modified.0, self.modified.1), (Color::AsciiDiff, self.diff.0, self.diff.1), (Color::AsciiNormHi, self.highlight.0, self.highlight.1), (Color::AsciiModHi, self.modified.0, self.highlight.1), (Color::AsciiDiffHi, self.diff.0, self.highlight.1), (Color::Offset, self.offset.0, self.offset.1), (Color::OffsetHi, self.highlight.0, self.highlight.1), (Color::Bar, self.bar.0, self.bar.1), (Color::Dialog, self.dialog.0, self.dialog.1), (Color::Error, self.error.0, self.error.1), (Color::Disabled, self.disabled.0, self.disabled.1), (Color::Focused, self.focused.0, self.focused.1), (Color::Input, self.input.0, self.input.1), (Color::Select, self.select.0, self.select.1), ] } } <file_sep>/Cargo.toml [package] name = "xvi" version = "1.2.0" authors = ["<NAME> <<EMAIL>>"] edition = "2018" homepage = "https://github.com/artemsen/xvi" [dependencies] ncurses = { version = "5.101.0", features = ["wide", "panel"] } unicode-segmentation = "1.8.0"
fcccc0acd8ceef5d757de7ef118a1b9528236781
[ "Markdown", "TOML", "Makefile", "INI", "Rust" ]
29
Rust
artemsen/xvi
b04e2496e10e2f60a0d5ac06ade6454e18b386be
2d136f7fe02c977668e3ab7bf4b97a6cbd7f171c
refs/heads/master
<file_sep># DEPRECATED & BROKEN A proof-of-concept ScraperWiki tool, built to work with an old version of the beta platform. **This will not work on beta.scraperwiki.com** but you're welcome to port it :-) <file_sep>#!/usr/bin/env python from __future__ import division import sys import scraperwiki import lxml.html import requests import re import json import urlparse # retry 5 times, as Highrise seems ropey # requests.defaults.defaults['max_retries'] = 5 user_list = {} def get_settings(): with open('../scraperwiki.json') as f: settings = json.load(f) try: return settings['highrise']['username'], \ settings['highrise']['password'], \ settings['highrise']['domain'] except KeyError as err: sys.stderr.write("Could not find your Highrise %s" % err.message) exit(1) def setup(): global user_list xml = get_xml('https://%s/users.xml' % DOMAIN) if xml == None or xml.strip() == '': sys.stderr.write("Couldn't connect to your domain: please check it.") exit(1) users = lxml.html.fromstring(xml) for user in users.cssselect('user'): id = int(user.cssselect('id')[0].text) name = user.cssselect('name')[0].text user_list[id] = name def get_xml(url): global APIKEY try: r=requests.get(url, auth=(APIKEY,'X'), verify=False) except: return None return r.content def get_text(item): try: return item.text except: try: return item[0].text except: return None def css_text(item, css): return get_text(item.cssselect(css)) def get_session(): global BASEURL, APIKEY s = requests.session() dom = lxml.html.fromstring(s.get('https://launchpad.37signals.com/highrise/signin', verify=False).content) token = dom.cssselect('input[name=authenticity_token]')[0].get('value') params = {} params['username'] = USERNAME params['password'] = <PASSWORD> params['product'] = 'highrise' params['authenticity_token'] = token r = s.post('https://launchpad.37signals.com/session', params, verify=False) url = r.url dom = lxml.html.fromstring(r.content) if 'failed_authentication=true' in url: errmsg = dom.cssselect('#login_dialog h2')[0].text_content() sys.stderr.write(errmsg) exit(1) user_id = dom.xpath('.//meta[@name="current-user"]')[0].get('content') r = s.get(urlparse.urljoin(url, '/users/%s/edit' % user_id)) dom = lxml.html.fromstring(r.content) APIKEY = dom.cssselect('#token')[0].text_content() return r def get_deals(): deal_lookup={'deal_name':'name', 'deal_id':'id', 'owner_id':'responsible-party-id', 'created':'created-at', 'updated':'updated-at', 'super_status':'status', 'price':'price'} deals = lxml.html.fromstring(get_xml('https://%s/deals.xml' % DOMAIN)).cssselect('deals deal') dealbuilder=[] for deal in deals: deal_info={} for item in deal_lookup: deal_info[item]=css_text(deal, deal_lookup[item]) print 'getting deal:', deal_info['deal_name'] oid = deal_info['owner_id'] try: oid = int(oid) deal_info['owner']=user_list[oid] except TypeError: print "skipping deal %r" % deal_info continue m = re.search(r'(^\d{3,4}|\d{3,4}i?p?$)', deal_info['deal_name'], re.IGNORECASE) if m: deal_info['ref_no'] = m.group(0) else: deal_info['ref_no'] = None try: # see if they're a company :-( deal_info['company']=deal.xpath('party/name')[0].text deal_info['company_id']=deal.xpath('party/id')[0].text except IndexError: # is a person, not a company :) deal_info['company']=deal.xpath('party/company-name')[0].text deal_info['contact']='%s %s'%(deal.xpath('party/first-name')[0].text , deal.xpath('party/last-name')[0].text) deal_info['company_id']=deal.xpath('party/company-id')[0].text deal_info['contact_id']=deal.xpath('party/id')[0].text donesomething=False deal_info['status'] = None deal_info['status_details'] = None deal_info['redflag'] = None deal_info['redflag_details'] = None deal_info['completed'] = None dealbuilder.append(deal_info) print 'saving data' scraperwiki.sqlite.execute('DROP TABLE IF EXISTS deals') scraperwiki.sqlite.execute('CREATE TABLE `deals` (`deal_id` integer, `ref_no` text, `deal_name` text, `super_status` text, `status` text, `status_details` text, `status_due` text, `created` text, `updated` text, `redflag` text, `redflag_details` text, `price` integer, `company` text, `company_id` integer, `contact` text, `contact_id` integer, `owner` text, `owner_id` integer, `dropbox` text)') scraperwiki.sqlite.commit() scraperwiki.sqlite.save(['deal_id'], dealbuilder, 'deals') USERNAME, PASSWORD, DOMAIN = get_settings() APIKEY = None get_session() setup() get_deals() <file_sep>#!/bin/sh set -e boxname=$(whoami | sed 's:\.:/:') # spreadsheet-install.sh # Installs the ScraperWiki spreadsheet tool into this box. ( cd ~/http if test -e spreadsheet-tool then # Should only get here in testing. ( cd spreadsheet-tool git pull ) else git clone git://github.com/scraperwiki/spreadsheet-tool.git fi sed -i "/^sqliteEndpoint/s@.*@sqliteEndpoint = '../../sqlite'; // Added by spreadsheet-install.sh@" spreadsheet-tool/js/spreadsheet-tool.js ) # Install CSV download tool. # :todo: Should really be in its own github repo. cat > download << 'EOF' #!/bin/sh # Generated by install-extras.sh tool=highrise dbfile=~/${tool}/scraperwiki.sqlite tables=$(sqlite3 $dbfile 'select name from sqlite_master where type="table" or type="view"') for name in $tables do sqlite3 -header -csv $dbfile "select * from $name" > "http/$tool-$name.csv" done set -- $tables if [ $# = 0 ] then printf '[]' exit 0 fi printf '[' while [ $# -gt 1 ] do printf '"%s-%s.csv",' $tool $1 shift done printf '"%s-%s.csv"' $tool $1 printf ']' EOF chmod +x download mkdir ~/http/csvdownload-tool cp ~/highrise/templates/csv.html ~/http/csvdownload-tool/index.html
2192f147dc4f3bf4726c1a1d0a71bd962c3c26ab
[ "Markdown", "Python", "Shell" ]
3
Markdown
scraperwiki/highrise-tool
4ff1018dfe9ed40af7bdacd8fd2afd90098fcc41
4cf07245b61a29772f767d5e1051489976576bc2
refs/heads/master
<repo_name>jokinL/frontend2<file_sep>/js/form.js // On load $(function(){ // Get list of post list = $(".section"); // Get first post post = $(".article").first(); /* ##################################### EVENTES ##################################### */ // Open/Close form $("#js-publish").click(viewform); $("#js-form").on("submit", addpost); }); /* ##################################### FUNCTIONS ##################################### */ // Open/Close form to publish Post function viewform(){ $("#js-form").slideToggle(); $(".article").slideToggle(); } // Add Post to html function addpost(){ // Put in var inputs values var title = $("#js-title").val(), autor = $("#js-autor").val(), tag = $("#js-tag").val(), // New var with .article html clone = post.clone(); // Find a and insert var title clone.find(".article--title a") .text(title); /*.attr("href", url)*/ clone.find(".article--autor a") .text(autor); clone.find(".article--tag") .text(tag); clone.hide(); // Insert clone inside list in first position list.prepend(clone); $("#js-form").slideToggle(); title = $("#js-title").val(""); autor = $("#js-autor").val(""); tag = $("#js-tag").val(""); $(".article").slideToggle(); /*$("#js-form input[type='text']").val("");*/ /*clone.fadeIn();*/ return false; }
9ccf6e3c75d2d8cbe249e8d658d90f243e62c918
[ "JavaScript" ]
1
JavaScript
jokinL/frontend2
0a157e46b64d014cbcafe04f19e6854cb4ad246a
1303335db15f2386e082034737ee0c3382225973
refs/heads/master
<file_sep> CHOICES = {'p'=>'paper','r'=>'rock','s'=>'scissors'} puts 'welcome to rock paper scissors' loop do def display_winning_message(human, computer, win_or_lose) if win_or_lose == "win" puts "you chose #{human} and the computer chose #{computer} you won!" elsif win_or_lose =="lose" puts "you chose #{human} and the computer chose #{computer} you lost!" else puts "you chose #{human} and the computer chose #{computer}, you tied!" end end #inner loop doesn't stop until player chooses a valid key from CHOICES constant begin puts 'return R/P/S for your choice' player_choice = gets.chomp.downcase end until CHOICES.keys.include?(player_choice) puts 'you picked correctly' computer_choice = CHOICES.keys.sample if player_choice == computer_choice display_winning_message(player_choice, computer_choice, "tie") #if player wins elsif player_choice == 'p' && computer_choice == 'r' || player_choice== 'r' && computer_choice == 's' || player_choice=='s' and computer_choice=='p' display_winning_message(player_choice,computer_choice, "win") #if player loses else display_winning_message(player_choice,computer_choice,"lose") end puts "would you like to play again? Y or N." restart = gets.chomp.downcase if restart == "n" break end end
933d9f99d4b267e3018b9c430d854530dde0fa62
[ "Ruby" ]
1
Ruby
merrillcook0/tealeaf_exercises
f5487960b2cb994f7e85691083ce670a4272af67
76944dc3c9e67e999c1da8b77152b13bc5b00caa
refs/heads/master
<file_sep>require 'hashie' require 'active_support' require 'active_support/core_ext' module Google module Calendar class Event # API Reference # * https://developers.google.com/google-apps/calendar/v3/reference/#Events # # Supported Google Calendar API (Events) # Method VERB PATH # -------- ------ -------------------------------------- # get GET /calendars/:calendarId/events/:eventId # list GET /calendars/:calendarId/events # insert POST /calendars/:calendarId/events # delete DELETE /calendars/:calendarId/events/:eventId # quickAdd POST /calendars/:calendarId/events/quickAdd # update PUT /calendars/:calendarId/events/:eventId attr_reader :id, :kind, :etag, :status, :htmlLink, :created, :updated attr_reader :creator, :organizer, :transparency, :iCalUID, :sequence, :reminders attr_accessor :summary, :start, :end def initialize(options={}) update_attributes(options) end # [API] get # GET /calendars/:calendarId/events/eventId def self.get(id) self.new(id: id).fetch end def fetch params = { calendarId: Calendar.id, eventId: id } request(Calendar.api.events.get, params) end # [API] list # GET /calendars/:calendarId/events def self.list(st, et) params = { calendarId: Calendar.id, orderBy: 'startTime', timeMax: et.to_time.utc.iso8601, timeMin: st.to_time.utc.iso8601, singleEvents: 'True' } request(Calendar.api.events.list, params) end # [API] insert # POST /calendars/:calendarId/events def insert params = { calendarId: Calendar.id } body = self.to_json request(Calendar.api.events.insert, params, body) end def self.insert(options={}) self.new(options).insert end # [API] delete # DELETE /calendars/:calendarId/events/:eventId def delete params = { calendarId: Calendar.id, eventId: id } request(Calendar.api.events.delete, params) self end def self.delete(id) self.new(id: id).fetch.delete end # [API] quickAdd # POST /calendars/:calendarId/events/quickAdd def self.quickAdd(text) params = { calendarId: Calendar.id, text: text } request(Calendar.api.events.quick_add, params) end # [API] update # PUT /calendars/:calendarId/events/:eventId def update params = { calendarId: Calendar.id, eventId: id } body = self.to_json request(Calendar.api.events.update, params, body) self end def to_hash self.instance_variables.inject(Hashie::Mash.new) do |hash, name| key = name.to_s.delete("@").to_sym hash[key] = self.instance_variable_get(name) hash end end def to_json self.to_hash.to_json end def num_of_days start_date = (self.start.date || self.start.dateTime).to_date end_date = (self.end.date || self.end.dateTime ).to_date (end_date - start_date).to_i + 1 end def self.today start_time = Date.today end_time = Date.tomorrow list(start_time, end_time) end def self.tomorrow start_time = Date.tomorrow end_time = Date.tomorrow.tomorrow list(start_time, end_time) end def self.yesterday start_time = Date.yesterday end_time = Date.today list(start_time, end_time) end def self.this_week start_time = Date.today.beginning_of_week end_time = Date.today.end_of_week list(start_time, end_time) end def self.this_month start_time = Date.today.beginning_of_month end_time = Date.today.end_of_month list(start_time, end_time) end def self.this_year start_time = Date.today.beginning_of_year end_time = Date.today.end_of_year list(start_time, end_time) end private def update_attributes(options={}) opts = Hashie::Mash.new(options) opts.each do |key, value| instance_variable_set("@#{key}".to_sym, value) if respond_to?(key) end end def request(api_method, params={}, body="") data = self.class.execute(api_method, params, body) if data.respond_to?(:to_hash) update_attributes(data.to_hash) elsif data.nil? {} else raise data.to_s end self end def self.request(api_method, params={}, body="") data = execute(api_method, params, body) if data.respond_to?(:items) data_to_events(data.items) elsif data.respond_to?(:to_hash) data_to_event(data) else raise data.to_s end end def self.execute(api_method, params={}, body="") response = Calendar.execute(api_method, params, body) response.data end def self.data_to_event(event_data) self.new(event_data.to_hash) end def self.data_to_events(events_data) events_data.inject([]) do |events, event_data| events << data_to_event(event_data) end end end end end <file_sep>require 'spec_helper' require 'pry' describe Google::Calendar::Event do let(:event_instance_variables) { [ :id, :kind, :etag, :status, :htmlLink, :created, :updated, :creator, :organizer, :transparency, :iCalUID, :sequence, :reminders, :summary, :start, :end ] } let(:calendar_id) { "<EMAIL>" } let(:client_id) { "1000000000000-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.apps.googleusercontent.com" } let(:client_execute_options) { { api_method: api_method, parameters: parameters, body: body, headers: { 'Content-Type' => 'application/json' } } } let(:test_data) { { kind: "calendar#event", etag: "\"1000000000000000\"", id: id, status: "confirmed", htmlLink: "https://www.google.com/calendar/event?eid=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", created: "2015-07-07T00:00:00.000Z", updated: "2015-07-07T01:00:00.000Z", summary: summary, creator: { email: "<EMAIL>", displayName: "testuser" }, organizer: { email: calendar_id, displayName: "testcalendar", self: true }, start: start_date, end: end_date, transparency: "transparent", iCalUID: id + "@google.com", sequence: 0, reminders: { useDefault: true } } } let(:id) { "aaaaaaaaaaaaaaaaaaaaaaaaaa" } let(:summary) { "Test Event" } let(:start_date) { { date: Date.today } } let(:end_date) { { date: Date.tomorrow } } before do Google::Calendar.id = calendar_id allow(Google::APIClient::KeyUtils).to receive(:load_key) { OpenSSL::PKey::RSA.new } allow(File).to receive(:exist?) { true } allow(File).to receive(:read) { { installed: { client_id: "100000000000000000000", project_id: "test-project-000001", auth_uri: "https://accounts.google.com/o/oauth2/auth", token_uri: "https://accounts.google.com/o/oauth2/token", auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs" } }.to_json } allow_any_instance_of(Signet::OAuth2::Client).to receive(:fetch_access_token!) { true } allow(Google::Calendar).to receive(:authorize?) { true } end describe '#initialize' do context 'without otpion' do it 'should be instance of Google::Calendar::Event' do event = Google::Calendar::Event.new expect(event).to be_instance_of Google::Calendar::Event event_instance_variables.each{|name| expect(event.send(name)).to be_nil } end end context 'with all otpion' do let(:options) { { summary: summary, start: { date: Date.today }, end: { date: Date.tomorrow } } } it 'should be instance of Google::Calendar::Event' do event = Google::Calendar::Event.new(options) expect(event).to be_instance_of Google::Calendar::Event event_instance_variables.each do |name| case name when :summary expect(event.send(name)).to eq options[name] when :start, :end expect(event.send(name).date).to eq options[name][:date] else expect(event.send(name)).to be_nil end end end end end # [API] get # GET /calendars/:calendarId/events/eventId describe 'GET /calendars/:calendarId/events/eventId' do let(:event) { Google::Calendar::Event.new(options) } let(:options) { { id: id, summary: summary, start: start_date, end: end_date } } let(:api_method) { Google::Calendar.api.events.get } let(:parameters) { { calendarId: calendar_id, eventId: id } } let(:body) { "" } let(:response) { Hashie::Mash.new( { status: status, data: data } ) } let(:status) { 200 } let(:data) { test_data } before do expect_any_instance_of(Google::APIClient).to receive(:execute!).with(client_execute_options) { response } end describe '.get' do it 'should be instance of Google::Calendar::Event' do event = Google::Calendar::Event.get(id) expect(event).to be_instance_of Google::Calendar::Event expect_event_to_eq_test_data(event, test_data) end end describe '#fetch' do it 'should be instance of Google::Calendar::Event' do event.fetch expect(event).to be_instance_of Google::Calendar::Event expect_event_to_eq_test_data(event, test_data) end end end # [API] list # GET /calendars/:calendarId/events describe 'GET /calendars/:calendarId/events' do let(:api_method) { Google::Calendar.api.events.list } let(:parameters) { { calendarId: calendar_id, orderBy: 'startTime', timeMax: end_time.to_time.utc.iso8601, timeMin: start_time.to_time.utc.iso8601, singleEvents: 'True' } } let(:body) { "" } let(:response) { Hashie::Mash.new( { status: status, data: data } ) } let(:status) { 200 } let(:data) { { items: [ test_data ] } } let(:start_time) { Date.today.beginning_of_week } let(:end_time) { Date.today.end_of_week } describe '.list' do before do expect_any_instance_of(Google::APIClient).to receive(:execute!).with(client_execute_options) { response } end it 'should be instance of Google::Calendar::Event' do events = Google::Calendar::Event.list(start_time, end_time) expect(events.size).to eq 1 event = events.first expect(event).to be_instance_of Google::Calendar::Event expect_event_to_eq_test_data(event, test_data) end end shared_examples 'Called Event.list and Recieve Start and End' do before { expect(Google::Calendar::Event).to receive(:list).with(start_time, end_time) } it { is_expected.not_to raise_error } end describe '.today' do let(:start_time) { Date.today } let(:end_time) { Date.tomorrow } subject { lambda { Google::Calendar::Event.today } } it_behaves_like 'Called Event.list and Recieve Start and End' end describe '.tomorrow' do let(:start_time) { Date.tomorrow } let(:end_time) { Date.tomorrow.tomorrow } subject { lambda { Google::Calendar::Event.tomorrow } } it_behaves_like 'Called Event.list and Recieve Start and End' end describe '.yesterday' do let(:start_time) { Date.yesterday } let(:end_time) { Date.today } subject { lambda { Google::Calendar::Event.yesterday } } it_behaves_like 'Called Event.list and Recieve Start and End' end describe '.this_week' do let(:start_time) { Date.today.beginning_of_week } let(:end_time) { Date.today.end_of_week } subject { lambda { Google::Calendar::Event.this_week } } it_behaves_like 'Called Event.list and Recieve Start and End' end describe '.this_month' do let(:start_time) { Date.today.beginning_of_month } let(:end_time) { Date.today.end_of_month } subject { lambda { Google::Calendar::Event.this_month } } it_behaves_like 'Called Event.list and Recieve Start and End' end describe '.this_year' do let(:start_time) { Date.today.beginning_of_year } let(:end_time) { Date.today.end_of_year } subject { lambda { Google::Calendar::Event.this_year } } it_behaves_like 'Called Event.list and Recieve Start and End' end end # [API] insert # POST /calendars/:calendarId/events describe 'POST /calendars/:calendarId/events' do let(:event) { Google::Calendar::Event.new(options) } let(:options) { { summary: summary, start: start_date, end: end_date } } let(:api_method) { Google::Calendar.api.events.insert } let(:parameters) { { calendarId: calendar_id } } let(:body) { event.to_json } let(:response) { Hashie::Mash.new( { status: status, data: test_data } ) } let(:status) { 200 } let(:data) { test_data } before do expect_any_instance_of(Google::APIClient).to receive(:execute!).with(client_execute_options) { response } end describe '#insert' do it 'should be instance of Google::Calendar::Event' do event.insert expect(event).to be_instance_of Google::Calendar::Event expect_event_to_eq_test_data(event, test_data) end end describe '.insert' do it 'should be instance of Google::Calendar::Event' do event = Google::Calendar::Event.insert(options) expect(event).to be_instance_of Google::Calendar::Event expect_event_to_eq_test_data(event, test_data) end end end # [API] delete # DELETE /calendars/:calendarId/events/:eventId describe 'DELETE /calendars/:calendarId/events/:eventId' do let(:event) { Google::Calendar::Event.new(options) } let(:options) { { id: id, summary: summary, start: start_date, end: end_date } } let(:api_method) { Google::Calendar.api.events.delete } let(:parameters) { { calendarId: calendar_id, eventId: id } } let(:body) { "" } let(:response) { Hashie::Mash.new( { status: status, data: test_data } ) } let(:status) { 204 } let(:data) { nil } before do allow_any_instance_of(Google::Calendar::Event).to receive(:fetch) { event } expect_any_instance_of(Google::APIClient).to receive(:execute!).with(client_execute_options) { response } end describe '#delete' do it 'should be instance of Google::Calendar::Event' do event.delete expect(event).to be_instance_of Google::Calendar::Event expect_event_to_eq_test_data(event, test_data) end end describe '.delete' do it 'should be instance of Google::Calendar::Event' do event = Google::Calendar::Event.delete(id) expect(event).to be_instance_of Google::Calendar::Event expect_event_to_eq_test_data(event, test_data) end end end # [API] quickAdd # POST /calendars/:calendarId/events/quickAdd describe 'POST /calendars/:calendarId/events/quickAdd' do let(:event) { Google::Calendar::Event.new(options) } let(:options) { { summary: summary, start: start_date, end: end_date } } let(:api_method) { Google::Calendar.api.events.quick_add } let(:parameters) { { calendarId: calendar_id, text: summary } } let(:body) { "" } let(:response) { Hashie::Mash.new( { status: status, data: test_data } ) } let(:status) { 200 } let(:data) { test_data } before do expect_any_instance_of(Google::APIClient).to receive(:execute!).with(client_execute_options) { response } end describe '#quickAdd' do it 'should be instance of Google::Calendar::Event' do event = Google::Calendar::Event.quickAdd(summary) expect(event).to be_instance_of Google::Calendar::Event expect_event_to_eq_test_data(event, test_data) end end end # [API] update # PUT /calendars/:calendarId/events/:eventId describe 'PUT /calendars/:calendarId/events/:eventId' do let(:event) { Google::Calendar::Event.new(options) } let(:options) { { id: id, summary: summary, start: start_date, end: end_date } } let(:api_method) { Google::Calendar.api.events.update } let(:parameters) { { calendarId: calendar_id, eventId: id } } let(:body) { event.to_json } let(:response) { Hashie::Mash.new( { status: status, data: test_data } ) } let(:status) { 200 } let(:data) { test_data } before do expect_any_instance_of(Google::APIClient).to receive(:execute!).with(client_execute_options) { response } end describe '#update' do it 'should be instance of Google::Calendar::Event' do event.update expect(event.summary).to eq summary expect(event).to be_instance_of Google::Calendar::Event expect_event_to_eq_test_data(event, test_data) end end end describe '#num_of_days' do let(:event) { Google::Calendar::Event.new(options) } let(:options) { { summary: summary, start: start_date, end: end_date } } # num_of_days : today ~ tomorrow subject { event.num_of_days } it { is_expected.to eq 2 } end def expect_event_to_eq_test_data(event, test_data) test_data.each_key do |key| case key when :creator, :organizer expect(event.send(key).email).to eq test_data[key][:email] expect(event.send(key).displayName).to eq test_data[key][:displayName] expect(event.send(key).self).to eq test_data[key][:self] if key == :organizer when :start, :end expect(event.send(key).date).to eq test_data[key][:date] when :reminders expect(event.send(key).useDefault).to eq test_data[key][:useDefault] else expect(event.send(key)).to eq test_data[key] end end end end <file_sep>module Google module Calendar class Errors class Error < StandardError; end end end end <file_sep>source 'https://rubygems.org' # Specify your gem's dependencies in gcevent.gemspec gemspec <file_sep>require 'google/service_account' require 'google/calendar/event' require 'google/api_client' require 'hashie' module Google class SecretKey < Hashie::Mash; end module Calendar class << self attr_accessor :id, :client_secret_path, :client_email end extend self def api authorize unless authorized? client.discovered_api('calendar', 'v3') end def client @client ||= Google::APIClient.new(:application_name => '') end def authorize raise Errno::ENOENT.new(secret_key.path) unless File.exist?(secret_key.path) client.authorization = Signet::OAuth2::Client.new( token_credential_uri: service_account.token_uri, audience: service_account.token_uri, scope: service_account.scope, issuer: service_account.client_email, signing_key: signing_key ) client.authorization.fetch_access_token! @authorized = true end def secret_key @secret_key ||= Google::SecretKey.new({ path: nil, password: nil }) end def service_account Google::ServiceAccount.new(client_secret_path, client_email) end def signing_key Google::APIClient::KeyUtils.load_from_pkcs12(secret_key.path, secret_key.password) end def authorized? @authorized end # MEMO : body_objectでなくbodyを使う # * 公式のReference的にはbody_object # * body_objectを空文字指定でEvent#getすると400 Bad Request # * 必要ないときはパラメータに含めない方がよさそう # * bodyパラメータなら空文字指定でもOK def execute(api_method, parameters={}, body="") options = { api_method: api_method, parameters: parameters, body: body, headers: { 'Content-Type' => 'application/json' } } client.execute!(options) end end end <file_sep>require 'spec_helper' describe Google::Calendar do let(:id) { "<EMAIL>" } let(:client_id) { "1000000000000-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.apps.googleusercontent.com" } let(:event_id) { "aaaaaaaaaaaaaaaaaaaaaaaaaa" } before do allow(Google::APIClient::KeyUtils).to receive(:load_key) { OpenSSL::PKey::RSA.new } allow(File).to receive(:exist?) { true } allow(File).to receive(:read) { { installed: { client_id: client_id } }.to_json } allow_any_instance_of(Signet::OAuth2::Client).to receive(:fetch_access_token!) { true } Google::Calendar.client_secret_path = "testpath" end describe '.api' do before { allow(Google::Calendar).to receive(:authorized?) { true } } subject { Google::Calendar.api } it { is_expected.to be_instance_of Google::APIClient::API } end describe '.client' do subject { Google::Calendar.client } it { is_expected.to be_instance_of Google::APIClient } end describe '.authorize' do subject { Google::Calendar.authorize } it { is_expected.to eq true } end describe '.secret_key' do subject { Google::Calendar.secret_key } it { is_expected.to be_instance_of Google::SecretKey } end describe '.service_account' do subject { Google::Calendar.service_account } it { is_expected.to be_instance_of Google::ServiceAccount } end describe '.singing_key' do subject { Google::Calendar.signing_key } it { is_expected.to be_instance_of OpenSSL::PKey::RSA } end describe 'authorized?' do subject { Google::Calendar.authorized? } context 'authorized instance is false or nil' do before { Google::Calendar.instance_variable_set(:@authorized, false) } it { is_expected.to eq false } end context 'authorized instance is true' do before { Google::Calendar.instance_variable_set(:@authorized, true) } it { is_expected.to eq true } end end describe 'execute' do let(:method) { Google::Calendar.api.events.get.class } let(:parameters) { { calendarId: id, eventId: event_id } } let(:body) { "" } let(:options) { { api_method: method, parameters: parameters, body: body, headers: { 'Content-Type' => 'application/json' } } } before do expect_any_instance_of(Google::APIClient).to receive(:execute!).with(options) { true } allow(Google::Calendar).to receive(:authorize?) { true } end subject { Google::Calendar.execute(method, parameters, body) } it { is_expected.to eq true } end end <file_sep>require 'spec_helper' describe Google::ServiceAccount do before { allow(File).to receive(:read) { secret.to_json } } let(:client_secret_path) { "./testpath" } let(:client_email) { "<EMAIL>" } let(:secret) { { installed: { client_id: "100000000000000000000", project_id: "test-project-000001", auth_uri: "https://accounts.google.com/o/oauth2/auth", token_uri: "https://accounts.google.com/o/oauth2/token", auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs" } } } describe '#initialize' do it 'should be instance of Google::ServiceAccount' do service_account = Google::ServiceAccount.new(client_secret_path, client_email) secret[:installed].each do |k, v| expect(service_account.send(k)).to eq v end expect(service_account.client_email).to eq client_email end end end <file_sep>require "google/calendar" module Gcevent end <file_sep>module Google class ServiceAccount SCOPE = 'https://www.googleapis.com/auth/calendar' attr_reader :auth_uri, :token_uri attr_reader :client_id, :client_email attr_reader :auth_provider_x509_cert_url, :client_x509_cert_url attr_reader :project_id attr_reader :scope def initialize(secret_path, email) JSON.parse(File.read(secret_path)).each do |key, secret| secret.each do |k, v| instance_varialbe_name = "@#{k}".to_sym instance_variable_set(instance_varialbe_name, v) end end @client_email ||= email @scope = SCOPE end end end <file_sep>[![Build Status](https://travis-ci.org/ogawatti/gcevent.svg?branch=master)](https://travis-ci.org/ogawatti/gcevent) [![Coverage Status](https://coveralls.io/repos/ogawatti/gcevent/badge.png?branch=master)](https://coveralls.io/r/ogawatti/gcevent?branch=master) [<img src="https://gemnasium.com/ogawatti/gcevent.png" />](https://gemnasium.com/ogawatti/gcevent) # Gcevent A wrapper of Google Calendar Event API. ## Installation Add this line to your application's Gemfile: ```ruby gem 'gcevent' ``` And then execute: $ bundle Or install it yourself as: $ gem install gcevent ## Usage ### Calendar Setting ```ruby Google::Calendar.id = "Id of a target Google Calendar" Google::Calendar.secret_key.path = "Path of xxx-privatekey.p12" Google::Calendar.secret_key.password = "<PASSWORD>" Google::Calendar.client_secret_path = "Path of client_secret_xxx.json" Google::Calendar.client_email = "Email address of service account" ``` ### Event#get ```ruby event_id = "Google Calendar Event ID" event = Google::Calendar::Event.get(event_id) ``` or ```ruby event = Google::Calendar::Event.new(event_id: event_id) event.fetch ``` ### Event#list specified date or time ```ruby start_date = Date.today.beginning_of_week end_date = Date.today.end_of_week events = Google::Calendar::Event.list(start_date, end_date) ``` today or this week or ... ```ruby Google::Calendar::Event.today Google::Calendar::Event.tomorrow Google::Calendar::Event.yesterday Google::Calendar::Event.this_week Google::Calendar::Event.this_month Google::Calendar::Event.this_year ``` ### Event#insert ```ruby event = Google::Calendar::Event.new event.summary = "Inserted #{Time.now}" event.start = { dateTime: Date.today.to_time.utc.iso8601 } event.end = { dateTime: Date.tomorrow.to_time.utc.iso8601 } event.insert ``` or ```ruby options = { summary: "Inserted #{Time.now}", start: { date: Date.today }, end: { date: Date.tomorrow } } event = Google::Calendar::Event.insert(options) ``` ### Event#quickAdd quick insert ```ruby text = "Quick Added" event = Google::Calendar::Event.quickAdd(text) ``` ### Event#update ```ruby event = Google::Calendar::Event.this_week.last event.summary = "Updated #{Time.now}" event.update ``` # Delete Phase ```ruby event = Google::Calendar::Event.this_week.first event.delete ``` or ```ruby event = Google::Calendar::Event.this_week.last Google::Calendar::Event.delete(event.id) ``` ## Contributing 1. Fork it ( https://github.com/[my-github-username]/gcevent/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request
e8b744ee99c59c9145c4e6d4ebc58d7129992af8
[ "Markdown", "Ruby" ]
10
Ruby
ogawatti/gcevent
2f094f5ad42be0af78056ec3ec6bfb41cb989169
ca246977f2ee54d510286b279c05a9e6c0aff499
refs/heads/master
<file_sep># Scheduler This is a scheduler including a task list and a deadline list. It was made in inspiration to those physical copies of daily task schedulers. Therefore, the elements represent paper to create that "real-life"-scheduler feel. ![Scheduler image](https://i.imgur.com/zi1OBcw.png "What Scheduler looks like") ## How to use 1. Download the scheduler code (duh!) 2. Extract it to your desired folder 3. Create 2 dummy JSONs on JSONbin.io. You can fill them in with whatever, such as { "test": "test" } 4. Copy your secret key from JSONbin and paste it in the "key" variable in main.js 5. Copy your bin IDs from JSONbin and paste them into "taskBin" and "deadLBin" respectively 6. Now you can open up the HTML file and use the scheduler to your desire. <file_sep>// Secret key and bin IDs from jsonbin const key = ""; const taskBin = ""; const deadLBin = ""; // Loads bg img and then content after request is done function loadContent() { const request = new XMLHttpRequest(); request.open('GET', "https://picsum.photos/2000/1800/?blur"); request.send(); request.addEventListener('load', function(){ const pic = this.responseURL; document.getElementById("all").style.backgroundImage = `url('${pic}')`; document.getElementById("all").style.opacity = 1; fillTimeline(); fillDeadL(); }) } // Fills the timeline with content function fillTimeline() { let table = []; const hours = 24; let htmltable = ""; let htmlselect = ""; const readrequest = new XMLHttpRequest(); readrequest.open("GET", "https://api.jsonbin.io/b/"+taskBin+"/latest", true); readrequest.setRequestHeader("secret-key", key); readrequest.send(); // Fetches today's date to compare it with the date in JSON file let today = new Date().toLocaleDateString(undefined).toString(); let d = {}; d.date = today; table.unshift(d); readrequest.onreadystatechange = () => { if (readrequest.readyState == XMLHttpRequest.DONE) { let filling = JSON.parse(readrequest.responseText); // Fills timeline with JSON if there is data to be fetched from today's date if((readrequest.responseText || readrequest.responseText != "") && filling.list && filling.list[0].date == today) { document.getElementById("tab").innerHTML=""; document.getElementById("addtask").innerHTML=""; for (i=1;i<filling.list.length;i++) { htmltable = ` <tr> <td class="time"> `+ filling.list[i].time +` </td> <td class="task"> `+ filling.list[i].task +` </td> </tr> `; htmlselect = ` <option value="`+filling.list[i].time+`">`+filling.list[i].time+`</option> ` document.getElementById("tab").insertAdjacentHTML("beforeend", htmltable); document.getElementById("addtask").insertAdjacentHTML("beforeend", htmlselect); } document.getElementById("timeline").style.opacity = 1; } // else creates a new timeline and updates JSON with that data else { for (i = 0; i < hours; i++) { let element = {}; element.time = i + ":00"; element.task = ""; table.push(element); } const jsonfill = { "list": table }; const jsrequest = new XMLHttpRequest(); jsrequest.open("PUT", "https://api.jsonbin.io/b/"+taskBin, true); jsrequest.setRequestHeader("Content-Type", "application/json"); jsrequest.setRequestHeader("secret-key", key); jsrequest.send(JSON.stringify(jsonfill)); jsrequest.onreadystatechange = () => { if (jsrequest.readyState == XMLHttpRequest.DONE) { const readrequest2 = new XMLHttpRequest(); readrequest2.open("GET", "https://api.jsonbin.io/b/"+taskBin+"/latest", true); readrequest2.setRequestHeader("secret-key", key); readrequest2.send(); readrequest2.onreadystatechange = () => { if (readrequest2.readyState == XMLHttpRequest.DONE) { let filling2 = JSON.parse(readrequest2.responseText); for (i=1;i<filling2.list.length;i++) { htmltable = ` <tr> <td class="time"> `+ filling2.list[i].time +` </td> <td class="task"> `+ filling2.list[i].task +` </td> </tr> `; htmlselect = ` <option value="`+filling2.list[i].time+`">`+filling2.list[i].time+`</option> ` document.getElementById("tab").insertAdjacentHTML("beforeend", htmltable); document.getElementById("addtask").insertAdjacentHTML("beforeend", htmlselect); } document.getElementById("timeline").style.opacity = 1; } } }; } } }; } } // function that adds tasks in the timeline function btnPush() { const readreq = new XMLHttpRequest(); readreq.open("GET", "https://api.jsonbin.io/b/"+taskBin+"/latest", true); readreq.setRequestHeader("secret-key", key); readreq.send(); readreq.onreadystatechange = () => { if (readreq.readyState == XMLHttpRequest.DONE) { let filling = JSON.parse(readreq.responseText); const timeval = document.getElementById("addtask"); const textval = document.getElementById("typetask"); const btnval = document.getElementById("taskbtn"); for (i=1;i < filling.list.length;i++) { // matches and adds task to correct time if task is defined if ((filling.list[i].time == timeval.value)) { if (!textval.value == "" || !textval.value == undefined || !textval.value == null) { filling.list[i].task += " • " + textval.value; const jsrequest = new XMLHttpRequest(); jsrequest.open("PUT", "https://api.jsonbin.io/b/"+taskBin, true); jsrequest.setRequestHeader("Content-Type", "application/json"); jsrequest.setRequestHeader("secret-key", key); jsrequest.send(JSON.stringify(filling)); jsrequest.onreadystatechange = () => { if (jsrequest.readyState == XMLHttpRequest.DONE) { btnval.value = "Task added!"; setTimeout(function() { btnval.value = "Add task"; }, 2000); fillTimeline(); } } break; } // error if task is not defined else { btnval.value = "Failed adding task"; setTimeout(function() { btnval.value = "Add task"; }, 2000); } } else { } } } } } // fills deadline with content function fillDeadL() { const jsrequest = new XMLHttpRequest(); let htmllist = ""; const today = new Date().toLocaleDateString(undefined).toString(); const differenceToday = Date.parse(today); jsrequest.open("GET", "https://api.jsonbin.io/b/"+deadLBin+"/latest", true); jsrequest.setRequestHeader("secret-key", key); jsrequest.send(); jsrequest.onreadystatechange = () => { if (jsrequest.readyState == XMLHttpRequest.DONE) { let filling = JSON.parse(jsrequest.responseText); document.getElementById("deadlinelist").innerHTML=""; if (jsrequest.responseText && filling.list) { let deadlineArray = filling.list; // sorts deadlines by date deadlineArray.sort(function(a,b) { return new Date(b.date) - new Date(a.date); }); // fills deadline for (i=0;i<filling.list.length;i++) { if (filling.list[i].date != "" && filling.list[i].line != "") { let deadlineDate = filling.list[i].date; const differenceDeadline = Date.parse(deadlineDate); // colour-sorts the deadlines depending on when their date is // date is in the past if (differenceToday > differenceDeadline) { htmllist = ` <li class="late">`+filling.list[i].date+`: `+filling.list[i].line+`<button class="btn remove" onclick="deleteDeadL(this)">x</button></li> `; document.getElementById("deadlinelist").insertAdjacentHTML("beforeend", htmllist); } // date is today else if (differenceToday == differenceDeadline) { htmllist = ` <li class="tday">`+filling.list[i].date+`: `+filling.list[i].line+`<button class="btn remove" onclick="deleteDeadL(this)">x</button></li> `; document.getElementById("deadlinelist").insertAdjacentHTML("beforeend", htmllist); } // date is not today / in the past AKA the futuuureeee else { htmllist = ` <li>`+filling.list[i].date+`: `+filling.list[i].line+`<button class="btn remove" onclick="deleteDeadL(this)">x</button></li> `; document.getElementById("deadlinelist").insertAdjacentHTML("beforeend", htmllist); } } else { } } } // sends JSON to JSONbin in correct format (first time) else { const fillEmptyJSON = new XMLHttpRequest(); fillEmptyJSON.open("PUT", "https://api.jsonbin.io/b/"+deadLBin, true); fillEmptyJSON.setRequestHeader("Content-Type", "application/json"); fillEmptyJSON.setRequestHeader("secret-key", key); const jsonfill = { "list": [ { "date": "", "line":"" } ] }; fillEmptyJSON.send(JSON.stringify(jsonfill)); fillEmptyJSON.onreadystatechange = () => { if (fillEmptyJSON.readyState == XMLHttpRequest.DONE) { } } } document.getElementById("deadline").style.opacity = 1; } } } // adds deadline function deadL() { const jsrequest = new XMLHttpRequest(); jsrequest.open("GET", "https://api.jsonbin.io/b/"+deadLBin+"/latest", true); jsrequest.setRequestHeader("Content-Type", "application/json"); jsrequest.setRequestHeader("secret-key", key); jsrequest.send(); jsrequest.onreadystatechange = () => { if (jsrequest.readyState == XMLHttpRequest.DONE) { let filling = JSON.parse(jsrequest.responseText); const timeval = document.getElementById("deadDate"); const textval = document.getElementById("typedead"); const btnval = document.getElementById("deadbtn"); // adds deadline if deadline is defined if (timeval.value != "" && timeval.value != undefined && textval.value != "" && textval.value != undefined) { filling["list"].push({"date": timeval.value, "line": textval.value}); const jsrequest2 = new XMLHttpRequest(); jsrequest2.open("PUT", "https://api.jsonbin.io/b/"+deadLBin, true); jsrequest2.setRequestHeader("Content-Type", "application/json"); jsrequest2.setRequestHeader("secret-key", key); jsrequest2.send(JSON.stringify(filling)); jsrequest2.onreadystatechange = () => { if (jsrequest2.readyState == XMLHttpRequest.DONE) { btnval.value = "Deadline added!"; setTimeout(function() { btnval.value = "Add deadline"; }, 2000); fillDeadL(); } } } else { btnval.value = "Failed adding deadline"; setTimeout(function() { btnval.value = "Add deadline"; }, 2000); } } } } // remove deadline from deadline list function deleteDeadL(obj) { const content = obj.parentElement.innerHTML; // creates substrings const date = content.substring(0, 10); const deadL = content.substring(content.lastIndexOf(date) + date.length + 2, content.lastIndexOf(`<button class="btn remove" onclick="deleteDeadL(this)">x</button>`)); // loading symbol obj.innerHTML = "⅁"; const getdeadL = new XMLHttpRequest(); getdeadL.open("GET", "https://api.jsonbin.io/b/"+deadLBin+"/latest", true); getdeadL.setRequestHeader("Content-Type", "application/json"); getdeadL.setRequestHeader("secret-key", key); getdeadL.send(); getdeadL.onreadystatechange = () => { if (getdeadL.readyState == XMLHttpRequest.DONE) { let filling = JSON.parse(getdeadL.responseText); for (i=0; i<filling.list.length; i++) { // removes deadline, sends new JSON to JSONbin, updates deadline list if (filling.list[i].date == date && filling.list[i].line == deadL) { filling.list.splice(i, 1); const updDeadL = new XMLHttpRequest(); updDeadL.open("PUT", "https://api.jsonbin.io/b/"+deadLBin, true); updDeadL.setRequestHeader("Content-Type", "application/json"); updDeadL.setRequestHeader("secret-key", key); updDeadL.send(JSON.stringify(filling)); updDeadL.onreadystatechange = () => { if (updDeadL.readyState == XMLHttpRequest.DONE) { fillDeadL(); } } updDeadL.ontimeout = () => { obj.innerHTML = "x"; } break; // only removes 1 deadline } else { } } } } }
7942623cf443e562dc3851d171d84c04fd3ba4e0
[ "Markdown", "JavaScript" ]
2
Markdown
c17julka/Scheduler
86a8b7aea5e482899d49a54308efe8a5722fc55e
d3a5273502de8718e88c783f40001af8db67faeb
refs/heads/main
<file_sep>package org.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; @XmlRootElement(namespace = "http://example.com/jaxb") @XmlAccessorType(XmlAccessType.FIELD) public class Department { private String deptNo; private String deptName; private String location; @XmlElementWrapper(name = "employees") @XmlElement(name = "employee") private List<Employee> employees; /** * This default constructor is required if there are other constructors. */ public Department() { } public Department(String deptNo, String deptName, String location) { this.deptNo = deptNo; this.deptName = deptName; } public String getDeptNo() { return deptNo; } public void setDeptNo(String deptNo) { this.deptNo = deptNo; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public List<Employee> getEmployees() { return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } }<file_sep>package org.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "employee") @XmlAccessorType(XmlAccessType.FIELD) public class Employee { private String empNo; private String empName; private String managerNo; /** * Must have empty constructor. */ public Employee() { } public Employee(String empNo, String empName, String managerNo) { this.empNo = empNo; this.empName = empName; this.managerNo = managerNo; } public String getEmpNo() { return empNo; } public void setEmpNo(String empNo) { this.empNo = empNo; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public String getManagerNo() { return managerNo; } public void setManager(String managerNo) { this.managerNo = managerNo; } }
4014545d7ce419c5efac11c8e43c580f9f9235d3
[ "Java" ]
2
Java
johnchroma/sample_jaxb_java7
f5a3484e9f5881419e6fc791bd88213a00dc6769
e75b10f6afb2582bf272fa0d370c0d69e9abb118
refs/heads/main
<file_sep>Gem::Specification.new do |s| s.name = 'cipherworld-amelia2021' s.version = '0.0.5' s.summary = 'Cipherworld' s.description = "A gem for encrypting and decrypting strings" s.authors = ["<NAME>"] s.email = '<EMAIL>' s.files = ["lib/cipherworld-amelia2021.rb", "assets/llc.txt", "assets/lnc.txt"] s.executables << 'cipherworld-amelia2021' s.license = 'MIT' end<file_sep>require 'cipher' describe 'Secret' do it 'should exist and take one argument' do Kernel.const_defined?('Secret') test = Secret.new "Testing, 1... 2... 3..!" end describe '#encrypt' do context 'When a new instance of Secret is created' do it 'should exist as a method of the Secret class and take one argument' do Secret.new('Test').encrypt(42) end end context 'When called on Secret.new("0")' do it 'should return "43" when passed 45' do plaintext, key, ciphertext = '0', 45, '43' expect(Secret.new(plaintext).encrypt(key)).to eq ciphertext end end context 'When called on Secret.new("Look over there!")' do it 'should return the right answer when passed 2374' do plaintext, key, ciphertext = 'Look over there!', 2374, '37141410981421041798190704170452' expect(Secret.new(plaintext).encrypt(key)).to eq ciphertext end it 'should return the right answer when passed 2473' do plaintext, key, ciphertext = 'Look over there!', 2473, '37141410981421041798190704170452' expect(Secret.new(plaintext).encrypt(key)).to eq ciphertext end it 'should return the right answer when passed 2572' do plaintext, key, ciphertext = 'Look over there!', 2572, '37141410981421041798190704170452' expect(Secret.new(plaintext).encrypt(key)).to eq ciphertext end end context 'When called on Secret.new("HELLO, 28 $$$!")' do it 'should return the right answer when passed 7' do plaintext, key, ciphertext = 'HELLO, 28 $$$!', 7, '4239464649850896030864646461' expect(Secret.new(plaintext).encrypt(key)).to eq ciphertext end end context 'When called on Secret.new(" ")' do it 'should return the right answer when passed 20' do plaintext, key, ciphertext = ' ', 20, '21212121212121' expect(Secret.new(plaintext).encrypt(key)).to eq ciphertext end end context "When called on Secret.new('\' a double quote can be tricky, as can be \\ backslashes)" do it 'should return the right answer when passed 43' do plaintext = "'\"' a double quote can be tricky, as can be \\ backslashes" key = 43 ciphertext = '181918444544485965465649446165596449444745584446494464625347556922444563444745584446494420444645475563564563524963' expect(Secret.new(plaintext).encrypt(key)).to eq ciphertext end end end end describe 'EncryptedSecret' do it 'should exist and take one argument' do Kernel.const_defined?('EncryptedSecret') test = EncryptedSecret.new "Testing, 1... 2... 3..!" end describe '#decrypt' do context 'When a new instance of EncryptedSecret is created' do it 'should exist as a method of the EncryptedSecret class and take one argument' do EncryptedSecret.new('Test').decrypt(42) end end context 'When passed the ciphertext for "0"' do it 'should decrypt it when encrypted with key 45' do plaintext, key = '0', 45 expect(EncryptedSecret.new(Secret.new(plaintext).encrypt(key)).decrypt(key)).to eq plaintext end end context 'When passed the ciphertext for "Look over there!"' do it 'should decrypt it when encrypted with key 2374' do plaintext, key = 'Look over there!', 2374 expect(EncryptedSecret.new(Secret.new(plaintext).encrypt(key)).decrypt(key)).to eq plaintext end it 'should decrypt it when encrypted with key 2473' do plaintext, key = 'Look over there!', 2473 expect(EncryptedSecret.new(Secret.new(plaintext).encrypt(key)).decrypt(key)).to eq plaintext end it 'should decrypt it when encrypted with key 2572' do plaintext, key = 'Look over there!', 2572 expect(EncryptedSecret.new(Secret.new(plaintext).encrypt(key)).decrypt(key)).to eq plaintext end end context 'When passed the ciphertext for "HELLO, 28 $$$!"' do it 'should decrypt it when encrypted with key 7' do plaintext, key = 'HELLO, 28 $$$!', 7 expect(EncryptedSecret.new(Secret.new(plaintext).encrypt(key)).decrypt(key)).to eq plaintext end end context 'When passed the ciphertext for " "' do it 'should decrypt it when encrypted with key 20' do plaintext, key = ' ', 20 expect(EncryptedSecret.new(Secret.new(plaintext).encrypt(key)).decrypt(key)).to eq plaintext end end context "When passed the ciphertext for '\' a double quote can be tricky, as can be \\ backslashes''" do it 'should decrypt it when encrypted with key 43' do plaintext = "'\"' a double quote can be tricky, as can be \\ backslashes" key = 43 expect(EncryptedSecret.new(Secret.new(plaintext).encrypt(key)).decrypt(key)).to eq plaintext end end end end<file_sep>module Cipher class LetterNumber def initialize(args) @charset = {} @key = args[:key] File.open(args[:charset], 'r') do |f| f.readlines.map(&:chomp).each { |str| @charset[str[0]] = str[str.rindex(",") + 2..-1] } end end def encrypt plaintext plaintext.chars.map do |char| "#{ (@charset[char].to_i + @key) % 99 }" .sub(/^[0-9]{1}$/) { |num| "0#{num}" } end.join end def decrypt ciphertext plaintext = "" ciphertext.chars.each_slice(2).map(&:join).each do |char| char = char[1..-1] if char[0] == "0" char = @charset.invert[(( char.to_i - @key ) % 99 ).to_s ] plaintext << char end plaintext end end class LetterLetter def initialize(args) @charset = {} @key = args[:key] File.open(args[:charset], 'r') do |f| f.readlines.map(&:chomp).each { |str| @charset[str[0]] = str[str.rindex(",") + 2..-1] } end end def encrypt plaintext plaintext.chars.map { |char| @charset[char] }.join end def decrypt ciphertext ciphertext.chars.map { |char| @charset.invert[char] }.join end end end<file_sep>require 'cipher' describe 'encrypt' do context 'When tested against the acceptance criteria' do it 'should return "4" when passed ("a", 3)', :fixed => true do expect( encrypt('a', 3) ).to eq '4' end it 'should return "11" when passed ("a", 10)', :fixed => true do expect( encrypt('a', 10) ).to eq '11' end it 'should return "5" when passed ("b", 3)', :fixed => true do expect( encrypt('b', 3) ).to eq '5' end it 'should return "456" when passed ("abc", 3)', :fixed => true do expect( encrypt('abc', 3) ).to eq '456' end it 'should return "43645" when passed ("a cab", 3)', :fixed => true do expect( encrypt('a cab', 3) ).to eq '43645' end end end<file_sep>module Cipher refine String do def encrypt num dict = (([' '] + ('a'..'z').to_a + ('A'..'Z').to_a + ['!']).zip((0..53).to_a.map { |n| n + num })).to_h self.chars.map { |char| dict[char] }.join end end end using Cipher class Secret def initialize str @str = str end def encrypt num @str.encrypt(num) end end<file_sep>#!/usr/bin/env ruby require 'cipherworld-amelia2021' cipher, method, filename, key = ARGV lnc_dict_path = File.join(File.dirname(__FILE__), "../assets/lnc.txt") llc_dict_path = File.join(File.dirname(__FILE__), "../assets/llc.txt") # Handle bad command line arguments if ['ln', 'll'].none? cipher puts "Unknown Cipher: #{cipher}. Available ciphers are ln and ll" return end if ['enc', 'dec'].none? method puts "Unknown Action: #{method}. Available actions are enc and dec" return end unless File.file? filename puts "No file found ./#{filename}." return end key = key.to_i ||= 0 # Main Script newname = method == 'enc' ? "#{filename}.enc" : "#{filename.sub(/\.enc$/, '')}" text = File.read filename if cipher == 'ln' lnc = Cipher::LetterNumber.new(charset: lnc_dict_path, key: key) result = method == 'enc' ? lnc.encrypt(text) : lnc.decrypt(text) else llc = Cipher::LetterLetter.new(charset: llc_dict_path) result = method == 'enc' ? llc.encrypt(text) : llc.decrypt(text) end File.write(newname, result)<file_sep>#!/usr/bin/env ruby module Cipher class LetterNumber def initialize(args) @charset = {} @key = args[:key] File.open(args[:charset], 'r') do |f| f.readlines.map(&:chomp).each { |str| @charset[str[0]] = str[str.rindex(",") + 2..-1] } end end def encrypt plaintext plaintext.chars.map do |char| "#{ (@charset[char].to_i + @key) % 99 }" .sub(/^[0-9]{1}$/) { |num| "0#{num}" } end.join end def decrypt ciphertext plaintext = "" ciphertext.chars.each_slice(2).map(&:join).each do |char| char = char[1..-1] if char[0] == "0" char = @charset.invert[(( char.to_i - @key ) % 99 ).to_s ] plaintext << char end plaintext end end class LetterLetter def initialize(args) @charset = {} @key = args[:key] File.open(args[:charset], 'r') do |f| f.readlines.map(&:chomp).each { |str| @charset[str[0]] = str[str.rindex(",") + 2..-1] } end end def encrypt plaintext plaintext.chars.map { |char| @charset[char] }.join end def decrypt ciphertext ciphertext.chars.map { |char| @charset.invert[char] }.join end end end cipher, method, filename, key = ARGV # Handle bad command line arguments if ['ln', 'll'].none? cipher puts "Unknown Cipher: #{cipher}. Available ciphers are ln and ll" return end if ['enc', 'dec'].none? method puts "Unknown Action: #{method}. Available actions are enc and dec" return end unless File.file? filename puts "No file found ./#{filename}." return end key = key.to_i ||= 0 # Main Script newname = method == 'enc' ? "#{filename}.enc" : "#{filename.sub(/\.enc$/, '')}" text = File.read filename if cipher == 'ln' lnc = Cipher::LetterNumber.new(charset: 'lnc.txt', key: key) result = method == 'enc' ? lnc.encrypt(text) : lnc.decrypt(text) else llc = Cipher::LetterLetter.new(charset: 'llc.txt') result = method == 'enc' ? llc.encrypt(text) : llc.decrypt(text) end File.write(newname, result) <file_sep>require 'cipher' describe 'Secret' do it 'should exist and take one argument' do Kernel.const_defined?('Secret') end before(:each) do @secret = Secret.new('My name is Edward!') end describe '#encrypt' do context 'When instantiated with "My name is Edward!"' do it 'should return the correct value when passed "3"' do expect( @secret.encrypt 3 ).to eq '4228317416831222334726421756' end it 'should return the correct value when passed "7"' do expect( @secret.encrypt 7 ).to eq '4632721820127162673811308251160' end end end end describe 'String' do using Cipher it 'should correctly implement the encrypt method' do expect( 'My name is Edward!'.encrypt 3 ).to eq '4228317416831222334726421756' end end<file_sep>require 'cipher' describe 'Secret' do it 'should exist and take one argument' do Kernel.const_defined?('Secret') test = Secret.new "Testing, 1... 2... 3..!" end describe '#encrypt' do context 'When a new instance of Secret is created' do it 'should exist as a method of the Secret class and take one argument' do Secret.new("Test").encrypt(42) end end context 'When called on Secret.new("0")' do it 'should return "43" when passed 45' do expect(Secret.new('0').encrypt(45)).to eq '43' end end context 'When called on Secret.new("Look over there!")' do it 'should return the right answer when passed 2374' do expect(Secret.new('Look over there!').encrypt(2374)).to eq '37141410981421041798190704170452' end it 'should return the right answer when passed 2473' do expect(Secret.new('Look over there!').encrypt(2473)).to eq '37141410981421041798190704170452' end it 'should return the right answer when passed 2572' do expect(Secret.new('Look over there!').encrypt(2572)).to eq '37141410981421041798190704170452' end end context 'When called on Secret.new("HELLO, 28 $$$!")' do it 'should return the right answer when passed 7' do expect(Secret.new('HELLO, 28 $$$!').encrypt(7)).to eq '4239464649850896030864646461' end end context 'When called on Secret.new(" ")' do it 'should return the right answer when passed 20' do expect(Secret.new(' ').encrypt(20)).to eq '21212121212121' end end context "When called on Secret.new('\' a double quote can be tricky, as can be \\ backslashes)" do it 'should return the right answer when passed 43' do expect(Secret.new("'\"' a double quote can be tricky, as can be \\ backslashes") .encrypt(43)).to eq '181918444544485965465649446165596449444745584446494464625347556922444563444745584446494420444645475563564563524963' end end end end<file_sep>require 'cipher' describe 'Cipher' do before(:each) do @charset1 = 'lib/character_set1.txt' @charset2 = 'lib/character_set2.txt' @plaintext = 'Look over there!' @number_ciphertext = '37141410981421041798190704170452' @letter_ciphertext = 'B!!ym!9DAm2§DAD ' @key = 2374 end describe '::LetterNumber' do it 'should succesfully encrypt plaintext' do @letter_number_cipher = Cipher::LetterNumber.new(charset: @charset1, key: @key) expect(@letter_number_cipher.encrypt(@plaintext)).to eq @number_ciphertext end it 'should succesfully decrypt ciphertext' do @letter_number_cipher = Cipher::LetterNumber.new(charset: @charset1, key: @key) expect(@letter_number_cipher.decrypt(@number_ciphertext)).to eq @plaintext end end describe '::LetterLetter' do it 'should succesfully encrypt plaintext' do @letter_letter_cipher = Cipher::LetterLetter.new(charset: @charset2) expect(@letter_letter_cipher.encrypt(@plaintext)).to eq @letter_ciphertext end it 'should succesfully decrypt ciphertext' do @letter_letter_cipher = Cipher::LetterLetter.new(charset: @charset2) expect(@letter_letter_cipher.decrypt(@letter_ciphertext)).to eq @plaintext end end end<file_sep>class Secret def initialize str @str = str @charset = {} File.open('lib/character_set1.txt', 'r') do |f| f.readlines.map(&:chomp).each { |str| @charset[str[0]] = str[str.rindex(",") + 2..-1] } end end def encrypt int @str.chars.map do |char| "#{(@charset[char].to_i + int) % 99}" .sub(/^[0-9]{1}$/) { |num| "0#{num}" } end.join end end<file_sep>def encrypt(str, n) dict = (('a'..'z').to_a.prepend(" ").zip((0..26).to_a.rotate(n))).to_h return str.chars.map { |char| dict[char] }.join end<file_sep>class Secret def initialize plaintext @plaintext = plaintext @charset = {} File.open('lib/character_set1.txt', 'r') do |f| f.readlines.map(&:chomp).each { |str| @charset[str[0]] = str[str.rindex(",") + 2..-1] } end end def encrypt int @plaintext.chars.map do |char| "#{ (@charset[char].to_i + int) % 99 }" .sub(/^[0-9]{1}$/) { |num| "0#{num}" } end.join end def self.charset @charset end end class EncryptedSecret def initialize ciphertext @ciphertext = ciphertext @charset = {} File.open('lib/character_set1.txt', 'r') do |f| f.readlines.map(&:chomp).each { |str| @charset[str[0]] = str[str.rindex(",") + 2..-1] } end end def decrypt int plaintext = "" @ciphertext.chars.each_slice(2).map(&:join).each do |char| char = char[1..-1] if char[0] == "0" char = @charset.invert[(( char.to_i - int ) % 99 ).to_s ] plaintext << char end plaintext end end
6018746a1027f5bc733cda9db95b50b90e845dd3
[ "Ruby" ]
13
Ruby
sa-mcquanzie/cipher-world
c31fb847f9337e7b20ace24e95592ff6028702d6
9403454119b575138f2d9fa25064d5c91bc1f4d3
refs/heads/master
<file_sep>#include <CoreServices/CoreServices.h> #include <CoreFoundation/CFString.h> #include <IOKit/IOKitLib.h> #include <mach/mach_port.h> #include <IOKit/IOKitLib.h> #include <IOKit/IOCFBundle.h> #include <IOKit/IOCFPlugIn.h> #include <IOKit/IOMessage.h> #include <IOKit/usb/IOUSBLib.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> typedef unsigned int UINT; bool IoRegistryGetProperty(io_service_t io_service, CFStringRef cfPropertyName, UInt32 &lProperty) { bool bResult = false; // Get property from io-registry CFTypeRef cfTypeReference = IORegistryEntryCreateCFProperty(io_service, cfPropertyName, kCFAllocatorDefault, kNilOptions); // Convert property to UInt32 if( cfTypeReference ) { bResult = CFNumberGetValue( (CFNumberRef)cfTypeReference, kCFNumberSInt32Type, &lProperty); CFRelease( cfTypeReference ); } return bResult; } bool IoRegistryGetProperty(io_service_t io_service, CFStringRef cfPropertyName, char *prop) { bool bResult = false; // Get property from io-registry CFTypeRef cfTypeReference = IORegistryEntryCreateCFProperty(io_service, cfPropertyName, kCFAllocatorDefault, kNilOptions); if (!cfTypeReference) return false; CFStringGetCString((CFStringRef)cfTypeReference, prop, 1024, kCFStringEncodingUTF8); CFRelease(cfTypeReference); return true; } static UINT GetUsbLocation(io_service_t usb) { UINT locationID = 0; IoRegistryGetProperty(usb, CFSTR(kUSBDevicePropertyLocationID), locationID); return locationID; } static io_service_t GetUsbService(UINT uLocationId) { io_iterator_t deviceIterator = 0; io_service_t usbDevice = 0; CFMutableDictionaryRef dictRef = IOServiceMatching(kIOUSBDeviceClassName/*"IOUSBHostDevice"*/); IOServiceGetMatchingServices(kIOMasterPortDefault, dictRef, &deviceIterator); while (IOIteratorIsValid(deviceIterator)) { usbDevice = IOIteratorNext(deviceIterator); if (!usbDevice) break; if (GetUsbLocation(usbDevice) == uLocationId) break; IOObjectRelease(usbDevice); usbDevice = 0; } IOObjectRelease(deviceIterator); return usbDevice; } static void dump_usb() { io_iterator_t deviceIterator = 0; CFMutableDictionaryRef dictRef = IOServiceMatching(kIOUSBDeviceClassName); IOServiceGetMatchingServices(kIOMasterPortDefault, dictRef, &deviceIterator); while (IOIteratorIsValid(deviceIterator)) { io_service_t usbDevice = IOIteratorNext(deviceIterator); if (!usbDevice) break; char sFriendlyName[1024]; IoRegistryGetProperty( usbDevice, CFSTR("USB Product Name"), sFriendlyName); printf("0x%08x %s\n", GetUsbLocation(usbDevice), sFriendlyName); IOObjectRelease(usbDevice); usbDevice = 0; } IOObjectRelease(deviceIterator); } static UINT get_facetime() { UINT rv = 0xffffffff; io_iterator_t deviceIterator = 0; CFMutableDictionaryRef dictRef = IOServiceMatching(kIOUSBDeviceClassName); IOServiceGetMatchingServices(kIOMasterPortDefault, dictRef, &deviceIterator); while (IOIteratorIsValid(deviceIterator)) { io_service_t usbDevice = IOIteratorNext(deviceIterator); if (!usbDevice) break; char sFriendlyName[1024]; IoRegistryGetProperty( usbDevice, CFSTR("USB Product Name"), sFriendlyName); UINT location = GetUsbLocation(usbDevice); IOObjectRelease(usbDevice); if (NULL != strstr(sFriendlyName, "FaceTime") || NULL != strstr(sFriendlyName, "Built-in iSight")) { rv = location; break; } } IOObjectRelease(deviceIterator); return rv; } static IOReturn GetUSBDeviceInterface(io_service_t usbDevice, IOUSBDeviceInterface650 ***iface) { IOReturn ret; SInt32 score = 0; IOCFPlugInInterface **plugInInterface = NULL; IOCFPlugInInterface ** interface; IUnknownVTbl ** iunknown; ret = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &plugInInterface, &score); if (ret != kIOReturnSuccess || !plugInInterface) { printf("Failed to create PluginInterface: 0x%x\n", ret); return ret; } (*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID650), (LPVOID*)iface); (*plugInInterface)->Release(plugInInterface); return 0; } int main(int argc, char *argv[]) { kern_return_t r; IOUSBDeviceInterface650 **iface; printf("========= list of usb devices =========\n"); dump_usb(); printf("======= end of usb devices list =======\n\n"); UINT uLocationId = get_facetime(); if (uLocationId == 0xffffffff) { printf("No facetime camera found, exiting.\n"); return -1; } printf("Facetime camera found at 0x%08x\n", uLocationId); if (geteuid() != 0) { printf("Error, not a root. Execute 'sudo %s'\n", argv[0]); return -1; } io_service_t usbDevice = GetUsbService(uLocationId); if (0 == usbDevice) { printf("Failed to open facetime camera device.\n"); return -1; } r = GetUSBDeviceInterface(usbDevice, &iface); if (0 != r) { printf("Failed to get facetime camera device interface: 0x%x\n", r); return -1; } IOObjectRelease(usbDevice); printf("replugging the Facetime camera device..\n"); r = (*iface)->USBDeviceReEnumerate(iface, kUSBReEnumerateReleaseDeviceMask); printf("replug result 0x%x\n", r); return 0; } <file_sep>all: mkdir -p ../bin g++ replug_facetime.cpp -framework IOKit -framework CoreFoundation -o ../bin/replug_facetime <file_sep>#include <CoreServices/CoreServices.h> #include <CoreFoundation/CFString.h> #include <IOKit/IOKitLib.h> #include <mach/mach_port.h> #include <IOKit/IOKitLib.h> #include <IOKit/IOCFBundle.h> #include <IOKit/IOCFPlugIn.h> #include <IOKit/IOMessage.h> #include <IOKit/usb/IOUSBLib.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> typedef unsigned int UINT; bool IoRegistryGetProperty(io_service_t io_service, CFStringRef cfPropertyName, UInt32 &lProperty) { bool bResult = false; // Get property from io-registry CFTypeRef cfTypeReference = IORegistryEntryCreateCFProperty(io_service, cfPropertyName, kCFAllocatorDefault, kNilOptions); // Convert property to UInt32 if( cfTypeReference ) { bResult = CFNumberGetValue( (CFNumberRef)cfTypeReference, kCFNumberSInt32Type, &lProperty); CFRelease( cfTypeReference ); } return bResult; } bool IoRegistryGetProperty(io_service_t io_service, CFStringRef cfPropertyName, char *prop) { bool bResult = false; // Get property from io-registry CFTypeRef cfTypeReference = IORegistryEntryCreateCFProperty(io_service, cfPropertyName, kCFAllocatorDefault, kNilOptions); if (!cfTypeReference) return false; CFStringGetCString((CFStringRef)cfTypeReference, prop, 1024, kCFStringEncodingUTF8); CFRelease(cfTypeReference); return true; } static UINT GetUsbLocation(io_service_t usb) { UINT locationID = 0; IoRegistryGetProperty(usb, CFSTR(kUSBDevicePropertyLocationID), locationID); return locationID; } static io_service_t GetUsbService(UINT uLocationId) { io_iterator_t deviceIterator = 0; io_service_t usbDevice = 0; CFMutableDictionaryRef dictRef = IOServiceMatching(kIOUSBDeviceClassName/*"IOUSBHostDevice"*/); IOServiceGetMatchingServices(kIOMasterPortDefault, dictRef, &deviceIterator); while (IOIteratorIsValid(deviceIterator)) { usbDevice = IOIteratorNext(deviceIterator); if (!usbDevice) break; if (GetUsbLocation(usbDevice) == uLocationId) break; IOObjectRelease(usbDevice); usbDevice = 0; } IOObjectRelease(deviceIterator); return usbDevice; } static void dump_usb() { io_iterator_t deviceIterator = 0; CFMutableDictionaryRef dictRef = IOServiceMatching(kIOUSBDeviceClassName); IOServiceGetMatchingServices(kIOMasterPortDefault, dictRef, &deviceIterator); while (IOIteratorIsValid(deviceIterator)) { io_service_t usbDevice = IOIteratorNext(deviceIterator); if (!usbDevice) break; char sFriendlyName[1024]; IoRegistryGetProperty( usbDevice, CFSTR("USB Product Name"), sFriendlyName); printf("0x%08x %s\n", GetUsbLocation(usbDevice), sFriendlyName); IOObjectRelease(usbDevice); usbDevice = 0; } IOObjectRelease(deviceIterator); } static IOReturn GetUSBDeviceInterface(io_service_t usbDevice, IOUSBDeviceInterface650 ***iface) { IOReturn ret; SInt32 score = 0; IOCFPlugInInterface **plugInInterface = NULL; IOCFPlugInInterface ** interface; IUnknownVTbl ** iunknown; ret = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &plugInInterface, &score); if (ret != kIOReturnSuccess || !plugInInterface) { printf("Failed to create PluginInterface: 0x%x\n", ret); return ret; } (*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID650), (LPVOID*)iface); (*plugInInterface)->Release(plugInInterface); return 0; } int main(int argc, char *argv[]) { kern_return_t r; IOUSBDeviceInterface650 **iface; if (argc < 2) { dump_usb(); return 0; } char *endptr; UINT uLocationId = strtol(argv[1], &endptr, 0); printf("searching for location 0x%08x\n", uLocationId); io_service_t usbDevice = GetUsbService(uLocationId); if (0 == usbDevice) { printf("not found\n"); return -1; } bool do_release = false; if (argc > 2 && 0 == strcmp(argv[2], "release")) do_release = true; //r = IOServiceAuthorize(usbDevice, kIOServiceInteractionAllowed); //assert(0 == r); r = GetUSBDeviceInterface(usbDevice, &iface); if (0 != r) { printf("Failed to get device interface: 0x%x\n", r); return -1; } IOObjectRelease(usbDevice); if (do_release) { printf("release device\n"); r = (*iface)->USBDeviceReEnumerate(iface, kUSBReEnumerateReleaseDeviceMask); } else { printf("capture device\n"); r = (*iface)->USBDeviceReEnumerate(iface, kUSBReEnumerateCaptureDeviceMask); } printf("reenumerate result 0x%x\n", r); return 0; } <file_sep>all: mkdir -p ../bin g++ eject_v2.cpp -framework IOKit -framework CoreFoundation -o ../bin/usb_eject<file_sep># mac_usb_eject Simple utility to list and replug USB-device in Mac OS <file_sep>all: g++ eject_v2.cpp -framework IOKit -framework CoreFoundation -o usb_eject
15ab32a7f18ad6de6f62ef23688f9ce77c9587d4
[ "Markdown", "Makefile", "C++" ]
6
C++
cmeh/mac_usb_eject
33370425706b5ea88fc807b051f0efa5fc41fd32
a3bedf7b22ee89451c51895c21a0b2da1bbc010d
refs/heads/master
<repo_name>jjonathan99/Hoja_de_trabajo-2<file_sep>/READ.md # Hoja_de_trabajo-2 <file_sep>/Ejercicio#1/ejercicio#1.cpp /*Ejercicio # 1: prueba git Se dispone de un archivo STOCK correspondiente a la existencia de artículos de un almacén y se desea señalar aquellos artículos cuyo nivel está por debajo del mínimo y que visualicen un mensaje “hacer pedido”. Cada artículo contiene un registro con los siguientes campos: número del código del artículo, nivel mínimo, nivel actual, proveedor, precio. El programa debe tener un menu que se especifiquen las siguientes opciones: 1) Agregar productos (Grabar datos a un archivo) 2) Leer archivo y mostrar en pantalla que productos tiene nivel minimo. *if (nivel actual==nivel mínimo) cout<<"Nivel Minimo"; */ #include <iostream> #include <stdlib.h> #include <stdio.h> #include <string> #include <fstream> #include <iomanip> using namespace std; struct datos{ int cod_art; int niv_min; int niv_act; char proveedor[20]; float precio; }est; void menu(); void pedirdatos(); void aniadir(); void leer(); void leer2(); int main(){ menu(); system("pause"); } void menu(){ int menu; do{ system("cls"); cout<<"\t\t\tMenu "<<endl; cout<<"\t\t\t1. Agregar producto"<<endl; cout<<"\t\t\t2. Leer archivo"<<endl; cout<<"\t\t\t3. Verificar producto por debajo del minimo"<<endl; cout<<"\t\t\t4. Salir"<<endl; cout<<"\t\t\tEliga una opcion: "; cin>>menu; switch(menu){ case 1: system("cls"); pedirdatos(); aniadir(); break; case 2: system("cls"); leer(); break; case 3: system("cls"); leer2(); break; case 4: menu = 4; break; } }while(menu != 4); } void pedirdatos(){ cout<<"ingrese el codigo del producto: "; cin>>est.cod_art; cout<<"ingrese la cantidad de producto minima: "; cin>>est.niv_min; cout<<"ingrese la cantidad del producto actual: "; cin>>est.niv_act; fflush(stdin); cout<<"ingrese el proveedor: "; cin.getline(est.proveedor,20,'\n'); cout<<"ingrese el precio del producto: "; cin>>est.precio; } void aniadir(){ ofstream archivo; try { archivo.open("datos.txt",ios::app); archivo<<est.cod_art<<"\t"<<est.niv_min<<"\t"<<est.niv_act<<"\t"<<est.proveedor<<"\t"<<est.precio<<endl; archivo.close(); cout<<"Datos grabados en el archivo"<<endl<<endl; } catch(exception X){ cout<<"Error al grabar en el archivo"<<endl<<endl; } //fin try/catch system("PAUSE"); archivo.close(); } void leer(){ system("cls"); ifstream leer; string archivo; int lineas=0, i; leer.open("datos.txt",ios::in); if(leer.fail()){ cout<<"No se pudo abrir el archivo"; exit(1); } while(getline(leer,archivo)){ lineas++; } leer.close(); datos vector[lineas]; leer.open("datos.txt",ios::in); if(leer.fail()){ cout<<"No se pudo abrir el archivo!!!"; exit(1); } for(i=0;i<lineas;i++){ leer>>vector[i].cod_art>>vector[i].niv_min>>vector[i].niv_act>>vector[i].proveedor>>vector[i].precio; } cout<<"\t Codigo del articulo | Nivel Minimo | Nivel Actual | Proveedor | Precio |"<<endl; for(i=0;i<lineas;i++){ cout<<"\t\t"<<vector[i].cod_art<<"\t\t\t"<<vector[i].niv_min<<"\t\t"<<vector[i].niv_act<<"\t\t"<<vector[i].proveedor<<"\t\t"<<vector[i].precio<<endl; } cout<<"\n\n"<<endl; system("pause"); leer.close(); } void leer2(){ system("cls"); ifstream leer; string archivo; int lineas=0, i, band=0; leer.open("datos.txt",ios::in); if(leer.fail()){ cout<<"No se pudo abrir el archivo"; exit(1); } while(getline(leer,archivo)){ lineas++; } leer.close(); datos vector[lineas]; leer.open("datos.txt",ios::in); if(leer.fail()){ cout<<"No se pudo abrir el archivo!!!"; exit(1); } for(i=0;i<lineas;i++){ leer>>vector[i].cod_art>>vector[i].niv_min>>vector[i].niv_act>>vector[i].proveedor>>vector[i].precio; } for(i=0;i<lineas;i++){ if((vector[i].niv_act==vector[i].niv_min) || (vector[i].niv_act<vector[i].niv_min)){ cout<<"El producto con el codigo "<<vector[i].cod_art<<endl; band = 1; //cout<<"ESTA IGUAL O POR DEBAJO DEL MINIMO !HACER PEDIDO¡ "<<endl<<endl; }else if(vector[i].niv_act>vector[i].niv_min){ band = 0; } } if(band == 1){ cout<<"\nESTA IGUAL O POR DEBAJO DEL MINIMO !HACER PEDIDO¡ "<<endl<<endl; }else if(band == 0){ cout<<"Ningun producto se encuentra por debajo del minimo"<<endl<<endl; } system("pause"); leer.close(); } <file_sep>/Ejercicio#2/problema2.cpp /*Ejercicio # 2: El director de un colegio desea realizar un programa que procese un archivo de registros correspondiente a los diferentes alumnos del centro a fin de obtener los siguientes datos: Nota más alta y número de identificación del alumno correspondiente. Nota media del colegio. Datos de Estudiantes: Identificación Nombre Nota*/ #include <iostream> #include <stdlib.h> #include <stdio.h> #include <string> #include <fstream> #include <iomanip> using namespace std; void pedirdatos(); void leer(); void mostraralumnos(); struct datos{ char identificacion[15]; char nombre[30]; float nota; }est; float aux=0; float notamedia, totalmedia; int menu, cont=0; int main(){ do{ system("cls"); cout<<"\t\t-------Menu Colegio------- "<<endl; cout<<"\t\t1. Ingresar Datos del Estudiante "<<endl; cout<<"\t\t2. Nota media del colegio y del mejor estudiante"<<endl; cout<<"\t\t3. Ver todos los estudiantes"<<endl; cout<<"\t\t4. Salir"<<endl; cout<<"\t\tIngrese una opcion: "; cin>>menu; if(menu==1){ pedirdatos(); }else if(menu==2){ leer(); }else if(menu==3){ mostraralumnos(); }else if(menu==4){ menu=4; } }while(menu != 4); system("pause"); } void leer(){ system("cls"); ifstream leer; string texto; int lineas=0, i; leer.open("datos.txt",ios::in); if(leer.fail()){ cout<<"No se pudo abrir el archivo"; exit(1); } while(getline(leer,texto)){ lineas++; } leer.close(); //Cerramos el archivo datos vector[lineas]; leer.open("datos.txt",ios::in); if(leer.fail()){ cout<<"No se pudo abrir el archivo!!!"; exit(1); } for(i=0;i<lineas;i++){ leer>>vector[i].identificacion>>vector[i].nombre>>vector[i].nota; } for(i=0;i<lineas;i++){ if(vector[i].nota>aux){ aux = vector[i].nota; } notamedia +=vector[i].nota; } for(i=0;i<lineas;i++){ if(aux == vector[i].nota){ cout<<"\t\t\t Datos del Estudiante con mejor nota"<<endl; cout<<"\t\t\t---------------------------------------------"<<endl; cout<<"\t\t\t*Identificacion: "<<vector[i].identificacion<<endl; cout<<"\t\t\t*Nombre: "<<vector[i].nombre<<endl; cout<<"\t\t\t*Nota: "<<vector[i].nota<<endl; } } totalmedia = notamedia/lineas; cout<<"\t\t\t*La nota media del colegio es: "<<totalmedia<<endl<<endl; system("pause"); } void pedirdatos(){ system("cls"); fflush(stdin); cout<<"Ingrese el numero de identificacion del estudiante: "; cin>>est.identificacion; fflush(stdin); cout<<"Ingrese el nombre del estudiante: "; cin.getline(est.nombre,30,'\n'); fflush(stdin); cout<<"Ingrese la nota del estudiante: "; cin>>est.nota; fflush(stdin); ofstream archivo; try { archivo.open("datos.txt",ios::app); archivo<<est.identificacion<<"\t"<<est.nombre<<"\t"<<est.nota<<"\t"<<endl; archivo.close(); cout<<"Datos grabados en el archivo"<<endl<<endl; } catch(exception X){ cout<<"Error al grabar en el archivo"<<endl<<endl; } //fin try/catch system("PAUSE"); archivo.close(); } void mostraralumnos(){ system("cls"); ifstream leer; string texto; int lineas=0, i; leer.open("datos.txt",ios::in); if(leer.fail()){ cout<<"No se pudo abrir el archivo"; exit(1); } while(getline(leer,texto)){ lineas++; } leer.close(); //Cerramos el archivo datos vector[lineas]; leer.open("datos.txt",ios::in); if(leer.fail()){ cout<<"No se pudo abrir el archivo!!!"; exit(1); } for(i=0;i<lineas;i++){ leer>>vector[i].identificacion>>vector[i].nombre>>vector[i].nota; } cout<<"\t\t\t\tIdentificacion| Nombre | Nota "<<endl; for(i=0;i<lineas;i++){ cout<<"\t\t\t\t"<<vector[i].identificacion<<"\t\t"<<vector[i].nombre<<"\t\t"<<vector[i].nota<<endl; } cout<<"\n\n"; system("pause"); leer.close(); }
9bfa62402f79826c3e137d2b6fb639b6e8141f44
[ "Markdown", "C++" ]
3
Markdown
jjonathan99/Hoja_de_trabajo-2
ef8fdc8b46234f2afd3153fa72ea449889dd2d85
785dc11d4b7d2d9afabca3d5f79e392c4ea7737f
refs/heads/master
<repo_name>barberj/log_graft<file_sep>/log_graft.gemspec $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = "log_graft" s.version = "0.0.1" s.platform = Gem::Platform::RUBY s.authors = ["<NAME>"] s.email = ["<EMAIL>"] s.homepage = "http://kevy.com" s.summary = "include default logging to objects" s.description = "include default logging to objects" s.files = Dir.glob("{lib}/*") s.require_path = 'lib' s.add_dependency 'logger' end <file_sep>/lib/log_graft.rb require 'logger' module LogGraft attr_writer :logger def logger defined?(@logger) ? @logger : self.class.logger end module ClassMethods def logger=(logger) @logger = logger end def logger @logger ||= Logger.new(STDERR) end end def self.included(base) base.extend(ClassMethods) end end
437d8a40075cfaf498ac428aa5788f5a4d0924b0
[ "Ruby" ]
2
Ruby
barberj/log_graft
491a2b589be8f319b19f929fa4a4064b82f514e3
27ebb7c316d8b319194a255d18a74edf40248e99
refs/heads/master
<file_sep>package com.example.mibandtextsender import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.EditText import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { val CHANNEL_ID = "PUSH_CHANNEL" var current_notification_id = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Create channel createNotificationChannel() var editText : EditText = findViewById(R.id.editText) button.setOnClickListener { with(NotificationManagerCompat.from(this)) { notify(current_notification_id, NotificationCompat.Builder(applicationContext, CHANNEL_ID) .setSmallIcon(R.drawable.push_icon) .setContentTitle("Your message\n") .setStyle(NotificationCompat.BigTextStyle() .bigText(editText.text)) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .build()) current_notification_id++ } } } private fun createNotificationChannel(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = getString(R.string.channel_name) val descriptionText = getString(R.string.channel_description) val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(CHANNEL_ID, name, importance).apply { description = descriptionText } // Register the channel with the system val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } }<file_sep>### Description It is the simple project, that totally only create a push notification with entered text, but you can send messages to your MiBand (on MiBand 4 tested), that could display a push notifications. Only allow MiBand catch notifications from this application. ### Current version - 0.0.1
54587f416c8fa262c42fe991198af684b0e0ded5
[ "Markdown", "Kotlin" ]
2
Kotlin
IvanBespalov64/MiBandTextWriter
59f3e427e65a1c4bf778119b50d0e932c4410892
41e8b811edb528e54dbb4bdc222c489e8bcbbe07
refs/heads/main
<file_sep>"""Module for the Saved Recipe Model""" from django.db import models from django.contrib.auth.models import User class Saved_Recipe(models.Model): spoonacular_id = models.IntegerField(null=True) user = models.ForeignKey(User, on_delete=models.CASCADE,) title = models.CharField(max_length=100) image = models.URLField() source_name = models.CharField(max_length=100, null=True) source_url = models.URLField(null=True) servings = models.IntegerField(null=True) ready_in_minutes = models.IntegerField(null=True) summary = models.CharField(max_length=5000, null=True) favorite = models.BooleanField() edited = models.BooleanField() @property def ingredients(self): return self.__ingredients @ingredients.setter def ingredients(self, value): self.__ingredients = value @property def equipment(self): return self.__equipment @equipment.setter def equipment(self, value): self.__equipment = value @property def intructions(self): return self.__intructions @intructions.setter def intructions(self, value): self.__intructions = value class Meta: verbose_name = ("saved_recipe") verbose_name_plural = ("saved_recipes")<file_sep>[FORMAT] good-names=i,j,ex,pk [MESSAGES CONTROL] disable=broad-except <file_sep>import base64 from rest_framework import status from rest_framework import serializers from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticatedOrReadOnly from django.http import HttpResponseServerError from django.core.files.base import ContentFile from django.contrib.auth.models import User from cookit_api.models import Saved_Recipe, Ingredient, Meal class ConciseRecipeSerializer(serializers.ModelSerializer): """JSON serializer for Saved Recipes""" class Meta: model = Saved_Recipe fields = ('id','spoonacular_id', 'title', 'image', 'source_name', 'source_url', 'servings', 'ready_in_minutes', 'summary', 'favorite', 'edited') class IngredientSerializer(serializers.ModelSerializer): """JSON serializer for Ingredients""" saved_recipe = ConciseRecipeSerializer(many=False) class Meta: model = Ingredient fields = ('id', 'spoonacular_id', 'saved_recipe', 'spoon_ingredient_id', 'amount', 'unit', 'name', 'original', 'aisle', 'aquired') depth = 1 class Grocery_List(ViewSet): """Request handlers ingredients from recipes listed in the meals queue.""" permission_classes = (IsAuthenticatedOrReadOnly,) def list(self, request): """ Handles GET requests for all of a users meals. """ meals = Meal.objects.filter(user=request.auth.user) grocery_list = [] for meal in meals: if meal.saved_recipe is None: recipe_ingredients = Ingredient.objects.filter(spoonacular_id=meal.spoonacular_id) for ingredient in recipe_ingredients: grocery_list.append(ingredient) elif meal.saved_recipe is not None: recipe_ingredients = Ingredient.objects.filter(saved_recipe=meal.saved_recipe) for ingredient in recipe_ingredients: grocery_list.append(ingredient) serializer = IngredientSerializer( grocery_list, many=True, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) @action(methods=['get'], detail=True) def aquired(self, request, pk=None): """Handles GET requests to aquired or unfavorite a recipe""" if request.method == "GET": try: ingredient = Ingredient.objects.get(pk=pk) if ingredient.aquired is False: ingredient.aquired = True ingredient.save(force_update=True) return Response({'message': 'ingredient has been aquired!'}, status=status.HTTP_204_NO_CONTENT) elif ingredient.aquired is True: ingredient.aquired = False ingredient.save(force_update=True) return Response({'message': 'ingredient status has been reset.'}, status=status.HTTP_204_NO_CONTENT) except Ingredient.DoesNotExist as ex: return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND) except Exception as ex: return HttpResponseServerError(ex, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response({}, status=status.HTTP_405_METHOD_NOT_ALLOWED)<file_sep>#!/bin/bash rm -rf cookit_api/migrations rm db.sqlite3 python3 manage.py migrate python3 manage.py makemigrations cookit_api python3 manage.py migrate cookit_api python3 manage.py loaddata users python3 manage.py loaddata tokens python3 manage.py loaddata saved_recipes python3 manage.py loaddata ingredients python3 manage.py loaddata instructions python3 manage.py loaddata equipment python3 manage.py loaddata meals <file_sep># Generated by Django 3.1.7 on 2021-06-01 15:58 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Saved_Recipe', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('spoonacular_id', models.IntegerField(null=True)), ('title', models.CharField(max_length=100)), ('image', models.URLField()), ('source_name', models.CharField(max_length=100, null=True)), ('source_url', models.URLField(null=True)), ('servings', models.IntegerField(null=True)), ('ready_in_minutes', models.IntegerField(null=True)), ('summary', models.CharField(max_length=5000, null=True)), ('favorite', models.BooleanField()), ('edited', models.BooleanField()), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'saved_recipe', 'verbose_name_plural': 'saved_recipes', }, ), migrations.CreateModel( name='Meal', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('spoonacular_id', models.IntegerField(null=True)), ('saved_recipe', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='cookit_api.saved_recipe')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'meal', 'verbose_name_plural': 'meals', }, ), migrations.CreateModel( name='Instruction', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('spoonacular_id', models.IntegerField(null=True)), ('step_number', models.IntegerField()), ('instruction', models.CharField(max_length=100, null=True)), ('saved_recipe', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='cookit_api.saved_recipe')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'instruction', 'verbose_name_plural': 'instructions', }, ), migrations.CreateModel( name='Ingredient', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('spoonacular_id', models.IntegerField(null=True)), ('spoon_ingredient_id', models.IntegerField(null=True)), ('amount', models.FloatField()), ('unit', models.CharField(max_length=100, null=True)), ('name', models.CharField(max_length=100, null=True)), ('original', models.CharField(max_length=100, null=True)), ('aisle', models.CharField(max_length=100, null=True)), ('aquired', models.BooleanField()), ('saved_recipe', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='cookit_api.saved_recipe')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'ingredient', 'verbose_name_plural': 'ingredients', }, ), migrations.CreateModel( name='Equipment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('spoonacular_id', models.IntegerField(null=True)), ('name', models.CharField(max_length=50)), ('saved_recipe', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='cookit_api.saved_recipe')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] <file_sep>from django.apps import AppConfig class CookitApiConfig(AppConfig): name = 'cookit_api' <file_sep># cookit-server The Back-End Capstone for https://github.com/Heath-Lester/cookit client. ## Installations 1. Python on Windows Subsystem for Linux ```sudo apt update ``` ```sudo apt install -y gcc make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev python-openssl python3 python3-pip``` 1. Homebrew ```/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"``` 1. Python on Mac ```xcode-select --install``` 1. Pyenv and Python on Mac ```brew install pyenv``` ```pyenv install 3.9.1``` ```pyenv global 3.9.1``` 1. Pipenv 3rd Party Tool ```pip3 install --user pipenv``` > If you get command not found: pipenv when trying to run pipenv: > > * Mac and Linux > * Open ~/.zshrc and add: > ```export PIPENV_DIR="$HOME/.local"``` > ```export PATH="$PIPENV_DIR/bin:$PYENV_ROOT/bin:$PATH"``` > > * Windows > * First run ```python -m site --user-site``` > * Copy what that returns, replacing ```site-packages``` with ```Scripts``` > * In the control panel add what was copied to the path 1. Virtual Environment ```pip3 install --user pipx``` ```pipx install pipenv``` 1. Start Virtual Project ```pipenv shell``` 1. Third-Party Packages ```pipenv install django autopep8 pylint djangorestframework django-cors-headers pylint-django``` 1. Migrate data ```./seed.sh``` 1. Start the Server ```python manage.py runserver```<file_sep>"""Module for the Meal Model""" from django.db import models from django.contrib.auth.models import User from .saved_recipe import Saved_Recipe class Meal(models.Model): spoonacular_id = models.IntegerField(null=True) saved_recipe = models.ForeignKey(Saved_Recipe, null=True, on_delete=models.CASCADE,) user = models.ForeignKey(User, on_delete=models.CASCADE,) class Meta: verbose_name = ("meal") verbose_name_plural = ("meals")<file_sep>"""Module for the Equipment Model""" from django.db import models from django.contrib.auth.models import User from .saved_recipe import Saved_Recipe class Equipment(models.Model): spoonacular_id = models.IntegerField(null=True) saved_recipe = models.ForeignKey(Saved_Recipe, null=True, on_delete=models.CASCADE,) user = models.ForeignKey(User, on_delete=models.CASCADE,) name = models.CharField(max_length=50) <file_sep>from .saved_recipe import Saved_Recipe from .meal import Meal from .instruction import Instruction from .ingredient import Ingredient from .equipment import Equipment<file_sep>asgiref==3.3.1 astroid==2.5.1 autopep8==1.5.5 Django==3.1.7 django-cors-headers==3.7.0 djangorestframework==3.12.2 isort==5.7.0 lazy-object-proxy==1.5.2 mccabe==0.6.1 pycodestyle==2.7.0 pylint==2.7.2 pylint-django==2.4.2 pylint-plugin-utils==0.6 python-decouple==3.4 pytz==2021.1 sqlparse==0.4.1 toml==0.10.2 wrapt==1.12.1<file_sep>"""cookit_server URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from rest_framework import routers from rest_framework.authtoken.views import obtain_auth_token from cookit_api.models import * from cookit_api.views import * router = routers.DefaultRouter(trailing_slash=False) router.register(r'recipes', Saved_Recipes, 'saved_recipe') router.register(r'meals', Meals, 'meals') router.register(r'grocerylist', Grocery_List, 'grocery_list') urlpatterns = [ url(r'^', include(router.urls)), url(r'^register$', register_user), url(r'^login$', login_user), url(r'^api-token-auth$', obtain_auth_token), url(r'^api-auth', include('rest_framework.urls', namespace='rest_framework')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <file_sep>"""Module for the Ingredient Model""" from django.db import models from django.contrib.auth.models import User from .saved_recipe import Saved_Recipe class Ingredient(models.Model): spoonacular_id = models.IntegerField(null=True) saved_recipe = models.ForeignKey(Saved_Recipe, null=True, on_delete=models.CASCADE,) user = models.ForeignKey(User, on_delete=models.CASCADE,) spoon_ingredient_id = models.IntegerField(null=True) amount = models.FloatField() unit = models.CharField(max_length=100, null=True) name = models.CharField(max_length=100, null=True) original = models.CharField(max_length=100, null=True) aisle = models.CharField(max_length=100, null=True) aquired = models.BooleanField() class Meta: verbose_name = ("ingredient") verbose_name_plural = ("ingredients")<file_sep>import base64 from rest_framework import status from rest_framework import serializers from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticatedOrReadOnly from django.http import HttpResponseServerError from django.core.files.base import ContentFile from django.contrib.auth.models import User from cookit_api.models import Saved_Recipe, Ingredient, Instruction, Equipment, Meal class IngredientSerializer(serializers.ModelSerializer): """JSON serializer for Ingredients""" class Meta: model = Ingredient fields = ('id', 'spoonacular_id', 'saved_recipe', 'spoon_ingredient_id', 'amount', 'unit', 'name', 'original', 'aisle', 'aquired') class InstructionSerializer(serializers.ModelSerializer): """JSON serializer for Instructions""" class Meta: model = Instruction fields = ('id', 'spoonacular_id', 'saved_recipe', 'step_number', 'instruction') class EquipmentSerializer(serializers.ModelSerializer): """JSON serializer for Equipment""" class Meta: model = Equipment fields = ('id', 'spoonacular_id', 'saved_recipe', 'name') class MealSerializer(serializers.ModelSerializer): """JSON serializer for a meal to prepare""" class Meta: model = Meal fields = ('id', 'spoonacular_id', 'saved_recipe') class ConciseRecipeSerializer(serializers.ModelSerializer): """JSON serializer for Saved Recipes""" class Meta: model = Saved_Recipe fields = ('id','spoonacular_id', 'title', 'image', 'source_name', 'source_url', 'servings', 'ready_in_minutes', 'summary', 'favorite', 'edited') class DetailedMealSerializer(serializers.ModelSerializer): """JSON serializer for a meal to prepare""" ingredients = IngredientSerializer(many=True) instructions = InstructionSerializer(many=True) equipment = EquipmentSerializer(many=True) saved_recipe = ConciseRecipeSerializer(many=False) class Meta: model = Meal fields = ('id', 'spoonacular_id', 'saved_recipe', 'ingredients', 'instructions', 'equipment') depth = 1 class Meals(ViewSet): """Request handlers for saved, new, or edited recipes added to the meals-to-prep queue.""" permission_classes = (IsAuthenticatedOrReadOnly,) def create(self, request): """ Handles POST request for a meal to prepare. """ user = User.objects.get(pk=request.auth.user.id) spoonacular_id = request.data["spoonacularId"] saved_recipe_id = request.data["savedRecipeId"] if spoonacular_id is None: user_made_recipe = Meal() user_made_recipe.saved_recipe = Saved_Recipe.objects.get(pk=saved_recipe_id) user_made_recipe.user = user user_made_recipe.save() serializer = MealSerializer( user_made_recipe, context={'request': request}) elif saved_recipe_id is None: non_saved_recipe = Meal() non_saved_recipe.spoonacular_id = spoonacular_id non_saved_recipe.user = user non_saved_recipe.save() new_ingredients = request.data["ingredients"] i=0 for ingredient in new_ingredients: ingredient = Ingredient() ingredient.spoonacular_id = non_saved_recipe.spoonacular_id ingredient.user = user ingredient.spoon_ingredient_id = request.data["ingredients"][i]["id"] ingredient.amount = request.data["ingredients"][i]["amount"] ingredient.unit = request.data["ingredients"][i]["unit"] ingredient.name = request.data["ingredients"][i]["name"] ingredient.original = request.data["ingredients"][i]["original"] ingredient.aisle = request.data["ingredients"][i]["aisle"] ingredient.aquired = False ingredient.save() i += 1 new_instructions = request.data["instructions"] i=0 for instruction in new_instructions: instruction = Instruction() instruction.spoonacular_id = non_saved_recipe.spoonacular_id instruction.user = user instruction.step_number = request.data["instructions"][i]["number"] instruction.instruction = request.data["instructions"][i]["step"] instruction.save() i += 1 new_eqiupment = request.data["equipment"] i=0 for equipment in new_eqiupment: equipment = Equipment() equipment.spoonacular_id = non_saved_recipe.spoonacular_id equipment.user = user equipment.name = request.data["equipment"][i]["name"] equipment.save() i += 1 non_saved_recipe.ingredients = Ingredient.objects.filter(spoonacular_id=non_saved_recipe.spoonacular_id) non_saved_recipe.instructions = Instruction.objects.filter(spoonacular_id=non_saved_recipe.spoonacular_id) non_saved_recipe.equipment = Equipment.objects.filter(spoonacular_id=non_saved_recipe.spoonacular_id) serializer = DetailedMealSerializer( non_saved_recipe, context={'request': request}) elif spoonacular_id is not None and saved_recipe_id is not None: saved_recipe = Meal() saved_recipe.spoonacular_id = spoonacular_id saved_recipe.saved_recipe = Saved_Recipe.objects.get(pk=saved_recipe_id) saved_recipe.user = user saved_recipe.save() serializer = MealSerializer( saved_recipe, context={'request': request}) return Response(serializer.data, status=status.HTTP_201_CREATED) def destroy(self, request, pk=None): """ Handles DELETE requests for all meals. """ user = User.objects.get(pk=request.auth.user.id) try: meal = Meal.objects.get(pk=pk, user=user) if meal.saved_recipe is None: ingredients = Ingredient.objects.filter(spoonacular_id=meal.spoonacular_id) instructions = Instruction.objects.filter(spoonacular_id=meal.spoonacular_id) equipment = Equipment.objects.filter(spoonacular_id=meal.spoonacular_id) for ingredient in ingredients: ingredient.delete() for instruction in instructions: instruction.delete() for item in equipment: item.delete() meal.delete() return Response({}, status=status.HTTP_204_NO_CONTENT) if meal.saved_recipe is not None: meal.delete() return Response({}, status=status.HTTP_204_NO_CONTENT) except Meal.DoesNotExist as ex: return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND) except Exception as ex: return Response({'message': ex.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def list(self, request): """ Handles GET requests for all of a users meals. """ meals = Meal.objects.filter(user=request.auth.user) for meal in meals: if meal.saved_recipe is None: meal.ingredients = Ingredient.objects.filter(spoonacular_id=meal.spoonacular_id) meal.instructions = Instruction.objects.filter(spoonacular_id=meal.spoonacular_id) meal.equipment = Equipment.objects.filter(spoonacular_id=meal.spoonacular_id) if meal.saved_recipe is not None: meal.ingredients = Ingredient.objects.filter(saved_recipe=meal.saved_recipe) meal.instructions = Instruction.objects.filter(saved_recipe=meal.saved_recipe) meal.equipment = Equipment.objects.filter(saved_recipe=meal.saved_recipe) serializer = DetailedMealSerializer( meals, many=True, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) @action(methods=['delete'], detail=False) def complete(self, request): """Handles DELETE requests to reset meal-to-prep queue.""" if request.method == "DELETE": all_user_meals = Meal.objects.filter(user=request.auth.user) for meal in all_user_meals: if meal.saved_recipe is None: ingredients = Ingredient.objects.filter(spoonacular_id=meal.spoonacular_id) instructions = Instruction.objects.filter(spoonacular_id=meal.spoonacular_id) equipment = Equipment.objects.filter(spoonacular_id=meal.spoonacular_id) for ingredient in ingredients: ingredient.delete() for instruction in instructions: instruction.delete() for item in equipment: item.delete() meal.delete() return Response({'message': 'Meal list has been reset!'}, status=status.HTTP_204_NO_CONTENT) return Response({}, status=status.HTTP_405_METHOD_NOT_ALLOWED) <file_sep>"""Register user""" import json from rest_framework import status from rest_framework.authtoken.models import Token from django.http import HttpResponse, HttpResponseNotAllowed from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.views.decorators.csrf import csrf_exempt @csrf_exempt def login_user(request): '''Handles the authentication of a user Method arguments: request -- The full HTTP request object ''' body = request.body.decode('utf-8') req_body = json.loads(body) # If the request is a HTTP POST, try to pull out the relevant information. if request.method == 'POST': # Use the built-in authenticate method to verify name = req_body['username'] pass_word = <PASSWORD>['<PASSWORD>'] authenticated_user = authenticate(username=name, password=<PASSWORD>) # If authentication was successful, respond with their token if authenticated_user is not None: token = Token.objects.get(user=authenticated_user) data = json.dumps({"valid": True, "token": token.key, "id": authenticated_user.id}) return HttpResponse(data, content_type='application/json', status=status.HTTP_202_ACCEPTED ) else: # Bad login details were provided. So we can't log the user in. data = json.dumps({"valid": False}) return HttpResponse(data, content_type='application/json') return HttpResponseNotAllowed(permitted_methods=['POST']) @csrf_exempt def register_user(request): '''Handles the creation of a new user for authentication Method arguments: request -- The full HTTP request object ''' req_body = json.loads(request.body.decode()) user = User.objects.create_user( first_name=req_body['firstName'], last_name=req_body['lastName'], username=req_body['username'], email=req_body['email'], password=<PASSWORD>['<PASSWORD>'] ) user.save() token = Token.objects.create(user=user) data = json.dumps({"token": token.key}) return HttpResponse(data, content_type='application/json', status=status.HTTP_201_CREATED)<file_sep>from .saved_recipes import Saved_Recipes from .register import register_user, login_user from .meals import Meals from .grocery_list import Grocery_List<file_sep>"""View module for handling requests about recipes""" import base64 from rest_framework import status from rest_framework import serializers from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticatedOrReadOnly from django.http import HttpResponseServerError from django.contrib.auth.models import User from cookit_api.models import Saved_Recipe, Ingredient, Instruction, Equipment class IngredientSerializer(serializers.ModelSerializer): """JSON serializer for Ingredients""" class Meta: model = Ingredient fields = ('id', 'spoonacular_id', 'saved_recipe', 'spoon_ingredient_id', 'amount', 'unit', 'name', 'original', 'aisle', 'aquired') class InstructionSerializer(serializers.ModelSerializer): """JSON serializer for Instructions""" class Meta: model = Instruction fields = ('id', 'spoonacular_id', 'saved_recipe', 'step_number', 'instruction') class EquipmentSerializer(serializers.ModelSerializer): """JSON serializer for Equipment""" class Meta: model = Equipment fields = ('id', 'spoonacular_id', 'saved_recipe', 'name') class RecipeSerializer(serializers.ModelSerializer): """JSON serializer for Saved Recipes""" ingredients = IngredientSerializer(many=True) instructions = InstructionSerializer(many=True) equipment = EquipmentSerializer(many=True) class Meta: model = Saved_Recipe fields = ('id','spoonacular_id', 'title', 'image', 'source_name', 'source_url', 'servings', 'ready_in_minutes', 'summary', 'favorite', 'edited', 'ingredients', 'instructions', 'equipment') depth = 1 class Saved_Recipes(ViewSet): """Request handlers for saved, new, or edited recipes from the Spoonacular API""" permission_classes = (IsAuthenticatedOrReadOnly,) def create(self, request): """ Handles POST request for a new recipe. """ user = User.objects.get(pk=request.auth.user.id) new_recipe = Saved_Recipe() new_recipe.spoonacular_id = request.data["spoonacularId"] new_recipe.user = user new_recipe.title = request.data["title"] new_recipe.image = request.data["image"] new_recipe.source_name = request.data["sourceName"] new_recipe.source_url = request.data["sourceUrl"] new_recipe.servings = request.data["servings"] new_recipe.ready_in_minutes = request.data["readyInMinutes"] new_recipe.summary = request.data["summary"] new_recipe.favorite = False new_recipe.edited = False new_recipe.save() new_ingredients = request.data["ingredients"] i=0 for new_ingredient in new_ingredients: new_ingredient = Ingredient() new_ingredient.spoonacular_id = new_recipe.spoonacular_id new_ingredient.saved_recipe = Saved_Recipe.objects.get(pk=new_recipe.id) new_ingredient.user = user new_ingredient.spoon_ingredient_id = request.data["ingredients"][i]["id"] new_ingredient.amount = request.data["ingredients"][i]["amount"] new_ingredient.unit = request.data["ingredients"][i]["measures"]["us"]["unitLong"] new_ingredient.name = request.data["ingredients"][i]["name"] new_ingredient.original = request.data["ingredients"][i]["original"] new_ingredient.aisle = request.data["ingredients"][i]["aisle"] new_ingredient.aquired = False new_ingredient.save() i += 1 new_instructions = request.data["instructions"] i=0 for new_instruction in new_instructions: new_instruction = Instruction() new_instruction.spoonacular_id = new_recipe.spoonacular_id new_instruction.saved_recipe = Saved_Recipe.objects.get(pk=new_recipe.id) new_instruction.user = user new_instruction.step_number = request.data["instructions"][i]["number"] new_instruction.instruction = request.data["instructions"][i]["step"] new_instruction.save() i += 1 new_eqiupment = request.data["equipment"] i=0 for new_item in new_eqiupment: new_item = Equipment() new_item.spoonacular_id = new_recipe.spoonacular_id new_item.saved_recipe = Saved_Recipe.objects.get(pk=new_recipe.id) new_item.user = user new_item.name = request.data["equipment"][i]["name"] new_item.save() i += 1 new_recipe.ingredients = Ingredient.objects.filter(saved_recipe=new_recipe.id) new_recipe.instructions = Instruction.objects.filter(saved_recipe=new_recipe.id) new_recipe.equipment = Equipment.objects.filter(saved_recipe=new_recipe.id) serializer = RecipeSerializer( new_recipe, context={'request': request}) return Response(serializer.data, status=status.HTTP_201_CREATED) def update(self, request, pk=None): """ Handles PUT requests for all saved recipes. """ user = User.objects.get(pk=request.auth.user.id) recipe = Saved_Recipe.objects.get(pk=pk) old_ingredients = Ingredient.objects.filter(saved_recipe=pk) old_instructions = Instruction.objects.filter(saved_recipe=pk) old_equipment = Equipment.objects.filter(saved_recipe=pk) # Deletes all old Ingredients, Instructions, and Equipment for ingredient in old_ingredients: ingredient.delete() for instruction in old_instructions: instruction.delete() for equipment in old_equipment: equipment.delete() recipe.title = request.data["title"] recipe.image = request.data["image"] recipe.servings = request.data["servings"] recipe.ready_in_minutes = request.data["readyInMinutes"] recipe.summary = request.data["summary"] recipe.edited = True recipe.save() new_ingredients = request.data["ingredients"] i=0 for ingredient in new_ingredients: new_ingredient = Ingredient() new_ingredient.saved_recipe = Saved_Recipe.objects.get(pk=recipe.id) new_ingredient.user = user new_ingredient.amount = float(request.data["ingredients"][i]["amount"]) new_ingredient.name = request.data["ingredients"][i]["title"] # Deconstructs the float 'amount' to create the 'original' ingredient description float_to_integer = str(new_ingredient.amount).split('.') whole_number = int(float_to_integer[0]) decimal = int(float_to_integer[1]) fraction = "" # Finds if spoonacular's tablespoon default is present string_divider = "" unit = request.data["ingredients"][i]["unit"] if unit == 'Tbsps' or unit == 'Tbsp': new_ingredient.unit = 'tablespoon' # Converts plural units to singular units elif str(unit).endswith('ves'): unit_list = list(unit) unit_list.pop(-1) unit_list.pop(-1) unit_list.pop(-1) unit_list.append('f') unit_tuple = tuple(unit_list) singular_unit = string_divider.join(unit_tuple) new_ingredient.unit = str(singular_unit) elif str(unit).endswith(tuple(['ches', 'ses', 'shes', 'sses', 'xes', 'zes', ])): unit_list = list(unit) unit_list.pop(-1) unit_list.pop(-1) unit_tuple = tuple(unit_list) singular_unit = string_divider.join(unit_tuple) new_ingredient.unit = str(singular_unit) elif str(unit).endswith(tuple(['boes', 'coes', 'does', 'foes', 'goes', 'hoes', 'joes', 'koes', 'loes', 'moes', 'noes', 'poes', 'qoes', 'roes', 'soes', 'toes', 'voes', 'woes', 'xoes', 'zoes', ])): unit_list = list(unit) unit_list.pop(-1) unit_list.pop(-1) unit_tuple = tuple(unit_list) singular_unit = string_divider.join(unit_tuple) new_ingredient.unit = str(singular_unit) elif str(unit).endswith('ies'): unit_list = list(unit) unit_list.pop(-1) unit_list.pop(-1) unit_list.pop(-1) unit_list.append('y') unit_tuple = tuple(unit_list) singular_unit = string_divider.join(unit_tuple) new_ingredient.unit = str(singular_unit) elif str(unit).endswith('s'): unit_list = list(unit) unit_list.pop(-1) unit_tuple = tuple(unit_list) singular_unit = string_divider.join(unit_tuple) new_ingredient.unit = str(singular_unit) else: new_ingredient.unit = request.data["ingredients"][i]["unit"] # Converts the decimal into a fraction if decimal != 0: if decimal == 25: fraction = "1/4" elif str(decimal).startswith('3') and str(decimal).endswith('3'): fraction = "1/3" elif decimal == 5: fraction = "1/2" elif str(decimal).startswith('6') and str(decimal).endswith('6'): fraction = "2/3" elif decimal == 75: fraction = "3/4" # Sentece builder for singular units measurements = set(("teaspoon", "tablespoon", "ounce", "cup", "pint", "quart", "gallon", "pound", "gram", "milligram", "inch", "centimeter", "slice", "serving", "piece", "stick", "pinch")) if whole_number <= 1: if decimal == 0: if new_ingredient.unit == '': new_ingredient.original = str(whole_number) + " " + new_ingredient.name elif new_ingredient.unit not in measurements: new_ingredient.original = str(whole_number) + " " + new_ingredient.unit + " " + new_ingredient.name else: new_ingredient.original = str(whole_number) + " " + new_ingredient.unit + " of " + new_ingredient.name else: if new_ingredient.unit == '': new_ingredient.original = fraction + " " + new_ingredient.name elif new_ingredient.unit not in measurements: new_ingredient.original = str(whole_number) + " " + new_ingredient.unit + " " + new_ingredient.name else: new_ingredient.original = fraction + " " + new_ingredient.unit + " of " + new_ingredient.name # Sentece builder for plural units elif whole_number > 1: if decimal == 0: if new_ingredient.unit == '': new_ingredient.original = str(whole_number) + " " + new_ingredient.name elif new_ingredient.unit not in measurements: new_ingredient.original = str(whole_number) + " " + new_ingredient.unit + " " + new_ingredient.name else: new_ingredient.original = str(whole_number) + " " + new_ingredient.unit + "s of " + new_ingredient.name elif decimal > 0: if new_ingredient.unit == '': new_ingredient.original = str(whole_number) + " " + fraction + " " + new_ingredient.name elif new_ingredient.unit not in measurements: new_ingredient.original = str(whole_number) + " " + fraction + " " + new_ingredient.unit + " " + new_ingredient.name elif new_ingredient.unit.endswith(tuple(['ch', 's', 'sh', 'ss', 'x', 'z', ])): new_ingredient.original = str(whole_number) + " " + fraction + " " + new_ingredient.unit + "es of " + new_ingredient.name elif new_ingredient.unit.endswith('f'): unit_list = list(new_ingredient) unit_list.pop(-1) unit_tuple = tuple(unit_list) unit_wo_affix = string_divider.join(unit_tuple) unit_string = str(unit_wo_affix) new_ingredient.original = str(whole_number) + " " + fraction + " " + unit_string + "ves of " + new_ingredient.name elif new_ingredient.unit.endswith('fe'): unit_list = list(new_ingredient) unit_list.pop(-1) unit_list.pop(-1) unit_tuple = tuple(unit_list) unit_wo_affix = string_divider.join(unit_tuple) unit_string = str(unit_wo_affix) new_ingredient.original = str(whole_number) + " " + fraction + " " + unit_string + "ves of " + new_ingredient.name elif new_ingredient.unit.endswith(tuple(['bo', 'co', 'do', 'fo', 'go', 'ho', 'jo', 'ko', 'lo', 'mo', 'no', 'po', 'qo', 'ro', 'so', 'to', 'vo', 'wo', 'xo', 'zo', ])): new_ingredient.original = str(whole_number) + " " + fraction + " " + new_ingredient.unit + "es of " + new_ingredient.name elif new_ingredient.unit.endswith(tuple(['by', 'cy', 'dy', 'fy', 'gy', 'hy', 'jy', 'ky', 'ly', 'my', 'ny', 'py', 'qy', 'ry', 'sy', 'ty', 'vy', 'wy', 'xy', 'zy', ])): unit_list = list(new_ingredient) unit_list.pop(-1) unit_tuple = tuple(unit_list) unit_wo_affix = string_divider.join(unit_tuple) unit_string = str(unit_wo_affix) new_ingredient.original = str(whole_number) + " " + fraction + " " + unit_string + "ies of " + new_ingredient.name else: new_ingredient.original = str(whole_number) + " " + fraction + " " + new_ingredient.unit + "s of " + new_ingredient.name new_ingredient.aisle = request.data["ingredients"][i]["aisle"] new_ingredient.aquired = False new_ingredient.save() i += 1 new_instructions = request.data["instructions"] i=0 for instruction in new_instructions: new_instruction = Instruction() new_instruction.saved_recipe = Saved_Recipe.objects.get(pk=recipe.id) new_instruction.user = user new_instruction.step_number = i + 1 new_instruction.instruction = request.data["instructions"][i]["instruction"] new_instruction.save() i += 1 new_eqiupment = request.data["equipment"] i=0 for item in new_eqiupment: new_item = Equipment() new_item.saved_recipe = Saved_Recipe.objects.get(pk=recipe.id) new_item.user = user new_item.name = request.data["equipment"][i]["name"] new_item.save() i += 1 return Response({}, status=status.HTTP_204_NO_CONTENT) def destroy(self, request, pk=None): """ Handles DELETE requests for all saved recipes. """ try: recipe = Saved_Recipe.objects.get(pk=pk) ingredients = Ingredient.objects.filter(saved_recipe=recipe.id) instructions = Instruction.objects.filter(saved_recipe=recipe.id) equipment = Equipment.objects.filter(saved_recipe=recipe.id) for ingredient in ingredients: ingredient.delete() for instruction in instructions: instruction.delete() for item in equipment: item.delete() recipe.delete() return Response({}, status=status.HTTP_204_NO_CONTENT) except Saved_Recipe.DoesNotExist as ex: return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND) except Exception as ex: return Response({'message': ex.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def retrieve(self, request, pk=None): """ Handles GET requests for a single recipe """ try: recipe = Saved_Recipe.objects.get(pk=pk) recipe.ingredients = Ingredient.objects.filter(saved_recipe=recipe.id) recipe.instructions = Instruction.objects.filter(saved_recipe=recipe.id) recipe.equipment = Equipment.objects.filter(saved_recipe=recipe.id) serializer = RecipeSerializer(recipe, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) except Saved_Recipe.DoesNotExist as ex: return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND) except Exception as ex: return HttpResponseServerError(ex, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def list(self, request): """ Handles GET requests for all saved recipes. """ user = User.objects.get(pk=request.auth.user.id) user_recipes = Saved_Recipe.objects.filter(user=user) for recipe in user_recipes: recipe.ingredients = Ingredient.objects.filter(saved_recipe=recipe.id) recipe.instructions = Instruction.objects.filter(saved_recipe=recipe.id) recipe.equipment = Equipment.objects.filter(saved_recipe=recipe.id) serializer = RecipeSerializer( user_recipes, many=True, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) @action(methods=['get'], detail=False) def favorites(self, request): """Handles GET requests for Favorite recipes""" if request.method == "GET": user_recipes = Saved_Recipe.objects.filter(user=request.auth.user) try: favorite_recipes = user_recipes.filter(favorite=True) for recipe in favorite_recipes: recipe.ingredients = Ingredient.objects.filter(saved_recipe=recipe.id) recipe.instructions = Instruction.objects.filter(saved_recipe=recipe.id) recipe.equipment = Equipment.objects.filter(saved_recipe=recipe.id) serializer = RecipeSerializer( favorite_recipes, many=True, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) except user_recipes.DoesNotExist as ex: return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND) except Exception as ex: return HttpResponseServerError(ex, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @action(methods=['get'], detail=True) def favorite(self, request, pk=None): """Handles GET requests to favorite or unfavorite a recipe""" if request.method == "GET": try: recipe = Saved_Recipe.objects.get(pk=pk) if recipe.favorite is False: recipe.favorite = True recipe.save(force_update=True) return Response({'message': 'Recipe has been favorited!'}, status=status.HTTP_204_NO_CONTENT) elif recipe.favorite is True: recipe.favorite = False recipe.save(force_update=True) return Response({'message': 'Recipe has been unfavorited.'}, status=status.HTTP_204_NO_CONTENT) except Saved_Recipe.DoesNotExist as ex: return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND) except Exception as ex: return HttpResponseServerError(ex, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response({}, status=status.HTTP_405_METHOD_NOT_ALLOWED) @action(methods=['post'], detail=False) def new(self, request): """Handles POST requests for user-made recipes""" if request.method == "POST": user = User.objects.get(pk=request.auth.user.id) new_recipe = Saved_Recipe() new_recipe.user = user new_recipe.title = request.data["title"] new_recipe.image = request.data["image"] new_recipe.source_name = user.first_name + " " + user.last_name new_recipe.servings = int(request.data["servings"]) new_recipe.ready_in_minutes = int(request.data["readyInMinutes"]) new_recipe.summary = request.data["summary"] new_recipe.favorite = False new_recipe.edited = False new_recipe.save() new_ingredients = request.data["ingredients"] i=0 for new_ingredient in new_ingredients: new_ingredient = Ingredient() new_ingredient.saved_recipe = Saved_Recipe.objects.get(pk=new_recipe.id) new_ingredient.user = user new_ingredient.amount = float(request.data["ingredients"][i]["amount"]) new_ingredient.unit = request.data["ingredients"][i]["unit"] new_ingredient.name = request.data["ingredients"][i]["title"] if new_ingredient.unit == "None" and new_ingredient.amount > 1.0: new_ingredient.original = str(new_ingredient.amount) + " " + new_ingredient.name + "s" elif new_ingredient.unit == "None" and new_ingredient.amount <= 1.0: new_ingredient.original = str(new_ingredient.amount) + " " + new_ingredient.name elif new_ingredient.amount > 1.0: new_ingredient.original = str(new_ingredient.amount) + " " + new_ingredient.unit + "s of " + new_ingredient.name elif new_ingredient.amount <= 1.0: new_ingredient.original = str(new_ingredient.amount) + " " + new_ingredient.unit + " of " + new_ingredient.name new_ingredient.aisle = request.data["ingredients"][i]["aisle"] new_ingredient.aquired = False new_ingredient.save() i += 1 new_instructions = request.data["instructions"] i=0 for new_instruction in new_instructions: new_instruction = Instruction() new_instruction.saved_recipe = Saved_Recipe.objects.get(pk=new_recipe.id) new_instruction.user = user new_instruction.step_number = i + 1 new_instruction.instruction = request.data["instructions"][i]["instruction"] new_instruction.save() i += 1 new_eqiupment = request.data["equipment"] i=0 for new_item in new_eqiupment: new_item = Equipment() new_item.saved_recipe = Saved_Recipe.objects.get(pk=new_recipe.id) new_item.user = user new_item.name = request.data["equipment"][i]["name"] new_item.save() i += 1 new_recipe.ingredients = Ingredient.objects.filter(saved_recipe=new_recipe.id) new_recipe.instructions = Instruction.objects.filter(saved_recipe=new_recipe.id) new_recipe.equipment = Equipment.objects.filter(saved_recipe=new_recipe.id) serializer = RecipeSerializer( new_recipe, context={'request': request}) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
68e6c989eb301e1ae2a5b0032b1120c9425cfe02
[ "Markdown", "INI", "Python", "Text", "Shell" ]
17
Python
Heath-Lester/cookit_server
e0520c71b57230908e83f8139d0347299746cb8f
817bf41a9bc0a4ae3b46c021dc07f1c00c4cf827
refs/heads/master
<repo_name>EandM/D228<file_sep>/sorting.cpp #include<stdio.h> #include<stdlib.h> #include<time.h> #define SIZE 100000 void setArray(int array[]) { srand(time(NULL)); for(int i = 0; i< SIZE;i++) { array[i] = rand()%100; } } void printArray(int array[]) { for(int i = 0; i< SIZE;i++) { printf("%d ", array[i]); } printf("\n"); } void sortArray(int array[]) { printf("\nAfter sorting: \n"); for(int i = 0; i < SIZE - 1; i++) { for(int j = 0; j < SIZE - i - 1; j++ ) { if(array[j+1] < array[j]){ int tmp = array[j+1]; array[j+1] = array[j]; array[j] = tmp; } } } } int main() { int *array = new int[SIZE]; setArray(array); printArray(array); sortArray(array); printArray(array); delete []array; return 0; }
00adf7fa02b4959f547396b4750955d6b8ddc466
[ "C++" ]
1
C++
EandM/D228
b71aeb9d0250052f18387d0254467b92cdf0417d
4ecea35a366ff4678aee6af15feeaf763295db4d
refs/heads/master
<file_sep>import pandas as pd import numpy as np import logging import os from .utils import mask_cell,mask_cell_surface,mask_cube_cell,get_bounding_box def cell_statistics_all(input_cubes,track,mask,aggregators,output_path='./',cell_selection=None,output_name='Profiles',width=10000,z_coord='model_level_number',dimensions=['x','y'],**kwargs): if cell_selection is None: cell_selection=np.unique(track['cell']) for cell in cell_selection : cell_statistics(input_cubes=input_cubes,track=track, mask=mask, dimensions=dimensions,aggregators=aggregators,cell=cell, output_path=output_path,output_name=output_name, width=width,z_coord=z_coord,**kwargs) def cell_statistics(input_cubes,track,mask,aggregators,cell,output_path='./',output_name='Profiles',width=10000,z_coord='model_level_number',dimensions=['x','y'],**kwargs): from iris.cube import Cube,CubeList from iris.coords import AuxCoord from iris import Constraint,save # If input is single cube, turn into cubelist if type(input_cubes) is Cube: input_cubes=CubeList([input_cubes]) logging.debug('Start calculating profiles for cell '+str(cell)) track_i=track[track['cell']==cell] cubes_profile={} for aggregator in aggregators: cubes_profile[aggregator.name()]=CubeList() for time_i in track_i['time'].values: constraint_time = Constraint(time=time_i) mask_i=mask.extract(constraint_time) mask_cell_i=mask_cell(mask_i,cell,track_i,masked=False) mask_cell_surface_i=mask_cell_surface(mask_i,cell,track_i,masked=False,z_coord=z_coord) x_dim=mask_cell_surface_i.coord_dims('projection_x_coordinate')[0] y_dim=mask_cell_surface_i.coord_dims('projection_y_coordinate')[0] x_coord=mask_cell_surface_i.coord('projection_x_coordinate') y_coord=mask_cell_surface_i.coord('projection_y_coordinate') if (mask_cell_surface_i.core_data()>0).any(): box_mask_i=get_bounding_box(mask_cell_surface_i.core_data(),buffer=1) box_mask=[[x_coord.points[box_mask_i[x_dim][0]],x_coord.points[box_mask_i[x_dim][1]]], [y_coord.points[box_mask_i[y_dim][0]],y_coord.points[box_mask_i[y_dim][1]]]] else: box_mask=[[np.nan,np.nan],[np.nan,np.nan]] x=track_i[track_i['time'].values==time_i]['projection_x_coordinate'].values[0] y=track_i[track_i['time'].values==time_i]['projection_y_coordinate'].values[0] box_slice=[[x-width,x+width],[y-width,y+width]] x_min=np.nanmin([box_mask[0][0],box_slice[0][0]]) x_max=np.nanmax([box_mask[0][1],box_slice[0][1]]) y_min=np.nanmin([box_mask[1][0],box_slice[1][0]]) y_max=np.nanmax([box_mask[1][1],box_slice[1][1]]) constraint_x=Constraint(projection_x_coordinate=lambda cell: int(x_min) < cell < int(x_max)) constraint_y=Constraint(projection_y_coordinate=lambda cell: int(y_min) < cell < int(y_max)) constraint=constraint_time & constraint_x & constraint_y # Mask_cell_surface_i=mask_cell_surface(Mask_w_i,cell,masked=False,z_coord='model_level_number') mask_cell_i=mask_cell_i.extract(constraint) mask_cell_surface_i=mask_cell_surface_i.extract(constraint) input_cubes_i=input_cubes.extract(constraint) for cube in input_cubes_i: cube_masked=mask_cube_cell(cube,mask_cell_i,cell,track_i) coords_remove=[] for coordinate in cube_masked.coords(dim_coords=False): if coordinate.name() not in dimensions: for dim in dimensions: if set(cube_masked.coord_dims(coordinate)).intersection(set(cube_masked.coord_dims(dim))): coords_remove.append(coordinate.name()) for coordinate in set(coords_remove): cube_masked.remove_coord(coordinate) for aggregator in aggregators: cube_collapsed=cube_masked.collapsed(dimensions,aggregator,**kwargs) #remove all collapsed coordinates (x and y dim, scalar now) and keep only time as all these coordinates are useless for coordinate in cube_collapsed.coords(): if not cube_collapsed.coord_dims(coordinate): if coordinate.name() is not 'time': cube_collapsed.remove_coord(coordinate) logging.debug(str(cube_collapsed)) cubes_profile[aggregator.name()].append(cube_collapsed) minutes=(track_i['time_cell']/pd.Timedelta(minutes=1)).values latitude=track_i['latitude'].values longitude=track_i['longitude'].values minutes_coord=AuxCoord(minutes,long_name='cell_time',units='min') latitude_coord=AuxCoord(latitude,long_name='latitude',units='degrees') longitude_coord=AuxCoord(longitude,long_name='longitude',units='degrees') for aggregator in aggregators: cubes_profile[aggregator.name()]=cubes_profile[aggregator.name()].merge() for cube in cubes_profile[aggregator.name()]: cube.add_aux_coord(minutes_coord,data_dims=cube.coord_dims('time')) cube.add_aux_coord(latitude_coord,data_dims=cube.coord_dims('time')) cube.add_aux_coord(longitude_coord,data_dims=cube.coord_dims('time')) os.makedirs(os.path.join(output_path,output_name,aggregator.name()),exist_ok=True) savefile=os.path.join(output_path,output_name,aggregator.name(),output_name+'_'+ aggregator.name()+'_'+str(int(cell))+'.nc') save(cubes_profile[aggregator.name()],savefile) def cog_cell(cell,Tracks=None,M_total=None,M_liquid=None, M_frozen=None, Mask=None, savedir=None): from iris import Constraint logging.debug('Start calculating COG for '+str(cell)) Track=Tracks[Tracks['cell']==cell] constraint_time=Constraint(time=lambda cell: Track.head(1)['time'].values[0] <= cell <= Track.tail(1)['time'].values[0]) M_total_i=M_total.extract(constraint_time) M_liquid_i=M_liquid.extract(constraint_time) M_frozen_i=M_frozen.extract(constraint_time) Mask_i=Mask.extract(constraint_time) savedir_cell=os.path.join(savedir,'cells',str(int(cell))) os.makedirs(savedir_cell,exist_ok=True) savefile_COG_total_i=os.path.join(savedir_cell,'COG_total'+'_'+str(int(cell))+'.h5') savefile_COG_liquid_i=os.path.join(savedir_cell,'COG_liquid'+'_'+str(int(cell))+'.h5') savefile_COG_frozen_i=os.path.join(savedir_cell,'COG_frozen'+'_'+str(int(cell))+'.h5') Tracks_COG_total_i=calculate_cog(Track,M_total_i,Mask_i) # Tracks_COG_total_list.append(Tracks_COG_total_i) logging.debug('COG total loaded for ' +str(cell)) Tracks_COG_liquid_i=calculate_cog(Track,M_liquid_i,Mask_i) # Tracks_COG_liquid_list.append(Tracks_COG_liquid_i) logging.debug('COG liquid loaded for ' +str(cell)) Tracks_COG_frozen_i=calculate_cog(Track,M_frozen_i,Mask_i) # Tracks_COG_frozen_list.append(Tracks_COG_frozen_i) logging.debug('COG frozen loaded for ' +str(cell)) Tracks_COG_total_i.to_hdf(savefile_COG_total_i,'table') Tracks_COG_liquid_i.to_hdf(savefile_COG_liquid_i,'table') Tracks_COG_frozen_i.to_hdf(savefile_COG_frozen_i,'table') logging.debug('individual COG calculated and saved to '+ savedir_cell) def lifetime_histogram(Track,bin_edges=np.arange(0,200,20),density=False,return_values=False): Track_cell=Track.groupby('cell') minutes=(Track_cell['time_cell'].max()/pd.Timedelta(minutes=1)).values hist, bin_edges = np.histogram(minutes, bin_edges,density=density) bin_centers=bin_edges[:-1]+0.5*np.diff(bin_edges) if return_values: return hist,bin_edges,bin_centers,minutes else: return hist,bin_edges,bin_centers def haversine(lat1,lon1,lat2,lon2): """Computes the Haversine distance in kilometres between two points (based on implementation CIS https://github.com/cedadev/cis) :param lat1: first point or points as array, each as array of latitude in degrees :param lon1: first point or points as array, each as array of longitude in degrees :param lat2: second point or points as array, each as array of latitude in degrees :param lon2: second point or points as array, each as array of longitude in degrees :return: distance between the two points in kilometres """ RADIUS_EARTH = 6378.0 lat1 = np.radians(lat1) lat2 = np.radians(lat2) lon1 = np.radians(lon1) lon2 = np.radians(lon2) #print(lat1,lat2,lon1,lon2) arclen = 2 * np.arcsin(np.sqrt((np.sin((lat2 - lat1) / 2)) ** 2 + np.cos(lat1) * np.cos(lat2) * (np.sin((lon2 - lon1) / 2)) ** 2)) return arclen * RADIUS_EARTH def calculate_distance(feature_1,feature_2,method_distance=None): """Computes distance between two features based on either lat/lon coordinates or x/y coordinates :param feature_1: first feature or points as array, each as array of latitude, longitude in degrees :param feature_2: second feature or points as array, each as array of latitude, longitude in degrees :return: distance between the two features in metres """ if method_distance is None: if ('projection_x_coordinate' in feature_1) and ('projection_y_coordinate' in feature_1) and ('projection_x_coordinate' in feature_2) and ('projection_y_coordinate' in feature_2) : method_distance='xy' elif ('latitude' in feature_1) and ('longitude' in feature_1) and ('latitude' in feature_2) and ('longitude' in feature_2): method_distance='latlon' else: raise ValueError('either latitude/longitude or projection_x_coordinate/projection_y_coordinate have to be present to calculate distances') if method_distance=='xy': distance=np.sqrt((feature_1['projection_x_coordinate']-feature_2['projection_x_coordinate'])**2 +(feature_1['projection_y_coordinate']-feature_2['projection_y_coordinate'])**2) elif method_distance=='latlon': distance=1000*haversine(feature_1['latitude'],feature_1['longitude'],feature_2['latitude'],feature_2['longitude']) else: raise ValueError('method undefined') return distance def calculate_velocity_individual(feature_old,feature_new,method_distance=None): distance=calculate_distance(feature_old,feature_new,method_distance=method_distance) diff_time=((feature_new['time']-feature_old['time']).total_seconds()) velocity=distance/diff_time return velocity def calculate_velocity(track,method_distance=None): for cell_i,track_i in track.groupby('cell'): index=track_i.index.values for i,index_i in enumerate(index[:-1]): velocity=calculate_velocity_individual(track_i.loc[index[i]],track_i.loc[index[i+1]],method_distance=method_distance) track.at[index_i,'v']=velocity return track def velocity_histogram(track,bin_edges=np.arange(0,30,1),density=False,method_distance=None,return_values=False): if 'v' not in track.columns: logging.info('calculate velocities') track=calculate_velocity(track) velocities=track['v'].values hist, bin_edges = np.histogram(velocities[~np.isnan(velocities)], bin_edges,density=density) if return_values: return hist,bin_edges,velocities else: return hist,bin_edges def calculate_nearestneighbordistance(features,method_distance=None): from itertools import combinations features['min_distance']=np.nan for time_i,features_i in features.groupby('time'): logging.debug(str(time_i)) indeces=combinations(features_i.index.values,2) #Loop over combinations to remove features that are closer together than min_distance and keep larger one (either higher threshold or larger area) distances=[] for index_1,index_2 in indeces: if index_1 is not index_2: distance=calculate_distance(features_i.loc[index_1],features_i.loc[index_2],method_distance=method_distance) distances.append(pd.DataFrame({'index_1':index_1,'index_2':index_2,'distance': distance}, index=[0])) if any([x is not None for x in distances]): distances=pd.concat(distances, ignore_index=True) for i in features_i.index: min_distance=distances.loc[(distances['index_1']==i) | (distances['index_2']==i),'distance'].min() features.at[i,'min_distance']=min_distance return features def nearestneighbordistance_histogram(features,bin_edges=np.arange(0,30000,500),density=False,method_distance=None,return_values=False): if 'min_distance' not in features.columns: logging.debug('calculate nearest neighbor distances') features=calculate_nearestneighbordistance(features,method_distance=method_distance) distances=features['min_distance'].values hist, bin_edges = np.histogram(distances[~np.isnan(distances)], bin_edges,density=density) if return_values: return hist,bin_edges,distances else: return hist,bin_edges # Treatment of 2D lat/lon coordinates to be added: # def calculate_areas_2Dlatlon(latitude_coord,longitude_coord): # lat=latitude_coord.core_data() # lon=longitude_coord.core_data() # area=np.zeros(lat.shape) # dx=np.zeros(lat.shape) # dy=np.zeros(lat.shape) # return area def calculate_area(features,mask,method_area=None): from tobac.utils import mask_features_surface,mask_features from iris import Constraint from iris.analysis.cartography import area_weights features['area']=np.nan mask_coords=[coord.name() for coord in mask.coords()] if method_area is None: if ('projection_x_coordinate' in mask_coords) and ('projection_y_coordinate' in mask_coords): method_area='xy' elif ('latitude' in mask_coords) and ('longitude' in mask_coords): method_area='latlon' else: raise ValueError('either latitude/longitude or projection_x_coordinate/projection_y_coordinate have to be present to calculate distances') logging.debug('calculating area using method '+ method_area) if method_area=='xy': if not (mask.coord('projection_x_coordinate').has_bounds() and mask.coord('projection_y_coordinate').has_bounds()): mask.coord('projection_x_coordinate').guess_bounds() mask.coord('projection_y_coordinate').guess_bounds() area=np.outer(np.diff(mask.coord('projection_x_coordinate').bounds,axis=1),np.diff(mask.coord('projection_y_coordinate').bounds,axis=1)) elif method_area=='latlon': if (mask.coord('latitude').ndim==1) and (mask.coord('latitude').ndim==1): if not (mask.coord('latitude').has_bounds() and mask.coord('longitude').has_bounds()): mask.coord('latitude').guess_bounds() mask.coord('longitude').guess_bounds() area=area_weights(mask,normalize=False) elif mask.coord('latitude').ndim==2 and mask.coord('longitude').ndim==2: raise ValueError('2D latitude/longitude coordinates not supported yet') # area=calculate_areas_2Dlatlon(mask.coord('latitude'),mask.coord('longitude')) else: raise ValueError('latitude/longitude coordinate shape not supported') else: raise ValueError('method undefined') for time_i,features_i in features.groupby('time'): logging.debug('timestep:'+ str(time_i)) constraint_time = Constraint(time=time_i) mask_i=mask.extract(constraint_time) for i in features_i.index: if len(mask_i.shape)==3: mask_i_surface = mask_features_surface(mask_i, features_i.loc[i,'feature'], z_coord='model_level_number') elif len(mask_i.shape)==2: mask_i_surface=mask_features(mask_i,features_i.loc[i,'feature']) area_feature=np.sum(area*(mask_i_surface.data>0)) features.at[i,'area']=area_feature return features def area_histogram(features,mask,bin_edges=np.arange(0,30000,500), density=False,method_area=None, return_values=False,representative_area=False): if 'area' not in features.columns: logging.info('calculate area') features=calculate_area(features,method_area) areas=features['area'].values # restrict to non NaN values: areas=areas[~np.isnan(areas)] if representative_area: weights=areas else: weights=None hist, bin_edges = np.histogram(areas, bin_edges,density=density,weights=weights) bin_centers=bin_edges[:-1]+0.5*np.diff(bin_edges) if return_values: return hist,bin_edges,bin_centers,areas else: return hist,bin_edges,bin_centers def histogram_cellwise(Track,variable=None,bin_edges=None,quantity='max',density=False): Track_cell=Track.groupby('cell') if quantity=='max': variable_cell=Track_cell[variable].max().values elif quantity=='min': variable_cell=Track_cell[variable].min().values elif quantity=='mean': variable_cell=Track_cell[variable].mean().values else: raise ValueError('quantity unknown, must be max, min or mean') hist, bin_edges = np.histogram(variable_cell, bin_edges,density=density) bin_centers=bin_edges[:-1]+0.5*np.diff(bin_edges) return hist,bin_edges, bin_centers def histogram_featurewise(Track,variable=None,bin_edges=None,density=False): hist, bin_edges = np.histogram(Track[variable].values, bin_edges,density=density) bin_centers=bin_edges[:-1]+0.5*np.diff(bin_edges) return hist,bin_edges, bin_centers def calculate_overlap(track_1,track_2,min_sum_inv_distance=None,min_mean_inv_distance=None): cells_1=track_1['cell'].unique() # n_cells_1_tot=len(cells_1) cells_2=track_2['cell'].unique() overlap=pd.DataFrame() for i_cell_1,cell_1 in enumerate(cells_1): for cell_2 in cells_2: track_1_i=track_1[track_1['cell']==cell_1] track_2_i=track_2[track_2['cell']==cell_2] track_1_i=track_1_i[track_1_i['time'].isin(track_2_i['time'])] track_2_i=track_2_i[track_2_i['time'].isin(track_1_i['time'])] if not track_1_i.empty: n_overlap=len(track_1_i) distances=[] for i in range(len(track_1_i)): distance=calculate_distance(track_1_i.iloc[[i]],track_2_i.iloc[[i]],method_distance='xy') distances.append(distance) # mean_distance=np.mean(distances) mean_inv_distance=np.mean(1/(1+np.array(distances)/1000)) # mean_inv_squaredistance=np.mean(1/(1+(np.array(distances)/1000)**2)) sum_inv_distance=np.sum(1/(1+np.array(distances)/1000)) # sum_inv_squaredistance=np.sum(1/(1+(np.array(distances)/1000)**2)) overlap=overlap.append({'cell_1':cell_1, 'cell_2':cell_2, 'n_overlap':n_overlap, # 'mean_distance':mean_distance, 'mean_inv_distance':mean_inv_distance, # 'mean_inv_squaredistance':mean_inv_squaredistance, 'sum_inv_distance':sum_inv_distance, # 'sum_inv_squaredistance':sum_inv_squaredistance },ignore_index=True) if min_sum_inv_distance: overlap=overlap[(overlap['sum_inv_distance']>=min_sum_inv_distance)] if min_mean_inv_distance: overlap=overlap[(overlap['mean_inv_distance']>=min_mean_inv_distance)] return overlap<file_sep>import datetime import numpy as np from xarray import DataArray def make_simple_sample_data_2D(data_type='iris'): """ function creating a simple dataset to use in tests for tobac. The grid has a grid spacing of 1km in both horizontal directions and 100 grid cells in x direction and 500 in y direction. Time resolution is 1 minute and the total length of the dataset is 100 minutes around a abritraty date (2000-01-01 12:00). The longitude and latitude coordinates are added as 2D aux coordinates and arbitrary, but in realisitic range. The data contains a single blob travelling on a linear trajectory through the dataset for part of the time. :param data_type: 'iris' or 'xarray' to chose the type of dataset to produce :return: sample dataset as an Iris.Cube.cube or xarray.DataArray """ from iris.cube import Cube from iris.coords import DimCoord,AuxCoord t_0=datetime.datetime(2000,1,1,12,0,0) x=np.arange(0,100e3,1000) y=np.arange(0,50e3,1000) t=t_0+np.arange(0,100,1)*datetime.timedelta(minutes=1) xx,yy=np.meshgrid(x,y) t_temp=np.arange(0,60,1) track1_t=t_0+t_temp*datetime.timedelta(minutes=1) x_0_1=10e3 y_0_1=10e3 track1_x=x_0_1+30*t_temp*60 track1_y=y_0_1+14*t_temp*60 track1_magnitude=10*np.ones(track1_x.shape) data=np.zeros((t.shape[0],y.shape[0],x.shape[0])) for i_t,t_i in enumerate(t): if np.any(t_i in track1_t): x_i=track1_x[track1_t==t_i] y_i=track1_y[track1_t==t_i] mag_i=track1_magnitude[track1_t==t_i] data[i_t]=data[i_t]+mag_i*np.exp(-np.power(xx - x_i,2.) / (2 * np.power(10e3, 2.)))*np.exp(-np.power(yy - y_i, 2.) / (2 * np.power(10e3, 2.))) t_start=datetime.datetime(1970,1,1,0,0) t_points=(t-t_start).astype("timedelta64[ms]").astype(int) / 1000 t_coord=DimCoord(t_points,standard_name='time',var_name='time',units='seconds since 1970-01-01 00:00') x_coord=DimCoord(x,standard_name='projection_x_coordinate',var_name='x',units='m') y_coord=DimCoord(y,standard_name='projection_y_coordinate',var_name='y',units='m') lat_coord=AuxCoord(24+1e-5*xx,standard_name='latitude',var_name='latitude',units='degree') lon_coord=AuxCoord(150+1e-5*yy,standard_name='longitude',var_name='longitude',units='degree') sample_data=Cube(data,dim_coords_and_dims=[(t_coord, 0),(y_coord, 1),(x_coord, 2)],aux_coords_and_dims=[(lat_coord, (1,2)),(lon_coord, (1,2))],var_name='w',units='m s-1') if data_type=='xarray': sample_data=DataArray.from_iris(sample_data) return sample_data def make_sample_data_2D_3blobs(data_type='iris'): from iris.cube import Cube from iris.coords import DimCoord,AuxCoord """ function creating a simple dataset to use in tests for tobac. The grid has a grid spacing of 1km in both horizontal directions and 100 grid cells in x direction and 200 in y direction. Time resolution is 1 minute and the total length of the dataset is 100 minutes around a abritraty date (2000-01-01 12:00). The longitude and latitude coordinates are added as 2D aux coordinates and arbitrary, but in realisitic range. The data contains a three individual blobs travelling on a linear trajectory through the dataset for part of the time. :param data_type: 'iris' or 'xarray' to chose the type of dataset to produce :return: sample dataset as an Iris.Cube.cube or xarray.DataArray """ t_0=datetime.datetime(2000,1,1,12,0,0) x=np.arange(0,100e3,1000) y=np.arange(0,200e3,1000) t=t_0+np.arange(0,100,1)*datetime.timedelta(minutes=1) xx,yy=np.meshgrid(x,y) t_temp=np.arange(0,60,1) track1_t=t_0+t_temp*datetime.timedelta(minutes=1) x_0_1=10e3 y_0_1=10e3 track1_x=x_0_1+30*t_temp*60 track1_y=y_0_1+14*t_temp*60 track1_magnitude=10*np.ones(track1_x.shape) t_temp=np.arange(0,30,1) track2_t=t_0+(t_temp+40)*datetime.timedelta(minutes=1) x_0_2=20e3 y_0_2=10e3 track2_x=x_0_2+24*(t_temp*60)**2/1000 track2_y=y_0_2+12*t_temp*60 track2_magnitude=20*np.ones(track2_x.shape) t_temp=np.arange(0,20,1) track3_t=t_0+(t_temp+50)*datetime.timedelta(minutes=1) x_0_3=70e3 y_0_3=110e3 track3_x=x_0_3+20*(t_temp*60)**2/1000 track3_y=y_0_3+20*t_temp*60 track3_magnitude=15*np.ones(track3_x.shape) data=np.zeros((t.shape[0],y.shape[0],x.shape[0])) for i_t,t_i in enumerate(t): if np.any(t_i in track1_t): x_i=track1_x[track1_t==t_i] y_i=track1_y[track1_t==t_i] mag_i=track1_magnitude[track1_t==t_i] data[i_t]=data[i_t]+mag_i*np.exp(-np.power(xx - x_i,2.) / (2 * np.power(10e3, 2.)))*np.exp(-np.power(yy - y_i, 2.) / (2 * np.power(10e3, 2.))) if np.any(t_i in track2_t): x_i=track2_x[track2_t==t_i] y_i=track2_y[track2_t==t_i] mag_i=track2_magnitude[track2_t==t_i] data[i_t]=data[i_t]+mag_i*np.exp(-np.power(xx - x_i,2.) / (2 * np.power(10e3, 2.)))*np.exp(-np.power(yy - y_i, 2.) / (2 * np.power(10e3, 2.))) if np.any(t_i in track3_t): x_i=track3_x[track3_t==t_i] y_i=track3_y[track3_t==t_i] mag_i=track3_magnitude[track3_t==t_i] data[i_t]=data[i_t]+mag_i*np.exp(-np.power(xx - x_i,2.) / (2 * np.power(10e3, 2.)))*np.exp(-np.power(yy - y_i, 2.) / (2 * np.power(10e3, 2.)))\ t_start=datetime.datetime(1970,1,1,0,0) t_points=(t-t_start).astype("timedelta64[ms]").astype(int) / 1000 t_coord=DimCoord(t_points,standard_name='time',var_name='time',units='seconds since 1970-01-01 00:00') x_coord=DimCoord(x,standard_name='projection_x_coordinate',var_name='x',units='m') y_coord=DimCoord(y,standard_name='projection_y_coordinate',var_name='y',units='m') lat_coord=AuxCoord(24+1e-5*xx,standard_name='latitude',var_name='latitude',units='degree') lon_coord=AuxCoord(150+1e-5*yy,standard_name='longitude',var_name='longitude',units='degree') sample_data=Cube(data,dim_coords_and_dims=[(t_coord, 0),(y_coord, 1),(x_coord, 2)],aux_coords_and_dims=[(lat_coord, (1,2)),(lon_coord, (1,2))],var_name='w',units='m s-1') if data_type=='xarray': sample_data=DataArray.from_iris(sample_data) return sample_data def make_sample_data_2D_3blobs_inv(data_type='iris'): """ function creating a version of the dataset created in the function make_sample_cube_2D, but with switched coordinate order for the horizontal coordinates for tests to ensure that this does not affect the results :param data_type: 'iris' or 'xarray' to chose the type of dataset to produce :return: sample dataset as an Iris.Cube.cube or xarray.DataArray """ from iris.cube import Cube from iris.coords import DimCoord,AuxCoord t_0=datetime.datetime(2000,1,1,12,0,0) x=np.arange(0,100e3,1000) y=np.arange(0,200e3,1000) t=t_0+np.arange(0,100,1)*datetime.timedelta(minutes=1) yy,xx=np.meshgrid(y,x) t_temp=np.arange(0,60,1) track1_t=t_0+t_temp*datetime.timedelta(minutes=1) x_0_1=10e3 y_0_1=10e3 track1_x=x_0_1+30*t_temp*60 track1_y=y_0_1+14*t_temp*60 track1_magnitude=10*np.ones(track1_x.shape) t_temp=np.arange(0,30,1) track2_t=t_0+(t_temp+40)*datetime.timedelta(minutes=1) x_0_2=20e3 y_0_2=10e3 track2_x=x_0_2+24*(t_temp*60)**2/1000 track2_y=y_0_2+12*t_temp*60 track2_magnitude=20*np.ones(track2_x.shape) t_temp=np.arange(0,20,1) track3_t=t_0+(t_temp+50)*datetime.timedelta(minutes=1) x_0_3=70e3 y_0_3=110e3 track3_x=x_0_3+20*(t_temp*60)**2/1000 track3_y=y_0_3+20*t_temp*60 track3_magnitude=15*np.ones(track3_x.shape) data=np.zeros((t.shape[0],x.shape[0],y.shape[0])) for i_t,t_i in enumerate(t): if np.any(t_i in track1_t): x_i=track1_x[track1_t==t_i] y_i=track1_y[track1_t==t_i] mag_i=track1_magnitude[track1_t==t_i] data[i_t]=data[i_t]+mag_i*np.exp(-np.power(xx - x_i,2.) / (2 * np.power(10e3, 2.)))*np.exp(-np.power(yy - y_i, 2.) / (2 * np.power(10e3, 2.))) if np.any(t_i in track2_t): x_i=track2_x[track2_t==t_i] y_i=track2_y[track2_t==t_i] mag_i=track2_magnitude[track2_t==t_i] data[i_t]=data[i_t]+mag_i*np.exp(-np.power(xx - x_i,2.) / (2 * np.power(10e3, 2.)))*np.exp(-np.power(yy - y_i, 2.) / (2 * np.power(10e3, 2.))) if np.any(t_i in track3_t): x_i=track3_x[track3_t==t_i] y_i=track3_y[track3_t==t_i] mag_i=track3_magnitude[track3_t==t_i] data[i_t]=data[i_t]+mag_i*np.exp(-np.power(xx - x_i,2.) / (2 * np.power(10e3, 2.)))*np.exp(-np.power(yy - y_i, 2.) / (2 * np.power(10e3, 2.))) t_start=datetime.datetime(1970,1,1,0,0) t_points=(t-t_start).astype("timedelta64[ms]").astype(int) / 1000 t_coord=DimCoord(t_points,standard_name='time',var_name='time',units='seconds since 1970-01-01 00:00') x_coord=DimCoord(x,standard_name='projection_x_coordinate',var_name='x',units='m') y_coord=DimCoord(y,standard_name='projection_y_coordinate',var_name='y',units='m') lat_coord=AuxCoord(24+1e-5*xx,standard_name='latitude',var_name='latitude',units='degree') lon_coord=AuxCoord(150+1e-5*yy,standard_name='longitude',var_name='longitude',units='degree') sample_data=Cube(data,dim_coords_and_dims=[(t_coord, 0),(y_coord, 2),(x_coord, 1)],aux_coords_and_dims=[(lat_coord, (1,2)),(lon_coord, (1,2))],var_name='w',units='m s-1') if data_type=='xarray': sample_data=DataArray.from_iris(sample_data) return sample_data def make_sample_data_3D_3blobs(data_type='iris',invert_xy=False): from iris.cube import Cube from iris.coords import DimCoord,AuxCoord """ function creating a simple dataset to use in tests for tobac. The grid has a grid spacing of 1km in both horizontal directions and 100 grid cells in x direction and 200 in y direction. Time resolution is 1 minute and the total length of the dataset is 100 minutes around a abritraty date (2000-01-01 12:00). The longitude and latitude coordinates are added as 2D aux coordinates and arbitrary, but in realisitic range. The data contains a three individual blobs travelling on a linear trajectory through the dataset for part of the time. :param data_type: 'iris' or 'xarray' to chose the type of dataset to produce :return: sample dataset as an Iris.Cube.cube or xarray.DataArray """ t_0=datetime.datetime(2000,1,1,12,0,0) x=np.arange(0,100e3,1000) y=np.arange(0,200e3,1000) z=np.arange(0,20e3,1000) t=t_0+np.arange(0,50,2)*datetime.timedelta(minutes=1) t_temp=np.arange(0,60,1) track1_t=t_0+t_temp*datetime.timedelta(minutes=1) x_0_1=10e3 y_0_1=10e3 z_0_1=4e3 track1_x=x_0_1+30*t_temp*60 track1_y=y_0_1+14*t_temp*60 track1_magnitude=10*np.ones(track1_x.shape) t_temp=np.arange(0,30,1) track2_t=t_0+(t_temp+40)*datetime.timedelta(minutes=1) x_0_2=20e3 y_0_2=10e3 z_0_2=6e3 track2_x=x_0_2+24*(t_temp*60)**2/1000 track2_y=y_0_2+12*t_temp*60 track2_magnitude=20*np.ones(track2_x.shape) t_temp=np.arange(0,20,1) track3_t=t_0+(t_temp+50)*datetime.timedelta(minutes=1) x_0_3=70e3 y_0_3=110e3 z_0_3=8e3 track3_x=x_0_3+20*(t_temp*60)**2/1000 track3_y=y_0_3+20*t_temp*60 track3_magnitude=15*np.ones(track3_x.shape) if invert_xy==False: zz,yy,xx=np.meshgrid(z,y,x,indexing='ij') y_dim=2 x_dim=3 data=np.zeros((t.shape[0],z.shape[0],y.shape[0],x.shape[0])) else: zz,xx,yy=np.meshgrid(z,x,y,indexing='ij') x_dim=2 y_dim=3 data=np.zeros((t.shape[0],z.shape[0],x.shape[0],y.shape[0])) for i_t,t_i in enumerate(t): if np.any(t_i in track1_t): x_i=track1_x[track1_t==t_i] y_i=track1_y[track1_t==t_i] z_i=z_0_1 mag_i=track1_magnitude[track1_t==t_i] data[i_t]=data[i_t]+mag_i*np.exp(-np.power(xx - x_i,2.) / (2 * np.power(10e3, 2.)))\ *np.exp(-np.power(yy - y_i, 2.) / (2 * np.power(10e3, 2.)))\ *np.exp(-np.power(zz - z_i, 2.) / (2 * np.power(5e3, 2.))) if np.any(t_i in track2_t): x_i=track2_x[track2_t==t_i] y_i=track2_y[track2_t==t_i] z_i=z_0_2 mag_i=track2_magnitude[track2_t==t_i] data[i_t]=data[i_t]+mag_i*np.exp(-np.power(xx - x_i,2.) / (2 * np.power(10e3, 2.)))\ *np.exp(-np.power(yy - y_i, 2.) / (2 * np.power(10e3, 2.)))\ *np.exp(-np.power(zz - z_i, 2.) / (2 * np.power(5e3, 2.))) if np.any(t_i in track3_t): x_i=track3_x[track3_t==t_i] y_i=track3_y[track3_t==t_i] z_i=z_0_3 mag_i=track3_magnitude[track3_t==t_i] data[i_t]=data[i_t]+mag_i*np.exp(-np.power(xx - x_i,2.) / (2 * np.power(10e3, 2.)))\ *np.exp(-np.power(yy - y_i, 2.) / (2 * np.power(10e3, 2.)))\ *np.exp(-np.power(zz - z_i, 2.) / (2 * np.power(5e3, 2.))) t_start=datetime.datetime(1970,1,1,0,0) t_points=(t-t_start).astype("timedelta64[ms]").astype(int) / 1000 t_coord=DimCoord(t_points,standard_name='time',var_name='time',units='seconds since 1970-01-01 00:00') z_coord=DimCoord(z,standard_name='geopotential_height',var_name='z',units='m') y_coord=DimCoord(y,standard_name='projection_y_coordinate',var_name='y',units='m') x_coord=DimCoord(x,standard_name='projection_x_coordinate',var_name='x',units='m') lat_coord=AuxCoord(24+1e-5*xx[0],standard_name='latitude',var_name='latitude',units='degree') lon_coord=AuxCoord(150+1e-5*yy[0],standard_name='longitude',var_name='longitude',units='degree') sample_data=Cube(data,dim_coords_and_dims=[(t_coord, 0),(z_coord, 1),(y_coord, y_dim),(x_coord, x_dim)],aux_coords_and_dims=[(lat_coord, (2,3)),(lon_coord, (2,3))],var_name='w',units='m s-1') if data_type=='xarray': sample_data=DataArray.from_iris(sample_data) return sample_data <file_sep>import logging import numpy as np import pandas as pd def linking_trackpy(features,field_in,dt,dxy, v_max=None,d_max=None,d_min=None,subnetwork_size=None, memory=0,stubs=1,time_cell_min=None, order=1,extrapolate=0, method_linking='random', adaptive_step=None,adaptive_stop=None, cell_number_start=1 ): """ Function to perform the linking of features in trajectories Parameters: features: pandas.DataFrame Detected features to be linked v_max: float speed at which features are allowed to move dt: float time resolution of tracked features dxy: float grid spacing of input data memory int number of output timesteps features allowed to vanish for to be still considered tracked subnetwork_size int maximim size of subnetwork for linking method_detection: str('trackpy' or 'threshold') flag choosing method used for feature detection method_linking: str('predict' or 'random') flag choosing method used for trajectory linking """ # from trackpy import link_df import trackpy as tp from copy import deepcopy # from trackpy import filter_stubs # from .utils import add_coordinates # calculate search range based on timestep and grid spacing if v_max is not None: search_range=int(dt*v_max/dxy) # calculate search range based on timestep and grid spacing if d_max is not None: search_range=int(d_max/dxy) # calculate search range based on timestep and grid spacing if d_min is not None: search_range=max(search_range,int(d_min/dxy)) if time_cell_min: stubs=np.floor(time_cell_min/dt)+1 logging.debug('stubs: '+ str(stubs)) logging.debug('start linking features into trajectories') #If subnetwork size given, set maximum subnet size if subnetwork_size is not None: tp.linking.Linker.MAX_SUB_NET_SIZE=subnetwork_size # deep copy to preserve features field: features_linking=deepcopy(features) if method_linking is 'random': # link features into trajectories: trajectories_unfiltered = tp.link(features_linking, search_range=search_range, memory=memory, t_column='frame', pos_columns=['hdim_2','hdim_1'], adaptive_step=adaptive_step,adaptive_stop=adaptive_stop, neighbor_strategy='KDTree', link_strategy='auto' ) elif method_linking is 'predict': pred = tp.predict.NearestVelocityPredict(span=1) trajectories_unfiltered = pred.link_df(features_linking, search_range=search_range, memory=memory, pos_columns=['hdim_1','hdim_2'], t_column='frame', neighbor_strategy='KDTree', link_strategy='auto', adaptive_step=adaptive_step,adaptive_stop=adaptive_stop # copy_features=False, diagnostics=False, # hash_size=None, box_size=None, verify_integrity=True, # retain_index=False ) else: raise ValueError('method_linking unknown') # Filter trajectories to exclude short trajectories that are likely to be spurious # trajectories_filtered = filter_stubs(trajectories_unfiltered,threshold=stubs) # trajectories_filtered=trajectories_filtered.reset_index(drop=True) # Reset particle numbers from the arbitray numbers at the end of the feature detection and linking to consecutive cell numbers # keep 'particle' for reference to the feature detection step. trajectories_unfiltered['cell']=None for i_particle,particle in enumerate(pd.Series.unique(trajectories_unfiltered['particle'])): cell=int(i_particle+cell_number_start) trajectories_unfiltered.loc[trajectories_unfiltered['particle']==particle,'cell']=cell trajectories_unfiltered.drop(columns=['particle'],inplace=True) trajectories_bycell=trajectories_unfiltered.groupby('cell') for cell,trajectories_cell in trajectories_bycell: logging.debug("cell: "+str(cell)) logging.debug("feature: "+str(trajectories_cell['feature'].values)) logging.debug("trajectories_cell.shape[0]: "+ str(trajectories_cell.shape[0])) if trajectories_cell.shape[0] < stubs: logging.debug("cell" + str(cell)+ " is a stub ("+str(trajectories_cell.shape[0])+ "), setting cell number to Nan..") trajectories_unfiltered.loc[trajectories_unfiltered['cell']==cell,'cell']=np.nan trajectories_filtered=trajectories_unfiltered #Interpolate to fill the gaps in the trajectories (left from allowing memory in the linking) trajectories_filtered_unfilled=deepcopy(trajectories_filtered) # trajectories_filtered_filled=fill_gaps(trajectories_filtered_unfilled,order=order, # extrapolate=extrapolate,frame_max=field_in.shape[0]-1, # hdim_1_max=field_in.shape[1],hdim_2_max=field_in.shape[2]) # add coorinates from input fields to output trajectories (time,dimensions) # logging.debug('start adding coordinates to trajectories') # trajectories_filtered_filled=add_coordinates(trajectories_filtered_filled,field_in) # add time coordinate relative to cell initiation: # logging.debug('start adding cell time to trajectories') trajectories_filtered_filled=trajectories_filtered_unfilled trajectories_final=add_cell_time(trajectories_filtered_filled) # add coordinate to raw features identified: logging.debug('start adding coordinates to detected features') logging.debug('feature linking completed') return trajectories_final def fill_gaps(t,order=1,extrapolate=0,frame_max=None,hdim_1_max=None,hdim_2_max=None): ''' add cell time as time since the initiation of each cell Input: t: pandas dataframe trajectories from trackpy order: int Order of polynomial used to extrapolate trajectory into gaps and beyond start and end point extrapolate int number of timesteps to extrapolate trajectories by frame_max: int size of input data along time axis hdim_1_max: int size of input data along first horizontal axis hdim_2_max: int size of input data along second horizontal axis Output: t: pandas dataframe trajectories from trackpy with with filled gaps and potentially extrapolated ''' from scipy.interpolate import InterpolatedUnivariateSpline logging.debug('start filling gaps') t_list=[] # empty list to store interpolated DataFrames # group by cell number and perform process for each cell individually: t_grouped=t.groupby('cell') for cell,track in t_grouped: # Setup interpolator from existing points (of order given as keyword) frame_in=track['frame'].values hdim_1_in=track['hdim_1'].values hdim_2_in=track['hdim_2'].values s_x = InterpolatedUnivariateSpline(frame_in, hdim_1_in, k=order) s_y = InterpolatedUnivariateSpline(frame_in, hdim_2_in, k=order) # Create new index filling in gaps and possibly extrapolating: index_min=min(frame_in)-extrapolate index_min=max(index_min,0) index_max=max(frame_in)+extrapolate index_max=min(index_max,frame_max) new_index=range(index_min,index_max+1) # +1 here to include last value track=track.reindex(new_index) # Interpolate to extended index: frame_out=new_index hdim_1_out=s_x(frame_out) hdim_2_out=s_y(frame_out) # Replace fields in data frame with track['frame']=new_index track['hdim_1']=hdim_1_out track['hdim_2']=hdim_2_out track['cell']=cell # Append DataFrame to list of DataFrames t_list.append(track) # Concatenate interpolated trajectories into one DataFrame: t_out=pd.concat(t_list) # Restrict output trajectories to input data in time and space: t_out=t_out.loc[(t_out['hdim_1']<hdim_1_max) & (t_out['hdim_2']<hdim_2_max) &(t_out['hdim_1']>0) & (t_out['hdim_2']>0)] t_out=t_out.reset_index(drop=True) return t_out def add_cell_time(t): ''' add cell time as time since the initiation of each cell Input: t: pandas DataFrame trajectories with added coordinates Output: t: pandas dataframe trajectories with added cell time ''' logging.debug('start adding time relative to cell initiation') t_grouped=t.groupby('cell') t['time_cell']=np.nan for cell,track in t_grouped: track_0=track.head(n=1) for i,row in track.iterrows(): t.loc[i,'time_cell']=row['time']-track_0.loc[track_0.index[0],'time'] # turn series into pandas timedelta DataSeries t['time_cell']=pd.to_timedelta(t['time_cell']) return t <file_sep>import pytest import tobac def test_dummy_function(): assert 1==1 <file_sep>#from .tracking import maketrack from .segmentation import segmentation_3D, segmentation_2D,watershedding_3D,watershedding_2D from .centerofgravity import calculate_cog,calculate_cog_untracked,calculate_cog_domain from .plotting import plot_tracks_mask_field,plot_tracks_mask_field_loop,plot_mask_cell_track_follow,plot_mask_cell_track_static,plot_mask_cell_track_static_timeseries from .plotting import plot_lifetime_histogram,plot_lifetime_histogram_bar,plot_histogram_cellwise,plot_histogram_featurewise from .plotting import plot_mask_cell_track_3Dstatic,plot_mask_cell_track_2D3Dstatic from .plotting import plot_mask_cell_individual_static,plot_mask_cell_individual_3Dstatic from .plotting import animation_mask_field from .plotting import make_map, map_tracks from .analysis import cell_statistics,cog_cell,lifetime_histogram,histogram_featurewise,histogram_cellwise from .analysis import calculate_velocity,calculate_distance,calculate_area from .analysis import calculate_nearestneighbordistance from .analysis import velocity_histogram,nearestneighbordistance_histogram,area_histogram from .analysis import calculate_overlap from .utils import mask_cell,mask_cell_surface,mask_cube_cell,mask_cube_untracked,mask_cube,column_mask_from2D,get_bounding_box from .utils import mask_features,mask_features_surface,mask_cube_features from .utils import add_coordinates,get_spacings from .feature_detection import feature_detection_multithreshold from .tracking import linking_trackpy from .wrapper import maketrack from .wrapper import tracking_wrapper <file_sep>import logging def calculate_cog(tracks,mass,mask): ''' caluclate centre of gravity and mass forech individual tracked cell in the simulation Input: tracks: pandas.DataFrame DataFrame containing trajectories of cell centres mass: iris.cube.Cube cube of quantity (need coordinates 'time', 'geopotential_height','projection_x_coordinate' and 'projection_y_coordinate') mask: iris.cube.Cube cube containing mask (int > where belonging to cloud volume, 0 everywhere else ) Output: tracks_out pandas.DataFrame Dataframe containing t,x,y,z positions of centre of gravity and total cloud mass each tracked cells at each timestep ''' from .utils import mask_cube_cell from iris import Constraint logging.info('start calculating centre of gravity for tracked cells') tracks_out=tracks[['time','frame','cell','time_cell']] for i_row,row in tracks_out.iterrows(): cell=row['cell'] constraint_time=Constraint(time=row['time']) mass_i=mass.extract(constraint_time) mask_i=mask.extract(constraint_time) mass_masked_i=mask_cube_cell(mass_i,mask_i,cell) x_M,y_M,z_M,mass_M=center_of_gravity(mass_masked_i) tracks_out.loc[i_row,'x_M']=float(x_M) tracks_out.loc[i_row,'y_M']=float(y_M) tracks_out.loc[i_row,'z_M']=float(z_M) tracks_out.loc[i_row,'mass']=float(mass_M) logging.info('Finished calculating centre of gravity for tracked cells') return tracks_out def calculate_cog_untracked(mass,mask): ''' caluclate centre of gravity and mass for untracked parts of domain Input: mass: iris.cube.Cube cube of quantity (need coordinates 'time', 'geopotential_height','projection_x_coordinate' and 'projection_y_coordinate') mask: iris.cube.Cube cube containing mask (int > where belonging to cloud volume, 0 everywhere else ) Output: tracks_out pandas.DataFrame Dataframe containing t,x,y,z positions of centre of gravity and total cloud mass for untracked part of dimain ''' from pandas import DataFrame from .utils import mask_cube_untracked from iris import Constraint logging.info('start calculating centre of gravity for untracked parts of the domain') tracks_out=DataFrame() time_coord=mass.coord('time') tracks_out['frame']=range(len(time_coord.points)) for i_row,row in tracks_out.iterrows(): time_i=time_coord.units.num2date(time_coord[int(row['frame'])].points[0]) constraint_time=Constraint(time=time_i) mass_i=mass.extract(constraint_time) mask_i=mask.extract(constraint_time) mass_untracked_i=mask_cube_untracked(mass_i,mask_i) x_M,y_M,z_M,mass_M=center_of_gravity(mass_untracked_i) tracks_out.loc[i_row,'time']=time_i tracks_out.loc[i_row,'x_M']=float(x_M) tracks_out.loc[i_row,'y_M']=float(y_M) tracks_out.loc[i_row,'z_M']=float(z_M) tracks_out.loc[i_row,'mass']=float(mass_M) logging.info('Finished calculating centre of gravity for untracked parts of the domain') return tracks_out def calculate_cog_domain(mass): ''' caluclate centre of gravity and mass for entire domain Input: mass: iris.cube.Cube cube of quantity (need coordinates 'time', 'geopotential_height','projection_x_coordinate' and 'projection_y_coordinate') Output: tracks_out pandas.DataFrame Dataframe containing t,x,y,z positions of centre of gravity and total cloud mass ''' from pandas import DataFrame from iris import Constraint logging.info('start calculating centre of gravity for entire domain') time_coord=mass.coord('time') tracks_out=DataFrame() tracks_out['frame']=range(len(time_coord.points)) for i_row,row in tracks_out.iterrows(): time_i=time_coord.units.num2date(time_coord[int(row['frame'])].points[0]) constraint_time=Constraint(time=time_i) mass_i=mass.extract(constraint_time) x_M,y_M,z_M,mass_M=center_of_gravity(mass_i) tracks_out.loc[i_row,'time']=time_i tracks_out.loc[i_row,'x_M']=float(x_M) tracks_out.loc[i_row,'y_M']=float(y_M) tracks_out.loc[i_row,'z_M']=float(z_M) tracks_out.loc[i_row,'mass']=float(mass_M) logging.info('Finished calculating centre of gravity for entire domain') return tracks_out def center_of_gravity(cube_in): ''' caluclate centre of gravity and sum of quantity Input: cube_in: iris.cube.Cube cube (potentially masked) of quantity (need coordinates 'geopotential_height','projection_x_coordinate' and 'projection_y_coordinate') Output: x: float x position of centre of gravity y: float y position of centre of gravity z: float z position of centre of gravity variable_sum: float sum of quantity of over unmasked part of the cube ''' from iris.analysis import SUM import numpy as np cube_sum=cube_in.collapsed(['bottom_top','south_north','west_east'],SUM) z=cube_in.coord('geopotential_height') x=cube_in.coord('projection_x_coordinate') y=cube_in.coord('projection_y_coordinate') dimensions_collapse=['model_level_number','x','y'] for coord in cube_in.coords(): if (coord.ndim>1 and (cube_in.coord_dims(dimensions_collapse[0])[0] in cube_in.coord_dims(coord) or cube_in.coord_dims(dimensions_collapse[1])[0] in cube_in.coord_dims(coord) or cube_in.coord_dims(dimensions_collapse[2])[0] in cube_in.coord_dims(coord))): cube_in.remove_coord(coord.name()) if cube_sum.data > 0: x=((cube_in*x).collapsed(['model_level_number','x','y'],SUM)/cube_sum).data y=((cube_in*y).collapsed(['model_level_number','x','y'],SUM)/cube_sum).data z=((cube_in*z.points).collapsed(['model_level_number','x','y'],SUM)/cube_sum).data else: x=np.nan y=np.nan z=np.nan variable_sum=cube_sum.data return(x,y,z,variable_sum) <file_sep>import logging def segmentation_3D(features,field,dxy,threshold=3e-3,target='maximum',level=None,method='watershed',max_distance=None): return segmentation(features,field,dxy,threshold=threshold,target=target,level=level,method=method,max_distance=max_distance) def segmentation_2D(features,field,dxy,threshold=3e-3,target='maximum',level=None,method='watershed',max_distance=None): return segmentation(features,field,dxy,threshold=threshold,target=target,level=level,method=method,max_distance=max_distance) def segmentation_timestep(field_in,features_in,dxy,threshold=3e-3,target='maximum',level=None,method='watershed',max_distance=None,vertical_coord='auto'): """ Function performing watershedding for an individual timestep of the data Parameters: features: pandas.DataFrame features for one specific point in time field: iris.cube.Cube input field to perform the watershedding on (2D or 3D for one specific point in time) threshold: float threshold for the watershedding field to be used for the mas target: string switch to determine if algorithm looks strating from maxima or minima in input field (maximum: starting from maxima (default), minimum: starting from minima) level slice levels at which to seed the cells for the watershedding algorithm method: string flag determining the algorithm to use (currently watershedding implemented) max_distance: float maximum distance from a marker allowed to be classified as belonging to that cell Output: segmentation_out: iris.cube.Cube cloud mask, 0 outside and integer numbers according to track inside the clouds features_out: pandas.DataFrame feature dataframe including the number of cells (2D or 3D) in the segmented area/volume of the feature at the timestep """ from skimage.morphology import watershed # from skimage.segmentation import random_walker from scipy.ndimage import distance_transform_edt from copy import deepcopy import numpy as np # copy feature dataframe for output features_out=deepcopy(features_in) # Create cube of the same dimensions and coordinates as input data to store mask: segmentation_out=1*field_in segmentation_out.rename('segmentation_mask') segmentation_out.units=1 #Create dask array from input data: data=field_in.core_data() #Set level at which to create "Seed" for each feature in the case of 3D watershedding: # If none, use all levels (later reduced to the ones fulfilling the theshold conditions) if level==None: level=slice(None) # transform max_distance in metres to distance in pixels: if max_distance is not None: max_distance_pixel=np.ceil(max_distance/dxy) # mask data outside region above/below threshold and invert data if tracking maxima: if target == 'maximum': unmasked=data>threshold data_segmentation=-1*data elif target == 'minimum': unmasked=data<threshold data_segmentation=data else: raise ValueError('unknown type of target') # set markers at the positions of the features: markers = np.zeros(unmasked.shape).astype(np.int32) if field_in.ndim==2: #2D watershedding for index, row in features_in.iterrows(): markers[int(row['hdim_1']), int(row['hdim_2'])]=row['feature'] elif field_in.ndim==3: #3D watershedding list_coord_names=[coord.name() for coord in field_in.coords()] #determine vertical axis: if vertical_coord=='auto': list_vertical=['z','model_level_number','altitude','geopotential_height'] for coord_name in list_vertical: if coord_name in list_coord_names: vertical_axis=coord_name break elif vertical_coord in list_coord_names: vertical_axis=vertical_coord else: raise ValueError('Plese specify vertical coordinate') ndim_vertical=field_in.coord_dims(vertical_axis) if len(ndim_vertical)>1: raise ValueError('please specify 1 dimensional vertical coordinate') for index, row in features_in.iterrows(): if ndim_vertical[0]==0: markers[:,int(row['hdim_1']), int(row['hdim_2'])]=row['feature'] elif ndim_vertical[0]==1: markers[int(row['hdim_1']),:, int(row['hdim_2'])]=row['feature'] elif ndim_vertical[0]==2: markers[int(row['hdim_1']), int(row['hdim_2']),:]=row['feature'] else: raise ValueError('Segmentations routine only possible with 2 or 3 spatial dimensions') # set markers in cells not fulfilling threshold condition to zero: markers[~unmasked]=0 # Turn into np arrays (not necessary for markers) as dask arrays don't yet seem to work for watershedding algorithm data_segmentation=np.array(data_segmentation) unmasked=np.array(unmasked) # perform segmentation: if method=='watershed': segmentation_mask = watershed(np.array(data_segmentation),markers.astype(np.int32), mask=unmasked) # elif method=='random_walker': # segmentation_mask=random_walker(data_segmentation, markers.astype(np.int32), # beta=130, mode='bf', tol=0.001, copy=True, multichannel=False, return_full_prob=False, spacing=None) else: raise ValueError('unknown method, must be watershed') # remove everything from the individual masks that is more than max_distance_pixel away from the markers if max_distance is not None: D=distance_transform_edt((markers==0).astype(int)) segmentation_mask[np.bitwise_and(segmentation_mask>0, D>max_distance_pixel)]=0 #Write resulting mask into cube for output segmentation_out.data=segmentation_mask # count number of grid cells asoociated to each tracked cell and write that into DataFrame: values, count = np.unique(segmentation_mask, return_counts=True) counts=dict(zip(values, count)) ncells=np.zeros(len(features_out)) for i,(index,row) in enumerate(features_out.iterrows()): if row['feature'] in counts.keys(): ncells=counts[row['feature']] features_out['ncells']=ncells return segmentation_out,features_out def segmentation(features,field,dxy,threshold=3e-3,target='maximum',level=None,method='watershed',max_distance=None,vertical_coord='auto'): """ Function using watershedding or random walker to determine cloud volumes associated with tracked updrafts Parameters: features: pandas.DataFrame output from trackpy/maketrack field: iris.cube.Cube containing the field to perform the watershedding on threshold: float threshold for the watershedding field to be used for the mask target: string Switch to determine if algorithm looks strating from maxima or minima in input field (maximum: starting from maxima (default), minimum: starting from minima) level slice levels at which to seed the cells for the watershedding algorithm method: str ('method') flag determining the algorithm to use (currently watershedding implemented) max_distance: float Maximum distance from a marker allowed to be classified as belonging to that cell Output: segmentation_out: iris.cube.Cube Cloud mask, 0 outside and integer numbers according to track inside the cloud """ import pandas as pd from iris.cube import CubeList logging.info('Start watershedding 3D') # check input for right dimensions: if not (field.ndim==3 or field.ndim==4): raise ValueError('input to segmentation step must be 3D or 4D including a time dimension') if 'time' not in [coord.name() for coord in field.coords()]: raise ValueError("input to segmentation step must include a dimension named 'time'") # CubeList and list to store individual segmentation masks and feature DataFrames with information about segmentation segmentation_out_list=CubeList() features_out_list=[] #loop over individual input timesteps for segmentation: field_time=field.slices_over('time') for i,field_i in enumerate(field_time): time_i=field_i.coord('time').units.num2date(field_i.coord('time').points[0]) features_i=features.loc[features['time']==time_i] segmentation_out_i,features_out_i=segmentation_timestep(field_i,features_i,dxy,threshold=threshold,target=target,level=level,method=method,max_distance=max_distance,vertical_coord=vertical_coord) segmentation_out_list.append(segmentation_out_i) features_out_list.append(features_out_i) logging.debug('Finished segmentation for '+time_i.strftime('%Y-%m-%d_%H:%M:%S')) #Merge output from individual timesteps: segmentation_out=segmentation_out_list.merge_cube() features_out=pd.concat(features_out_list) logging.debug('Finished segmentation') return segmentation_out,features_out def watershedding_3D(track,field_in,**kwargs): kwargs.pop('method',None) return segmentation_3D(track,field_in,method='watershed',**kwargs) def watershedding_2D(track,field_in,**kwargs): kwargs.pop('method',None) return segmentation_2D(track,field_in,method='watershed',**kwargs) <file_sep># Python dependencies numpy scipy scikit-image pandas pytables matplotlib iris cf-units xarray cartopy trackpy <file_sep>""" Tests for tobac based on simple sample datasets with moving blobs. These tests should be adapted to be more modular in the future. """ from tobac.testing import make_sample_data_2D_3blobs, make_sample_data_2D_3blobs_inv, make_sample_data_3D_3blobs from tobac import feature_detection_multithreshold,linking_trackpy,get_spacings,segmentation_2D, segmentation_3D from iris.analysis import MEAN,MAX,MIN from pandas.testing import assert_frame_equal from numpy.testing import assert_allclose import pandas as pd def test_sample_data(): """ Test to make sure that sample datasets in the following tests are set up the right way """ sample_data=make_sample_data_2D_3blobs() sample_data_inv=make_sample_data_2D_3blobs_inv() assert sample_data.coord('projection_x_coordinate')==sample_data_inv.coord('projection_x_coordinate') assert sample_data.coord('projection_y_coordinate')==sample_data_inv.coord('projection_y_coordinate') assert sample_data.coord('time')==sample_data_inv.coord('time') minimum=sample_data.collapsed(('time','projection_x_coordinate','projection_y_coordinate'),MIN).data minimum_inv=sample_data_inv.collapsed(('time','projection_x_coordinate','projection_y_coordinate'),MIN).data assert_allclose(minimum,minimum_inv) mean=sample_data.collapsed(('time','projection_x_coordinate','projection_y_coordinate'),MEAN).data mean_inv=sample_data_inv.collapsed(('time','projection_x_coordinate','projection_y_coordinate'),MEAN).data assert_allclose(mean,mean_inv) def test_tracking_coord_order(): """ Test a tracking applications to make sure that coordinate order does not lead to different results """ sample_data=make_sample_data_2D_3blobs() sample_data_inv=make_sample_data_2D_3blobs_inv() # Keyword arguments for feature detection step: parameters_features={} parameters_features['position_threshold']='weighted_diff' parameters_features['sigma_threshold']=0.5 parameters_features['min_num']=3 parameters_features['min_distance']=0 parameters_features['sigma_threshold']=1 parameters_features['threshold']=[3,5,10] #m/s parameters_features['n_erosion_threshold']=0 parameters_features['n_min_threshold']=3 #calculate dxy,dt dxy,dt=get_spacings(sample_data) dxy_inv,dt_inv=get_spacings(sample_data_inv) #Test that dt and dxy are the same for different order of coordinates assert_allclose(dxy,dxy_inv) assert_allclose(dt,dt_inv) #Test that dt and dxy are as expected assert_allclose(dt,60) assert_allclose(dxy,1000) #Find features Features=feature_detection_multithreshold(sample_data,dxy,**parameters_features) Features_inv=feature_detection_multithreshold(sample_data_inv,dxy_inv,**parameters_features) # Assert that output of feature detection not empty: assert type(Features) == pd.core.frame.DataFrame assert type(Features_inv) == pd.core.frame.DataFrame assert not Features.empty assert not Features_inv.empty # perform watershedding segmentation parameters_segmentation={} parameters_segmentation['target']='maximum' parameters_segmentation['method']='watershed' segmentation_mask,features_segmentation=segmentation_2D(Features,sample_data,dxy=dxy,**parameters_segmentation) segmentation_mask_inv,features_segmentation=segmentation_2D(Features_inv,sample_data_inv,dxy=dxy_inv,**parameters_segmentation) # perform trajectory linking parameters_linking={} parameters_linking['method_linking']='predict' parameters_linking['adaptive_stop']=0.2 parameters_linking['adaptive_step']=0.95 parameters_linking['extrapolate']=0 parameters_linking['order']=1 parameters_linking['subnetwork_size']=100 parameters_linking['memory']=0 parameters_linking['time_cell_min']=5*60 parameters_linking['method_linking']='predict' parameters_linking['v_max']=100 parameters_linking['d_min']=2000 Track=linking_trackpy(Features,sample_data,dt=dt,dxy=dxy,**parameters_linking) Track_inv=linking_trackpy(Features_inv,sample_data_inv,dt=dt_inv,dxy=dxy_inv,**parameters_linking) def test_tracking_3D(): """ Test a tracking applications to make sure that coordinate order does not lead to different results """ sample_data=make_sample_data_3D_3blobs() sample_data_inv=make_sample_data_3D_3blobs(invert_xy=True) # Keyword arguments for feature detection step: parameters_features={} parameters_features['position_threshold']='weighted_diff' parameters_features['sigma_threshold']=0.5 parameters_features['min_num']=3 parameters_features['min_distance']=0 parameters_features['sigma_threshold']=1 parameters_features['threshold']=[3,5,10] #m/s parameters_features['n_erosion_threshold']=0 parameters_features['n_min_threshold']=3 sample_data_max=sample_data.collapsed('geopotential_height',MAX) sample_data_max_inv=sample_data.collapsed('geopotential_height',MAX) #calculate dxy,dt dxy,dt=get_spacings(sample_data_max) dxy_inv,dt_inv=get_spacings(sample_data_max_inv) #Test that dt and dxy are the same for different order of coordinates assert_allclose(dxy,dxy_inv) assert_allclose(dt,dt_inv) #Test that dt and dxy are as expected assert_allclose(dt,120) assert_allclose(dxy,1000) #Find features Features=feature_detection_multithreshold(sample_data_max,dxy,**parameters_features) Features_inv=feature_detection_multithreshold(sample_data_max_inv,dxy_inv,**parameters_features) # perform watershedding segmentation parameters_segmentation={} parameters_segmentation['target']='maximum' parameters_segmentation['method']='watershed' segmentation_mask,features_segmentation=segmentation_3D(Features,sample_data_max,dxy=dxy,**parameters_segmentation) segmentation_mask_inv,features_segmentation=segmentation_3D(Features_inv,sample_data_max_inv,dxy=dxy_inv,**parameters_segmentation) # perform trajectory linking parameters_linking={} parameters_linking['method_linking']='predict' parameters_linking['adaptive_stop']=0.2 parameters_linking['adaptive_step']=0.95 parameters_linking['extrapolate']=0 parameters_linking['order']=1 parameters_linking['subnetwork_size']=100 parameters_linking['memory']=0 parameters_linking['time_cell_min']=5*60 parameters_linking['method_linking']='predict' parameters_linking['v_max']=100 parameters_linking['d_min']=2000 Track=linking_trackpy(Features,sample_data,dt=dt,dxy=dxy,**parameters_linking) Track_inv=linking_trackpy(Features_inv,sample_data_inv,dt=dt_inv,dxy=dxy_inv,**parameters_linking) # Assert that output of feature detection not empty: assert not Track.empty assert not Track_inv.empty <file_sep>import logging import numpy as np import pandas as pd def feature_position(hdim1_indices,hdim2_indeces,region,track_data,threshold_i,position_threshold, target): ''' function to determine feature position Input: hdim1_indices: list hdim2_indeces: list region: list list of 2-element tuples track_data: numpy.ndarray 2D numpy array containing the data threshold_i: float position_threshold: str target: str Output: hdim1_index: float feature position along 1st horizontal dimension hdim2_index: float feature position along 2nd horizontal dimension ''' if position_threshold=='center': # get position as geometrical centre of identified region: hdim1_index=np.mean(hdim1_indices) hdim2_index=np.mean(hdim2_indeces) elif position_threshold=='extreme': #get position as max/min position inside the identified region: if target == 'maximum': index=np.argmax(track_data[region]) hdim1_index=hdim1_indices[index] hdim2_index=hdim2_indeces[index] if target == 'minimum': index=np.argmin(track_data[region]) hdim1_index=hdim1_indices[index] hdim2_index=hdim2_indeces[index] elif position_threshold=='weighted_diff': # get position as centre of identified region, weighted by difference from the threshold: weights=abs(track_data[region]-threshold_i) if sum(weights)==0: weights=None hdim1_index=np.average(hdim1_indices,weights=weights) hdim2_index=np.average(hdim2_indeces,weights=weights) elif position_threshold=='weighted_abs': # get position as centre of identified region, weighted by absolute values if the field: weights=abs(track_data[region]) if sum(weights)==0: weights=None hdim1_index=np.average(hdim1_indices,weights=weights) hdim2_index=np.average(hdim2_indeces,weights=weights) else: raise ValueError('position_threshold must be center,extreme,weighted_diff or weighted_abs') return hdim1_index,hdim2_index def test_overlap(region_inner,region_outer): ''' function to test for overlap between two regions (probably scope for further speedup here) Input: region_1: list list of 2-element tuples defining the indeces of all cell in the region region_2: list list of 2-element tuples defining the indeces of all cell in the region Output: overlap: bool True if there are any shared points between the two regions ''' overlap=frozenset(region_outer).isdisjoint(region_inner) return not overlap def remove_parents(features_thresholds,regions_i,regions_old): ''' function to remove features whose regions surround newly detected feature regions Input: features_thresholds: pandas.DataFrame Dataframe containing detected features regions_i: dict dictionary containing the regions above/below threshold for the newly detected feature (feature ids as keys) regions_old: dict dictionary containing the regions above/below threshold from previous threshold (feature ids as keys) Output: features_thresholds pandas.DataFrame Dataframe containing detected features excluding those that are superseded by newly detected ones ''' list_remove=[] for idx_i,region_i in regions_i.items(): for idx_old,region_old in regions_old.items(): if test_overlap(regions_old[idx_old],regions_i[idx_i]): list_remove.append(idx_old) list_remove=list(set(list_remove)) # remove parent regions: if features_thresholds is not None: features_thresholds=features_thresholds[~features_thresholds['idx'].isin(list_remove)] return features_thresholds def feature_detection_threshold(data_i,i_time, threshold=None, min_num=0, target='maximum', position_threshold='center', sigma_threshold=0.5, n_erosion_threshold=0, n_min_threshold=0, min_distance=0, idx_start=0): ''' function to find features based on individual threshold value: Input: data_i: iris.cube.Cube 2D field to perform the feature detection (single timestep) i_time: int number of the current timestep threshold: float threshold value used to select target regions to track target: str ('minimum' or 'maximum') flag to determine if tracking is targetting minima or maxima in the data position_threshold: str('extreme', 'weighted_diff', 'weighted_abs' or 'center') flag choosing method used for the position of the tracked feature sigma_threshold: float standard deviation for intial filtering step n_erosion_threshold: int number of pixel by which to erode the identified features n_min_threshold: int minimum number of identified features min_distance: float minimum distance between detected features (m) idx_start: int feature id to start with Output: features_threshold: pandas DataFrame detected features for individual threshold regions: dict dictionary containing the regions above/below threshold used for each feature (feature ids as keys) ''' from skimage.measure import label from skimage.morphology import binary_erosion # if looking for minima, set values above threshold to 0 and scale by data minimum: if target == 'maximum': mask=1*(data_i >= threshold) # if looking for minima, set values above threshold to 0 and scale by data minimum: elif target == 'minimum': mask=1*(data_i <= threshold) # only include values greater than threshold # erode selected regions by n pixels if n_erosion_threshold>0: selem=np.ones((n_erosion_threshold,n_erosion_threshold)) mask=binary_erosion(mask,selem).astype(np.int64) # detect individual regions, label and count the number of pixels included: labels = label(mask, background=0) values, count = np.unique(labels[:,:].ravel(), return_counts=True) values_counts=dict(zip(values, count)) # Filter out regions that have less pixels than n_min_threshold values_counts={k:v for k, v in values_counts.items() if v>n_min_threshold} #check if not entire domain filled as one feature if 0 in values_counts: #Remove background counts: values_counts.pop(0) #create empty list to store individual features for this threshold list_features_threshold=[] #create empty dict to store regions for individual features for this threshold regions=dict() #create emptry list of features to remove from parent threshold value #loop over individual regions: for cur_idx,count in values_counts.items(): region=labels[:,:] == cur_idx [hdim1_indices,hdim2_indeces]= np.nonzero(region) #write region for individual threshold and feature to dict region_i=list(zip(hdim1_indices,hdim2_indeces)) regions[cur_idx+idx_start]=region_i # Determine feature position for region by one of the following methods: hdim1_index,hdim2_index=feature_position(hdim1_indices,hdim2_indeces,region,data_i,threshold,position_threshold,target) #create individual DataFrame row in tracky format for identified feature list_features_threshold.append({'frame': int(i_time), 'idx':cur_idx+idx_start, 'hdim_1': hdim1_index, 'hdim_2':hdim2_index, 'num':count, 'threshold_value':threshold}) features_threshold=pd.DataFrame(list_features_threshold) else: features_threshold=pd.DataFrame() regions=dict() return features_threshold, regions def feature_detection_multithreshold_timestep(data_i,i_time, threshold=None, min_num=0, target='maximum', position_threshold='center', sigma_threshold=0.5, n_erosion_threshold=0, n_min_threshold=0, min_distance=0, feature_number_start=1 ): ''' function to find features in each timestep based on iteratively finding regions above/below a set of thresholds Input: data_i: iris.cube.Cube 2D field to perform the feature detection (single timestep) i_time: int number of the current timestep threshold: list of floats threshold values used to select target regions to track dxy: float grid spacing of the input data (m) target: str ('minimum' or 'maximum') flag to determine if tracking is targetting minima or maxima in the data position_threshold: str('extreme', 'weighted_diff', 'weighted_abs' or 'center') flag choosing method used for the position of the tracked feature sigma_threshold: float standard deviation for intial filtering step n_erosion_threshold: int number of pixel by which to erode the identified features n_min_threshold: int minimum number of identified features min_distance: float minimum distance between detected features (m) feature_number_start: int feature number to start with Output: features_threshold: pandas DataFrame detected features for individual timestep ''' from scipy.ndimage.filters import gaussian_filter track_data = data_i.core_data() track_data=gaussian_filter(track_data, sigma=sigma_threshold) #smooth data slightly to create rounded, continuous field # create empty lists to store regions and features for individual timestep features_thresholds=pd.DataFrame() for i_threshold,threshold_i in enumerate(threshold): if (i_threshold>0 and not features_thresholds.empty): idx_start=features_thresholds['idx'].max()+1 else: idx_start=0 features_threshold_i,regions_i=feature_detection_threshold(track_data,i_time, threshold=threshold_i, sigma_threshold=sigma_threshold, min_num=min_num, target=target, position_threshold=position_threshold, n_erosion_threshold=n_erosion_threshold, n_min_threshold=n_min_threshold, min_distance=min_distance, idx_start=idx_start ) if any([x is not None for x in features_threshold_i]): features_thresholds=features_thresholds.append(features_threshold_i) # For multiple threshold, and features found both in the current and previous step, remove "parent" features from Dataframe if (i_threshold>0 and not features_thresholds.empty and regions_old): # for each threshold value: check if newly found features are surrounded by feature based on less restrictive threshold features_thresholds=remove_parents(features_thresholds,regions_i,regions_old) regions_old=regions_i logging.debug('Finished feature detection for threshold '+str(i_threshold) + ' : ' + str(threshold_i) ) return features_thresholds def feature_detection_multithreshold(field_in, dxy, threshold=None, min_num=0, target='maximum', position_threshold='center', sigma_threshold=0.5, n_erosion_threshold=0, n_min_threshold=0, min_distance=0, feature_number_start=1 ): ''' Function to perform feature detection based on contiguous regions above/below a threshold Input: field_in: iris.cube.Cube 2D field to perform the tracking on (needs to have coordinate 'time' along one of its dimensions) thresholds: list of floats threshold values used to select target regions to track dxy: float grid spacing of the input data (m) target: str ('minimum' or 'maximum') flag to determine if tracking is targetting minima or maxima in the data position_threshold: str('extreme', 'weighted_diff', 'weighted_abs' or 'center') flag choosing method used for the position of the tracked feature sigma_threshold: float standard deviation for intial filtering step n_erosion_threshold: int number of pixel by which to erode the identified features n_min_threshold: int minimum number of identified features min_distance: float minimum distance between detected features (m) Output: features: pandas DataFrame detected features ''' from .utils import add_coordinates logging.debug('start feature detection based on thresholds') # create empty list to store features for all timesteps list_features_timesteps=[] # loop over timesteps for feature identification: data_time=field_in.slices_over('time') # if single threshold is put in as a single value, turn it into a list if type(threshold) in [int,float]: threshold=[threshold] for i_time,data_i in enumerate(data_time): time_i=data_i.coord('time').units.num2date(data_i.coord('time').points[0]) features_thresholds=feature_detection_multithreshold_timestep(data_i,i_time, threshold=threshold, sigma_threshold=sigma_threshold, min_num=min_num, target=target, position_threshold=position_threshold, n_erosion_threshold=n_erosion_threshold, n_min_threshold=n_min_threshold, min_distance=min_distance, feature_number_start=feature_number_start ) #check if list of features is not empty, then merge features from different threshold values #into one DataFrame and append to list for individual timesteps: if not features_thresholds.empty: #Loop over DataFrame to remove features that are closer than distance_min to each other: if (min_distance > 0): features_thresholds=filter_min_distance(features_thresholds,dxy,min_distance) list_features_timesteps.append(features_thresholds) logging.debug('Finished feature detection for ' + time_i.strftime('%Y-%m-%d_%H:%M:%S')) logging.debug('feature detection: merging DataFrames') # Check if features are detected and then concatenate features from different timesteps into one pandas DataFrame # If no features are detected raise error if any([not x.empty for x in list_features_timesteps]): features=pd.concat(list_features_timesteps, ignore_index=True) features['feature']=features.index+feature_number_start # features_filtered = features.drop(features[features['num'] < min_num].index) # features_filtered.drop(columns=['idx','num','threshold_value'],inplace=True) features=add_coordinates(features,field_in) else: features=None logging.info('No features detected') logging.debug('feature detection completed') return features def filter_min_distance(features,dxy,min_distance): ''' Function to perform feature detection based on contiguous regions above/below a threshold Input: features: pandas DataFrame features dxy: float horzontal grid spacing (m) min_distance: float minimum distance between detected features (m) Output: features: pandas DataFrame features ''' from itertools import combinations remove_list_distance=[] #create list of tuples with all combinations of features at the timestep: indeces=combinations(features.index.values,2) #Loop over combinations to remove features that are closer together than min_distance and keep larger one (either higher threshold or larger area) for index_1,index_2 in indeces: if index_1 is not index_2: features.loc[index_1,'hdim_1'] distance=dxy*np.sqrt((features.loc[index_1,'hdim_1']-features.loc[index_2,'hdim_1'])**2+(features.loc[index_1,'hdim_2']-features.loc[index_2,'hdim_2'])**2) if distance <= min_distance: # logging.debug('distance<= min_distance: ' + str(distance)) if features.loc[index_1,'threshold_value']>features.loc[index_2,'threshold_value']: remove_list_distance.append(index_2) elif features.loc[index_1,'threshold_value']<features.loc[index_2,'threshold_value']: remove_list_distance.append(index_1) elif features.loc[index_1,'threshold_value']==features.loc[index_2,'threshold_value']: if features.loc[index_1,'num']>features.loc[index_2,'num']: remove_list_distance.append(index_2) elif features.loc[index_1,'num']<features.loc[index_2,'num']: remove_list_distance.append(index_1) elif features.loc[index_1,'num']==features.loc[index_2,'num']: remove_list_distance.append(index_2) features=features[~features.index.isin(remove_list_distance)] return features <file_sep>Installation ------------ tobac is now capable of working with both Python 2 and Python 3 (tested for 2.7,3.6 and 3.7) installations. The easiest way is to install the most recent version of tobac via conda and the conda-forge channel: ``` conda install -c conda-forge tobac ``` This will take care of all necessary dependencies and should do the job for most users and also allows for an easy update of the installation by ``` conda update -c conda-forge tobac ``` You can also install conda via pip, which is mainly interesting for development purposed or to use specific development branches for the Github repository. The follwoing python packages are required (including dependencies of these packages): *trackpy*, *scipy*, *numpy*, *iris*, *scikit-learn*, *scikit-image*, *cartopy*, *pandas*, *pytables* If you are using anaconda, the following command should make sure all dependencies are met and up to date: ``conda install -c conda-forge -y trackpy scipy numpy iris scikit-learn scikit-image cartopy pandas pytables`` You can directly install the package directly from github with pip and either of the two following commands: ``pip install --upgrade git+ssh://git@github.com/climate-processes/tobac.git`` ``pip install --upgrade git+https://github.com/climate-processes/tobac.git`` You can also clone the package with any of the two following commands: ``git clone git@github.com:climate-processes/tobac.git`` ``git clone https://github.com/climate-processes/tobac.git`` and install the package from the locally cloned version (The trailing slash is actually necessary): ``pip install --upgrade tobac/`` <file_sep>from setuptools import setup setup(name='tobac', version='1.2', description='Tracking and object-based analysis of clouds', url='http://github.com/climate-processes/tobac', author='<NAME>', author_email='<EMAIL>', license='GNU', packages=['tobac'], install_requires=[], zip_safe=False) <file_sep>tobac - Tracking and Object-Based Analysis of Clouds ----------- **tobac** is a Python package to identify, track and analyse clouds in different types of gridded datasets, such as 3D model output from cloud resolving model simulations or 2D data from satellite retrievals. The software is set up in a modular way to include different algorithms for feature identification, tracking and analyses. In the current implementation, individual features are indentified as either maxima or minima in a two dimensional time varying field. The volume/are associated with the identified object can be determined based on a time-varying 2D or 3D field and a threshold value. In the tracking step, the identified objects are linked into consistent trajectories representing the cloud over its lifecycle. Analysis and visualisation methods provide a convenient way to use and display the tracking results. Version 1.0 of tobac and some example applications are described in a paper that is currently in discussion for the journal "Geoscientific Model Development" as: <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>.: tobac v1.0: towards a flexible framework for tracking and analysis of clouds in diverse datasets, Geosci. Model Dev. Discuss., `https://doi.org/10.5194/gmd-2019-105 <https://doi.org/10.5194/gmd-2019-105>`_ , in review, 2019. The project is currently extended by several contributors to include additional workflows and algorithms using the same structure, synthax and data formats. .. toctree:: :maxdepth: 2 :numbered: installation data_input feature_detection segmentation linking analysis plotting examples <file_sep>import logging def column_mask_from2D(mask_2D,cube,z_coord='model_level_number'): ''' function to turn 2D watershedding mask into a 3D mask of selected columns Input: cube: iris.cube.Cube data cube mask_2D: iris.cube.Cube 2D cube containing mask (int id for tacked volumes 0 everywhere else) z_coord: str name of the vertical coordinate in the cube Output: mask_2D: iris.cube.Cube 3D cube containing columns of 2D mask (int id for tacked volumes 0 everywhere else) ''' from copy import deepcopy mask_3D=deepcopy(cube) mask_3D.rename('segmentation_mask') dim=mask_3D.coord_dims(z_coord)[0] for i in range(len(mask_3D.coord(z_coord).points)): slc = [slice(None)] * len(mask_3D.shape) slc[dim] = slice(i,i+1) mask_out=mask_3D[slc] mask_3D.data[slc]=mask_2D.core_data() return mask_3D def mask_cube_cell(variable_cube,mask,cell,track): ''' Mask cube for tracked volume of an individual cell Input: variable_cube: iris.cube.Cube unmasked data cube mask: iris.cube.Cube cube containing mask (int id for tacked volumes 0 everywhere else) cell: int interger id of cell to create masked cube for Output: variable_cube_out: iris.cube.Cube Masked cube with data for respective cell ''' from copy import deepcopy variable_cube_out=deepcopy(variable_cube) feature_ids=track.loc[track['cell']==cell,'feature'].values variable_cube_out=mask_cube_features(variable_cube,mask,feature_ids) return variable_cube_out def mask_cube_all(variable_cube,mask): ''' Mask cube for untracked volume Input: variable_cube: iris.cube.Cube unmasked data cube mask: iris.cube.Cube cube containing mask (int id for tacked volumes 0 everywhere else) Output: variable_cube_out: iris.cube.Cube Masked cube for untracked volume ''' from dask.array import ma from copy import deepcopy variable_cube_out=deepcopy(variable_cube) variable_cube_out.data=ma.masked_where(mask.core_data()==0,variable_cube_out.core_data()) return variable_cube_out def mask_cube_untracked(variable_cube,mask): ''' Mask cube for untracked volume Input: variable_cube: iris.cube.Cube unmasked data cube mask: iris.cube.Cube cube containing mask (int id for tacked volumes 0 everywhere else) Output: variable_cube_out: iris.cube.Cube Masked cube for untracked volume ''' from dask.array import ma from copy import deepcopy variable_cube_out=deepcopy(variable_cube) variable_cube_out.data=ma.masked_where(mask.core_data()>0,variable_cube_out.core_data()) return variable_cube_out def mask_cube(cube_in,mask): ''' Mask cube where mask is larger than zero Input: cube_in: iris.cube.Cube unmasked data cube mask: numpy.ndarray or dask.array mask to use for masking, >0 where cube is supposed to be masked Output: cube_out: iris.cube.Cube Masked cube ''' from dask.array import ma from copy import deepcopy cube_out=deepcopy(cube_in) cube_out.data=ma.masked_where(mask!=0,cube_in.core_data()) return cube_out def mask_cell(mask,cell,track,masked=False): ''' create mask for specific cell Input: mask: iris.cube.Cube cube containing mask (int id for tacked volumes 0 everywhere else) Output: variable_cube_out: numpy.ndarray Masked cube for untracked volume ''' feature_ids=track.loc[track['cell']==cell,'feature'].values mask_i=mask_features(mask,feature_ids,masked=masked) return mask_i def mask_cell_surface(mask,cell,track,masked=False,z_coord='model_level_number'): '''Create surface projection of mask for individual cell Input: mask: iris.cube.Cube cube containing mask (int id for tacked volumes 0 everywhere else) Output: variable_cube_out: iris.cube.Cube Masked cube for untracked volume ''' feature_ids=track.loc[track['cell']==cell,'feature'].values mask_i_surface=mask_features_surface(mask,feature_ids,masked=masked,z_coord=z_coord) return mask_i_surface def mask_cell_columns(mask,cell,track,masked=False,z_coord='model_level_number'): '''Create mask with entire columns for individual cell Input: mask: iris.cube.Cube cube containing mask (int id for tacked volumes 0 everywhere else) Output: variable_cube_out: iris.cube.Cube Masked cube for untracked volume ''' feature_ids=track.loc[track['cell']==cell].loc['feature'] mask_i=mask_features_columns(mask,feature_ids,masked=masked,z_coord=z_coord) return mask_i def mask_cube_features(variable_cube,mask,feature_ids): ''' Mask cube for tracked volume of an individual cell Input: variable_cube: iris.cube.Cube unmasked data cube mask: iris.cube.Cube cube containing mask (int id for tacked volumes 0 everywhere else) cell: int interger id of cell to create masked cube for Output: variable_cube_out: iris.cube.Cube Masked cube with data for respective cell ''' from dask.array import ma,isin from copy import deepcopy variable_cube_out=deepcopy(variable_cube) variable_cube_out.data=ma.masked_where(~isin(mask.core_data(),feature_ids),variable_cube_out.core_data()) return variable_cube_out def mask_features(mask,feature_ids,masked=False): ''' create mask for specific features Input: mask: iris.cube.Cube cube containing mask (int id for tacked volumes 0 everywhere else) Output: variable_cube_out: numpy.ndarray Masked cube for untracked volume ''' from dask.array import ma,isin from copy import deepcopy mask_i=deepcopy(mask) mask_i_data=mask_i.core_data() mask_i_data[~isin(mask_i.core_data(),feature_ids)]=0 if masked: mask_i.data=ma.masked_equal(mask_i.core_data(),0) return mask_i def mask_features_surface(mask,feature_ids,masked=False,z_coord='model_level_number'): ''' create surface mask for individual features Input: mask: iris.cube.Cube cube containing mask (int id for tacked volumes 0 everywhere else) Output: variable_cube_out: iris.cube.Cube Masked cube for untracked volume ''' from iris.analysis import MAX from dask.array import ma,isin from copy import deepcopy mask_i=deepcopy(mask) # mask_i.data=[~isin(mask_i.data,feature_ids)]=0 mask_i_data=mask_i.core_data() mask_i_data[~isin(mask_i.core_data(),feature_ids)]=0 mask_i_surface=mask_i.collapsed(z_coord,MAX) if masked: mask_i_surface.data=ma.masked_equal(mask_i_surface.core_data(),0) return mask_i_surface def mask_all_surface(mask,masked=False,z_coord='model_level_number'): ''' create surface mask for individual features Input: mask: iris.cube.Cube cube containing mask (int id for tacked volumes 0 everywhere else) Output: mask_i_surface: iris.cube.Cube (2D) Mask with 1 below features and 0 everywhere else ''' from iris.analysis import MAX from dask.array import ma,isin from copy import deepcopy mask_i=deepcopy(mask) mask_i_surface=mask_i.collapsed(z_coord,MAX) mask_i_surface_data=mask_i_surface.core_data() mask_i_surface[mask_i_surface_data>0]=1 if masked: mask_i_surface.data=ma.masked_equal(mask_i_surface.core_data(),0) return mask_i_surface # def mask_features_columns(mask,feature_ids,masked=False,z_coord='model_level_number'): # ''' Mask cube for untracked volume # Input: # variable_cube: iris.cube.Cube # unmasked data cube # mask: iris.cube.Cube # cube containing mask (int id for tacked volumes 0 everywhere else) # Output: # variable_cube_out: iris.cube.Cube # Masked cube for untracked volume # ''' # from iris.analysis import MAX # import numpy as np # from copy import deepcopy # mask_i=deepcopy(mask) # mask_i.data[~np.isin(mask_i.data,feature_ids)]=0 # mask_i_surface=mask_i.collapsed(z_coord,MAX) # for cube_slice in mask_i.slices(['time','x','y']): # cube_slice.data=mask_i_surface.core_data() # if masked: # mask_i.data=np.ma.array(mask_i.data,mask=mask_i.data) # return mask_i #def constraint_cell(track,mask_cell,width=None,x=None,): # from iris import Constraint # import numpy as np # # time_coord=mask_cell.coord('time') # time_units=time_coord.units # # def time_condition(cell): # return time_units.num2date(track.head(n=1)['time']) <= cell <= time_units.num2date(track.tail(n=1)['time']) # # constraint_time=Constraint(time=time_condition) ## mask_cell_i=mask_cell.extract(constraint_time) # mask_cell_surface_i=mask_cell_surface.extract(constraint_time) # # x_dim=mask_cell_surface_i.coord_dims('projection_x_coordinate')[0] # y_dim=mask_cell_surface_i.coord_dims('projection_y_coordinate')[0] # x_coord=mask_cell_surface_i.coord('projection_x_coordinate') # y_coord=mask_cell_surface_i.coord('projection_y_coordinate') # # if (mask_cell_surface_i.core_data()>0).any(): # box_mask_i=get_bounding_box(mask_cell_surface_i.core_data(),buffer=1) # # box_mask=[[x_coord.points[box_mask_i[x_dim][0]],x_coord.points[box_mask_i[x_dim][1]]], # [y_coord.points[box_mask_i[y_dim][0]],y_coord.points[box_mask_i[y_dim][1]]]] # else: # box_mask=[[np.nan,np.nan],[np.nan,np.nan]] # # x_min=box_mask[0][0] # x_max=box_mask[0][1] # y_min=box_mask[1][0] # y_max=box_mask[1][1] # constraint_x=Constraint(projection_x_coordinate=lambda cell: int(x_min) < cell < int(x_max)) # constraint_y=Constraint(projection_y_coordinate=lambda cell: int(y_min) < cell < int(y_max)) # # constraint=constraint_time & constraint_x & constraint_y # return constraint def add_coordinates(t,variable_cube): import numpy as np ''' Function adding coordinates from the tracking cube to the trajectories: time, longitude&latitude, x&y dimensions Input: t: pandas DataFrame trajectories/features variable_cube: iris.cube.Cube Cube containing the dimensions 'time','longitude','latitude','x_projection_coordinate','y_projection_coordinate', usually cube that the tracking is performed on Output: t: pandas DataFrame trajectories with added coordinated ''' from scipy.interpolate import interp2d, interp1d logging.debug('start adding coordinates from cube') # pull time as datetime object and timestr from input data and add it to DataFrame: t['time']=None t['timestr']=None logging.debug('adding time coordinate') time_in=variable_cube.coord('time') time_in_datetime=time_in.units.num2date(time_in.points) t["time"]=time_in_datetime[t['frame']] t["timestr"]=[x.strftime('%Y-%m-%d %H:%M:%S') for x in time_in_datetime[t['frame']]] # Get list of all coordinates in input cube except for time (already treated): coord_names=[coord.name() for coord in variable_cube.coords()] coord_names.remove('time') logging.debug('time coordinate added') # chose right dimension for horizontal axis based on time dimension: ndim_time=variable_cube.coord_dims('time')[0] if ndim_time==0: hdim_1=1 hdim_2=2 elif ndim_time==1: hdim_1=0 hdim_2=2 elif ndim_time==2: hdim_1=0 hdim_2=1 # create vectors to use to interpolate from pixels to coordinates dimvec_1=np.arange(variable_cube.shape[hdim_1]) dimvec_2=np.arange(variable_cube.shape[hdim_2]) # loop over coordinates in input data: for coord in coord_names: logging.debug('adding coord: '+ coord) # interpolate 2D coordinates: if variable_cube.coord(coord).ndim==1: if variable_cube.coord_dims(coord)==(hdim_1,): f=interp1d(dimvec_1,variable_cube.coord(coord).points,fill_value="extrapolate") coordinate_points=f(t['hdim_1']) if variable_cube.coord_dims(coord)==(hdim_2,): f=interp1d(dimvec_2,variable_cube.coord(coord).points,fill_value="extrapolate") coordinate_points=f(t['hdim_2']) # interpolate 2D coordinates: elif variable_cube.coord(coord).ndim==2: if variable_cube.coord_dims(coord)==(hdim_1,hdim_2): f=interp2d(dimvec_2,dimvec_1,variable_cube.coord(coord).points) coordinate_points=[f(a,b) for a,b in zip(t['hdim_2'],t['hdim_1'])] if variable_cube.coord_dims(coord)==(hdim_2,hdim_1): f=interp2d(dimvec_1,dimvec_2,variable_cube.coord(coord).points) coordinate_points=[f(a,b) for a,b in zip(t['hdim_1'],t['hdim_2'])] # interpolate 3D coordinates: # mainly workaround for wrf latitude and longitude (to be fixed in future) elif variable_cube.coord(coord).ndim==3: if variable_cube.coord_dims(coord)==(ndim_time,hdim_1,hdim_2): f=interp2d(dimvec_2,dimvec_1,variable_cube[0,:,:].coord(coord).points) coordinate_points=[f(a,b) for a,b in zip(t['hdim_2'],t['hdim_1'])] if variable_cube.coord_dims(coord)==(ndim_time,hdim_2,hdim_1): f=interp2d(dimvec_1,dimvec_2,variable_cube[0,:,:].coord(coord).points) coordinate_points=[f(a,b) for a,b in zip(t['hdim_1'],t['hdim_2'])] if variable_cube.coord_dims(coord)==(hdim_1,ndim_time,hdim_2): f=interp2d(dimvec_2,dimvec_1,variable_cube[:,0,:].coord(coord).points) coordinate_points=[f(a,b) for a,b in zip(t['hdim_2'],t['hdim_1'])] if variable_cube.coord_dims(coord)==(hdim_1,hdim_2,ndim_time): f=interp2d(dimvec_2,dimvec_1,variable_cube[:,:,0].coord(coord).points) coordinate_points=[f(a,b) for a,b in zip(t['hdim_2'],t['hdim1'])] if variable_cube.coord_dims(coord)==(hdim_2,ndim_time,hdim_1): f=interp2d(dimvec_1,dimvec_2,variable_cube[:,0,:].coord(coord).points) coordinate_points=[f(a,b) for a,b in zip(t['hdim_1'],t['hdim_2'])] if variable_cube.coord_dims(coord)==(hdim_2,hdim_1,ndim_time): f=interp2d(dimvec_1,dimvec_2,variable_cube[:,:,0].coord(coord).points) coordinate_points=[f(a,b) for a,b in zip(t['hdim_1'],t['hdim_2'])] # write resulting array or list into DataFrame: t[coord]=coordinate_points logging.debug('added coord: '+ coord) return t def get_bounding_box(x,buffer=1): from numpy import delete,arange,diff,nonzero,array """ Calculates the bounding box of a ndarray https://stackoverflow.com/questions/31400769/bounding-box-of-numpy-array """ mask = x == 0 bbox = [] all_axis = arange(x.ndim) #loop over dimensions for kdim in all_axis: nk_dim = delete(all_axis, kdim) mask_i = mask.all(axis=tuple(nk_dim)) dmask_i = diff(mask_i) idx_i = nonzero(dmask_i)[0] # for case where there is no value in idx_i if len(idx_i) == 0: idx_i=array([0,x.shape[kdim]-1]) # for case where there is only one value in idx_i elif len(idx_i) == 1: idx_i=array([idx_i,idx_i]) # make sure there is two values in idx_i elif len(idx_i) > 2: idx_i=array([idx_i[0],idx_i[-1]]) # caluclate min and max values for idx_i and append them to list idx_min=max(0,idx_i[0]+1-buffer) idx_max=min(x.shape[kdim]-1,idx_i[1]+1+buffer) bbox.append([idx_min, idx_max]) return bbox def get_spacings(field_in,grid_spacing=None,time_spacing=None): import numpy as np from copy import deepcopy # set horizontal grid spacing of input data # If cartesian x and y corrdinates are present, use these to determine dxy (vertical grid spacing used to transfer pixel distances to real distances): coord_names=[coord.name() for coord in field_in.coords()] if (('projection_x_coordinate' in coord_names and 'projection_y_coordinate' in coord_names) and (grid_spacing is None)): x_coord=deepcopy(field_in.coord('projection_x_coordinate')) x_coord.convert_units('metre') dx=np.diff(field_in.coord('projection_y_coordinate')[0:2].points)[0] y_coord=deepcopy(field_in.coord('projection_y_coordinate')) y_coord.convert_units('metre') dy=np.diff(field_in.coord('projection_y_coordinate')[0:2].points)[0] dxy=0.5*(dx+dy) elif grid_spacing is not None: dxy=grid_spacing else: ValueError('no information about grid spacing, need either input cube with projection_x_coord and projection_y_coord or keyword argument grid_spacing') # set horizontal grid spacing of input data if (time_spacing is None): # get time resolution of input data from first to steps of input cube: time_coord=field_in.coord('time') dt=(time_coord.units.num2date(time_coord.points[1])-time_coord.units.num2date(time_coord.points[0])).seconds elif (time_spacing is not None): # use value of time_spacing for dt: dt=time_spacing return dxy,dt <file_sep>import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import logging from .analysis import lifetime_histogram from .analysis import histogram_cellwise,histogram_featurewise import numpy as np def plot_tracks_mask_field_loop(track,field,mask,features,axes=None,name=None,plot_dir='./', figsize=(10./2.54,10./2.54),dpi=300, margin_left=0.05,margin_right=0.05,margin_bottom=0.05,margin_top=0.05, **kwargs): import cartopy.crs as ccrs import os from iris import Constraint os.makedirs(plot_dir,exist_ok=True) time=mask.coord('time') if name is None: name=field.name() for time_i in time.points: datetime_i=time.units.num2date(time_i) constraint_time = Constraint(time=datetime_i) fig1,ax1=plt.subplots(ncols=1, nrows=1,figsize=figsize, subplot_kw={'projection': ccrs.PlateCarree()}) datestring_file=datetime_i.strftime('%Y-%m-%d_%H:%M:%S') field_i=field.extract(constraint_time) mask_i=mask.extract(constraint_time) track_i=track[track['time']==datetime_i] features_i=features[features['time']==datetime_i] ax1=plot_tracks_mask_field(track=track_i,field=field_i,mask=mask_i,features=features_i, axes=ax1,**kwargs) fig1.subplots_adjust(left=margin_left, bottom=margin_bottom, right=1-margin_right, top=1-margin_top) os.makedirs(plot_dir, exist_ok=True) savepath_png=os.path.join(plot_dir,name+'_'+datestring_file+'.png') fig1.savefig(savepath_png,dpi=dpi) logging.debug('Figure plotted to ' + str(savepath_png)) plt.close() def plot_tracks_mask_field(track,field,mask,features,axes=None,axis_extent=None, plot_outline=True, plot_marker=True,marker_track='x',markersize_track=4, plot_number=True, plot_features=False,marker_feature=None,markersize_feature=None, title=None,title_str=None, vmin=None,vmax=None,n_levels=50, cmap='viridis',extend='neither', orientation_colorbar='horizontal',pad_colorbar=0.05, label_colorbar=None,fraction_colorbar=0.046, rasterized=True,linewidth_contour=1 ): import cartopy from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import iris.plot as iplt from matplotlib.ticker import MaxNLocator import cartopy.feature as cfeature from .utils import mask_features,mask_features_surface from matplotlib import ticker if type(axes) is not cartopy.mpl.geoaxes.GeoAxesSubplot: raise ValueError('axes had to be cartopy.mpl.geoaxes.GeoAxesSubplot') datestr=field.coord('time').units.num2date(field.coord('time').points[0]).strftime('%Y-%m-%d %H:%M:%S') if title is 'datestr': if title_str is None: titlestring=datestr elif type(title_str is str): titlestring=title+ ' ' + datestr axes.set_title(titlestring,horizontalalignment='left',loc='left') gl = axes.gridlines(draw_labels=True) majorLocator = MaxNLocator(nbins=5,steps=[1,2,5,10]) gl.xlocator=majorLocator gl.ylocator=majorLocator gl.xformatter = LONGITUDE_FORMATTER axes.tick_params(axis='both', which='major') gl.yformatter = LATITUDE_FORMATTER gl.xlabels_top = False gl.ylabels_right = False axes.coastlines('10m') # rivers=cfeature.NaturalEarthFeature(category='physical', name='rivers_lake_centerlines',scale='10m',facecolor='none') lakes=cfeature.NaturalEarthFeature(category='physical', name='lakes',scale='10m',facecolor='none') axes.add_feature(lakes, edgecolor='black') axes.set_xlabel('longitude') axes.set_ylabel('latitude') # Plot the background field if np.any(~np.isnan(field.data)): # check if field to plot is not only nan, which causes error: plot_field=iplt.contourf(field,coords=['longitude','latitude'], levels=np.linspace(vmin,vmax,num=n_levels),extend=extend, axes=axes, cmap=cmap,vmin=vmin,vmax=vmax,zorder=1 ) if rasterized: axes.set_rasterization_zorder(1) # create colorbar for background field: cbar=plt.colorbar(plot_field,orientation=orientation_colorbar, pad=pad_colorbar,fraction=fraction_colorbar,ax=axes) if label_colorbar is None: label_colorbar=field.name()+ '('+field.units.symbol +')' if orientation_colorbar is 'horizontal': cbar.ax.set_xlabel(label_colorbar) elif orientation_colorbar is 'vertical': cbar.ax.set_ylabel(label_colorbar) tick_locator = ticker.MaxNLocator(nbins=5) cbar.locator = tick_locator cbar.update_ticks() colors_mask=['darkred','orange','crimson','red','darkorange'] #if marker_feature is not explicitly given, set it to marker_track (will then be overwritten by the coloured markers) if marker_feature is None: maker_feature=marker_track if markersize_feature is None: makersize_feature=markersize_track #Plot the identified features by looping over rows of DataFrame: if plot_features: for i_row,row in features.iterrows(): axes.plot(row['longitude'],row['latitude'], color='grey',marker=maker_feature,markersize=makersize_feature) # restrict features to featues inside axis extent track=track.loc[(track['longitude'] > axis_extent[0]) & (track['longitude'] < axis_extent[1]) & (track['latitude'] > axis_extent[2]) & (track['latitude'] < axis_extent[3])] #Plot tracked features by looping over rows of Dataframe for i_row,row in track.iterrows(): feature=row['feature'] cell=row['cell'] if not np.isnan(cell): color=colors_mask[int(cell%len(colors_mask))] if plot_number: cell_string=' '+str(int(row['cell'])) axes.text(row['longitude'],row['latitude'],cell_string, color=color,fontsize=6, clip_on=True) else: color='grey' if plot_outline: mask_i=None # if mask is 3D, create surface projection, if mask is 2D keep the mask if mask.ndim==2: mask_i=mask_features(mask,feature,masked=False) elif mask.ndim==3: mask_i=mask_features_surface(mask,feature,masked=False,z_coord='model_level_number') else: raise ValueError('mask has shape that cannot be understood') # plot countour lines around the edges of the mask iplt.contour(mask_i,coords=['longitude','latitude'], levels=[0,feature], colors=color,linewidths=linewidth_contour, axes=axes) if plot_marker: axes.plot(row['longitude'],row['latitude'], color=color,marker=marker_track,markersize=markersize_track) axes.set_extent(axis_extent) return axes def animation_mask_field(track,features,field,mask,interval=500,figsize=(10,10),**kwargs): import cartopy.crs as ccrs import matplotlib.pyplot as plt import matplotlib.animation from iris import Constraint fig=plt.figure(figsize=figsize) plt.close() def update(time_in): fig.clf() ax=fig.add_subplot(111,projection=ccrs.PlateCarree()) constraint_time = Constraint(time=time_in) field_i=field.extract(constraint_time) mask_i=mask.extract(constraint_time) track_i=track[track['time']==time_in] features_i=features[features['time']==time_in] #fig1,ax1=plt.subplots(ncols=1, nrows=1,figsize=figsize, subplot_kw={'projection': ccrs.PlateCarree()}) plot_tobac=plot_tracks_mask_field(track_i,field=field_i,mask=mask_i,features=features_i, axes=ax, **kwargs) ax.set_title('{}'.format(time_in)) time=field.coord('time') datetimes=time.units.num2date(time.points) animation = matplotlib.animation.FuncAnimation(fig, update,init_func=None, frames=datetimes,interval=interval, blit=False) return animation def plot_mask_cell_track_follow(cell,track, cog, features, mask_total, field_contour, field_filled, width=10000, name= 'test', plotdir='./', file_format=['png'],figsize=(10/2.54, 10/2.54),dpi=300, **kwargs): '''Make plots for all cells centred around cell and with one background field as filling and one background field as contrours Input: Output: ''' from iris import Constraint from numpy import unique import os track_cell=track[track['cell']==cell] for i_row,row in track_cell.iterrows(): constraint_time = Constraint(time=row['time']) constraint_x = Constraint(projection_x_coordinate = lambda cell: row['projection_x_coordinate']-width < cell < row['projection_x_coordinate']+width) constraint_y = Constraint(projection_y_coordinate = lambda cell: row['projection_y_coordinate']-width < cell < row['projection_y_coordinate']+width) constraint = constraint_time & constraint_x & constraint_y mask_total_i=mask_total.extract(constraint) if field_contour is None: field_contour_i=None else: field_contour_i=field_contour.extract(constraint) if field_filled is None: field_filled_i=None else: field_filled_i=field_filled.extract(constraint) cells=list(unique(mask_total_i.core_data())) if cell not in cells: cells.append(cell) if 0 in cells: cells.remove(0) track_i=track[track['cell'].isin(cells)] track_i=track_i[track_i['time']==row['time']] if cog is None: cog_i=None else: cog_i=cog[cog['cell'].isin(cells)] cog_i=cog_i[cog_i['time']==row['time']] if features is None: features_i=None else: features_i=features[features['time']==row['time']] fig1, ax1 = plt.subplots(ncols=1, nrows=1, figsize=figsize) fig1.subplots_adjust(left=0.2, bottom=0.15, right=0.85, top=0.80) datestring_stamp = row['time'].strftime('%Y-%m-%d %H:%M:%S') celltime_stamp = "%02d:%02d:%02d" % (row['time_cell'].dt.total_seconds() // 3600,(row['time_cell'].dt.total_seconds() % 3600) // 60, row['time_cell'].dt.total_seconds() % 60 ) title=datestring_stamp + ' , ' + celltime_stamp datestring_file = row['time'].strftime('%Y-%m-%d_%H%M%S') ax1=plot_mask_cell_individual_follow(cell_i=cell,track=track_i, cog=cog_i,features=features_i, mask_total=mask_total_i, field_contour=field_contour_i, field_filled=field_filled_i, width=width, axes=ax1,title=title, **kwargs) out_dir = os.path.join(plotdir, name) os.makedirs(out_dir, exist_ok=True) if 'png' in file_format: savepath_png = os.path.join(out_dir, name + '_' + datestring_file + '.png') fig1.savefig(savepath_png, dpi=dpi) logging.debug('field_contour field_filled Mask plot saved to ' + savepath_png) if 'pdf' in file_format: savepath_pdf = os.path.join(out_dir, name + '_' + datestring_file + '.pdf') fig1.savefig(savepath_pdf, dpi=dpi) logging.debug('field_contour field_filled Mask plot saved to ' + savepath_pdf) plt.close() plt.clf() def plot_mask_cell_individual_follow(cell_i,track, cog,features, mask_total, field_contour, field_filled, axes=None,width=10000, label_field_contour=None, cmap_field_contour='Blues',norm_field_contour=None, linewidths_contour=0.8,contour_labels=False, vmin_field_contour=0,vmax_field_contour=50,levels_field_contour=None,nlevels_field_contour=10, label_field_filled=None,cmap_field_filled='summer',norm_field_filled=None, vmin_field_filled=0,vmax_field_filled=100,levels_field_filled=None,nlevels_field_filled=10, title=None ): '''Make individual plot for cell centred around cell and with one background field as filling and one background field as contrours Input: Output: ''' import numpy as np from .utils import mask_cell_surface from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.colors import Normalize divider = make_axes_locatable(axes) x_pos=track[track['cell']==cell_i]['projection_x_coordinate'].item() y_pos=track[track['cell']==cell_i]['projection_y_coordinate'].item() if field_filled is not None: if levels_field_filled is None: levels_field_filled=np.linspace(vmin_field_filled,vmax_field_filled, nlevels_field_filled) plot_field_filled = axes.contourf((field_filled.coord('projection_x_coordinate').points-x_pos)/1000, (field_filled.coord('projection_y_coordinate').points-y_pos)/1000, field_filled.data, cmap=cmap_field_filled,norm=norm_field_filled, levels=levels_field_filled,vmin=vmin_field_filled, vmax=vmax_field_filled) cax_filled = divider.append_axes("right", size="5%", pad=0.1) norm_filled= Normalize(vmin=vmin_field_filled, vmax=vmax_field_filled) sm_filled= plt.cm.ScalarMappable(norm=norm_filled, cmap = plot_field_filled.cmap) sm_filled.set_array([]) cbar_field_filled = plt.colorbar(sm_filled, orientation='vertical',cax=cax_filled) cbar_field_filled.ax.set_ylabel(label_field_filled) cbar_field_filled.set_clim(vmin_field_filled, vmax_field_filled) if field_contour is not None: if levels_field_contour is None: levels_field_contour=np.linspace(vmin_field_contour, vmax_field_contour, nlevels_field_contour) if norm_field_contour: vmin_field_contour=None, vmax_field_contour=None, plot_field_contour = axes.contour((field_contour.coord('projection_x_coordinate').points-x_pos)/1000, (field_contour.coord('projection_y_coordinate').points-y_pos)/1000, field_contour.data, cmap=cmap_field_contour,norm=norm_field_contour, levels=levels_field_contour,vmin=vmin_field_contour, vmax=vmax_field_contour, linewidths=linewidths_contour) if contour_labels: axes.clabel(plot_field_contour, fontsize=10) cax_contour = divider.append_axes("bottom", size="5%", pad=0.1) if norm_field_contour: vmin_field_contour=None vmax_field_contour=None norm_contour=norm_field_contour else: norm_contour= Normalize(vmin=vmin_field_contour, vmax=vmax_field_contour) sm_contour= plt.cm.ScalarMappable(norm=norm_contour, cmap = plot_field_contour.cmap) sm_contour.set_array([]) cbar_field_contour = plt.colorbar(sm_contour, orientation='horizontal',ticks=levels_field_contour,cax=cax_contour) cbar_field_contour.ax.set_xlabel(label_field_contour) cbar_field_contour.set_clim(vmin_field_contour, vmax_field_contour) for i_row, row in track.iterrows(): cell = int(row['cell']) if cell==cell_i: color='darkred' else: color='darkorange' cell_string=' '+str(int(row['cell'])) axes.text((row['projection_x_coordinate']-x_pos)/1000, (row['projection_y_coordinate']-y_pos)/1000, cell_string,color=color,fontsize=6, clip_on=True) # Plot marker for tracked cell centre as a cross axes.plot((row['projection_x_coordinate']-x_pos)/1000, (row['projection_y_coordinate']-y_pos)/1000, 'x', color=color,markersize=4) #Create surface projection of mask for the respective cell and plot it in the right color z_coord = 'model_level_number' if len(mask_total.shape)==3: mask_total_i_surface = mask_cell_surface(mask_total, cell, track, masked=False, z_coord=z_coord) elif len(mask_total.shape)==2: mask_total_i_surface=mask_total axes.contour((mask_total_i_surface.coord('projection_x_coordinate').points-x_pos)/1000, (mask_total_i_surface.coord('projection_y_coordinate').points-y_pos)/1000, mask_total_i_surface.data, levels=[0, cell], colors=color, linestyles=':',linewidth=1) if cog is not None: for i_row, row in cog.iterrows(): cell = row['cell'] if cell==cell_i: color='darkred' else: color='darkorange' # plot marker for centre of gravity as a circle axes.plot((row['x_M']-x_pos)/1000, (row['y_M']-y_pos)/1000, 'o', markeredgecolor=color, markerfacecolor='None',markersize=4) if features is not None: for i_row, row in features.iterrows(): color='purple' axes.plot((row['projection_x_coordinate']-x_pos)/1000, (row['projection_y_coordinate']-y_pos)/1000, '+', color=color,markersize=3) axes.set_xlabel('x (km)') axes.set_ylabel('y (km)') axes.set_xlim([-1*width/1000, width/1000]) axes.set_ylim([-1*width/1000, width/1000]) axes.xaxis.set_label_position('top') axes.xaxis.set_ticks_position('top') axes.set_title(title,pad=35,fontsize=10,horizontalalignment='left',loc='left') return axes def plot_mask_cell_track_static(cell,track, cog, features, mask_total, field_contour, field_filled, width=10000,n_extend=1, name= 'test', plotdir='./', file_format=['png'],figsize=(10/2.54, 10/2.54),dpi=300, **kwargs): '''Make plots for all cells with fixed frame including entire development of the cell and with one background field as filling and one background field as contrours Input: Output: ''' from iris import Constraint from numpy import unique import os track_cell=track[track['cell']==cell] x_min=track_cell['projection_x_coordinate'].min()-width x_max=track_cell['projection_x_coordinate'].max()+width y_min=track_cell['projection_y_coordinate'].min()-width y_max=track_cell['projection_y_coordinate'].max()+width #set up looping over time based on mask's time coordinate to allow for one timestep before and after the track time_coord=mask_total.coord('time') time=time_coord.units.num2date(time_coord.points) i_start=max(0,np.where(time==track_cell['time'].values[0])[0][0]-n_extend) i_end=min(len(time)-1,np.where(time==track_cell['time'].values[-1])[0][0]+n_extend+1) time_cell=time[slice(i_start,i_end)] for time_i in time_cell: # for i_row,row in track_cell.iterrows(): # time_i=row['time'] # constraint_time = Constraint(time=row['time']) constraint_time = Constraint(time=time_i) constraint_x = Constraint(projection_x_coordinate = lambda cell: x_min < cell < x_max) constraint_y = Constraint(projection_y_coordinate = lambda cell: y_min < cell < y_max) constraint = constraint_time & constraint_x & constraint_y mask_total_i=mask_total.extract(constraint) if field_contour is None: field_contour_i=None else: field_contour_i=field_contour.extract(constraint) if field_filled is None: field_filled_i=None else: field_filled_i=field_filled.extract(constraint) track_i=track[track['time']==time_i] cells_mask=list(unique(mask_total_i.core_data())) track_cells=track_i.loc[(track_i['projection_x_coordinate'] > x_min) & (track_i['projection_x_coordinate'] < x_max) & (track_i['projection_y_coordinate'] > y_min) & (track_i['projection_y_coordinate'] < y_max)] cells_track=list(track_cells['cell'].values) cells=list(set( cells_mask + cells_track )) if cell not in cells: cells.append(cell) if 0 in cells: cells.remove(0) track_i=track_i[track_i['cell'].isin(cells)] if cog is None: cog_i=None else: cog_i=cog[cog['cell'].isin(cells)] cog_i=cog_i[cog_i['time']==time_i] if features is None: features_i=None else: features_i=features[features['time']==time_i] fig1, ax1 = plt.subplots(ncols=1, nrows=1, figsize=figsize) fig1.subplots_adjust(left=0.2, bottom=0.15, right=0.80, top=0.85) datestring_stamp = time_i.strftime('%Y-%m-%d %H:%M:%S') if time_i in track_cell['time'].values: time_cell_i=track_cell[track_cell['time'].values==time_i]['time_cell'] celltime_stamp = "%02d:%02d:%02d" % (time_cell_i.dt.total_seconds() // 3600, (time_cell_i.dt.total_seconds() % 3600) // 60, time_cell_i.dt.total_seconds() % 60 ) else: celltime_stamp=' - ' title=datestring_stamp + ' , ' + celltime_stamp datestring_file = time_i.strftime('%Y-%m-%d_%H%M%S') ax1=plot_mask_cell_individual_static(cell_i=cell, track=track_i, cog=cog_i,features=features_i, mask_total=mask_total_i, field_contour=field_contour_i, field_filled=field_filled_i, xlim=[x_min/1000,x_max/1000],ylim=[y_min/1000,y_max/1000], axes=ax1,title=title,**kwargs) out_dir = os.path.join(plotdir, name) os.makedirs(out_dir, exist_ok=True) if 'png' in file_format: savepath_png = os.path.join(out_dir, name + '_' + datestring_file + '.png') fig1.savefig(savepath_png, dpi=dpi) logging.debug('Mask static plot saved to ' + savepath_png) if 'pdf' in file_format: savepath_pdf = os.path.join(out_dir, name + '_' + datestring_file + '.pdf') fig1.savefig(savepath_pdf, dpi=dpi) logging.debug('Mask static plot saved to ' + savepath_pdf) plt.close() plt.clf() def plot_mask_cell_individual_static(cell_i,track, cog, features, mask_total, field_contour, field_filled, axes=None,xlim=None,ylim=None, label_field_contour=None, cmap_field_contour='Blues',norm_field_contour=None, linewidths_contour=0.8,contour_labels=False, vmin_field_contour=0,vmax_field_contour=50,levels_field_contour=None,nlevels_field_contour=10, label_field_filled=None,cmap_field_filled='summer',norm_field_filled=None, vmin_field_filled=0,vmax_field_filled=100,levels_field_filled=None,nlevels_field_filled=10, title=None,feature_number=False ): '''Make plots for cell in fixed frame and with one background field as filling and one background field as contrours Input: Output: ''' import numpy as np from .utils import mask_features,mask_features_surface from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.colors import Normalize divider = make_axes_locatable(axes) if field_filled is not None: if levels_field_filled is None: levels_field_filled=np.linspace(vmin_field_filled,vmax_field_filled, 10) plot_field_filled = axes.contourf(field_filled.coord('projection_x_coordinate').points/1000, field_filled.coord('projection_y_coordinate').points/1000, field_filled.data, levels=levels_field_filled, norm=norm_field_filled, cmap=cmap_field_filled, vmin=vmin_field_filled, vmax=vmax_field_filled) cax_filled = divider.append_axes("right", size="5%", pad=0.1) norm_filled= Normalize(vmin=vmin_field_filled, vmax=vmax_field_filled) sm1= plt.cm.ScalarMappable(norm=norm_filled, cmap = plot_field_filled.cmap) sm1.set_array([]) cbar_field_filled = plt.colorbar(sm1, orientation='vertical',cax=cax_filled) cbar_field_filled.ax.set_ylabel(label_field_filled) cbar_field_filled.set_clim(vmin_field_filled, vmax_field_filled) if field_contour is not None: if levels_field_contour is None: levels_field_contour=np.linspace(vmin_field_contour, vmax_field_contour, 5) plot_field_contour = axes.contour(field_contour.coord('projection_x_coordinate').points/1000, field_contour.coord('projection_y_coordinate').points/1000, field_contour.data, cmap=cmap_field_contour,norm=norm_field_contour, levels=levels_field_contour,vmin=vmin_field_contour, vmax=vmax_field_contour, linewidths=linewidths_contour) if contour_labels: axes.clabel(plot_field_contour, fontsize=10) cax_contour = divider.append_axes("bottom", size="5%", pad=0.1) if norm_field_contour: vmin_field_contour=None vmax_field_contour=None norm_contour=norm_field_contour else: norm_contour= Normalize(vmin=vmin_field_contour, vmax=vmax_field_contour) sm_contour= plt.cm.ScalarMappable(norm=norm_contour, cmap = plot_field_contour.cmap) sm_contour.set_array([]) cbar_field_contour = plt.colorbar(sm_contour, orientation='horizontal',ticks=levels_field_contour,cax=cax_contour) cbar_field_contour.ax.set_xlabel(label_field_contour) cbar_field_contour.set_clim(vmin_field_contour, vmax_field_contour) for i_row, row in track.iterrows(): cell = row['cell'] feature = row['feature'] # logging.debug("cell: "+ str(row['cell'])) # logging.debug("feature: "+ str(row['feature'])) if cell==cell_i: color='darkred' if feature_number: cell_string=' '+str(int(cell))+' ('+str(int(feature))+')' else: cell_string=' '+str(int(cell)) elif np.isnan(cell): color='gray' if feature_number: cell_string=' '+'('+str(int(feature))+')' else: cell_string=' ' else: color='darkorange' if feature_number: cell_string=' '+str(int(cell))+' ('+str(int(feature))+')' else: cell_string=' '+str(int(cell)) axes.text(row['projection_x_coordinate']/1000, row['projection_y_coordinate']/1000, cell_string,color=color,fontsize=6, clip_on=True) # Plot marker for tracked cell centre as a cross axes.plot(row['projection_x_coordinate']/1000, row['projection_y_coordinate']/1000, 'x', color=color,markersize=4) #Create surface projection of mask for the respective cell and plot it in the right color z_coord = 'model_level_number' if len(mask_total.shape)==3: mask_total_i_surface = mask_features_surface(mask_total, feature, masked=False, z_coord=z_coord) elif len(mask_total.shape)==2: mask_total_i_surface=mask_features(mask_total, feature, masked=False, z_coord=z_coord) axes.contour(mask_total_i_surface.coord('projection_x_coordinate').points/1000, mask_total_i_surface.coord('projection_y_coordinate').points/1000, mask_total_i_surface.data, levels=[0, feature], colors=color, linestyles=':',linewidth=1) if cog is not None: for i_row, row in cog.iterrows(): cell = row['cell'] if cell==cell_i: color='darkred' else: color='darkorange' # plot marker for centre of gravity as a circle axes.plot(row['x_M']/1000, row['y_M']/1000, 'o', markeredgecolor=color, markerfacecolor='None',markersize=4) if features is not None: for i_row, row in features.iterrows(): color='purple' axes.plot(row['projection_x_coordinate']/1000, row['projection_y_coordinate']/1000, '+', color=color,markersize=3) axes.set_xlabel('x (km)') axes.set_ylabel('y (km)') axes.set_xlim(xlim) axes.set_ylim(ylim) axes.xaxis.set_label_position('top') axes.xaxis.set_ticks_position('top') axes.set_title(title,pad=35,fontsize=10,horizontalalignment='left',loc='left') return axes def plot_mask_cell_track_2D3Dstatic(cell,track, cog, features, mask_total, field_contour, field_filled, width=10000,n_extend=1, name= 'test', plotdir='./', file_format=['png'],figsize=(10/2.54, 10/2.54),dpi=300, ele=10,azim=30, **kwargs): '''Make plots for all cells with fixed frame including entire development of the cell and with one background field as filling and one background field as contrours Input: Output: ''' from iris import Constraint from numpy import unique import os from mpl_toolkits.mplot3d import Axes3D import matplotlib.gridspec as gridspec track_cell=track[track['cell']==cell] x_min=track_cell['projection_x_coordinate'].min()-width x_max=track_cell['projection_x_coordinate'].max()+width y_min=track_cell['projection_y_coordinate'].min()-width y_max=track_cell['projection_y_coordinate'].max()+width #set up looping over time based on mask's time coordinate to allow for one timestep before and after the track time_coord=mask_total.coord('time') time=time_coord.units.num2date(time_coord.points) i_start=max(0,np.where(time==track_cell['time'].values[0])[0][0]-n_extend) i_end=min(len(time)-1,np.where(time==track_cell['time'].values[-1])[0][0]+n_extend+1) time_cell=time[slice(i_start,i_end)] for time_i in time_cell: # for i_row,row in track_cell.iterrows(): # time_i=row['time'] # constraint_time = Constraint(time=row['time']) constraint_time = Constraint(time=time_i) constraint_x = Constraint(projection_x_coordinate = lambda cell: x_min < cell < x_max) constraint_y = Constraint(projection_y_coordinate = lambda cell: y_min < cell < y_max) constraint = constraint_time & constraint_x & constraint_y mask_total_i=mask_total.extract(constraint) if field_contour is None: field_contour_i=None else: field_contour_i=field_contour.extract(constraint) if field_filled is None: field_filled_i=None else: field_filled_i=field_filled.extract(constraint) track_i=track[track['time']==time_i] cells_mask=list(unique(mask_total_i.core_data())) track_cells=track_i.loc[(track_i['projection_x_coordinate'] > x_min) & (track_i['projection_x_coordinate'] < x_max) & (track_i['projection_y_coordinate'] > y_min) & (track_i['projection_y_coordinate'] < y_max)] cells_track=list(track_cells['cell'].values) cells=list(set( cells_mask + cells_track )) if cell not in cells: cells.append(cell) if 0 in cells: cells.remove(0) track_i=track_i[track_i['cell'].isin(cells)] if cog is None: cog_i=None else: cog_i=cog[cog['cell'].isin(cells)] cog_i=cog_i[cog_i['time']==time_i] if features is None: features_i=None else: features_i=features[features['time']==time_i] fig1=plt.figure(figsize=(20 / 2.54, 10 / 2.54)) fig1.subplots_adjust(left=0.1, bottom=0.15, right=0.9, top=0.9,wspace=0.3, hspace=0.25) # make two subplots for figure: gs1 = gridspec.GridSpec(1, 2,width_ratios=[1,1.2]) fig1.add_subplot(gs1[0]) fig1.add_subplot(gs1[1], projection='3d') ax1 = fig1.get_axes() datestring_stamp = time_i.strftime('%Y-%m-%d %H:%M:%S') if time_i in track_cell['time'].values: time_cell_i=track_cell[track_cell['time'].values==time_i]['time_cell'] celltime_stamp = "%02d:%02d:%02d" % (time_cell_i.dt.total_seconds() // 3600, (time_cell_i.dt.total_seconds() % 3600) // 60, time_cell_i.dt.total_seconds() % 60 ) else: celltime_stamp=' - ' title=datestring_stamp + ' , ' + celltime_stamp datestring_file = time_i.strftime('%Y-%m-%d_%H%M%S') ax1[0]=plot_mask_cell_individual_static(cell_i=cell, track=track_i, cog=cog_i,features=features_i, mask_total=mask_total_i, field_contour=field_contour_i, field_filled=field_filled_i, xlim=[x_min/1000,x_max/1000],ylim=[y_min/1000,y_max/1000], axes=ax1[0],title=title,**kwargs) ax1[1]=plot_mask_cell_individual_3Dstatic(cell_i=cell, track=track_i, cog=cog_i,features=features_i, mask_total=mask_total_i, field_contour=field_contour_i, field_filled=field_filled_i, xlim=[x_min/1000,x_max/1000],ylim=[y_min/1000,y_max/1000], axes=ax1[1],title=title, ele=ele,azim=azim, **kwargs) out_dir = os.path.join(plotdir, name) os.makedirs(out_dir, exist_ok=True) if 'png' in file_format: savepath_png = os.path.join(out_dir, name + '_' + datestring_file + '.png') fig1.savefig(savepath_png, dpi=dpi) logging.debug('Mask static 2d/3D plot saved to ' + savepath_png) if 'pdf' in file_format: savepath_pdf = os.path.join(out_dir, name + '_' + datestring_file + '.pdf') fig1.savefig(savepath_pdf, dpi=dpi) logging.debug('Mask static 2d/3D plot saved to ' + savepath_pdf) plt.close() plt.clf() def plot_mask_cell_track_3Dstatic(cell,track, cog, features, mask_total, field_contour, field_filled, width=10000,n_extend=1, name= 'test', plotdir='./', file_format=['png'],figsize=(10/2.54, 10/2.54),dpi=300, **kwargs): '''Make plots for all cells with fixed frame including entire development of the cell and with one background field as filling and one background field as contrours Input: Output: ''' from iris import Constraint from numpy import unique import os from mpl_toolkits.mplot3d import Axes3D track_cell=track[track['cell']==cell] x_min=track_cell['projection_x_coordinate'].min()-width x_max=track_cell['projection_x_coordinate'].max()+width y_min=track_cell['projection_y_coordinate'].min()-width y_max=track_cell['projection_y_coordinate'].max()+width #set up looping over time based on mask's time coordinate to allow for one timestep before and after the track time_coord=mask_total.coord('time') time=time_coord.units.num2date(time_coord.points) i_start=max(0,np.where(time==track_cell['time'].values[0])[0][0]-n_extend) i_end=min(len(time)-1,np.where(time==track_cell['time'].values[-1])[0][0]+n_extend+1) time_cell=time[slice(i_start,i_end)] for time_i in time_cell: # for i_row,row in track_cell.iterrows(): # time_i=row['time'] # constraint_time = Constraint(time=row['time']) constraint_time = Constraint(time=time_i) constraint_x = Constraint(projection_x_coordinate = lambda cell: x_min < cell < x_max) constraint_y = Constraint(projection_y_coordinate = lambda cell: y_min < cell < y_max) constraint = constraint_time & constraint_x & constraint_y mask_total_i=mask_total.extract(constraint) if field_contour is None: field_contour_i=None else: field_contour_i=field_contour.extract(constraint) if field_filled is None: field_filled_i=None else: field_filled_i=field_filled.extract(constraint) track_i=track[track['time']==time_i] cells_mask=list(unique(mask_total_i.core_data())) track_cells=track_i.loc[(track_i['projection_x_coordinate'] > x_min) & (track_i['projection_x_coordinate'] < x_max) & (track_i['projection_y_coordinate'] > y_min) & (track_i['projection_y_coordinate'] < y_max)] cells_track=list(track_cells['cell'].values) cells=list(set( cells_mask + cells_track )) if cell not in cells: cells.append(cell) if 0 in cells: cells.remove(0) track_i=track_i[track_i['cell'].isin(cells)] if cog is None: cog_i=None else: cog_i=cog[cog['cell'].isin(cells)] cog_i=cog_i[cog_i['time']==time_i] if features is None: features_i=None else: features_i=features[features['time']==time_i] # fig1, ax1 = plt.subplots(ncols=1, nrows=1, figsize=figsize) # fig1.subplots_adjust(left=0.2, bottom=0.15, right=0.80, top=0.85) fig1, ax1 = plt.subplots(ncols=1, nrows=1, figsize=(10/2.54, 10/2.54), subplot_kw={'projection': '3d'}) datestring_stamp = time_i.strftime('%Y-%m-%d %H:%M:%S') if time_i in track_cell['time'].values: time_cell_i=track_cell[track_cell['time'].values==time_i]['time_cell'] celltime_stamp = "%02d:%02d:%02d" % (time_cell_i.dt.total_seconds() // 3600, (time_cell_i.dt.total_seconds() % 3600) // 60, time_cell_i.dt.total_seconds() % 60 ) else: celltime_stamp=' - ' title=datestring_stamp + ' , ' + celltime_stamp datestring_file = time_i.strftime('%Y-%m-%d_%H%M%S') ax1=plot_mask_cell_individual_3Dstatic(cell_i=cell, track=track_i, cog=cog_i,features=features_i, mask_total=mask_total_i, field_contour=field_contour_i, field_filled=field_filled_i, xlim=[x_min/1000,x_max/1000],ylim=[y_min/1000,y_max/1000], axes=ax1,title=title,**kwargs) out_dir = os.path.join(plotdir, name) os.makedirs(out_dir, exist_ok=True) if 'png' in file_format: savepath_png = os.path.join(out_dir, name + '_' + datestring_file + '.png') fig1.savefig(savepath_png, dpi=dpi) logging.debug('Mask static plot saved to ' + savepath_png) if 'pdf' in file_format: savepath_pdf = os.path.join(out_dir, name + '_' + datestring_file + '.pdf') fig1.savefig(savepath_pdf, dpi=dpi) logging.debug('Mask static plot saved to ' + savepath_pdf) plt.close() plt.clf() def plot_mask_cell_individual_3Dstatic(cell_i,track, cog, features, mask_total, field_contour, field_filled, axes=None,xlim=None,ylim=None, label_field_contour=None, cmap_field_contour='Blues',norm_field_contour=None, linewidths_contour=0.8,contour_labels=False, vmin_field_contour=0,vmax_field_contour=50,levels_field_contour=None,nlevels_field_contour=10, label_field_filled=None,cmap_field_filled='summer',norm_field_filled=None, vmin_field_filled=0,vmax_field_filled=100,levels_field_filled=None,nlevels_field_filled=10, title=None,feature_number=False, ele=10.,azim=210. ): '''Make plots for cell in fixed frame and with one background field as filling and one background field as contrours Input: Output: ''' import numpy as np from .utils import mask_features,mask_features_surface # from mpl_toolkits.axes_grid1 import make_axes_locatable # from matplotlib.colors import Normalize from mpl_toolkits.mplot3d import Axes3D axes.view_init(elev=ele, azim=azim) axes.grid(b=False) axes.set_frame_on(False) # make the panes transparent axes.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) axes.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) axes.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) # make the grid lines transparent axes.xaxis._axinfo["grid"]['color'] = (1,1,1,0) axes.yaxis._axinfo["grid"]['color'] = (1,1,1,0) axes.zaxis._axinfo["grid"]['color'] = (1,1,1,0) if title is not None: axes.set_title(title,horizontalalignment='left',loc='left') # colors_mask = ['pink','darkred', 'orange', 'darkred', 'red', 'darkorange'] x = mask_total.coord('projection_x_coordinate').points y = mask_total.coord('projection_y_coordinate').points z = mask_total.coord('model_level_number').points # z = mask_total.coord('geopotential_height').points zz, yy, xx = np.meshgrid(z, y, x, indexing='ij') # z_alt = mask_total.coord('geopotential_height').points # divider = make_axes_locatable(axes) # if field_filled is not None: # if levels_field_filled is None: # levels_field_filled=np.linspace(vmin_field_filled,vmax_field_filled, 10) # plot_field_filled = axes.contourf(field_filled.coord('projection_x_coordinate').points/1000, # field_filled.coord('projection_y_coordinate').points/1000, # field_filled.data, # levels=levels_field_filled, norm=norm_field_filled, # cmap=cmap_field_filled, vmin=vmin_field_filled, vmax=vmax_field_filled) # cax_filled = divider.append_axes("right", size="5%", pad=0.1) # norm_filled= Normalize(vmin=vmin_field_filled, vmax=vmax_field_filled) # sm1= plt.cm.ScalarMappable(norm=norm_filled, cmap = plot_field_filled.cmap) # sm1.set_array([]) # cbar_field_filled = plt.colorbar(sm1, orientation='vertical',cax=cax_filled) # cbar_field_filled.ax.set_ylabel(label_field_filled) # cbar_field_filled.set_clim(vmin_field_filled, vmax_field_filled) # if field_contour is not None: # if levels_field_contour is None: # levels_field_contour=np.linspace(vmin_field_contour, vmax_field_contour, 5) # plot_field_contour = axes.contour(field_contour.coord('projection_x_coordinate').points/1000, # field_contour.coord('projection_y_coordinate').points/1000, # field_contour.data, # cmap=cmap_field_contour,norm=norm_field_contour, # levels=levels_field_contour,vmin=vmin_field_contour, vmax=vmax_field_contour, # linewidths=linewidths_contour) # if contour_labels: # axes.clabel(plot_field_contour, fontsize=10) # cax_contour = divider.append_axes("bottom", size="5%", pad=0.1) # if norm_field_contour: # vmin_field_contour=None # vmax_field_contour=None # norm_contour=norm_field_contour # else: # norm_contour= Normalize(vmin=vmin_field_contour, vmax=vmax_field_contour) # # sm_contour= plt.cm.ScalarMappable(norm=norm_contour, cmap = plot_field_contour.cmap) # sm_contour.set_array([]) # # cbar_field_contour = plt.colorbar(sm_contour, orientation='horizontal',ticks=levels_field_contour,cax=cax_contour) # cbar_field_contour.ax.set_xlabel(label_field_contour) # cbar_field_contour.set_clim(vmin_field_contour, vmax_field_contour) # for i_row, row in track.iterrows(): cell = row['cell'] feature = row['feature'] # logging.debug("cell: "+ str(row['cell'])) # logging.debug("feature: "+ str(row['feature'])) if cell==cell_i: color='darkred' if feature_number: cell_string=' '+str(int(cell))+' ('+str(int(feature))+')' else: cell_string=' '+str(int(cell)) elif np.isnan(cell): color='gray' if feature_number: cell_string=' '+'('+str(int(feature))+')' else: cell_string=' ' else: color='darkorange' if feature_number: cell_string=' '+str(int(cell))+' ('+str(int(feature))+')' else: cell_string=' '+str(int(cell)) # axes.text(row['projection_x_coordinate']/1000, # row['projection_y_coordinate']/1000, # 0, # cell_string,color=color,fontsize=6, clip_on=True) # # Plot marker for tracked cell centre as a cross # axes.plot(row['projection_x_coordinate']/1000, # row['projection_y_coordinate']/1000, # 0, # 'x', color=color,markersize=4) #Create surface projection of mask for the respective cell and plot it in the right color # z_coord = 'model_level_number' # if len(mask_total.shape)==3: # mask_total_i_surface = mask_features_surface(mask_total, feature, masked=False, z_coord=z_coord) # elif len(mask_total.shape)==2: # mask_total_i_surface=mask_features(mask_total, feature, masked=False, z_coord=z_coord) # axes.contour(mask_total_i_surface.coord('projection_x_coordinate').points/1000, # mask_total_i_surface.coord('projection_y_coordinate').points/1000, # 0, # mask_total_i_surface.data, # levels=[0, feature], colors=color, linestyles=':',linewidth=1) mask_feature = mask_total.data == feature axes.scatter( # xx[mask_feature]/1000, yy[mask_feature]/1000, zz[mask_feature]/1000, xx[mask_feature]/1000, yy[mask_feature]/1000, zz[mask_feature], c=color, marker=',', s=5,#60000.0 * TWC_i[Mask_particle], alpha=0.3, cmap='inferno', label=cell_string,rasterized=True) axes.set_xlim(xlim) axes.set_ylim(ylim) axes.set_zlim([0, 100]) # axes.set_zlim([0, 20]) # axes.set_zticks([0, 5,10,15, 20]) axes.set_xlabel('x (km)') axes.set_ylabel('y (km)') axes.zaxis.set_rotate_label(False) # disable automatic rotation # axes.set_zlabel('z (km)', rotation=90) axes.set_zlabel('model level', rotation=90) return axes def plot_mask_cell_track_static_timeseries(cell,track, cog, features, mask_total, field_contour, field_filled, track_variable=None,variable=None,variable_ylabel=None,variable_label=[None],variable_legend=False,variable_color=None, width=10000,n_extend=1, name= 'test', plotdir='./', file_format=['png'],figsize=(20/2.54, 10/2.54),dpi=300, **kwargs): '''Make plots for all cells with fixed frame including entire development of the cell and with one background field as filling and one background field as contrours Input: Output: ''' '''Make plots for all cells with fixed frame including entire development of the cell and with one background field as filling and one background field as contrours Input: Output: ''' from iris import Constraint from numpy import unique import os import pandas as pd track_cell=track[track['cell']==cell] x_min=track_cell['projection_x_coordinate'].min()-width x_max=track_cell['projection_x_coordinate'].max()+width y_min=track_cell['projection_y_coordinate'].min()-width y_max=track_cell['projection_y_coordinate'].max()+width time_min=track_cell['time'].min() # time_max=track_cell['time'].max() track_variable_cell=track_variable[track_variable['cell']==cell] track_variable_cell['time_cell']=pd.to_timedelta(track_variable_cell['time_cell']) # track_variable_cell=track_variable_cell[(track_variable_cell['time']>=time_min) & (track_variable_cell['time']<=time_max)] #set up looping over time based on mask's time coordinate to allow for one timestep before and after the track time_coord=mask_total.coord('time') time=time_coord.units.num2date(time_coord.points) i_start=max(0,np.where(time==track_cell['time'].values[0])[0][0]-n_extend) i_end=min(len(time)-1,np.where(time==track_cell['time'].values[-1])[0][0]+n_extend+1) time_cell=time[slice(i_start,i_end)] for time_i in time_cell: constraint_time = Constraint(time=time_i) constraint_x = Constraint(projection_x_coordinate = lambda cell: x_min < cell < x_max) constraint_y = Constraint(projection_y_coordinate = lambda cell: y_min < cell < y_max) constraint = constraint_time & constraint_x & constraint_y mask_total_i=mask_total.extract(constraint) if field_contour is None: field_contour_i=None else: field_contour_i=field_contour.extract(constraint) if field_filled is None: field_filled_i=None else: field_filled_i=field_filled.extract(constraint) track_i=track[track['time']==time_i] cells_mask=list(unique(mask_total_i.core_data())) track_cells=track_i.loc[(track_i['projection_x_coordinate'] > x_min) & (track_i['projection_x_coordinate'] < x_max) & (track_i['projection_y_coordinate'] > y_min) & (track_i['projection_y_coordinate'] < y_max)] cells_track=list(track_cells['cell'].values) cells=list(set( cells_mask + cells_track )) if cell not in cells: cells.append(cell) if 0 in cells: cells.remove(0) track_i=track_i[track_i['cell'].isin(cells)] if cog is None: cog_i=None else: cog_i=cog[cog['cell'].isin(cells)] cog_i=cog_i[cog_i['time']==time_i] if features is None: features_i=None else: features_i=features[features['time']==time_i] fig1, ax1 = plt.subplots(ncols=2, nrows=1, figsize=figsize) fig1.subplots_adjust(left=0.1, bottom=0.15, right=0.90, top=0.85,wspace=0.3) datestring_stamp = time_i.strftime('%Y-%m-%d %H:%M:%S') if time_i in track_cell['time'].values: time_cell_i=track_cell[track_cell['time'].values==time_i]['time_cell'] celltime_stamp = "%02d:%02d:%02d" % (time_cell_i.dt.total_seconds() // 3600, (time_cell_i.dt.total_seconds() % 3600) // 60, time_cell_i.dt.total_seconds() % 60 ) else: celltime_stamp=' - ' title=celltime_stamp + ' , ' + datestring_stamp datestring_file = time_i.strftime('%Y-%m-%d_%H%M%S') # plot evolving timeseries of variable to second axis: ax1[0]=plot_mask_cell_individual_static(cell_i=cell, track=track_i, cog=cog_i,features=features_i, mask_total=mask_total_i, field_contour=field_contour_i, field_filled=field_filled_i, xlim=[x_min/1000,x_max/1000],ylim=[y_min/1000,y_max/1000], axes=ax1[0],title=title,**kwargs) track_variable_past=track_variable_cell[(track_variable_cell['time']>=time_min) & (track_variable_cell['time']<=time_i)] track_variable_current=track_variable_cell[track_variable_cell['time']==time_i] if variable_color is None: variable_color='navy' if type(variable) is str: # logging.debug('variable: '+str(variable)) if type(variable_color) is str: variable_color={variable:variable_color} variable=[variable] for i_variable,variable_i in enumerate(variable): color=variable_color[variable_i] ax1[1].plot(track_variable_past['time_cell'].dt.total_seconds()/ 60.,track_variable_past[variable_i].values,color=color,linestyle='-',label=variable_label[i_variable]) ax1[1].plot(track_variable_current['time_cell'].dt.total_seconds()/ 60.,track_variable_current[variable_i].values,color=color,marker='o',markersize=4,fillstyle='full') ax1[1].yaxis.tick_right() ax1[1].yaxis.set_label_position("right") ax1[1].set_xlim([0,2*60]) ax1[1].set_xticks(np.arange(0,120,15)) ax1[1].set_ylim([0,max(10,1.25*track_variable_cell[variable].max().max())]) ax1[1].set_xlabel('cell lifetime (min)') if variable_ylabel==None: variable_ylabel=variable ax1[1].set_ylabel(variable_ylabel) ax1[1].set_title(title) # insert legend, if flag is True if variable_legend: if (len(variable_label)<5): ncol=1 else: ncol=2 ax1[1].legend(loc='upper right', bbox_to_anchor=(1, 1),ncol=ncol,fontsize=8) out_dir = os.path.join(plotdir, name) os.makedirs(out_dir, exist_ok=True) if 'png' in file_format: savepath_png = os.path.join(out_dir, name + '_' + datestring_file + '.png') fig1.savefig(savepath_png, dpi=dpi) logging.debug('Mask static plot saved to ' + savepath_png) if 'pdf' in file_format: savepath_pdf = os.path.join(out_dir, name + '_' + datestring_file + '.pdf') fig1.savefig(savepath_pdf, dpi=dpi) logging.debug('Mask static plot saved to ' + savepath_pdf) plt.close() plt.clf() def map_tracks(track,axis_extent=None,figsize=(10,10),axes=None): for cell in track['cell'].dropna().unique(): track_i=track[track['cell']==cell] axes.plot(track_i['longitude'],track_i['latitude'],'-') if axis_extent: axes.set_extent(axis_extent) axes=make_map(axes) return axes def make_map(axes): import matplotlib.ticker as mticker import cartopy.crs as ccrs from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER gl = axes.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='gray', alpha=0.5, linestyle='-') axes.coastlines('10m') gl.xlabels_top = False gl.ylabels_right = False gl.xlocator = mticker.MaxNLocator(nbins=5,min_n_ticks=3,steps=None) gl.ylocator = mticker.MaxNLocator(nbins=5,min_n_ticks=3,steps=None) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER #gl.xlabel_style = {'size': 15, 'color': 'gray'} #gl.xlabel_style = {'color': 'red', 'weight': 'bold'} return axes def plot_lifetime_histogram(track,axes=None,bin_edges=np.arange(0,200,20),density=False,**kwargs): hist, bin_edges,bin_centers = lifetime_histogram(track,bin_edges=bin_edges,density=density) plot_hist=axes.plot(bin_centers, hist,**kwargs) return plot_hist def plot_lifetime_histogram_bar(track,axes=None,bin_edges=np.arange(0,200,20),density=False,width_bar=1,shift=0.5,**kwargs): hist, bin_edges, bin_centers = lifetime_histogram(track,bin_edges=bin_edges,density=density) plot_hist=axes.bar(bin_centers+shift,hist,width=width_bar,**kwargs) return plot_hist def plot_histogram_cellwise(track,bin_edges,variable,quantity,axes=None,density=False,**kwargs): hist, bin_edges,bin_centers = histogram_cellwise(track,bin_edges=bin_edges,variable=variable,quantity=quantity,density=density) plot_hist=axes.plot(bin_centers, hist,**kwargs) return plot_hist def plot_histogram_featurewise(Track,bin_edges,variable,axes=None,density=False,**kwargs): hist, bin_edges, bin_centers = histogram_featurewise(Track,bin_edges=bin_edges,variable=variable,density=density) plot_hist=axes.plot(bin_centers, hist,**kwargs) return plot_hist
7746bc6553e721b3cb1afcac1a1d21f5fe169b99
[ "Python", "Text", "reStructuredText" ]
15
Python
zxdawn/tobac
61be9af85e0f1e8dd287b337bebdb5af8d0a768f
9a64f8b93a73947068044f36a149a95ae3a3ddba
refs/heads/master
<repo_name>Czakero/sql-gs<file_sep>/src/main/java/com/sqlcsv/sqlcsv/controller/exception/ParseQueryException.java package com.sqlcsv.sqlcsv.controller.exception; public class ParseQueryException extends RuntimeException { public ParseQueryException(String message) { super(message); } } <file_sep>/src/main/java/com/sqlcsv/sqlcsv/controller/ErrorController.java package com.sqlcsv.sqlcsv.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController { @RequestMapping("/error") public void handleError(HttpServletResponse response) throws IOException { response.sendRedirect("/auth"); } @Override public String getErrorPath() { return "/error"; } } <file_sep>/src/main/java/com/sqlcsv/sqlcsv/interfaces/IQueryChecker.java package com.sqlcsv.sqlcsv.interfaces; import com.sqlcsv.sqlcsv.controller.exception.ParseQueryException; import net.sf.jsqlparser.parser.CCJSqlParserManager; public interface IQueryChecker { CCJSqlParserManager parserManager = new CCJSqlParserManager(); void checkQuery(String query) throws ParseQueryException; } <file_sep>/src/main/java/com/sqlcsv/sqlcsv/service/googleservice/DriveService.java package com.sqlcsv.sqlcsv.service.googleservice; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; import com.sqlcsv.sqlcsv.google.GoogleAuthorizationFlow; import com.sqlcsv.sqlcsv.enums.ServicesEnum; import com.sqlcsv.sqlcsv.interfaces.IDriveService; import org.springframework.stereotype.Service; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @Service public class DriveService implements IDriveService { private static final String SPREADSHEET = "application/vnd.google-apps.spreadsheet"; public Map<String, String> getAllSpreadsheets(String userId) throws IOException, GeneralSecurityException { Drive userDrive = (Drive) GoogleAuthorizationFlow.getService(ServicesEnum.DRIVE, userId); FileList files = Objects.requireNonNull(userDrive).files().list().execute(); return files.getFiles() .stream() .filter(s -> s.getMimeType().equals(SPREADSHEET)) .collect(Collectors.toMap(File::getName, File::getId)); } } <file_sep>/src/main/java/com/sqlcsv/sqlcsv/interfaces/IQueryExecutor.java package com.sqlcsv.sqlcsv.interfaces; import com.sqlcsv.sqlcsv.controller.exception.ParseQueryException; import com.sqlcsv.sqlcsv.enums.SQLKeywords; import java.util.List; import java.util.Map; public interface IQueryExecutor { String[][] executeQuery(String[][] queriedSheet, Map<SQLKeywords, List<String>> parsedQuery) throws ParseQueryException; } <file_sep>/src/main/java/com/sqlcsv/sqlcsv/service/queryhandlers/OperatorsHandler.java package com.sqlcsv.sqlcsv.service.queryhandlers; import com.sqlcsv.sqlcsv.controller.exception.ParseQueryException; import org.springframework.stereotype.Component; import java.util.stream.IntStream; @Component public class OperatorsHandler { public int[] getIndexes(String[][] queriedSheet, int questionedColumnIndex, String whereOperator, String parameter) throws ParseQueryException { try { switch (whereOperator) { case "=": return equalCase(queriedSheet, questionedColumnIndex, parameter); case "!=": return notEqualCase(queriedSheet, questionedColumnIndex, parameter); case "<": return lesserThanCase(queriedSheet, questionedColumnIndex, parameter); case ">": return biggerThanCase(queriedSheet, questionedColumnIndex, parameter); case "<=": return lesserOrEqualCase(queriedSheet, questionedColumnIndex, parameter); case ">=": return biggerOrEqualCase(queriedSheet, questionedColumnIndex, parameter); default: return null; } } catch (NumberFormatException e) { throw new ParseQueryException("Provided parameter in where clause is not a number!"); } } private int[] biggerOrEqualCase(String[][] queriedSheet, int questionedColumnIndex, String parameter) throws NumberFormatException { return IntStream .range(0 , queriedSheet.length) .filter(i -> Integer.valueOf(queriedSheet[i][questionedColumnIndex]) >= Integer.valueOf(parameter)) .toArray(); } private int[] lesserOrEqualCase(String[][] queriedSheet, int questionedColumnIndex, String parameter) throws NumberFormatException { return IntStream .range(0 , queriedSheet.length) .filter(i -> Integer.valueOf(queriedSheet[i][questionedColumnIndex]) <= Integer.valueOf(parameter)) .toArray(); } private int[] biggerThanCase(String[][] queriedSheet, int questionedColumnIndex, String parameter) throws NumberFormatException { return IntStream .range(0 , queriedSheet.length) .filter(i -> Integer.valueOf(queriedSheet[i][questionedColumnIndex]) > Integer.valueOf(parameter)) .toArray(); } private int[] lesserThanCase(String[][] queriedSheet, int questionedColumnIndex, String parameter) throws NumberFormatException { return IntStream .range(0 , queriedSheet.length) .filter(i -> Integer.valueOf(queriedSheet[i][questionedColumnIndex]) < Integer.valueOf(parameter)) .toArray(); } private int[] notEqualCase(String[][] queriedSheet, int questionedColumnIndex, String parameter) { return IntStream .range(0 , queriedSheet.length) .filter(i -> !queriedSheet[i][questionedColumnIndex].equals(parameter)) .toArray(); } private int[] equalCase(String[][] queriedSheet, int questionedColumnIndex, String parameter) { return IntStream .range(0, queriedSheet.length) .filter(i -> queriedSheet[i][questionedColumnIndex].equals(parameter)) .toArray(); } } <file_sep>/src/main/java/com/sqlcsv/sqlcsv/service/googleservice/SheetsService.java package com.sqlcsv.sqlcsv.service.googleservice; import com.google.api.services.sheets.v4.Sheets; import com.google.api.services.sheets.v4.model.Spreadsheet; import com.google.api.services.sheets.v4.model.ValueRange; import com.sqlcsv.sqlcsv.google.GoogleAuthorizationFlow; import com.sqlcsv.sqlcsv.enums.ServicesEnum; import com.sqlcsv.sqlcsv.interfaces.ISheetsService; import com.sqlcsv.sqlcsv.service.parser.SheetsParser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; import java.util.Objects; @Service public class SheetsService implements ISheetsService { private SheetsParser sheetsParser; @Autowired public SheetsService(SheetsParser sheetsParser) { this.sheetsParser = sheetsParser; } public String[][] getSheetFromSpreadsheet(String spreadsheetId, String sheetName, String userId) throws IOException, GeneralSecurityException { Sheets sheetsService = (Sheets) GoogleAuthorizationFlow.getService(ServicesEnum.SHEETS, userId); return sheetsParser.parseSheetValues(obtainSheetContent(spreadsheetId, sheetName, sheetsService)); } public List<String> getSheetsNamesFromSpreadsheet(String spreadsheetId, String userId) throws IOException, GeneralSecurityException { Sheets sheetsService = (Sheets) GoogleAuthorizationFlow.getService(ServicesEnum.SHEETS, userId); Spreadsheet spreadsheet = Objects.requireNonNull(sheetsService).spreadsheets().get(spreadsheetId).execute(); return sheetsParser.parseSheetNamesFromSpreadSheet(spreadsheet.getSheets()); } private ValueRange obtainSheetContent(String spreadsheetId, String sheetName, Sheets sheetsService) throws IOException { return Objects.requireNonNull(sheetsService) .spreadsheets() .values() .get(spreadsheetId, sheetName) .execute(); } } <file_sep>/src/main/java/com/sqlcsv/sqlcsv/service/queryhandlers/QueryMapper.java package com.sqlcsv.sqlcsv.service.queryhandlers; import com.sqlcsv.sqlcsv.controller.exception.ParseQueryException; import com.sqlcsv.sqlcsv.enums.SQLKeywords; import com.sqlcsv.sqlcsv.interfaces.IQueryMapper; import org.springframework.stereotype.Component; import java.util.*; @Component public class QueryMapper implements IQueryMapper { @SuppressWarnings("OptionalGetWithoutIsPresent") @Override public Map<SQLKeywords, List<String>> mapQuery(String query) throws ParseQueryException { Map<SQLKeywords, List<String>> result = new EnumMap<>(SQLKeywords.class); String keyword = ""; for (String word : query.split(" ")) { if (SQLKeywords.contains(word.toUpperCase())) { keyword = word; result.put(SQLKeywords.getByName(keyword).get(), new ArrayList<>()); } else if (NOT_SUPPORTED_KEYWORDS.contains(word.toUpperCase())) { throw new ParseQueryException(word.toUpperCase() + " statement is not supported now! Maybe in the future."); } else { result.get(SQLKeywords.getByName(keyword).get()).add(word.replaceAll(",", "").replaceAll(";", "").replaceAll("'", "")); } } return result; } } <file_sep>/README.md ### SQL your CSV [![Build Status](https://travis-ci.org/Czakero/sql-gs.svg?branch=dev)](https://travis-ci.org/Czakero/sql-gs) Web-app which uses Google API for authorization and retrieving services (sheets, drive) to let user obtain data from their sheets, stored on google drive with simple SQL queries. ### Built with: 1. Maven - Dependency Management 2. Spring Boot ### Tools: 1. IntelliJ IDEA ### Authors: - <NAME> [Github profile](https://github.com/Czakero) - <NAME> [Github profile](https://github.com/cyan0505) - <NAME> [Github profile](https://github.com/Szwajcii) - <NAME> [Github profile](https://github.com/Pieczkowski) <file_sep>/src/main/java/com/sqlcsv/sqlcsv/service/googleservice/AuthService.java package com.sqlcsv.sqlcsv.service.googleservice; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; import com.sqlcsv.sqlcsv.google.GoogleAuthorizationFlow; import com.sqlcsv.sqlcsv.interfaces.IAuthService; import org.springframework.stereotype.Service; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.security.GeneralSecurityException; @Service public class AuthService implements IAuthService { @Override public String createNewAuthorizationUrl() throws IOException, GeneralSecurityException { return GoogleAuthorizationFlow.getFlow().newAuthorizationUrl() .setRedirectUri("http://localhost:8080/callback") .build(); } @Override public String authorizeAndSaveToken(String code) throws IOException, GeneralSecurityException { GoogleAuthorizationCodeFlow flow = GoogleAuthorizationFlow.getFlow(); GoogleTokenResponse tokenResponse = flow .newTokenRequest(code) .setRedirectUri("http://localhost:8080/callback") .setClientAuthentication(flow.getClientAuthentication()) .setCode(code) .set("response-type", "code") .setGrantType("authorization_code") .execute(); String userId = getUserEmail(tokenResponse); flow.createAndStoreCredential(tokenResponse, userId); return userId; } private String getUserEmail(GoogleTokenResponse tokenResponse) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + tokenResponse.getAccessToken()).openConnection(); connection.setRequestMethod("GET"); JsonNode json = new ObjectMapper().readTree(connection.getInputStream()); return json.findValue("email").toString().replaceAll("\"", ""); } }
57a40f3dd32e597b229fa9e3c1c7e2c399e9ba1a
[ "Markdown", "Java" ]
10
Java
Czakero/sql-gs
0bbb890a3d942c76a4d743279b891d47b019eaff
02b52ae922712c6e8132cf9dd5709c4729d312df
refs/heads/master
<repo_name>frankdev95/RESTful-API-node-rest-shop<file_sep>/server.js const http = require('http'); const app = require('./app'); let port = process.env.PORT !== undefined ? process.env.PORT : 3000; // create a simple http server and pass in app which acts as a request handler, app is exported from app.js. const server = http.createServer(app); server.listen(port, () => console.log(`Listening on port ${port}`)); <file_sep>/api/routes/user.js const express = require('express'); const router = express.Router(); const checkAuth = require('../middleware/check-auth'); const userController = require('../controllers/users'); router.get('/', checkAuth, userController.users_find_all); router.get('/:id', checkAuth, userController.user_get_single); router.post('/signup', userController.user_sign_up); router.post('/login', userController.user_log_in); router.delete('/:id', checkAuth, userController.user_delete_single); module.exports = router; <file_sep>/api/controllers/users.js const User = require('../models/user'); const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const saltRounds = 10; const jwt = require('jsonwebtoken'); module.exports.users_find_all = (req, res, next) => { User.find() .then(users => { res.status(200).json({ count: users.count, users: users.map(user => { return { _id: user._id, email: user.email, password: <PASSWORD>, request: { method: 'GET', description: "Get the individual user", url: `http://localhost:3000/user/${user._id}` } } }) }); }) .catch(err => { res.status(500).json({ error: err }) }); } module.exports.user_get_single = (req, res) => { User.findById(req.params.id) .then(user => { if(!user) { res.status(404).json({ message: 'Please enter a valid user ID' }); } res.status(200).json({ message: "User obtained", user: user, request: { method: 'GET', description: 'Get all users', url: 'http://localhost:3000/user' } }); }) .catch(err => { res.status(500).json({ error: err }); }) } module.exports.user_sign_up = (req, res, next) => { User.findOne({email: req.body.email}) .then(user => { if(user) { return res.status(409).json({ message: "User with given email already exists" }); } else { bcrypt.hash(req.body.password, saltRounds, (err, hash) => { if(err) { return res.status(500).json({ error: err }); } const user = new User({ _id: new mongoose.Types.ObjectId(), email: req.body.email, password: <PASSWORD> }); user.save() .then(user => { res.status(201).json({ message: "New user created", user: { _id: user._id, email: user.email, password: <PASSWORD> }, request: { method: "GET", description: "Get the individual user", url: `http://localhost:3000/user/${user._id}` } }); }) .catch(err => { res.status(500).json({ error: err }); }); }); } }); } module.exports.user_log_in = (req, res, next) => { User.findOne({email: req.body.email}) .then(user => { if(!user) { return res.status(401).json({ message: "Authorization failed" }); } bcrypt.compare(req.body.password, <PASSWORD>, (err, result) => { if(err || !result) { return res.status(401).json({ message: "Authorization failed" }); } if(result) { /* JWT (JSON Web Token) - allows a token to be sent back to the client with relevant information after authorization is successful, this means the user can access the API until the token expires, preventing them from having to receive authorization every time they need data from the API. A secret key is specified during token creation, so that when the user accesses the API for all subsequent data retrievals, the token is passed back and the key is compared, if it matches the key supplied during token creation, the user is authorized. */ // If you set the jwt.sign to a variable the function runs synchronously and is stored in the // variable, you can always specify a callback for asynchronous functionality. const token = jwt.sign({ // payload specifies what information is sent back to the user via the token, which is used to create the key email: user.email, userID: user._id }, process.env.JWT_KEY, { // allows options for the token such as token expiry date expiresIn: '1h', // 1h is a good duration for security reasons. }); res.status(200).json({ message: "Authorization successful", token: token // pass the token back to the authorized user via the response }); } }); }) .catch(err => { res.status(500).json({ error: err }); }); } module.exports.user_delete_single = (req, res) => { User.deleteOne({_id: req.params.id}) .then(result => { if(result.deletedCount > 0) { return res.status(200).json({ message: "User deleted" }); } res.status(404).json({ message: "Please enter a valid user ID" }); }) .catch(err => { res.status(500).json({ error: err }) }) } <file_sep>/api/controllers/orders.js const Order = require('../models/order'); const Product = require('../models/product'); const mongoose = require('mongoose'); module.exports.orders_get_all = (req, res, next) => { Order.find() .select('product quantity') .populate('product', '_id name') .then(orders => { res.status(200).json({ count: orders.length, orders: orders.map(order => { return { order: { _id: order._id, product: order.product, quantity: order.quantity, }, request: { method: 'GET', description: 'Get the individual order', url: `http://localhost:3000/orders/${order._id}` } } }) }); }) .catch(err => { res.status(500).json({ error: err }) }) } module.exports.orders_get_single = (req, res, next) => { Order.findById(req.params.id) .populate('product') .then(order => { console.log(order); if(!order) { return res.status(404).json({ message: 'Please enter a valid order ID' }) } res.status(200).json({ message: 'Order obtained', order: { _id: order._id, product: order.product, quantity: order.quantity }, request: { method: 'GET', description: 'Get all orders', url: 'http://localhost:300/orders' } }); }) .catch(err => { console.error(err); res.status(500).json({ error: err }) }) } module.exports.orders_create_order = (req, res, next) => { Product.findById(req.body.productID) .then(product => { if(!product) { return res.status(404).json({ message: 'Please enter a valid product ID' }); } const order = new Order({ _id: mongoose.Types.ObjectId(), product: product._id, quantity: req.body.quantity, }); return order.save(); }) .then(order => { console.log(order); res.status(201).json({ message: 'New order created', createdProduct: { _id: order._id, product: order.product, quantity: order.quantity }, request: { method: 'GET', description: 'Get the individual product', url: `http://localhost:3000/orders/${order._id}` } }); }) .catch(err => { res.status(500).json({ message: 'Please specify a valid ID', error: err }); }); } module.exports.orders_delete_order = (req, res, next) => { Order.deleteOne({_id: req.params.id}) .then(result => { if(!result.deletedCount > 0) { res.status(404).json({ message: "Please enter a valid order ID" }); } res.status(200).json({ message: 'Order deleted', request: { method: 'POST', description: 'Create a new order', url: 'http://localhost:3000/orders', data: { productID: 'ID', quantity: 'Number' } } }); }) .catch(err => { console.log(err); res.status(500).json({ message: 'Unable to delete order with id specified', error: err }); }); } <file_sep>/api/routes/products.js const express = require('express'); const router = express.Router(); const multer = require('multer'); const checkAuth = require('../middleware/check-auth'); const productsController = require('../controllers/products'); const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, './uploads'); // Params: (potential error, filepath) }, filename: function(req, file, cb) { cb(null, `${Date.now()}${file.originalname}`); // Params: (potential error, filename) } }); const fileFilter = (req, file, cb) => { if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') return cb(null, true); // reject a file: cb(new Error('File has to be an image file - (jpeg, png)'), false); // accept a file: // cb(null, true); } const upload = multer({ storage: storage, limits: { fileSize: 1024 * 1024 * 5 }, fileFilter: fileFilter }); router.get('/', productsController.products_get_all); router.get('/:id', productsController.products_get_single); router.post('/', upload.single('productImage'), checkAuth, productsController.products_create_product); router.patch('/:id', checkAuth, productsController.products_update_single); router.delete('/:id', checkAuth, productsController.product_delete_single); module.exports = router;
d3f41ddeca5ede4830b0d97b589db7efecb07b62
[ "JavaScript" ]
5
JavaScript
frankdev95/RESTful-API-node-rest-shop
3cbd1c2f2b69169c38f3105aedc59b7c00551a5d
6a9d3c08e9f823bc9b109ed97c78994645c5635a
refs/heads/master
<repo_name>mpantoj/MobileAppGoogleMaps<file_sep>/src/pages/home/home.ts import { Component } from '@angular/core'; import { NavController, AlertController, //Controlador de alertas LoadingController, //Controlador de carga Loading, //Mensajes de carga Platform, //Conocer en que plataforma se corre la app ToastController //Mostrar mensajes toast } from 'ionic-angular'; //Diagnostico de nuestro Hardware import { Diagnostic } from '@ionic-native/diagnostic'; //Geoloclaización import { Geolocation } from '@ionic-native/geolocation'; //Permisos import { AndroidPermissions } from '@ionic-native/android-permissions'; import {GmapsProvider} from '../../providers/gmaps/gmaps' @Component({ selector: 'page-home', templateUrl: 'home.html', providers:[GmapsProvider] }) export class HomePage { loading: Loading; //Objeto de carga //Marcado del mapa y coordenadas m = <marker>{}; //Aquí obtendremos la dirección obtenida direccion:string lat: number = 19.5196998; lng: number = -99.1430755; constructor( public navCtrl: NavController, private alertCtrl: AlertController, private diagnostic: Diagnostic, private geolocation: Geolocation, private androidPermissions: AndroidPermissions, private loadingCtrl: LoadingController, private platform: Platform, private toastCtrl:ToastController, private gmapsProvider:GmapsProvider) { this.m.lat = this.lat this.m.lng = this.lng this.m.draggable=true } markerDragEnd(m: marker, $event){ this.m.lat = $event.coords.lat this.m.lng = $event.coords.lng this.showLoading() this.gmapsProvider.getAddressData(this.m.lat,this.m.lng).subscribe( response=>{ try{ //Obtenemos la direccion de las nuevas coordenadas this.direccion = response.results[0].formatted_address this.m.label = this.direccion this.loading.dismissAll() }catch(error){ this.errorInterno() } }, error=>{ this.errorInterno() } ) } async buscarUbicacion(){ //Verificamos si estamos en un celular if(!this.platform.is("cordova")){ this.mostrarToast("No es un celular") return; } //Mostrar mensaje this.showLoading() try{ //Verificamos si esta autorizado el permiso de localizacion var authorized = await this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.ACCESS_FINE_LOCATION) if (authorized){ //Si esta autorizado verificamos si esta activado el GPS let locationEnabled = await this.diagnostic.isLocationEnabled() //Si esta activa la localizacion obtenemos la posicion if (locationEnabled){ let location = await this.geolocation.getCurrentPosition() if(location!=null){ this.lat = location.coords.latitude this.lng = location.coords.longitude /**Una vez encontradas las coordenadas tenemos que mostrar * el mapa y pintar el punto**/ this.gmapsProvider.getAddressData(this.lat, this.lng) .subscribe( response=>{ try{ //Quitamos la carga this.loading.dismissAll() //Asignamos lat y lng al marcador this.m.lat = this.lat this.m.lng = this.lng //Definimos el marcador como arrastrable this.m.draggable = true //Seteamos en la variable dirección //La dirección obtenida this.direccion = response.results[0].formatted_address this.m.label = this.direccion //Mostramos mensaje this.displayMessage( 'Fija el pin en la ubicación correcta', 'Ubicación encontrada' ) } catch(error){ this.errorInterno() } }, error=>{ this.errorInterno() } ) this.loading.dismissAll() }else{ this.loading.dismissAll() throw Error('Location not found') } }else{ this.loading.dismissAll() //Si no esta activa la localizacion mandamos al usuario a activarla this.displayMessageForPermission("Activa tu GPS","Advertencia") } } //Si no esta autorizado pedimos los permisos else{ this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.ACCESS_FINE_LOCATION) this.loading.dismissAll() } }catch(error){ this.loading.dismissAll() this.displayMessage(error,'Error interno del sistema') } } //función que se encarga de mostrar mensaje Alerta private displayMessage(err:string,title:string){ let alert = this.alertCtrl.create({ title: title, subTitle: err, buttons: [ "Ok" ] }); alert.present(); } //Función que se encarga de mostrar un mensaje de alerta y al presionar OK //Mandamos al usuario a que active la geolocalizacion private displayMessageForPermission(err:string, title:string){ let alert = this.alertCtrl.create({ title: title, subTitle: err, buttons: [ { text:"Ok", handler: ()=>{ this.diagnostic.switchToLocationSettings() } } ] }); alert.present(); } //función que se encarga de mostrar mensajes Toast private mostrarToast(texto:string){ this.toastCtrl.create( { message:texto, duration:3000 }).present(); } //función que se encarga de mostrar alerta de carga private showLoading() { this.loading = this.loadingCtrl.create({ content: 'Por favor espera...', dismissOnPageChange: true }); this.loading.present(); } private errorInterno(){ this.loading.dismissAll() this.displayMessage('Ocurrió un error','Error interno del sistema') } } //Interface que define los atributos del marcador interface marker { lat: number; //Latitud lng: number; //Longitud label?:string; //Label de la dirección draggable: boolean; //Bandera que indica si se puede tomar }
b2f0b0dba3e06985376356bf73a5ed4f02bc85a5
[ "TypeScript" ]
1
TypeScript
mpantoj/MobileAppGoogleMaps
a3a3dfb240bef20cf38c41aaa268691f6d96fd9a
dae7c224156ba3bc4565ee3ec553ef2d015559b8
refs/heads/master
<repo_name>nikhils4/project-solution<file_sep>/first.py s = input() j = list(s) p = list(map(int, j)) lenp = len(p) cost=[0,3.5,2.5,4,3.5,1.75,1.5,2.25,3.75,1.25] final = 0 for i in range(0,lenp): final = final + cost[p[i]] print('$',"%.2f"%final)
d38c51fccec3c8ffa3644b910e733f557bdb7bb8
[ "Python" ]
1
Python
nikhils4/project-solution
a39510f2aa5e8ff20fa3fb2c21b9ae696e75de96
91e692f883c6c02210c59df439ff39b3f0c0c7af
refs/heads/master
<file_sep># pc-acs-upb laboratoare upb acs probleme rezolvate de andrei radu de la seria ac grupa 312. <file_sep>#include <stdio.h> #include <stdbool.h> #include <limits.h> void main () { int vector[10], n; float medie = 0.0f; printf("Introdu numarul de elemente: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("vector[%d] = "); scanf("%d", vector[i]); medie += vector[i]; } // subpunct a medie /= n; bool existaMedia = false; for (int i = 0; i < n && existaMedia == false; ++i) { if (medie == vector[i]) existaMedia = true; } if (existaMedia == true) printf("Media elementelor din vector se regaseste in acesta.\n"); else printf("Media elementelor din vector nu se regaseste in acesta.\n"); // subpunct b int minim = INT_MAX; for (int i = 0; i < n; ++i) { if (vector[i] < minim) minim = vector[i]; } printf("Valoarea minima este: %d\n", minim); printf("Pozitiile pe care apare sunt: "); for (int i = 0; i < n; ++i) { if (vector[i] == minim) printf("%d ", i); } }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> void adaugaInFisier(FILE* fisier) { char linie[1000]; while (strcmp(linie, "EOF") != 0) { scanf(" %[^\n]s", linie); if (strcmp(linie, "EOF") == 0) { break; } fprintf(fisier, "%s\n", linie); } } void afiseazaColoane(FILE* fisier, int m, int n) { char linie[1000]; fseek(fisier, 0, SEEK_SET); while (fgets(linie, 1000, fisier)) { for (int i = m; i <= n; ++i) { printf("%c", linie[i]); } printf("\n"); } } void main () { FILE* fisier = fopen("P19.txt", "w+"); if (!fisier) { printf("Nu s-a putut deschide!"); exit(1); } adaugaInFisier(fisier); int m, n; scanf("%d%d", &m, &n); afiseazaColoane(fisier, m, n); }<file_sep>#include <stdio.h> void main () { int numar; // citire printf("Introduceti un numar de la tastatura: "); scanf("%d", &numar); numar *= 2; // dublul numarului // afisare in bazele cerute printf("In baza 10: %d\n", numar); printf("In baza 8: %o\n", numar); printf("In baza 16: %x\n", numar); }<file_sep>#include <stdio.h> #include <string.h> #include <ctype.h> void main () { char sir[256]; printf("Introdu o propozitie: "); scanf("%[^\n]s", sir); int cuvinte = 1; for (int i = 0; i < strlen(sir); ++i) { if (sir[i] == ' ' && isalpha(sir[i + 1])) { cuvinte++; printf("\n"); i++; } printf("%c", sir[i]); } printf("\nSirul are %d cuvinte.", cuvinte); }<file_sep>#include <stdio.h> int fibo(int n) { int a0 = 0, a1 = 1, t; for (int i = 2; i <= n; ++i) { t = a0 + a1; a0 = a1; a1 = t; } return t; } int fact(int n) { int f = 1; if (n <= 1) return f; for (int i = 2; i <= n; ++i) { f *= i; } return f; } float expresie(int n) { float exp = 1.0f * fibo(n) / fact(n); printf("%f\n", exp); return exp; } void main () { int n; printf("Introdu numarul n: "); scanf("%d", &n); printf("fibo = %d\n", fibo(n)); printf("fact = %d\n", fact(n)); printf("%f", expresie(n)); }<file_sep>#include <stdio.h> void main () { int v[25], n, p; printf("Introdu numarul de elemente: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("v[%d] = ", i); scanf("%d", &v[i]); } printf("Introdu numarul de permutari la dreapta: "); scanf("%d", &p); // la dreapta while (p--) { int element = v[n - 1]; for (int i = n - 2; i >= 0; --i) { v[i + 1] = v[i]; } v[0] = element; } for (int i = 0; i < n; ++i) { printf("%d ", v[i]); } printf("\nIntrodu numarul de permutari la stanga: "); scanf("%d", &p); // la stanga while (p--) { int element = v[0]; for (int i = 1; i < n; ++i) { v[i - 1] = v[i]; } v[n - 1] = element; } for (int i = 0; i < n; ++i) { printf("%d ", v[i]); } }<file_sep>#include <stdio.h> void main () { int vector[10], n, vectorS[10]; printf("Introdu numarul de elemente: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("vector[%d] = ", i); scanf("%d", &vector[i]); vectorS[i] = vector[i]; } // metoda 1 for (int i = 0; i < n - 1; ++i) { for (int j = 0; j < n - i - 1; ++j) { if (vector[j] < vector[j + 1]) { int temp = vector[j]; vector[j] = vector[j + 1]; vector[j + 1] = temp; } } } for (int i = 0; i < n; ++i) { printf("%d ", vector[i]); } printf("\n"); // metoda 2 int j = 0; for (int i = 1; i < n; ++i) { for (j = 0; j < i && vectorS[j] >= vectorS[i]; ++j); int temp = vectorS[i]; for (int k = i - 1; k >= j; --k) { vectorS[k + 1] = vectorS[k]; } vectorS[j] = temp; } for (int i = 0; i < n; ++i) { printf("%d ", vectorS[i]); } }<file_sep>#include <stdio.h> #include <stdlib.h> void citesteVector(int* vector, int lungimeVector, char* numeVector) { for (int i = 0; i < lungimeVector; ++i) { printf("%s[%d] = ", numeVector, i); scanf("%d", &vector[i]); } } void unesteVectori(int* v1, int lungimeV1, int* v2, int lungimeV2) { int contor = 0; if (lungimeV1 < lungimeV2) { v1 = (int*)realloc(v1, lungimeV1 + lungimeV2); for (int i = lungimeV1; i < lungimeV1 + lungimeV2; ++i) { v1[i] = v2[contor]; contor++; } } else { v2 = (int*)realloc(v2, lungimeV1 + lungimeV2); for (int i = lungimeV2; i < lungimeV1 + lungimeV2; ++i) { v2[i] = v1[contor]; contor++; } } } void main () { int n1, n2; printf("Introdu lungimile celor 2 vectori: "); scanf("%d%d", &n1, &n2); int* primulVector = (int*)calloc(n1, sizeof(int)); int* alDoileaVector = (int*)calloc(n2, sizeof(int)); if (primulVector == NULL) { printf("Nu s-a alocat la primul"); return; } if (alDoileaVector == NULL) { printf("Nu s-a alocat la al doilea."); return; } citesteVector(primulVector, n1, "primulVector"); citesteVector(alDoileaVector, n2, "alDoileaVector"); printf("Vectorii cititi sunt: \n"); for (int i = 0; i < n1; ++i) { printf("%d ", primulVector[i]); } printf("\n"); for (int i = 0; i < n2; ++i) { printf("%d ", alDoileaVector[i]); } printf("\n"); unesteVectori(primulVector, n1, alDoileaVector, n2); printf("Vectorul format prin unirea celor 2 este:\n "); if (n1 < n2) { for (int i = 0; i < n1 + n2; ++i) { printf("%d ", primulVector[i]); } } else { for (int i = 0; i < n1 + n2; ++i) { printf("%d ", alDoileaVector[i]); } } free(primulVector); free(alDoileaVector); }<file_sep>#include <stdio.h> #include <string.h> #include <ctype.h> void interschimbaLitere(char* sir) { if (strlen(sir) % 2) return; // daca nu are numar par de litere nu face interschimbarile(ar ramane o litera ce nu are cu ce sa se schimbe) for (int i = 0; i < strlen(sir); i += 2) { char temp = sir[i]; sir[i] = sir[i + 1]; sir[i + 1] = temp; } } void main () { char cuvant[25]; printf("Introdu un cuvant: "); scanf("%[^\n]s", cuvant); printf("%s\n", cuvant); interschimbaLitere(cuvant); printf("%s\n", cuvant); }<file_sep>#include <stdio.h> void main () { int n; printf("Introduceti un numar: "); scanf("%d", &n); int suma = 0, produs = 1, coeficient = 1; for (int i = 1; i <= n; ++i) { produs *= coeficient; // calculeaza ce trebuie adunat la suma, pt coeficient = 1, produs = 1 * coeficient = 1, coeficient = 2, produs = 1 * coeficient = 1 * 2 = 2, etc... suma += produs; coeficient++; } printf("suma = %d", suma); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> void main () { FILE* fisierText = fopen("problema3Text.txt", "w+"); FILE* fisierBinar = fopen("problema3Binar.bin", "wb"); if (fisierText == NULL || fisierBinar == NULL) { printf("Unul din fisiere nu a putut fi deschis."); exit(1); } int* vector = (int*)calloc(200, sizeof(int)); int lungime; printf("Introdu lungimea vectorului: "); scanf("%d", &lungime); for (int i = 0; i < lungime; ++i) { printf("vector[%d] = ", i); scanf("%d", &vector[i]); fprintf(fisierText, "%d ", vector[i]); } fwrite(vector, sizeof(int), sizeof(vector), fisierBinar); fclose(fisierBinar); int vectorBinar[lungime]; fisierBinar = fopen("problema3Binar.bin", "rb"); rewind(fisierText); printf("Inputul din fisierul binar: "); fread(vectorBinar, sizeof(int), sizeof(vector), fisierBinar); for (int i = 0; i < lungime; ++i) { printf("%d ", vectorBinar[i]); } printf("\n"); char prop[256]; printf("Inputul din fisierul text: "); int contor = 0, vectorText[lungime]; while (fgets(prop, 256, fisierText)) { char* numarString = strtok(prop, " "); while (numarString) { char nr[10]; strcpy(nr, numarString); int contorCifra = 0; vectorText[contor] = 0; while (nr[contorCifra] != 0) { vectorText[contor] = vectorText[contor] * 10 + (nr[contorCifra] - '0'); contorCifra++; } contor++; numarString = strtok(NULL, " "); } } for (int i = 0; i < lungime; ++i) { printf("%d ", vectorText[i]); } }<file_sep>#include <stdio.h> void main () { int n; printf("Introduceti un numar: "); scanf("%d", &n); for (int i = 1; i <= n; ++i) { // for sa stim ce numar trebuie scris for (int linii = 1; linii <= i; ++linii) { // for sa stim pe ce linie suntem for (int j = 0; j < i; ++j) { printf("%d ", i); // for sa stim cate numere sa scriem pe linie } printf("\n"); } } }<file_sep>#include <stdio.h> #include <string.h> #include <stdbool.h> /* Sirul suf contine sufixul, sirul str trebuie sa se termine cu sirul suf astfel parcurgem sirul suf si verificam de la coada la cap daca acesta e sufix in sirul str. Daca gasim un caracter diferit in parcurgere returnam false. */ bool eSufix(char str[], char suf[]) { if (strlen(str) < strlen(suf)) return false; for (int i = 0; i < strlen(suf); ++i) { if (str[strlen(str) - i - 1] != suf[strlen(suf) - i - 1]) return false; } return true; } void main () { char sir1[256], sir2[256]; printf("Introdu sirul in care vrei sa cauti: "); scanf("%[^\n]s", sir1); printf("Introdu sirul pe care vrei sa il cauti: "); scanf(" %[^\n]s", sir2); bool rezultat = eSufix(sir1, sir2); if (!rezultat) printf("Negativ"); else printf("Afirmativ"); }<file_sep>#include <stdio.h> struct nr_complex { int real; int imaginar; }; struct nr_complex calculeazaSuma(struct nr_complex nr1, struct nr_complex nr2) { struct nr_complex rezultat; rezultat.real = nr1.real + nr2.real; rezultat.imaginar = nr1.imaginar + nr2.imaginar; return rezultat; } struct nr_complex calculeazaDiferenta(struct nr_complex nr1, struct nr_complex nr2) { struct nr_complex rezultat; rezultat.real = nr1.real - nr2.real; rezultat.imaginar = nr1.imaginar - nr2.imaginar; return rezultat; } void main () { struct nr_complex numar1, numar2; scanf("%d%d", &numar1.real, &numar1.imaginar); scanf("%d%d", &numar2.real, &numar2.imaginar); struct nr_complex rezult1, rezult2; rezult1 = calculeazaSuma(numar1, numar2); rezult2 = calculeazaDiferenta(numar1, numar2); printf("%d + %d * i", rezult1.real, rezult1.imaginar); printf("%d + %d * i", rezult2.real, rezult2.imaginar); }<file_sep>#include <stdio.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> bool isVowel(char a) { if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u') return true; return false; } void main () { char* sir = (char*)calloc(256, sizeof(char)); printf("Introdu un sir: "); scanf("%[^\n]s", sir); int sursa = 0, destinatie = 0; while (true) { // luam caracterul si crestem indicele din sir. char caracter = sir[sursa++]; // daca caracter e caracterul null atunci inseamna ca am ajuns la finalul sirului if (caracter == '\0') break; // sarim peste vocale if (isVowel(caracter)) continue; // copiem caracterul la noua destinatie sir[destinatie] = caracter; // crestem destinatia doar daca am copiat o consoana ++destinatie; } // adaug caracterul null la finalul sirului sir[destinatie] = 0; sir = realloc(sir, destinatie); printf("Sirul dupa stergerea vocalelor: %s\n", sir); int p, q; printf("Introdu 2 pozitii: "); scanf("%d%d", &p, &q); for (int i = p; i < q; ++i) { printf("%c", sir[i]); } }<file_sep>#include <stdio.h> void interschimbaVectori(int* vectorA, int len, int* vectorB) { for (int i = 0; i < len; ++i) { int temp = vectorA[i]; vectorA[i] = vectorB[i]; vectorB[i] = temp; } } void main () { }<file_sep>#include <stdio.h> char testareCaracter(int a, int b, int c) { if ((a < b) && (a < c) && (b < c)) return 'C'; else if ((a > b) && (b > c) && (a > c)) return 'D'; else if ((a == b) && (b == c) && (a == c)) return 'I'; else return 'N'; } void main () { int teste, a, b, c; printf("Introdu numarul de teste: "); scanf("%d", &teste); while (teste--) { printf("a = "); scanf("%d", &a); printf("b = "); scanf("%d", &b); printf("c = "); scanf("%d", &c); printf("%c\n", testareCaracter(a, b, c)); } }<file_sep>#include <stdio.h> void main () { int lungime, latime; printf("Introduceti lungimea si latimea: \n"); printf("Introduceti lungimea: "); scanf("%d", &lungime); printf("Introduceti latimea: "); scanf("%d", &latime); printf("perimetru = %d", 2 * (lungime + latime)); }<file_sep>#include <stdio.h> #include <math.h> #include <stdbool.h> int delta(int a, int b, int c) { return pow(b, 2) - 4 * a * c; } bool rezultat(int a, int b, int c, float *x, float *y) { int d = delta(a, b, c); if (d < 0) return false; *x = (-b + sqrt(d)) / (2 * a); *y = (-b - sqrt(d)) / (2 * a); return true; } void main () { int a, b, c; float x1, x2; printf("Introdu coeficientii ecuatiei: "); scanf("%d%d%d", &a, &b, &c); bool rezolvat = rezultat(a, b, c, &x1, &x2); if (!rezolvat) printf("Delta < 0."); else printf("Solutiile ecuatiei sunt x1 = %.2f, x2 = %.2f.", x1, x2); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> void main () { int nrPropozitii; printf("Introdu numarul de propozitii: "); scanf("%d", &nrPropozitii); FILE* fisier = fopen("problema2.txt", "w+"); if (fisier == NULL) { printf("Nu a putut fi deschis fisierul pentru problema 2."); exit(1); } for (int i = 0; i < nrPropozitii; ++i) { char propozitie[256]; scanf(" %[^\n]s", propozitie); fputs(propozitie, fisier); fputs("\n", fisier); } // SUBPUNCT A rewind(fisier); printf("\n"); char prop[256]; while (fgets(prop, 256, fisier)) { // citesc fiecare linie si o afisez printf("%s", prop); } // SUBPUNCT B char cuvantCautat[256]; int linie = 0; printf("Introdu cuvantul pe care vrei sa il cauti: "); scanf(" %s", cuvantCautat); rewind(fisier); printf("Liniile pe care apare cuvantul %s sunt: ", cuvantCautat); while (fgets(prop, 256, fisier)) { char* cuv = strtok(prop, " \n"); // parcurg cuvant cu cuvant fisierul dupa separatorii spatiu sau \n while (cuv) { //printf("%s %s\n", cuv, cuvantCautat); if (strcmp(cuv, cuvantCautat) == 0) { printf("%d ", linie + 1); break; // daca l-am gasit deja pe linia pe care ma aflu opresc while si trec la urmatoarea. } cuv = strtok(NULL, " \n"); } linie++; } printf("\n"); // SUBPUNCT C rewind(fisier); int cuvinte = 0, caractere = 0; while (fgets(prop, 256, fisier)) { char* cuv = strtok(prop, " \n"); while (cuv) { cuvinte++; caractere += strlen(cuv); cuv = strtok(NULL, " \n"); } // nu am considerat spatiile si liniile noi drept caractere. doar literele } printf("Fisierul contine %d cuvinte si %d caractere.\n", cuvinte, caractere); // SUBPUNCT D rewind(fisier); int lungimeMaxima = INT_MIN; while (fgets(prop, 256, fisier)) { // parcurg fisierul si aflu lungimea maxima a fiecarei linii apoi il mai parcurg o data si afisez liniile care au lungimea respectiva int lungimeCurenta = strlen(prop); if (lungimeMaxima < lungimeCurenta) { lungimeMaxima = lungimeCurenta; } } rewind(fisier); printf("Propozitia cu lungime maxima este: \n"); while (fgets(prop, 256, fisier)) { if (lungimeMaxima == strlen(prop)) { printf("%s\n", prop); } } fclose(fisier); }<file_sep>#include <stdio.h> void stergePrimulElement(int* vectorDeSters, int* lVector) { int prim = vectorDeSters[0], deSters = 0; for (int i = 0; i < *lVector; ++i) { if (vectorDeSters[i] == prim) deSters++; } for (int i = 0; i < *lVector; ++i) { if (vectorDeSters[i] == prim) { int pozitie = i; pozitie++; while (vectorDeSters[pozitie] == prim && pozitie < *lVector) pozitie++; vectorDeSters[i] = vectorDeSters[pozitie]; vectorDeSters[pozitie] = prim; } } *lVector -= deSters; } void main () { int vector[100], n; printf("Introdu lungimea vectorului: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("v[%d] = ", i); scanf("%d", &vector[i]); } stergePrimulElement(vector, &n); for (int i = 0; i < n; ++i) { printf("%d ", vector[i]); } }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct maplocalitati { char nume[50]; int persoane; } mapLocalitati; /* Am implementat o structura mapLocalitati care are o functionare asemanatoare HashMap-urilor din Java. Aceasta contine un camp cheie(nume) si un camp valoare(persoane). Pentru aceasta am implementat o functie care verifica daca un nume de oras apare deja in vectorul de structura si o functie care construieste vectorul verificand daca o localitate exista deja in vector. In cazul in care exista creste numarul de persoane cu 1 iar in cazul in care nu exista o adauga si seteaza numarul de persoane la 1. */ void adaugaInFisier(FILE* fisier) { char* linie = (char*)malloc(1000); while (strcmp(linie, "EOF") != 0) { scanf(" %[^\n]s", linie); if (strcmp(linie, "EOF") == 0) { break; } fprintf(fisier, "%s\n", linie); } free(linie); } int numaraLocalitati(FILE* fisier) { fseek(fisier, 0, SEEK_SET); int rezultat = 0; char linie[1000]; while (fgets(linie, 1000, fisier) != NULL) { rezultat++; } return rezultat; } int contineLocalitate(mapLocalitati* harta, int lungime, char* localitate) { for (int i = 0; i < lungime; ++i) { char loc[100]; if (strcmp(harta[i].nume, localitate) == 0) { return i; } } return -1; } int construiesteMap(FILE* fisier, mapLocalitati* harta, int nrLocalitati) { fseek(fisier, 0, SEEK_SET); int contor = 0; char localitate[1000]; while (fscanf(fisier, "%s", localitate) != EOF) { int rez = contineLocalitate(harta, contor, localitate); if (rez != -1) { harta[rez].persoane++; } else { strcpy(harta[contor].nume, localitate); harta[contor].persoane = 1; contor++; } } return contor; } void main () { FILE* localitati = fopen("P14.txt", "w+"); if (!localitati) { printf("Nu am putut deschide fisierul."); exit(1); } adaugaInFisier(localitati); int nrLocalitati = numaraLocalitati(localitati); mapLocalitati* map = (mapLocalitati*)malloc(nrLocalitati); int lungimeHashMap = construiesteMap(localitati, map, nrLocalitati); for (int i = 0; i < lungimeHashMap; ++i) { printf("%s -> %d\n", map[i].nume, map[i].persoane); } free(map); fclose(localitati); }<file_sep>#include <stdio.h> #include <limits.h> #include <string.h> struct Informatie { char firma[24]; char produs[10]; int cantitate; }; void main () { int n; printf("Introdu numarul de firme: "); scanf("%d", &n); struct Informatie informatii[10]; for (int i = 0; i < n; ++i) { printf("Introdu informatii despre firma %d: ", i); scanf(" %[^\n]s", informatii[i].firma); scanf(" %[^\n]s", informatii[i].produs); scanf("%d", &informatii[i].cantitate); } /*for (int i = 0; i < n; ++i) { printf("Firma %d: %s %s %d", i, informatii[i].firma, informatii[i].produs, informatii[i].cantitate); }*/ char produsDeCautat[10]; printf("Introdu produsul pe care vrei sa il cauti: "); scanf(" %[^\n]s", produsDeCautat); // subpunct a int cantMaxim = INT_MIN; char firmaRezultat[10]; for (int i = 0; i < n; ++i) { if (strcmp(informatii[i].produs, produsDeCautat) == 0) { if (informatii[i].cantitate > cantMaxim) { cantMaxim = informatii[i].cantitate; strcpy(firmaRezultat, informatii[i].firma); } } } printf("Firma cu cea mai mare productie pentru produsul %s este %s.\n", produsDeCautat, firmaRezultat); // subpunct b char Produs[10]; int cantitate = 0; printf("Introdu produsul pentru care vrei sa aflii cantitatea: "); scanf(" %[^\n]s", Produs); for (int i = 0; i < n; ++i) { if (strcmp(informatii[i].produs, Produs) == 0) { cantitate += informatii[i].cantitate; } } printf("Cantiteatea totala care poate fi cumparata din produsul %s este %d.", Produs, cantitate); }<file_sep>#include <stdio.h> void main () { int n; printf("Introduceti un numar: "); scanf("%d", &n); do { if (n >= 0) break; printf("Ati introdus un numar negativ. Introduceti o valoare pozitiva: "); scanf("%d", &n); } while (n < 0); printf("Ati introdus numarul pozitiv: %d.", n); }<file_sep>#include <stdio.h> void numaraPerechi(int* v, int len, int* per) { int perechi = 0; for (int i = 0; i < len - 1; ++i) { if (v[i] == v[i + 1]) { perechi++; } } *per = perechi; } void main () { int vector[] = {2, 3, 3, 3, 5, 7, 7, 9}; int lungimeVector = sizeof(vector) / sizeof(vector[0]); int perechi; numaraPerechi(vector, lungimeVector, &perechi); printf("In vector exista %d perechi de elemente consecutiv identice.", perechi); }<file_sep>#include <stdio.h> void main () { int mat[10][10], n, m; printf("Introdu dimensiunile matricii: "); scanf("%d%d", &n, &m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { printf("mat[%d][%d] = ", i, j); scanf("%d", &mat[i][j]); } } printf("Matricea inainte de ordonarea elementelor pare de pe linie para: \n"); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { printf("%d ", mat[i][j]); } printf("\n"); } printf("\n"); for (int i = 0; i < n; i += 2) { int linie = i; for (int l = 0; l < m - 1; ++l) { for (int k = 0; k < m - l - 1; ++k) { if (mat[linie][k] % 2 == 0) { int kVechi = k; k++; while (mat[linie][k] % 2 != 0 && k < m - l - 1) { k++; } if (mat[linie][kVechi] > mat[linie][k]) { int temp = mat[linie][kVechi]; mat[linie][kVechi] = mat[linie][k]; mat[linie][k] = temp; } } } } } /* Am parcurs liniile vectorului din 2 in 2 pentru a verifica doar liniile pare, apoi am folosit bubble sort pe coloane doar pentru elementele care erau pare Cand gaseam un element par ii salvam pozitia pe linie in kVechi iar apoi cautam urmatorul element par iar in cazul in care primul era > decat al doilea le interschimbam input folosit: 4 3 2 4 5 6 6 2 12 output: 2 3 4 4 5 6 2 6 12 */ printf("Matricea dupa ordonarea elementelor pare de pe linie para: \n"); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { printf("%d ", mat[i][j]); } printf("\n"); } }<file_sep>#include <stdio.h> void main () { int matrice[10][10], n; printf("Introdu lungimea matricei: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { printf("matrice[%d][%d] = ", i, j); scanf("%d", &matrice[i][j]); } } char subpunct; printf("Ce subpunct vrei sa testezi pe matricea introdusa?: "); scanf(" %c", &subpunct); printf("Matricea inainte de ordonare: \n"); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { printf("%d ", matrice[i][j]); } printf("\n"); } if (subpunct == 'a' || subpunct == 'A') { // voi ordona crescator elementele de pe fiecare linie folosind bubble sort for (int i = 0; i < n; ++i) { for (int j = 0; j < n - 1; ++j) { for (int l = 0; l < n - j - 1; ++l) { if (matrice[i][l] > matrice[i][l + 1]) { int temp = matrice[i][l]; matrice[i][l] = matrice[i][l + 1]; matrice[i][l + 1] = temp; } } } } printf("Matricea cu liniile ordonate: \n"); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { printf("%d ", matrice[i][j]); } printf("\n"); } } else if (subpunct == 'b' || subpunct == 'B') { // voi ordona crescator // (sortez decat prima linie iar apoi pentru fiecare element interschimbat de pe prima linie, interschimb coloanele) for (int i = 0; i < n; ++i) { for (int j = 0; j < n - i - 1; ++j) { if (matrice[0][j] > matrice[0][j + 1]) { int temp = matrice[0][j]; matrice[0][j] = matrice[0][j + 1]; matrice[0][j + 1] = temp; for (int l = 1; l < n; ++l) { // am inceput de la l = 1 deoarece linia 0 e deja sortata int aux = matrice[l][j]; matrice[l][j] = matrice[l][j + 1]; matrice[l][j + 1] = aux; } } } } printf("Matricea dupa efectuarea operatiilor: \n"); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { printf("%d ", matrice[i][j]); } printf("\n"); } } else { printf("Acel subpunct nu exista."); } }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> void adaugaInFisier(FILE* fisier) { char linie[1000]; printf("Scrie o noua linie pentru a o adauga in fisier: \n"); scanf(" %[^\n]s", linie); fprintf(fisier, "%s", linie); fprintf(fisier, "\n"); } void inlocuieste(char* sir, char* vechi, char* nou) { char* pozitie, temp[1024]; int index, lungimeVechi = strlen(vechi); // trect prin toata propozitia pana nu mai gasesc cuvantul cautat while ((pozitie = strstr(sir, vechi)) != NULL) { strcpy(temp, sir); index = pozitie - sir; sir[index] = 0; strcat(sir, nou); strcat(sir, temp + index + lungimeVechi); } } void main () { FILE* text = fopen("P2.txt", "w+"); if (text == NULL) { printf("Nu l-am putut deschide."); exit(1); } adaugaInFisier(text); char cuvantCautat[100], cuvantNou[100]; printf("Care este cuvantul pe care vrei sa il cauti? "); scanf(" %s", cuvantCautat); printf("Care este cuvantul cu care vrei sa il inlocuiesti? "); scanf(" %s", cuvantNou); FILE* temp = fopen("temp.txt", "w"); if (temp == NULL) { printf("Nu am putut deschide fisierul temporar."); exit(1); } char cuvant[100]; fseek(text, 0, SEEK_SET); while ((fgets(cuvant, 1024, text)) != NULL) { inlocuieste(cuvant, cuvantCautat, cuvantNou); fputs(cuvant, temp); } fclose(text); fclose(temp); remove("P2.txt"); rename("temp.txt", "P2.txt"); fclose(temp); }<file_sep>#include <stdio.h> void main () { int vector[10], n; printf("Introdu numarul de elemente: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("vector[%d] = ", i); scanf("%d", &vector[i]); } int pozitieStart = 0, pozitieFinal = 0, pozitieStartEx = 0, pozitieFinalEx = 0; for (int i = 0; i < n - 1; ++i) { pozitieStartEx = i; while (vector[i] < vector[i + 1]) { i++; } pozitieFinalEx = i + 1; if (pozitieFinal - pozitieStart < pozitieFinalEx - pozitieStartEx) { pozitieFinal = pozitieFinalEx; pozitieStart = pozitieStartEx; } } for (int i = pozitieStart; i < pozitieFinal; ++i) { printf("%d ", vector[i]); } }<file_sep>#include <stdio.h> void main () { int vector[10], poz[10], n, p; printf("Dati numarul de elemente din vector: "); scanf("%d", &n); printf("Dati numarul de elemente din vectorul de pozitii: "); scanf("%d", &p); for (int i = 0; i < n; ++i) { printf("vector[%d] = ", i); scanf("%d", &vector[i]); } int q = 0; do { int elem; printf("poz[%d] = ", q); scanf("%d", &elem); if (poz[q] >= 0 && poz[q] < n) { poz[q] = elem; q++; } else printf("Valoarea trebuie sa fie cuprinsa intre 0 si n.\n"); } while (poz[q] >= 0 && poz[q] < n && q < p); for (int i = 0; i < p; ++i) { printf("%d ", vector[poz[i]]); } }<file_sep>#include <stdio.h> #include <stdbool.h> void main () { int vector[10], n; printf("Introdu numarul de elemente: "); scanf("%d", &n); bool cititCorect = true; int i = 0; printf("vector[%d] = ", i); scanf("%d", &vector[i]); i++; for ( ; i < n && cititCorect == true; ++i) { printf("vector[%d] = ", i); int element; scanf("%d", &element); if (element < vector[i - 1]) { cititCorect = false; } vector[i] = element; } if (cititCorect == true) { printf("Vectorul ordonat a fost citit cu succes! Elementele lui sunt: \n"); for (int i = 0; i < n; ++i) { printf("%d ", vector[i]); } printf("\n"); int numar, pozitieDeAdaugat = n; // in cazul in care nu o sa gasesc loc intre elementele vectorului, il voi adauga la final. printf("Introdu numarul pe care vrei sa il adaugi la vector: "); scanf("%d", &numar); for (int i = 0; i < n; ++i) { if (numar > vector[i - 1] && numar < vector[i]) { pozitieDeAdaugat = i; break; } } for (int i = n; i >= pozitieDeAdaugat; --i) { vector[i] = vector[i - 1]; } vector[pozitieDeAdaugat] = numar; printf("Vectorul dupa ce am adaugat un nou element: "); for (int i = 0; i < n + 1; ++i) { printf("%d ", vector[i]); } } else { printf("Vectorul nu a fost citit corect."); } }<file_sep>#include <stdio.h> #include <string.h> void main () { char nume1[16], nume2[16]; int varsta1, varsta2; printf("Introdu datele primei persoane: \n"); printf("Nume: "); gets(nume1); fflush(stdin); printf("Varsta: "); scanf("%d", &varsta1); fflush(stdin); printf("Introdu datele primei persoane: \n"); printf("Nume: "); gets(nume2); fflush(stdin); printf("Varsta: "); scanf("%d", &varsta2); if (strcmp(nume1, nume2)) { varsta1 < varsta2 ? printf("%s", nume1) : printf("%s", nume2); printf("\n"); if (varsta1 == varsta2) printf("%s \n %s", nume1, nume2); } }<file_sep>#include <stdio.h> void main () { char c; printf("Introduceti un caracter: "); scanf("%c", &c); // subpunct a) printf("Codul ASCII al caracterului %c este %d.\n", c, c); // subpunct b) printf("Urmatorul caracter in ordine lexicografica este %c.\n", c + 1); // subpunct c) char s = 'a'; printf("%c%c%c%c%c\n", s, s + 1, s + 2, s + 3, s + 4); // subpunct d) char ex = 'A'; printf("A 16-a litera mare din alfabet este %c", ex + 15); }<file_sep>#include <stdio.h> void numara(int* vector, int len, int* nul, int* poz, int* neg) { for (int i = 0; i < len; ++i) { if (*(vector + i) < 0) (*neg)++; else if (*(vector + i) == 0) (*nul)++; else (*poz)++; } } void main () { int vector[] = {5, -6, -8, 0, 0, 11, 14, -3}; int lungime = sizeof(vector) / sizeof(vector[0]); int nule = 0, pozitive = 0, negative = 0; numara(vector, lungime, &nule, &pozitive, &negative); printf("Vectorul dat are %d elemente nule, %d elemente pozitive si %d elemente negative.", nule, pozitive, negative); }<file_sep>#include <stdio.h> #include <limits.h> void main () { int A[10][10], n; printf("Introdu numarul de elemente: "); scanf("%d", &n); // subpunct a int minim = INT_MAX, maxim = INT_MIN; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { printf("A[%d][%d] = ", i, j); scanf("%d", &A[i][j]); if (A[i][j] < minim) minim = A[i][j]; if (A[i][j] > maxim) maxim = A[i][j]; } } printf("Maximul gasit in matrice este %d.\n", maxim); printf("Minimul gasit in matrice este %d.\n", minim); // subpunct b for (int i = 0; i < n; ++i) { A[i][i] = maxim; } printf("Matricea A dupa inlocuirea elementelor de pe diagonala principala cu maximul gasit: \n"); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { printf("%d ", A[i][j]); } printf("\n"); } printf("\n"); // subpunct c for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (j >= n - i) { A[i][j] = minim; } } } printf("Matricea A dupa inlocuirea elementelor de sub diagonala secundara cu minimul gasit: \n"); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { printf("%d ", A[i][j]); } printf("\n"); } }<file_sep>#include <stdio.h> #include <limits.h> void gasesteMaximLiniiColoane(int mat[][10], int len, int* maxL, int* maxCol) { int sumaL = 0, sumaLin = 0, sumaC = 0, sumaCol = 0; for (int i = 0; i < len; ++i) { for (int j = 0; j < len; ++j) { sumaL += mat[i][j]; } if (sumaL > sumaLin) { *maxL = i; sumaLin = sumaL; } } for (int i = 0; i < len; ++i) { int linie = 0; while (linie < len) { sumaC += mat[linie][i]; linie++; } if (sumaC > sumaCol) { *maxCol = i; sumaCol = sumaC; } } } void main () { int matrice[10][10], n; printf("Introdu dimensiunile matricei: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { printf("matrice[%d][%d] = ", i, j); scanf("%d", &matrice[i][j]); } } int maximLinie = INT_MIN, maximColoana = INT_MIN; gasesteMaximLiniiColoane(matrice, n, &maximLinie, &maximColoana); printf("Suma maxima pe linii se afla pe linia %d.\n", maximLinie); printf("Suma maxima pe coloane se afla pe coloana %d.", maximColoana); } <file_sep>#include <stdio.h> void main () { int n; printf("Introduceti un numar: "); scanf("%d", &n); int suma = 0, nr, contor = 0; do { printf("Introduceti termenul %d din medie: ", contor + 1); scanf("%d", &nr); // citim un numar si il adaugam la suma cat timp contor != n, contor creste la fiecare pas suma += nr; contor++; } while (contor != n); printf("Media numerelor citite = %.2f", (float)suma / n); // am afisat media cu doar 2 zecimale } /* Diferenta dintre programele cu for si while si programul cu do while este ca in cel cu do while codul va fi executat o data fara sa se verifice conditia de oprire. */<file_sep>#include <stdio.h> void main () { int n; printf("Introduceti un numar: "); scanf("%d", &n); int suma = 0, nr; for (int i = 0; i < n; ++i) { printf("Introduceti termenul %d din medie: ", i + 1); scanf("%d", &nr); // citim un nou termen pana i ajunge n si il adaugam la suma suma += nr; } printf("Media numerelor citite este: %.2f", (float)suma / n); // am afisat media cu doar 2 zecimale }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> void adaugaInFisier(FILE* fisier) { char linie[1000]; while (1) { if (strcmp(linie, "EOF") == 0) { return; } scanf(" %[^\n]s", linie); fprintf(fisier, "%s", linie); fprintf(fisier, "\n"); } } void afiseazaFisier(FILE* fisier) { char linie[1000]; int nrOrdine = 0; while (fgets(linie, 1000, fisier) != NULL || nrOrdine != 20) { printf("%s", linie); nrOrdine++; } } void main () { FILE* fisier = fopen("P20.txt", "w+"); if (!fisier) { printf("Nu s-a putut deschide!"); exit(1); } adaugaInFisier(fisier); fseek(fisier, 0, SEEK_SET); afiseazaFisier(fisier); char opt; scanf(" %c", &opt); while (opt != 's') { afiseazaFisier(fisier); scanf(" %c", &opt); } }<file_sep>#include <stdio.h> void main () { int n; char varianta; do { printf("Introdu un numar: "); scanf("%d", &n); printf("Ati introuds numarul %d. \n", n); if (n % 2 == 0) printf("Ati introdus un numar par.\n"); else printf("Ati introdus un numar impar.\n"); printf("Doriti sa continuati? D/N: "); scanf(" %c", &varianta); } while (varianta != 'N'); } /* In citirea variabilei varianta a fost folosit un spatiu liber inainte de %c pentru a face scanf() sa sara peste caracterul \n care e inaintea caracterului pe care vrem sa il citim.*/<file_sep>#include <stdio.h> void main () { int a, b; printf("Introduceti valoarea lui a: "); scanf("%d", &a); printf("Introduceti valoarea lui b: "); scanf("%d", &b); // schimbam variabilele int temp = a; a = b; b = temp; printf("a = %d\n", a); printf("b = %d\n", b); printf("media = %.2f", (float)(a + b) / 2); }<file_sep>#include <stdio.h> void main () { int a, b, c; printf("Introduceti numarul a: "); scanf("%d", &a); printf("Introduceti numarul b: "); scanf("%d", &b); printf("Introduceti numarul c: "); scanf("%d", &c); printf("%d + %d = %d\n", a, b, a + b); printf("%d + %d = %d\n", a, c, a + c); printf("%d + %d = %d\n", b, c, b + c); }<file_sep>#include <stdio.h> void main () { int zi; printf("Introduceti un numar: "); scanf("%d", &zi); switch (zi) { case 1: { printf("Luni"); break; } case 2: { printf("Marti"); break; } case 3: { printf("Miercuri"); break; } case 4: { printf("Joi"); break; } case 5: { printf("Vineri"); break; } case 6: { printf("Sambata"); break; } case 7: { printf("Duminica"); break; } default : printf("eroare"); } }<file_sep>#include <stdio.h> #include <math.h> void main () { int n; printf("Introdu numarul de elemente: "); scanf("%d", &n); int v[20]; for (int i = 0; i < n; ++i) { printf("v[%d]=", i); scanf("%d", &v[i]); } // subpunct a) int prag; printf("Introdu pragul: "); scanf("%d", &prag); printf("Subpunct a:\n"); for (int i = 0; i < n; ++i) { if (v[i] > prag) { printf("%d apare pe pozitia %d \n", v[i], i); } } printf("\n"); // subpunct b) printf("Subpunct b:\n"); for (int i = 0; i < n; i += 2) { // am plecat cu i de la 0 si am crescut cu 2 deci vom afisa doar v[0], v[2], v[4]...adica elementele de pe pozitii pare printf("%d\n", v[i]); } printf("\n"); // subpunct c) int sterse = 0; // cate elemente de 0 vom sterge for (int i = 0; i < n; ++i) { if (v[i] == 0) sterse++; } for (int i = 0; i < n; ++i) { if (v[i] == 0) { int pozitie = i; pozitie++; while (v[pozitie] == 0 && pozitie < n) { pozitie++; } // daca avem valori consecutive de 0 trecem peste ele pana gasim una diferita de 0 fara sa depasim limita vectorului. v[i] = v[pozitie]; v[pozitie] = 0; } } printf("Subpunct c:\n"); for (int i = 0; i < n - 1 - sterse; ++i) { printf("%d ", v[i]); } printf("\n"); // subpunct d) for (int i = 0; i < n - sterse - 1; ++i) { // am setat i < n - sterse deoarece de la n - sterse + 1 se gasesc valorile de 0 din vector int element = v[i], nrdivizori = 1; // 1 este divizor al oricarui numar asa ca vom incepe loop-ul de la 2. for (int j = 2; j <= element; ++j) { if (element % j == 0) nrdivizori++; } v[i] = nrdivizori; } printf("Subpunct d:\n"); for (int i = 0; i < n - sterse - 1; ++i) { printf("%d ", v[i]); } } <file_sep>#include <stdio.h> void main () { int n; printf("Introduceti un numar: "); scanf("%d", &n); int a0 = 0, a1 = 1, nr; printf("%d %d ", a0, a1); for (int i = 2; i < n; ++i) { nr = a0 + a1; a0 = a1; a1 = nr; printf("%d ", nr); } }<file_sep>#include <stdio.h> #include <stdbool.h> bool transform(int nr, int *trans) { int pare = 0, nrPare = 0; while (nr) { if (nr % 2 == 0) { nrPare = nrPare * 10 + nr % 10; pare++; } nr /= 10; } *trans = 0; while (nrPare) { *trans = *trans * 10 + nrPare % 10; nrPare /= 10; } if (pare) return true; else return false; } void main () { int numar, trans = 0; bool transformat; printf("Introdu un numar: "); scanf("%d", &numar); transformat = transform(numar, &trans); if (!transformat) printf("Numarul nu contine cifre pare."); else printf("Numarul obtinut din %d este %d.", numar, trans); }<file_sep>#include <stdio.h> #include <string.h> struct Autor { char nume[256], prenume[256], gen; }; struct Carte { char titlul[256]; int an; struct Autor autor; }; void sortareLexicografica(struct Carte carti[], int n) { for (int i = 0; i < n; ++i) { struct Carte cheie; memcpy(&cheie, &carti[i], sizeof(struct Carte)); int j = i - 1; while (j >= 0 && strcmp(carti[j].titlul, cheie.titlul) > 0) { memcpy(&carti[j + 1], &carti[j], sizeof(struct Carte)); j--; } memcpy(&carti[j + 1], &cheie, sizeof(struct Carte)); } } void main () { int nrCarti; struct Carte carti[10]; printf("Introdu numarul de carti: "); scanf("%d", &nrCarti); // subpunct a for (int i = 0; i < nrCarti; ++i) { printf("Cartea %d\n", i); printf("Titlu: "); scanf(" %[^\n]s", carti[i].titlul); printf("Anul: "); scanf("%d", &carti[i].an); printf("Date autor: "); scanf(" %[^\n]s", carti[i].autor.nume); scanf(" %[^\n]s", carti[i].autor.prenume); scanf(" %c", &carti[i].autor.gen); } // subpunct b // subpunct c int an; char gen; printf("Introdu anul si genul: "); scanf("%d %c", &an, &gen); for (int i = 0; i < nrCarti; ++i) { if (carti[i].an == an && carti[i].autor.gen == gen) { printf("%s\n", carti[i].titlul); } } // subpunct d printf("\n"); sortareLexicografica(carti, nrCarti); for (int i = 0; i < nrCarti; ++i) { printf("%s\n", carti[i].titlul); } }<file_sep>#include <stdio.h> #include <stdbool.h> bool eNumarPerfect(int n) { int perfect = 1; // am initializat cu 1 deoarece 1 e divizorul oricarui numar for (int i = 2; i <= n / 2; ++i) { // am parcurs pana la n / 2 deoarece dupa jumatatea numarului nu mai exista alt divizor in afara de el insusi if (n % i == 0) perfect += i; } if (perfect == n) return true; else return false; } void main () { printf("%d\n", eNumarPerfect(6)); printf("%d\n", eNumarPerfect(28)); printf("%d\n", eNumarPerfect(29)); }<file_sep>#include <stdio.h> #include <stdbool.h> bool verificaIdentitateVector(int* vectorA, int lVA, int* vectorB, int lVB) { bool gasit = true; if (lVA != lVB) return false; for (int i = 0; i < lVA; ++i) { gasit = false; for (int j = 0; j < lVA; ++j) { if (vectorA[i] == vectorB[j]) { gasit = true; } } if (gasit == false) return gasit; } return true; } void citesteMatrice(int matrice[][10], int* lungimeMatrice, char numeMatrice) { printf("Introdu lungimea matricei %c: ", numeMatrice); scanf("%d", lungimeMatrice); for (int i = 0; i < *lungimeMatrice; ++i) { for (int j = 0; j < *lungimeMatrice; ++j) { printf("%c[%d][%d] = ", numeMatrice, i, j); scanf("%d", &matrice[i][j]); } } } void citesteVector(int* vector, int* lungimeVector, char numeVector) { printf("Introdu lungimea vectorului %c: ", numeVector); scanf("%d", lungimeVector); for (int i = 0; i < *lungimeVector; ++i) { printf("%c[%d] = ", numeVector, i); scanf("%d", &vector[i]); } } void main () { int A[10], M[10][10], lA, lM; citesteMatrice(M, &lM, 'M'); citesteVector(A, &lA, 'A'); bool verificat; int verificari = 0; if (lA != lM) verificat = false; else { for (int i = 0; i < lA; ++i) { verificat = verificaIdentitateVector(A, lA, M[i], lM); if (verificat) { printf("Vectorul coincide cu linia %d din matrice.\n", i); verificari++; } } } if (verificari == 0) printf("Vectorul nu coincide cu nicio linie din matrice."); } <file_sep>#include <stdio.h> #include <limits.h> void cautaPozitiiMinim(int* vectorCautat, int lungimeVector, int* vectorPozitii, int* lPozitii) { int contor = 0, min = INT_MAX; for (int i = 0; i < lungimeVector; ++i) { if (vectorCautat[i] < min) min = vectorCautat[i]; } for (int i = 0; i < lungimeVector; ++i) { if (vectorCautat[i] == min) { vectorPozitii[contor++] = i; } } *lPozitii = contor; } void main () { int vector[100], n; printf("Introdu lungimea vectorului: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("v[%d] = ", i); scanf("%d", &vector[i]); } int pozitii[100], lungimePozitii = 0; cautaPozitiiMinim(vector, n, pozitii, &lungimePozitii); for (int i = 0; i < lungimePozitii; ++i) { printf("%d ", pozitii[i]); } }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> void main () { char sir[256]; printf("Introdu un sir: "); //gets(sir); scanf("%[^\n]s", sir); int lungime = 0; for (int i = 0; sir[i] != '\0'; ++i) { lungime++; } printf("Sirul citit are lungimea %d.\n", lungime); for (int i = 0; i < lungime; ++i) { printf("%c", sir[i]); } }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> typedef struct persoana { char nume[24]; char prenume[24]; char adresa[128]; char sex; float greutate; int varsta; char culoarePar[15]; char culoareOchi[15]; } Persoana; void scrieFisier(FILE* fisier, Persoana* persoane, int final) { // scrie vectorul de persoane in fisier for (int i = 0; i < final; ++i) { fprintf(fisier, "Nume: %s\n", persoane[i].nume); fprintf(fisier, "Prenume: %s\n", persoane[i].prenume); fprintf(fisier, "Adresa: %s\n", persoane[i].adresa); fprintf(fisier, "Sex: %c\n", persoane[i].sex); fprintf(fisier, "Greutate: %.2f\n", persoane[i].greutate); fprintf(fisier, "Varsta: %d\n", persoane[i].varsta); fprintf(fisier, "Par: %s\n", persoane[i].culoarePar); fprintf(fisier, "Ochi: %s\n", persoane[i].culoareOchi); } } void citestePersoane(Persoana* persoane, int nrPersoane, int* existente) { // citeste persoane in vectorul precizat if (*existente + nrPersoane > 1000) { printf("Limita de persoane a fost depasita!"); return; } for (int i = *existente; i < nrPersoane + *existente; ++i) { printf("Nume: "); scanf(" %[^\n]s", persoane[i].nume); printf("Prenume:"); scanf(" %[^\n]s", persoane[i].prenume); printf("Adresa: "); scanf(" %[^\n]s", persoane[i].adresa); printf("Sex: "); scanf(" %c", &persoane[i].sex); printf("Greutate: "); scanf(" %f", &persoane[i].greutate); printf("Varsta: "); scanf(" %d", &persoane[i].varsta); printf("Par: "); scanf(" %[^\n]s", persoane[i].culoarePar); printf("Ochi: "); scanf(" %[^\n]s", persoane[i].culoareOchi); } *existente += nrPersoane; } void afiseazaFisier(FILE* fisier) { // afiseaza tot fisierul fseek(fisier, 0, SEEK_SET); char propozitie[1000]; while (fgets(propozitie, 1000, fisier)) { printf("%s", propozitie); } } void afiseazaPersoana(FILE* fisier, char* nume) { // functie care parcurge fisierul si afiseaza toate persoanele care au numele de familie precizat fseek(fisier, 0, SEEK_SET); char linie[1000]; while (fgets(linie, 1000, fisier)) { char* pozitie = strstr(linie, nume); if (pozitie != NULL) { printf("%s", linie); for (int i = 0; i < 7; ++i) { fgets(linie, 1000, fisier); printf("%s", linie); } } } } void main () { Persoana* vectorPersoane = (Persoana*)calloc(1000, sizeof(Persoana)); FILE* fisier = fopen("P4.txt", "w+"); if (!fisier) { printf("Nu am putut deschide fisierul."); exit(1); } int existente = 0; char opt[50]; printf("Lista optiuni: \n"); printf("inchide = inchide program\n"); printf("adauga = citeste date pentru un numar precizat de persoane si le scrie in fisier\n"); printf("nume = te pune sa citesti un nume si afiseaza datele despre toate persoanele cu numele acela\n"); printf("daca nume == oricare se afiseaza toata lista de persoane\n"); while (strcmp(opt, "inchide") != 0) { printf("Introdu o optiune: "); scanf(" %[^\n]s", opt); if (strcmp(opt, "adauga") == 0) { int nr; printf("Cate persoane vrei sa adaugi? "); scanf(" %d", &nr); citestePersoane(vectorPersoane, nr, &existente); scrieFisier(fisier, vectorPersoane, existente); } else if (strcmp(opt, "nume") == 0) { char nume[50]; scanf(" %[^\n]s", nume); if (strcmp(nume, "oricare") == 0) { afiseazaFisier(fisier); } else { afiseazaPersoana(fisier, nume); } } } free(vectorPersoane); }<file_sep>#include <stdio.h> #include <stdlib.h> void main () { FILE* fisier = fopen("problema5.txt", "w+"); if (fisier == NULL) { printf("Nu s-a alocat bine fisierul."); exit(1); } char secventa[256]; printf("Introdu secventa de valori: "); scanf("%[^\n]s", secventa); fprintf(fisier, "%s", secventa); char secventaFisier[256]; rewind(fisier); fgets(secventaFisier, 256, fisier); printf("%s", secventaFisier); }<file_sep>#include <stdio.h> void main () { int n; printf("Introdu cate numere vrei sa citesti: "); scanf("%d", &n); int v[101] = {}; // am stabilit un interval de valori 0 <= v[i] <= 101 si vom rezolva folosind un vector de frecventa for (int i = 0; i < n; ++i) { int q; printf("Introdu un numar: "); scanf("%d", &q); v[q]++; } int maxim = 0; for (int i = 0; i < 101; ++i) { if (v[i] > maxim) maxim = v[i]; } for (int i = 0; i < 101; ++i) { if (v[i] == maxim) printf("%d ", i); } // Alta varianta(fara vector de frecventa) printf("\nAlta varianta\n"); int vector[10]; for (int i = 0; i < n; ++i) { printf("vector[%d] = ", i); scanf("%d", &vector[i]); } for (int i = 0; i < n - 1; ++i) { for (int j = 0; j < n - i - 1; ++j) { if (vector[j] > vector[j + 1]) { int temp = vector[j]; vector[j] = vector[j + 1]; vector[j + 1] = temp; } } } int elementCurent = vector[0], maximCurent = 0, element = 0; maxim = 0; for (int i = 0; i < n; ++i) { if (elementCurent == vector[i]) maximCurent++; else { if (maximCurent > maxim) { element = elementCurent; maxim = maximCurent; elementCurent = vector[i]; maximCurent = 0; } } } printf("Elementul care apare de cele mai multe ori in vector este %d, cu %d aparitii.", element, maxim); /* Am sortat vectorul folosind bubble sort, astfel toate elementele care sunt identice vor fi unul langa altul si le voi putea numara foarte usor, elementCurent are rolul sa stocheze elementul pe care il verific in momentul de fata, maximCurent are rolul sa numere de cate ori apare elementCurent in vector, in cazul in care elementul pe care il verific se schimba, voi verifica daca numarul sau de aparitii este mai mare decat ultimul numar verificat, in acel caz voi schimba element cu elementCurent si maxim va deveni maximCurent. */ }<file_sep>#include <stdio.h> struct Timp { int ora; int minut; int secunda; }; struct Timp calculeazaTimp(struct Timp m1, struct Timp m2) { struct Timp rezultat = { .ora = 0, .minut = 0, .secunda = 0, }; if (m1.secunda + m2.secunda > 59) { rezultat.minut += 1; rezultat.secunda = m1.secunda + m2.secunda - 60; } else rezultat.secunda = m1.secunda + m2.secunda; if (m1.minut + m2.minut > 59) { rezultat.ora += 1; rezultat.minut = m1.minut + m2.minut - 60; } else rezultat.minut = m1.minut + m2.minut; if (m1.ora + m2.ora > 23) { rezultat.ora = m1.ora + m2.ora - 24; } else rezultat.ora = m1.ora + m2.ora; return rezultat; } void main () { struct Timp moment1, moment2, result; printf("Introdu primul timp: "); scanf("%d%d%d", &moment1.ora, &moment1.minut, &moment1.secunda); printf("\nIntrodu al doilea timp: "); scanf("%d%d%d", &moment2.ora, &moment2.minut, &moment2.secunda); result = calculeazaTimp(moment1, moment2); if (result.ora < 10) { printf("0%d:", result.ora); } else printf("%d:", result.ora); if (result.minut < 10) { printf("0%d:", result.minut); } else printf("%d:", result.minut); if (result.secunda < 10) { printf("0%d", result.secunda); } else printf("%d", result.secunda); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> void adaugaInFisier(FILE* fisier) { char linie[1000]; while (1) { if (strcmp(linie, "EOF") == 0) { return; } scanf(" %[^\n]s", linie); fprintf(fisier, "%s", linie); fprintf(fisier, "\n"); } } int numaraCaractere(FILE* fisier) { fseek(fisier, 0, SEEK_SET); int caractere = 0; char caracter = fgetc(fisier); while (caracter != EOF) { if (caracter != '\n') caractere++; caracter = fgetc(fisier); } return caractere; } int numaraCuvinte(FILE* fisier) { fseek(fisier, 0, SEEK_SET); int cuvinte = 0; char cuvant[100]; while (fscanf(fisier, "%s", cuvant) != EOF) { cuvinte++; } return cuvinte; } int numaraLinii(FILE* fisier) { fseek(fisier, 0, SEEK_SET); int linii = 0; int caracter = fgetc(fisier); while (caracter != EOF) { if (caracter == '\n') linii++; caracter = fgetc(fisier); } return linii - 1; // functia care adauga text in fisier mai pune o linie inainte sa termine de citit deci scadem o linie care e goala oricum } int lungimeaCuvantului(FILE* fisier, int nrOrdine) { fseek(fisier, 0, SEEK_SET); int cuvinte = 0; char cuvant[100]; while (fscanf(fisier, "%s", cuvant) != EOF) { cuvinte++; if (cuvinte == nrOrdine) { return strlen(cuvant); } } return 0; } void main () { FILE* fisier = fopen("P3.txt", "w+"); if (!fisier) { printf("Nu s-a putut deschide."); exit(1); } adaugaInFisier(fisier); printf("Fisierul contine %d caractere.\n", numaraCaractere(fisier)); printf("Fisierul are %d cuvinte.\n", numaraCuvinte(fisier)); printf("Fisierul are %d linii.\n", numaraLinii(fisier)); int nr; printf("Introdu un numar de ordine: "); scanf("%d", &nr); int lungimeCuvant = lungimeaCuvantului(fisier, nr); if (lungimeCuvant != 0) { printf("Cuvantul cautat are %d caractere.", lungimeCuvant); } else { printf("Nu exista un cuvant cu acel numar de ordine."); } }<file_sep>#include <stdio.h> void main () { int zi; printf("Introduceti un numar: "); scanf("%d", &zi); if (zi == 1) printf("Luni"); else if (zi == 2) printf("Marti"); else if (zi == 3) printf("Miercuri"); else if (zi == 4) printf("Joi"); else if (zi == 5) printf("Vineri"); else if (zi == 6) printf("Sambata"); else if (zi == 7) printf("Duminica"); else printf("eroare"); }<file_sep>#include <stdio.h> #include <string.h> #include <ctype.h> void inlcouiesteLitere(char* sir) { sir[0] = toupper(sir[0]); sir[strlen(sir) - 1] = toupper(sir[strlen(sir) - 1]); for (int i = 1; i < strlen(sir) - 1; ++i) { // parcurg de la 1 la strlen(sir) - 1 deoarece primul si ultimul caracter le-am transformat deja. if (sir[i] == ' ' && isalpha(sir[i - 1])) { sir[i - 1] = toupper(sir[i - 1]); } if (sir[i] == ' ' && isalpha(sir[i + 1])) { sir[i + 1] = toupper(sir[i + 1]); } } } void main () { char sir[256]; printf("Introdu un sir: "); scanf("%[^\n]s", sir); inlcouiesteLitere(sir); printf("Sirul dupa modificari: \n"); printf("%s", sir); }<file_sep>#include <stdio.h> #include <stdbool.h> void main () { int vector[20], n; printf("Introdu numarul de elemente: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("vector[%d] = ", i); scanf("%d", &vector[i]); } int distincte = 0; for (int i = 0; i < n - 1; ++i) { for (int j = 0; j < n - i - 1; ++j) { if (vector[j] > vector[j + 1]) { int temp = vector[j]; vector[j] = vector[j + 1]; vector[j + 1] = temp; } } } for (int i = 0; i < n - 1; ++i) { for (int j = 1; j < n; ++j) { if (vector[i] != vector[j]) distincte++; } } if (distincte == n) printf("Toate distincte."); else if (distincte == 0) printf("Toate identice."); else printf("Oarecare"); /* Am sortat vectorul folosind bubble sort si apoi am luat fiecare element si l-am comparat cu restul iar apoi am facut verificarea. Daca numarul de elemente distincte == n atunci inseamna ca toate sunt distincte, daca distincte == 0 atunci toate sunt identice, iar daca nu se trece de niciuna din cele 2 verificari atunci vectorul este oarecare. */ }<file_sep>#include <stdio.h> void permutaCircularLaDreapta(int* vector, int len) { int element = vector[len - 1]; for (int i = len - 2; i >= 0; --i) { vector[i + 1] = vector[i]; } vector[0] = element; } void main () { int matrice[10][10], n; printf("Introdu numarul de elemente: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { printf("matrice[%d][%d] = ", i, j); scanf("%d", &matrice[i][j]); } } for (int i = 0; i < n; ++i) { int I = i; while (I--) { permutaCircularLaDreapta(*(matrice + i), n); } } printf("Matricea cu elementele permutate: \n"); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { printf("%d ", matrice[i][j]); } printf("\n"); } }<file_sep>#include <stdio.h> #include <stdbool.h> #include <math.h> void main () { int numar; printf("Introdu un numar: "); scanf("%d", &numar); bool verificare = true; /* se porneste de la ideea ca numarul e prim si adaugam o conditie suplimentara in for (verificare != 0), in momentul in care verificare = 0 for se opreste si se trece la ultimul if. */ for (int i = 2; i < sqrt(numar) && verificare != false; ++i) { if (numar % i == 0) { verificare = 0; } } if (verificare == false) printf("Numarul %d nu este prim.", numar); else printf("Numarul %d este prim.", numar); }<file_sep>#include <stdio.h> #include <string.h> void main () { char sir[256]; printf("Introdu textul pe care vrei sa il codifici: "); scanf("%[^\n]s", sir); for (int i = 0; i < strlen(sir); ++i) { if (sir[i] != ' ') { if (sir[i] == 'z') sir[i] = 'a'; else { sir[i]++; } } } printf("%s", sir); }<file_sep>#include <stdio.h> void main () { int n; printf("Introdu un numar n: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { if (i % 2 == 0) printf("%d ", i); } }<file_sep>#include <stdio.h> #include <stdbool.h> bool construiesteVectorComune(int* vA, int lA, int* vB, int lB, int* construit, int* lConstruit) { int contor = 0; for (int i = 0; i < lA; ++i) { for (int j = 0; j < lB; ++j) { if (vA[i] == vB[j]) { construit[contor++] = vA[i]; } } } if (contor == 0) return false; else { *lConstruit = contor; return true; } } void main () { int vectorA[] = {2, 6, 8, 11, 33, 28, 55, 79, 81}; int vectorB[] = {6, 8, 12, 34, 28, 56, 81, 79}; int lungimeA = sizeof(vectorA) / sizeof(vectorA[0]); int lungimeB = sizeof(vectorB) / sizeof(vectorB[0]); int vectorConstruit[9], elementeConstruit = 0; bool aFostConstruit = construiesteVectorComune(vectorA, lungimeA, vectorB, lungimeB, vectorConstruit, &elementeConstruit); if (!aFostConstruit) printf("Cei 2 vectori nu au elemente comune."); else { for (int i = 0; i < elementeConstruit; ++i) { printf("%d ", vectorConstruit[i]); } } }<file_sep>#include <stdio.h> void construiesteVector(int* initial, int lInitial, int* vPare, int* lPare, int* vImpare, int* lImpare) { *lPare = 0; *lImpare = 0; for (int i = 0; i < lInitial; ++i) { if (initial[i] % 2) { vImpare[(*lImpare)++] = initial[i]; } else { vPare[(*lPare)++] = initial[i]; } } } void main () { int vectorInit[100], n; printf("Introdu lungimea vectorului initial: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("vectorInit[%d] = ", i); scanf("%d", &vectorInit[i]); } int vectorPare[100], vectorImpare[100], lungimePare = 0, lungimeImpare = 0; construiesteVector(vectorInit, n, vectorPare, &lungimePare, vectorImpare, &lungimeImpare); if (lungimePare == 0) { printf("In vectorul initial nu au fost elemente pare.\n"); } else { printf("Vectorul cu elemente pare: "); for (int i = 0; i < lungimePare; ++i) { printf("%d ", vectorPare[i]); } printf("\n"); } if (lungimeImpare == 0) { printf("In vectorul initial nu au fost elemente impare.\n"); } else { printf("Vectorul cu elemente impare: "); for (int i = 0; i < lungimeImpare; ++i) { printf("%d ", vectorImpare[i]); } printf("\n"); } }<file_sep>#include <stdio.h> #include <string.h> void main () { char sir[101]; printf("Introdu un sir: "); scanf("%[^\n]s", sir); int indiceDeEliminat = 0; while (indiceDeEliminat < strlen(sir)) { for (int i = 0; i < strlen(sir); ++i) { if (i != indiceDeEliminat) printf("%c", sir[i]); } printf("\n"); indiceDeEliminat++; } }<file_sep>#include <stdio.h> #include <stdbool.h> void main () { int vector[25], Vector[25], n; printf("Introdu numarul de elemente: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("vector[%d] = ", i); scanf("%d", &vector[i]); } int contor = 0; for (int i = 0; i < n; ++i) { bool gasit = false; int element = vector[i]; for (int j = 0; j < contor; ++j) { if (element == Vector[j]) gasit = true; } if (gasit == false) { // daca nu am gasit deja elementul in vector atunci il adaugam si crestem contorul. Vector[contor] = vector[i]; contor++; } } printf("Vectorul format este: "); for(int i = 0; i < contor; ++i) { printf("%d ", Vector[i]); } // Varianta int VVector[25]; contor = 0; for (int i = 0; i < n; ++i) { bool dublura = false; int element = vector[i]; for (int j = 0; j < n; ++j) { if (j == i) continue; if (vector[j] == element) dublura = true; } if (dublura == false) { // daca nu am gasit dublura pentru elementul cautat atunci il adaugam in vector. VVector[contor] = element; contor++; } } printf("\nVectorul format este: "); for (int i = 0; i < contor; ++i) { printf("%d, ", VVector[i]); } }<file_sep>#include <stdio.h> void main () { printf("*\n"); printf("**\n"); printf("***\n"); char litera; printf("Introdu o litera: "); scanf("%c", &litera); printf("%c\n", litera); printf("%c%c\n", litera, litera); printf("%c%c%c", litera, litera, litera); }<file_sep>#include <stdio.h> #include <string.h> #include <stdbool.h> bool isVowel(char a) { if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u') return true; return false; } void main () { char sir[256]; printf("Introdu un sir de caractere: "); scanf("%[^\n]s", sir); int cuvinteCareIncepCuVocala = 0; for (int i = 0; i < strlen(sir); ++i) { if (isVowel(sir[i]) && (i == 0 || sir[i - 1] == ' ')) { int pozitie = i; while (sir[i] != ' ' && i < strlen(sir)) { i++; } if (isVowel(sir[i - 1])) cuvinteCareIncepCuVocala++; } } printf("%d cuvinte din input incep cu vocala.", cuvinteCareIncepCuVocala); }<file_sep>#include <stdio.h> #include <ctype.h> #include <stdbool.h> void transformaCaractere(char *c1, char *c2, char *c3, bool *rezultat) { if (isalpha(*c1) && isalpha(*c2) && isalpha(*c3)) { *c1 = toupper(*c1); *c2 = toupper(*c2); *c3 = toupper(*c3); *rezultat = true; } else *rezultat = false; } void main () { char caracter1, caracter2, caracter3; printf("Introdu cele 3 caractere: "); scanf("%c %c %c", &caracter1, &caracter2, &caracter3); bool succes = false; transformaCaractere(&caracter1, &caracter2, &caracter3, &succes); if (succes) { printf("Transformarea a avut loc cu scucces!\n"); printf("%c %c %c", caracter1, caracter2, caracter3); } else { printf("Transformarea nu a putut avea loc!"); } }<file_sep>#include <stdio.h> #include <stdlib.h> void main () { char sir1[256], sir2[256]; scanf("%s", &sir1); printf("%s\n", sir1); fflush(stdin); gets(sir2); printf("%s", sir2); } /* Observatii: functia scanf citeste un cuvant pana cand gaseste caracterul space, iar functia gets citeste un sir intreg. */<file_sep>#include <stdio.h> void main () { for (int i = 1; i <= 10; ++i) { for (int j = 1; j <= 10; ++j) { printf("%7dx%d=%d", i, j, i*j); } printf("\n"); } }<file_sep>#include <stdio.h> int palindrom(int n) { int save = n, oglindit = 0; // am salvat numarul pentru verificarea din final while (n) { oglindit = oglindit * 10 + n % 10; n /= 10; } if (save == oglindit) return 1; else return 0; } void main () { printf("%d\n", palindrom(15651)); printf("%d\n", palindrom(23532)); printf("%d\n", palindrom(15652)); printf("%d\n", palindrom(23534)); }<file_sep>#include <stdio.h> void main () { int a[5][5]; int linii; printf("Introdu numarul de linii: "); scanf("%d", &linii); // e patratica deci linii == coloane for (int i = 0; i < linii; ++i) { for (int j = 0; j < linii; ++j) { printf("a[%d][%d] = ", i, j); scanf("%d", &a[i][j]); } } // Subpunct a for (int i = 0; i < linii; ++i) { for (int j = 0; j < linii; ++j) { printf("%d ", a[i][j]); } printf("\n"); } // Subpunct b printf("Diagonala principala: "); for (int i = 0; i < linii; ++i) printf("%d ", a[i][i]); printf("\nDiagonala secundara: "); for (int i = 0; i < linii; ++i) { printf("%d ", a[i][linii - i - 1]); } // Subpunct c printf("\nValorile din triunghiul superior: \n"); for (int i = 0; i < linii; ++i) { for (int j = i + 1; j < linii; ++j) { printf("%d ", a[i][j]); } } printf("\nValorile din triunghiul inferior: "); for (int i = 0; i < linii; ++i) { for (int j = 0; j < i; ++j) { printf("%d ", a[i][j]); } printf("\n"); } // Subpunct d printf("\nElementele de pe contur:\n "); for (int i = 0; i < linii; ++i) { printf("%d ", a[0][i]); } printf("\n"); for (int i = 0; i < linii; ++i) { printf("%d ", a[i][linii - 1]); } printf("\n"); for (int i = linii - 1; i >= 0; --i) { printf("%d ", a[linii - 1][i]); } printf("\n"); for (int i = linii - 1; i >= 0; --i) { printf("%d ", a[i][0]); } printf("\nElementele din interiorul conturului: "); for (int i = 1; i < linii - 1; ++i) { for (int j = 1; j < linii - 1; ++j) { printf("%d ", a[i][j]); } printf("\n"); } // Subpunct e printf("Parcurgerea in spirala: "); int contor = 0; while (contor < linii) { if (contor == linii - 1) { printf("%d", a[contor][contor]); break; } for (int i = contor; i < linii; ++i) { printf("%d ", a[contor][i]); } for (int i = contor; i < linii; ++i) { printf("%d ", a[i][linii - 1]); } for (int i = linii - 1; i >= contor; --i) { printf("%d ", a[linii - 1][i]); } for (int i = linii - 1; i >= contor; --i) { printf("%d ", a[i][contor]); } contor++; linii--; } }<file_sep>#include <stdio.h> #include <string.h> void main () { char sir1[256], sir2[256], sir3[256]; printf("Introdu un sir: "); gets(sir1); fflush(stdin); printf("Introdu un sir: "); gets(sir2); fflush(stdin); printf("Introdu un sir: "); gets(sir3); fflush(stdin); int lungime1 = strlen(sir1), lungime2 = strlen(sir2), lungime3 = strlen(sir3); int lungime = lungime1 + lungime2; int c = 0; for (int i = lungime1; i < lungime; ++i) { sir1[i] = sir2[c]; c++; } // am concatenat sir1 cu sir 2 int final = lungime1 + lungime2 + lungime3; c = 0; for (int i = lungime; i < final; ++i) { sir1[i] = sir3[c]; c++; } for (int i = 0; i < final; ++i) { printf("%c", sir1[i]); } }<file_sep>#include <stdio.h> #include <limits.h> int gasesteMaximImpar(int* v, int lungimeV) { int maximImpar = INT_MIN; for (int i = 0; i < lungimeV; ++i) { if (v[i] % 2 && v[i] > maximImpar) maximImpar = v[i]; } return maximImpar; } void main () { int vector[10], n; printf("Introdu lungimea vectorului: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("vector[%d] = ", i); scanf("%d", &vector[i]); } int maxImpar = gasesteMaximImpar(vector, n); printf("Maximul impar din vector este %d.", maxImpar); }<file_sep>#include <stdio.h> #include <stdbool.h> bool verificaIdentitateVector(int* vectorA, int lVA, int* vectorB, int lVB) { bool gasit = true; if (lVA != lVB) return false; for (int i = 0; i < lVA; ++i) { gasit = false; for (int j = 0; j < lVA; ++j) { if (vectorA[i] == vectorB[j]) { gasit = true; } } if (gasit == false) return gasit; } return true; } void main () { int matriceA[10][10], lungimeA, matriceB[10][10], lungimeB; printf("Introdu numarul de elemente din matricea A: "); scanf("%d", &lungimeA); printf("Introdu numarul de elemente din matricea B: "); scanf("%d", &lungimeB); for (int i = 0; i < lungimeA; ++i) { for (int j = 0; j < lungimeA; ++j) { printf("matriceA[%d][%d] = ", i, j); scanf("%d", &matriceA[i][j]); } } for (int i = 0; i < lungimeB; ++i) { for (int j = 0; j < lungimeB; ++j) { printf("matriceB[%d][%d] = ", i, j); scanf("%d", &matriceB[i][j]); } } bool verificare = true; if (lungimeA != lungimeB) verificare = false; // daca nu au acelasi numar de linii si coloane nu mai are rost sa verific nimic din matrice. else { for (int i = 0; i < lungimeA && verificare != false; ++i) { verificare = verificaIdentitateVector(matriceA[i], lungimeA, matriceB[i], lungimeB); } } if (verificare == false) { printf("Matricele nu sunt identice."); } else { printf("Matricele sunt identice."); } } /* In cadrul rezolvarii am considerat ca 2 matrice sunt identice daca au aceleasi elemente pe aceeasi linie indiferent de pozitia lor. Deci daca pe linia 0 vom avea 1 3 2 respectiv 1 2 3, functia verificaIdentitateVector va intoarce true deoarece are aceleasi elemente, fara sa conteze ordinea. In cazul in care vrem sa conteze ordinea, scoatem al doilea for din functie si punem verificarea if (vectorA[i] != vectorB[i]) return false; astfel daca nu au aceeasi ordine, atunci functia va intoarce false. */<file_sep>#include <stdio.h> void main () { int n; printf("Introduceti un numar: "); scanf("%d", &n); int contor = 0; int nr, suma = 0; while (contor != n) { printf("Introduceti termenul %d din medie: ", contor + 1); scanf("%d", &nr); // citim un numar si il adaugam la suma cat timp contor != n, contor creste la fiecare pas suma += nr; contor++; } printf("Media numerelor citite = %.2f", (float)suma / n); // am afisat media cu doar 2 zecimale }<file_sep>#include <stdio.h> #include <stdbool.h> #include <limits.h> #include <string.h> struct Student { char nume[50]; int nota1; int nota2; int nota3; }; void sortare(struct Student studenti[], int lungime) { for (int i = 0; i < lungime; ++i) { struct Student cheie = studenti[i]; int j = i - 1; while (j >= 0 && studenti[j].nota2 < cheie.nota2) { studenti[j + 1] = studenti[j]; j--; } studenti[j + 1] = cheie; } } void main () { struct Student studenti[20]; int n; printf("Introdu numarul de studenti: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("Introdu numele studentului %d:", i); scanf(" %[^\n]s", studenti[i].nume); printf("Introdu nota la programare: "); scanf("%d", &studenti[i].nota1); printf("Introdu nota la analiza: "); scanf("%d", &studenti[i].nota2); printf("Introdu nota la algebra: "); scanf("%d", &studenti[i].nota3); } char studentCautat[20]; printf("Introdu numele studentului cautat: "); scanf(" %[^\n]s", studentCautat); bool gasit = false; for (int i = 0; i < n; ++i) { if (strcmp(studenti[i].nume, studentCautat) == 0) { gasit = true; printf("Nota programare: %d\n", studenti[i].nota1); printf("Nota analiza: %d\n", studenti[i].nota2); printf("Nota algebra: %d\n", studenti[i].nota3); } } if (!gasit) printf("Nu a fost gasit studentul cautat."); char materie[20]; printf("Pentru ce materie vrei sa aflii cel mai bun student? "); scanf(" %[^\n]s", materie); int notaMax = INT_MIN; if (strcmp(materie, "programare") == 0) { for (int i = 0; i < n; ++i) { if (studenti[i].nota1 > notaMax) { notaMax = studenti[i].nota1; } } printf("Cea mai mare nota: %d\n", notaMax); for (int i = 0; i < n; ++i) { if (studenti[i].nota1 == notaMax) { printf("%s\n", studenti[i].nume); } } } else if (strcmp(materie, "algebra") == 0) { for (int i = 0; i < n; ++i) { if (studenti[i].nota2 > notaMax) { notaMax = studenti[i].nota2; } } printf("Cea mai mare nota: %d\n", notaMax); for (int i = 0; i < n; ++i) { if (studenti[i].nota2 == notaMax) { printf("%s\n", studenti[i].nume); } } } else if (strcmp(materie, "analiza") == 0) { for (int i = 0; i < n; ++i) { if (studenti[i].nota3 > notaMax) { notaMax = studenti[i].nota3; } } printf("Cea mai mare nota: %d\n", notaMax); for (int i = 0; i < n; ++i) { if (studenti[i].nota3 == notaMax) { printf("%s\n", studenti[i].nume); } } } else { printf("Nu exista acea materie.\n"); } float medieGenMax = 0.0f; for (int i = 0; i < n; ++i) { float medieGen = (float)((studenti[i].nota1 + studenti[i].nota2 + studenti[i].nota3) / 3); if (medieGen > medieGenMax) medieGenMax = medieGen; } printf("Premiantii grupei: "); for (int i = 0; i < n; ++i) { float medieGen = (float)((studenti[i].nota1 + studenti[i].nota2 + studenti[i].nota3) / 3); if (medieGen == medieGenMax) printf("%s\n", studenti[i].nume); } sortare(studenti, n); for (int i = 0; i < n; ++i) { printf("Nume: %s. Nota: %d\n", studenti[i].nume, studenti[i].nota2); } int nepromovati = 0; for (int i = 0; i < n; ++i) { if (studenti[i].nota1 < 5 || studenti[i].nota2 < 5 || studenti[i].nota3 < 5) { nepromovati++; } } if (nepromovati == 0) printf("Toti studentii au promovat."); else printf("In total nu au promovat %d studenti.", nepromovati); }<file_sep>#include <stdio.h> #include <string.h> #include <stdbool.h> #include <ctype.h> bool isVowel(char a) { if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u') return true; return false; } void inlocuiesteVocala(char* vocala) { if (!isVowel(*vocala)) return; if (islower(*vocala)) *vocala = toupper(*vocala); } void main () { char sir[256]; printf("Introdu un sir: "); scanf("%[^\n]s", sir); for (int i = 0; i < strlen(sir); ++i) { inlocuiesteVocala(&sir[i]); } printf("%s", sir); }<file_sep>#include <stdio.h> struct Timp { int ora; int minut; int secunda; }; struct Data { int zi; int luna; int an; struct Timp moment; }; void main () { struct Data data; printf("Introdu ziua, luna si anul: "); scanf("%d%d%d", &data.zi, &data.luna, &data.an); printf("Introdu momentul(ora, minut, secunda): "); scanf("%d%d%d", &data.moment.ora, &data.moment.minut, &data.moment.secunda); printf("Datele introduse sunt: \n"); printf("Data: %d/%d/%d", data.zi, data.luna, data.an); printf("Moment: "); data.moment.ora < 10 ? printf("0%d:", data.moment.ora) : printf("%d:", data.moment.ora); data.moment.minut < 10 ? printf("0%d:", data.moment.minut) : printf("%d:", data.moment.minut); data.moment.secunda < 10 ? printf("0%d", data.moment.secunda) : printf("%d", data.moment.secunda); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <ctype.h> #include <string.h> bool verificaCuvant(char* cuvant, int len) { // daca nu contine doar litere, cifre sau cratima false for (int i = 0; i < len - 1; ++i) { if (isalpha(cuvant[i])) continue; else if (isdigit(cuvant[i])) continue; else if (cuvant[i] == '-'); else return false; } if (cuvant[len - 1] == '.' || cuvant[len - 1] == '!' || cuvant[len - 1] == '?') return true; } int verificaPropozitie(char* propozitie, int lungime) { int count = 0; for (int i = 0; i < lungime; ++i) { if (propozitie[i] == '.' || propozitie[i] == '!' || propozitie[i] == '?') count++; if (propozitie[i] == 0 && isalpha(propozitie[i - 1])) count++; } return count; } int numaraCuvinte(FILE* fisier) { int cuvinte = 0; char cuvant[100]; fseek(fisier, 0, SEEK_SET); while (fscanf(fisier, "%s", cuvant) != EOF) { int lungime = strlen(cuvant); if (verificaCuvant(cuvant, lungime)) cuvinte++; } return cuvinte; } int numaraPropozitii(FILE* fisier) { fseek(fisier, 0, SEEK_SET); int propozitii = 0; char propozitie[1000]; while (fgets(propozitie, 1000, fisier)) { int lungime = strlen(propozitie); int nr = verificaPropozitie(propozitie, lungime); propozitii += nr; } return propozitii; } void adaugaInFisier(FILE* fisier) { char optiune = 'D'; do { char linie[1000]; printf("Scrie o noua linie pentru a o adauga in fisier: \n"); scanf(" %[^\n]s", linie); fprintf(fisier, "%s", linie); printf("Vrei sa adaugi o noua linie? (D / N) "); scanf(" %c", &optiune); fprintf(fisier, "\n"); } while (optiune != 'N'); } void main () { FILE* fisierPropozitii = fopen("P1.txt", "w+"); if (fisierPropozitii == NULL) { printf("Nu s-a putut deschide fisierul."); exit(1); } adaugaInFisier(fisierPropozitii); fseek(fisierPropozitii, 0, SEEK_SET); int cuv = numaraCuvinte(fisierPropozitii); printf("Fisierul are %d cuvinte.\n", cuv); int prop = numaraPropozitii(fisierPropozitii); printf("Fisierul are %d propozitii.\n", prop); }<file_sep>#include <stdio.h> void main () { int A[5][5], B[5][5], m, n, p, q; printf("Introdu dimensiunile lui A(m, n): "); scanf("%d%d", &m, &n); printf("Introdu dimensiunile lui B(p, q): "); scanf("%d%d", &p, &q); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { printf("A[%d][%d] = ", i, j); scanf("%d", &A[i][j]); } } for (int i = 0; i < p; ++i) { for (int j = 0; j < q; ++j) { printf("B[%d][%d] = ", i, j); scanf("%d", &B[i][j]); } } int Suma[5][5]; // Adunare if (m != p || n != q) printf("Nu se poate efectua adunarea!"); // daca numarul de linii sau coloane al lui A este diferit de cel al lui B nu se poate efectua adunarea else { for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { Suma[i][j] = A[i][j] + B[i][j]; } } for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { printf("%d ", Suma[i][j]); } printf("\n"); } } // Inmultire if (n != p) printf("Nu se poate efectua inmultirea!"); // daca numarul de coloane al lui a e diferit de numarul de coloane al lui b nu se poate efectua inmultirea else { int Produs[5][5]; for (int i = 0; i < m; ++i) { for (int j = 0; j < p; ++j) { Produs[i][j] = 0; for (int k = 0; k < n; ++k) { Produs[i][j] += A[i][k] * B[k][j]; } } } for (int i = 0; i < m; ++i) { for (int j = 0; j < p; ++j) { printf("%d ", Produs[i][j]); } printf("\n"); } } }<file_sep>#include <stdio.h> void main () { int A[50], B[50], elA, elB; printf("Introdu numarul de elemente al lui A: "); scanf("%d", &elA); printf("Introdu numarul de elemente al lui B: "); scanf("%d", &elB); for (int i = 0; i < elA; ++i) { printf("A[%d] = ", i); scanf("%d", &A[i]); } for (int i = 0; i < elB; ++i) { printf("B[%d] = ", i); scanf("%d", &B[i]); } int C[50], elC = 0, contorA = 0, contorB = 0; while (contorA < elA && contorB < elB) { if (A[contorA] < B[contorB]) { if (A[contorA] % 2 != 0) { C[elC] = A[contorA]; elC++; } contorA++; } else { if (B[contorB] % 2 != 0) { C[elC] = B[contorB]; elC++; } contorB++; } } if (contorA <= elA) { for (int i = contorA; i < elA; ++i) { if (A[i] % 2 != 0) { C[elC] = A[i]; elC++; } } } if (contorB <= elB) { for (int i = contorB; i < elB; ++i) { if (B[i] % 2 != 0) { C[elC] = B[i]; elC++; } } } for (int i = 0; i < elC; ++i) { printf("%d ", C[i]); } }<file_sep>#include <stdio.h> void main () { int n, negative = 0, pozitive = 0; do { printf("Introdu un numar: "); scanf("%d", &n); if (n < 0) negative ++; else pozitive ++; } while (n != 0); printf("pozitive = %d\n", pozitive); printf("negative = %d", negative); }<file_sep>#include <stdio.h> void main () { int a, b, c; // laturile triunghiului printf("Introduceti prima latura: "); scanf("%d", &a); printf("Introduceti a doua latura: "); scanf("%d", &b); printf("Introduceti a treia latura: "); scanf("%d", &c); if ((a > 0 && b > 0 && c > 0) && (a + b > c && a + c > b && b + c > a)) { printf("Cele trei laturi pot forma un triunghi.\n"); if (a == b && a == c && b == c) printf("Triunghiul este echilateral.\n"); else if (a == b || a == c || b == c) printf("Triunghiul este isoscel.\n"); else if ((a * a + b * b == c * c) || (a * a + c * c == b * b) || (b * b + c * c == a * a)) printf("Triunghiul este dreptunghic.\n"); else printf("Triunghiul este oarecare.\n"); } else printf("Cele trei laturi nu pot forma un triunghi."); }<file_sep>#include <stdio.h> #include <string.h> #include <stdbool.h> bool eAnagrama(char* cuvant1, char* cuvant2) { if (strlen(cuvant1) != strlen(cuvant2)) return false; char frecventaCuvant[26], frecventaCuvant2[26]; int contor = 0; while (cuvant1[contor] != '\0') { frecventaCuvant[cuvant1[contor]]++; contor++; } contor = 0; while (cuvant2[contor] != '\0') { frecventaCuvant2[cuvant2[contor]]++; contor++; } for (int i = 0; i < 26; ++i) { if (frecventaCuvant[i] != frecventaCuvant2[i]) return false; } return true; } void main () { int n; char primul[256]; printf("Introdu un numar: "); scanf("%d", &n); printf("Introdu %d cuvinte: ", n); scanf(" %[^\n]s", primul); n--; int anagrame = 0; while (n--) { char cuvant[256]; scanf(" %[^\n]s", cuvant); if (eAnagrama(primul, cuvant) == true) anagrame++; } printf("S-au gasit %d anagrame.", anagrame); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <limits.h> #include <string.h> typedef struct client { char nume[128]; float debit; float credit; int codClient; } Client; void afiseaza(Client* list, int len) { for (int i = 0; i < len; ++i) { printf("%s\n", list[i].nume); } } int codClientMaxim(Client* lista, int intrari) { int max = INT_MIN; for (int i = 0; i < intrari; ++i) { if (lista[i].codClient > max) max = lista[i].codClient; } return max; } void sorteazaClientiAlfabetic(Client* clienti, int nrClienti) { for (int i = 0; i < nrClienti; ++i) { Client cheie; memcpy(&cheie, &clienti[i], sizeof(Client)); int j = i - 1; while (j >= 0 && strcmp(clienti[j].nume, cheie.nume) > 0) { memcpy(&clienti[j + 1], &clienti[j], sizeof(Client)); j--; } memcpy(&clienti[j + 1], &cheie, sizeof(Client)); } } void unesteClientii(Client* lista1, int clienti1, Client* lista2, int clienti2, Client* primaBanca, int* clientiPrima, Client* aDouaBanca, int* clientiADoua, Client* clientiComuni, int* nrComuni) { sorteazaClientiAlfabetic(lista1, clienti1); sorteazaClientiAlfabetic(lista2, clienti2); afiseaza(lista1, clienti1); printf("\n\n"); afiseaza(lista2, clienti2); int comuni = 0, prima = 0, aDoua = 0; for (int i = 0; i < clienti1; ++i) { for (int j = 0; j < clienti2; ++j) { if (strcmp(lista1[i].nume, lista2[j].nume) == 0) { memcpy(&clientiComuni[comuni], &lista1[i], sizeof(Client)); clientiComuni[comuni].codClient = lista2[j].codClient; comuni++; } } } for (int i = 0; i < clienti1; ++i) { for (int j = 0; j < comuni; ++j) { if (strcmp(lista1[i].nume, clientiComuni[j].nume) == 0) continue; memcpy(&primaBanca[prima], &lista1[i], sizeof(Client)); prima++; } } for (int i = 0; i < clienti2; ++i) { for (int j = 0; j < comuni; ++j) { if (strcmp(lista1[i].nume, clientiComuni[j].nume) == 0) continue; memcpy(&aDouaBanca[aDoua], &lista2[i], sizeof(Client)); aDoua++; } } *clientiPrima = prima; *clientiADoua = aDoua; *nrComuni = comuni; } void citesteFisier(FILE* fis, Client* lista, int* persoane) { fseek(fis, 0, SEEK_SET); char linie[128]; int contor = 0; while (fgets(linie, 128, fis)) { strcpy(lista[contor].nume, linie); lista[contor].nume[strlen(lista[contor].nume) - 1] = 0; fgets(linie, 128, fis); linie[strlen(linie) - 1] = 0; lista[contor].debit = atof(linie); fgets(linie, 128, fis); linie[strlen(linie) - 1] = 0; lista[contor].credit = atof(linie); fgets(linie, 128, fis); lista[contor].codClient = atoi(linie); contor++; } *persoane = contor; } void main () { FILE* fisier1 = fopen("banca1.txt", "r"); FILE* fisier2 = fopen("banca2.txt", "r"); if (!fisier1 || !fisier2) { printf("Unul din fisiere nu a putut fi deschis."); exit(1); } Client* banca1 = (Client*)malloc(1000); Client* banca2 = (Client*)malloc(1000); int clientiBanca1 = 0, clientiBanca2 = 0; citesteFisier(fisier1, banca1, &clientiBanca1); citesteFisier(fisier2, banca2, &clientiBanca2); banca1 = realloc(banca1, clientiBanca1 + 1); banca2 = realloc(banca2, clientiBanca2 + 1); int cmax = codClientMaxim(banca1, clientiBanca1); Client* primaBanca = (Client*)malloc(1000); Client* aDouaBanca = (Client*)malloc(1000); Client* comuni = (Client*)malloc(1000); int prima = 0, aDoua = 0, clientiComuni = 0; unesteClientii(banca1, clientiBanca1, banca2, clientiBanca2, primaBanca, &prima, aDouaBanca, &aDoua, comuni, &clientiComuni); FILE* fisierUnit = fopen("Unit.dat", "wb"); if (!fisierUnit) { printf("Nu am putut deschide fisierul final."); exit(1); } if (aDoua > 0) { fwrite(aDouaBanca, sizeof(Client) * aDoua, 1, fisierUnit); } if (clientiComuni > 0) { fwrite(comuni, sizeof(Client) * clientiComuni, 1, fisierUnit); } if (prima > 0) { for (int i = 0; i < prima; ++i) { primaBanca[i].codClient = cmax + i + 1; } fwrite(primaBanca, sizeof(Client) * prima, 1, fisierUnit); } printf("Numarul total de clienti este %d.", prima + aDoua + clientiComuni); fclose(fisier1); fclose(fisier2); fclose(fisierUnit); free(banca1); free(banca2); free(primaBanca); free(aDouaBanca); free(comuni); }<file_sep>#include <stdio.h> void main () { float nr1, nr2; printf("Introduceti 2 numere: "); scanf("%f%f", &nr1, &nr2); // citirea datelor de la tastatura // subpunct a) printf("Afisarea cu 3 zecimale: %.3f %.3f\n", nr1, nr2); printf("Afisarea cu 5 zecimale: %.5f %.5f\n", nr1, nr2); printf("Afisearea cu 2 zecimale: %.2f, %.2f\n", nr1, nr2); /* Observam ca atunci cand afisam cu 3 zecimale se afiseaza exact numerele pe care le-am introdus. * Observam ca atunci cand afisam cu 5 zecimale apare cifra 0 de 2 ori la finalul numarului afisat. * Observam ca atunci cand afisam cu 2 zecimale numerele sunt rotunjite. Exemplu: input: 1.345 => output: 1.35. */ // subpunct b) printf("Valorile celor doua numere in format mantissa-exponent sunt: %E %E\n", nr1, nr2); // subpunct c) printf("Afisarea sumei folosind un numar intreg: %d\n", nr1 + nr2); printf("Afisarea sumei folosind un numar real: %f\n", nr1 + nr2); // Observam ca primim un numar aleator, nu ce trebuia sa afiseze. // subpunct d) float f; scanf("%d", &f); // am citit un float de la tastatura folosind %d printf("%f\n", f); // l-am afisat folosind %f si am observat ca are valoarea 0.000000 // Observam ca nu i se atribuie nici o valoare lui variabilei f. // subpunct e) float nr = 5; printf("Am afisat un float cu 3 zecimale: %.3f", nr); }<file_sep>#include <stdio.h> #include <stdlib.h> typedef struct persoana { char nume[25]; char prenume[25]; float varsta; } Persoana; void scrieInFisier(Persoana* pers, FILE* text, FILE* binar) { for (int i = 0; i < 1; ++i) { printf("Introdu numele persoanei %d: ", i + 1); scanf(" %[^\n]s", pers[i].nume); printf("Introdu prenumele persoanei %d: ", i + 1); scanf(" %[^\n]s", pers[i].prenume); printf("Introdu varsta persoanei %d: ", i + 1); scanf("%f", &pers[i].varsta); fprintf(text, "%s %s %f\n", pers[i].nume, pers[i].prenume, pers[i].varsta); fwrite(&pers[i], sizeof(pers), 3, binar); } } void main () { Persoana* persoane = (Persoana*)calloc(5, sizeof(Persoana)); if (persoane == NULL) { printf("Nu am putut aloca vectorul de persoane."); exit(1); } FILE* fisierText = fopen("problema6Text.txt", "w+"); FILE* fisierBinar = fopen("problema6Binar.txt", "wb"); scrieInFisier(persoane, fisierText, fisierBinar); fclose(fisierText); fclose(fisierBinar); }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> void inlocuieste(char* sir, char* vechi, char* nou) { char* pozitie, temp[1024]; int index, lungimeVechi = strlen(vechi); // trect prin toata propozitia pana nu mai gasesc cuvantul cautat while ((pozitie = strstr(sir, vechi)) != NULL) { strcpy(temp, sir); // salvez in temp propozitia curenta index = pozitie - sir; // pozitia unde a fost gasit cuvantul sir[index] = 0; // pun terminatorul de sir la pozitia unde a fost gasit vechiul cuvant strcat(sir, nou); // concatenez sirul cu caracterul de sfarsit la pozitia vechiului cuvant cu noul cuvant strcat(sir, temp + index + lungimeVechi); // concatenez sirul care se termina la noul cuvant cu restul sirului salvat deja in temp } } void main () { FILE* output = fopen("outputProblema1.txt", "w"); if (output == NULL) { printf("Fisierul nu a putut sa fie deschis."); return; } char text[256]; scanf("%[^\n]s", text); // SUBPUNCT A // asezarea textului cu totul in fisier fputs(text, output); fputs("\n", output); // asezarea textului caracter cu caracter for (int i = 0; i < strlen(text); ++i) { fputc(text[i], output); } fputs("\n", output); char saveText[256]; strcpy(saveText, text); // am salvat textul deoarece dupa ce foloseam strtok se pierdea input-ul initial // asezarea textului cuvant cu cuvant char* cuv = strtok(text, " "); while (cuv) { fputs(cuv, output); cuv = strtok(NULL, " "); } fputs("\n", output); // asezarea textului cuvant cu cuvant, un cuvant pe linie cuv = strtok(saveText, " "); while (cuv) { fprintf(output, "%s\n", cuv); cuv = strtok(NULL, " "); } // SUBPUNCT B // citit si afisat caracter cu caracter fclose(output); // am inchis fisierul apoi l-am redeschis in read & write mode. output = fopen("outputProblema1.txt", "r+"); int caracter = fgetc(output); while (caracter != EOF) { printf("%c", caracter); caracter = fgetc(output); } printf("\n"); // citit si afisat cuvant cu cuvant fseek(output, 0, SEEK_SET); // am resetat pozitia unde se afla in parcurgerea sirului char cuvant[1024]; while (fscanf(output, "%s", cuvant) != EOF) { printf("%s ", cuvant); } printf("\n\n"); // citit si afisat tot fisierul fseek(output, 0, SEEK_SET); char intreg[1024]; fscanf(output, "%[^\0]s", intreg); printf("%s", intreg); // SUBPUNCT C char cautat[35], inlocuit[35]; printf("\nIntrodu cuvantul pe care vrei sa il cauti: "); scanf(" %s", cautat); printf("Introdu cu ce vrei sa il inlocuiesti: "); scanf(" %s", inlocuit); // voi folosi textul pe care il am deja citit de la subpunctul b (intreg) fseek(output, 0, SEEK_SET); FILE* temporar = fopen("temporarProblema1.txt", "w"); if (temporar == NULL) { printf("Nu s-a putut deschide fisierul temporar."); return; } char cuv_fis[1024]; while ((fgets(cuv_fis, 1024, output)) != NULL) { inlocuieste(cuv_fis, cautat, inlocuit); fputs(cuv_fis, temporar); } fclose(temporar); fclose(output); remove("outputProblema1.txt"); rename("temporarProblema1.txt", "outputProblema1.txt"); // FINAL fclose(temporar); fclose(output); }<file_sep>#include <stdio.h> void main () { float numar; int pozitive = 0, negative = 0; do { printf("Introduceti un numar: "); scanf("%f", &numar); if (numar < 0.0) negative ++; else if (numar > 0.0) pozitive ++; } while (numar != 0.0); printf("pozitive = %d\n", pozitive); printf("negative = %d", negative); }<file_sep>#include <stdio.h> void main () { int A[5][5], c1, c2, m, n; printf("Introdu dimensiunile lui A(m,n): "); scanf("%d%d", &m, &n); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { printf("A[%d][%d] = ", i, j); scanf("%d", &A[i][j]); } } printf("Introdu coloanele pe care vrei sa le interschimbi: "); scanf("%d%d", &c1, &c2); printf("Inainte de interschimbarea coloanelor: %d si %d\n", c1, c2); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { printf("%d ", A[i][j]); } printf("\n"); } for (int i = 0; i < m; ++i) { int temp = A[i][c1 - 1]; A[i][c1 - 1] = A[i][c2 - 1]; A[i][c2 - 1] = temp; } /* Am parcurs doar liniile din matrice deoarece indicii coloanelor ii stiam deja(c1, c2) si am folosit c1 - 1, respectiv c2 - 1 deoarece in input vom folosi, de exemplu c1 = 3 si c2 = 1 astfel aratam ca vrem sa interschimbam elementele de pe coloana 3 cu cele de pe coloana 1, care au de fapt indicii 2 si 0 in matrice atunci cand parcurgem cu for. */ printf("Dupa interschimbarea coloanelor: %d si %d\n", c1, c2); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { printf("%d ", A[i][j]); } printf("\n"); } }<file_sep>#include <stdio.h> void numarCifre(int nr, int *vectorCifre, int *nrC) { if (nr < 0) nr = -nr; // daca numarul e negativ atunci il fac pozitiv pentru a nu imi afisa cifrele cu - in fata. int cifre = 0; while (nr) { *(vectorCifre + cifre) = nr % 10; nr /= 10; cifre++; } *nrC = cifre; } // am transmis numarul prin valoare deoarece nu am vrut sa pierd continutul variabilei in care era stocat. void main () { int numar, cifre[3], nrCifre; printf("Introdu un numar care sa aiba cel mult 3 cifre: "); scanf("%d", &numar); if (numar >= -999 && numar <= 999) { numarCifre(numar, cifre, &nrCifre); printf("Numarul %d are %d cifre. Acestea sunt: ", numar, nrCifre); for (int i = 0; i < nrCifre; ++i) { printf("%d ", cifre[i]); } } else printf("Numarul introdus are mai mult de 3 cifre."); } <file_sep>#include <stdio.h> #include <limits.h> #include <stdlib.h> void main () { int vector[10], n; printf("Introdu numarul de elemente: "); scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("vector[%d] = ", i); scanf("%d", &vector[i]); } int minim = INT_MAX, maxim = INT_MIN, pozMin = 0, pozMax = 0; for (int i = 0; i < n; ++i) { if (vector[i] < minim) { minim = vector[i]; pozMin = i; } if (vector[i] > maxim) { maxim = vector[i]; pozMax = i; } } int l = pozMin < pozMax ? pozMin : pozMax; int u = pozMin > pozMax ? pozMin : pozMax; for (int i = l; i <= u - 1; ++i) { for (int j = l; j <= u - 1; ++j) { if (vector[j] > vector[j + 1]) { int temp = vector[j]; vector[j] = vector[j + 1]; vector[j + 1] = temp; } } } for (int i = 0; i < n; ++i) { printf("%d ", vector[i]); } }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> void adaugaInFisier(FILE* fisier) { char* linie = (char*)malloc(1000); while (strcmp(linie, "EOF") != 0) { scanf(" %[^\n]s", linie); if (strcmp(linie, "EOF") == 0) { break; } fprintf(fisier, "%s\n", linie); } free(linie); } void unesteFisiere(FILE* output, FILE* primul, FILE* alDoilea) { fseek(output, 0, SEEK_SET); fseek(primul, 0, SEEK_SET); fseek(alDoilea, 0, SEEK_SET); char linie1[1000], linie2[1000]; while (fgets(linie1, 1000, primul) != NULL && fgets(linie2, 1000, alDoilea) != NULL) { if (linie1 != NULL) { fprintf(output, "%s", linie1); } if (linie2 != NULL) { fprintf(output, "%s", linie2); } } } void main () { FILE* fisierOutput = fopen("P18.txt", "w+"); FILE* fisier1 = fopen("fis1.txt", "w+"); FILE* fisier2 = fopen("fis2.txt", "w+"); if (!fisierOutput || !fisier1 || !fisier2) { printf("Nu am putut deschide unul din fisiere."); exit(1); } printf("Scrie continutul primului fisier: \n"); adaugaInFisier(fisier1); printf("Scrie continutul celui de-al doilea fisier: \n"); adaugaInFisier(fisier2); unesteFisiere(fisierOutput, fisier1, fisier2); }<file_sep>#include <stdio.h> void main () { int nr; do { printf("Introduceti un numar mai mare sau egal cu 3: "); scanf("%d", &nr); } while (nr < 3); // afisarea in linie printf("%d %d %d\n", nr - 1, nr, nr + 1); // afisarea in coloana printf("%d\n%d\n%d", nr - 1, nr, nr + 1); }<file_sep>#include <stdio.h> #include <ctype.h> void main () { char caracter; printf("Introduceti un caracter: "); scanf("%c", &caracter); if (isdigit(caracter) != 0) printf("Caracterul %c este o cifra.\n", caracter); else if (isalpha(caracter) != 0 && islower(caracter) != 0) printf("Caracterul %c este o litera mica.\n", caracter); else if (isalpha(caracter) != 0 && isupper(caracter) != 0) printf("Caracterul %c este o litera mare.\n", caracter); else printf("Caracterul %c este alt caracter.", caracter); /* printf("Verificare functie isdigit('2'): %d\n", isdigit('2')); printf("Verificare functie isdigit('a'): %d\n", isdigit('a')); printf("Verificare functie isalpha('a'): %d\n", isalpha('a')); printf("Verificare functie isalpha('/'): %d\n", isalpha('/')); printf("Verificare functie islower('a'): %d\n", islower('a')); printf("Verificare functie islower('/'): %d\n", islower('/')); printf("Verificare functie isupper('A'): %d\n", isupper('A')); printf("Verificare functie isupper('a'): %d\n", isupper('a'));*/ // >= <= == > < != || }<file_sep>#include <stdio.h> #include <math.h> #include <ctype.h> struct fig_geom { char nume; int raza; int lungime; int latime; }; void main () { char figura; printf("Introdu ce tip de figura vrei(c - cerc, p - patrat, d - dreptunghi): "); scanf("%c", &figura); figura = tolower(figura); struct fig_geom figuraGeometrica; switch (figura) { case 'c': { printf("Introdu raza: "); scanf("%d", &figuraGeometrica.raza); printf("Perimetrul cercului: %f\n", 2 * (M_PI) * figuraGeometrica.raza); printf("Aria cercului: %f", (M_PI) * pow(figuraGeometrica.raza, 2)); break; } case 'p': { printf("Introdu lungimea: "); scanf("%d", &figuraGeometrica.lungime); figuraGeometrica.latime = figuraGeometrica.lungime; printf("Perimetrul patratului: %d\n", 4 * figuraGeometrica.lungime); printf("Aria patratului: %d\n", figuraGeometrica.lungime * figuraGeometrica.latime); break; } case 'd': { printf("Introdu lungimea: "); scanf("%d", &figuraGeometrica.lungime); printf("Introdu latimea: "); scanf("%d", &figuraGeometrica.latime); printf("Perimetrul dreptunghiului: %d\n", 2 * (figuraGeometrica.lungime + figuraGeometrica.latime)); printf("Aria dreptunghiului: %d\n", figuraGeometrica.lungime * figuraGeometrica.latime); break; } default: printf("Nu exista"); } }<file_sep>#include <stdio.h> void main () { int n; printf("Introdu numarul de elemente: "); scanf("%d", &n); int v[100], im = 0, p = 0, pare[50], impare[50]; for (int i = 0; i < n; ++i) { printf("v[%d]=", i); scanf("%d", &v[i]); if (v[i] % 2) { impare[im] = v[i]; im++; } else { pare[p] = v[i]; p++; } } for (int i = 0; i < im; ++i) { printf("%d ", impare[i]); } printf("\n"); for (int i = 0; i < p; ++i) { printf("%d ", pare[i]); } }
3cca082fddde69970b7ad314a64634962b5b79ea
[ "Markdown", "C" ]
101
Markdown
brospresident/pc-acs-upb
79f6569d2055f8ded5cf745459cd1ec6c8747f0d
3ef2da7d0954f8d12fe3507d6e1408280753d889
refs/heads/master
<file_sep># hello-world Miscellaneous - Just getting used to using GitHub. <file_sep>name_age = input("Please enter your name and age:") for i in range(len(name_age)): if name_age[i] in '01023456789': name = name_age[: i - 1] age = name_age[i - 1 :] print (name.rstrip() + ', you will be 100 years old in ' + str(100 - int(age)) + ' years.')
73c88987d8491a7dcf62004e64d3ee67a7b3abb6
[ "Markdown", "Python" ]
2
Markdown
penkelver/hello-world
0230bbeaf1c636864d35f78dbc31b46168a7e4cb
94a5067681d7ed5b2fff88ddea64b43f0e1eb8fb
refs/heads/main
<file_sep># alcumus-ad-remover Removes the ready for next ad from alcumus on AoPs. # Installation Install tampermonkey here <a href='https://www.tampermonkey.net/'>Tampermonkey</a>. Then, click <a href='https://github.com/leocabbage2008/alcumus-ad-remover/raw/main/main.user.js'>here</a>. <file_sep>// ==UserScript== // @name alcumus ad remover // @namespace https://github.com/thispageisntactuallyhere // @version 1 // @description take over the world // @author volkie boy // @match https://artofproblemsolving.com/* // @grant none // @run-at document-start // @license MIT // ==/UserScript== setTimeout(function() { let ad = document.getElementsByClassName("ready-for-next")[0]; let side = document.getElementById("side-column"); let log = document.getElementsByClassName("aops-scrollbar-not-visible")[0]; ad.remove(); log.style.height=(side.offsetHeight-306)+"px"; }, 2000);
a79d68ee7a1bd456b8b2d6f9ba32d485dfc7516f
[ "Markdown", "JavaScript" ]
2
Markdown
leocabbage2008/alcumus-ad-remover
70d8d11f27910f5593d267611752881268fde127
c638a2c2ac6e5f4753db0e0d965dc5477b376b0d
refs/heads/master
<file_sep> import pytest import wcf @pytest.fixture def conn(): conn = wcf.Scraper() return conn def test_name_reformat(conn): assert conn._reformat_name('Sweden') == 'SWE' assert conn._reformat_name('Czech Republic') == 'CZE' assert conn._reformat_name('United States of America') == 'USA' <file_sep> import pytest import wcf @pytest.fixture def conn(): conn = wcf.API() return conn def test_loaded_credentials(conn): assert conn.credentials is not None assert 'Username' in conn.credentials assert 'Password' in conn.credentials def test_connect_to_database(conn): conn.connect() assert conn.token is not None <file_sep>''' wcf.py -- Access results database through official means The World Curling Federation maintains a results database that can be accessed through normal REST means, but requires you to login and append your credentials to every request. To ease this, here is a way to access the database through official channels. ''' import json import requests class API: ''' create connection to WCF database cred_path: credential file location. If not specified, assume in current directory and named credentials.json timeout: seconds until requests times out ''' def __init__(self, cred_path=None, *, timeout=10.0): self.base = r'http://resultsapi.azurewebsites.net/api' self.timeout = timeout cred_path = cred_path or 'credentials.json' with open(cred_path, 'r') as f: self.credentials = json.load(f) self.token = None def connect(self): r = requests.post('{}/Authorize'.format(self.base), data=self.credentials, timeout=self.timeout) self.token = self._check_and_return(r) return self def get_draws_by_tournament(self, id_, *, details='ends'): params = {'tournamentId': id_, 'details': details} return self._access_wcf('Games', params=params) def get_tournaments_by_type(self, id_): return self._access_wcf(f'Tournaments/Type/{id_}') def _access_wcf(self, endpoint, **kwargs): r = requests.get(f'{self.base}/{endpoint}', headers={'Authorize': self.token}, timeout=self.timeout, **kwargs) return self._check_and_return(r) def _check_and_return(self, r): assert r.status_code == requests.codes.ok, r.status_code return r.json() <file_sep>Not actively maintained here. See `Gitlab <https://gitlab.com/mmoran0032/wcf>`_ for details. wcf -- World Curling Federation Database Interface ================================================== *Note: this package is not officially endorsed or supported by the WCF* Pull tournament and game data from the `World Curling Federation's <http://worldcurling.org/>`__ `results site <http://results.worldcurling.org>`__, using ``requests``. Requires an active and stable internet connection. This package was originally created to supplement my needs of pulling the data while I was waiting for official API access. It also includes accessing the results database through official means. API --- Official access to the WCF's results database must be obtained prior to using the official API to access the information. Access follows standard REST conventions. Create a ``credentials.json`` file as follows:: { "Username": "user", "Password": "<PASSWORD>" } The file can either be placed in the same directory, or you can pass the path to the file to ``WCF.API()`` as an argument. The data is returned as a formatted JSON response, as each use case of the data could require different portions of the response. Since development was directed by what *I* needed, not the entire API is implemented. Usage is as follows:: import wcf conn = wcf.API().connect() # alternatively: # conn = wcf.API('credentials/wcf.json') # conn.connect() draws = conn.get_draws_by_tournament(555) Testing ------- Testing requires that you have a credentials file located in this directory. The test suite can be run with:: py.test --cov=wcf <file_sep> import sys from setuptools import setup, find_packages if sys.version_info < (3, 5): sys.exit('Python 3.5 or above required') with open('README.rst', 'r') as f: readme = f.read() with open('LICENSE', 'r') as f: license = f.read() with open('wcf/__init__.py', 'r') as f: data = f.read().split('\n') for line in data: if line.startswith('__version__'): version = line.split()[-1].replace('\'', '') elif line.startswith('__author__'): author = ' '.join(line.split()[-2:]).replace('\'', '') setup( name='wcf', version=version, description='Tournament data wrangler for the World Curling Federation', long_description=readme, author=author, author_email='<EMAIL>', url=r'https://github.com/mmoran0032/wcf', license=license, packages=find_packages() ) <file_sep>''' wcf_scraper.py -- pull web-based results from WCF website The World Curling Federation maintains a results database that can be accessed through normal REST means, but requires you to login and append your credentials to every request. Without credentials, you must scrape the website in order to get the results. To ease post-processing, the scraper will format the tournament results in a similar manner to the official API. We will build out the JSON "response" to return to our calling program. ''' from bs4 import BeautifulSoup import requests class Scraper: def __init__(self, *, timeout=10.0): self.base = r'http://results.worldcurling.org/Championship' self.timeout = timeout def get_draws_by_tournament(self, id_): r = self._scrape_from_wcf(id_) return self._format_response(r, id_) def _scrape_from_wcf(self, id_): params = {'tournamentId': id_, 'associationId': 0, 'drawNumber': 0} r = requests.get(f'{self.base}/DisplayResults', timeout=self.timeout, params=params) assert r.status_code == requests.codes.ok, r.status_code return r def _format_response(self, r, id_): soup = BeautifulSoup(r.text, 'html.parser') games = soup.find_all('table', class_='game-table') return [self._format_single_game(g, id_) for g in games] def _format_single_game(self, game, id_): ''' build out single game dict as below''' _toss_winner = self._extract_hammer(game) _ends = self._extract_ends(game) _round = self._extract_round(game) _team1, _team2 = self._extract_teams(game) return dict(tournamentId=id_, Id=0, Round=dict(Abbreviation=_round), TossWinner=_toss_winner, Ends=_ends, Team1=_team1, Team2=_team2) def _extract_hammer(self, game): _hammer = game.find_all('td', class_='game-hammer') _hammer = [entry.text.strip() for entry in _hammer] return _hammer.index('*') + 1 # correct indexing to match WCF database def _extract_ends(self, game): _ends = game.find_all('tr', class_=None) new_ends = [] for row in _ends: scores = row.find_all('td', 'game-end10') scores = [d.text.strip().replace('X', '') for d in scores] new_ends.append([int(d) for d in scores if d]) paired = list(zip(*new_ends)) return [dict(Team1=e[0], Team2=e[1]) for e in paired] def _extract_round(self, game): return game.find('th', class_='game-header').text.strip()[0] def _extract_teams(self, game): _results = game.find_all('td', class_='game-total') _results = [int(data.text.strip()) for data in _results] _names = game.find_all('td', class_='game-team') _names = [self._reformat_name(name.text.strip()) for name in _names] _team1 = dict(Result=_results[0], Percentage=0, Team=dict(Code=_names[0])) _team2 = dict(Result=_results[1], Percentage=0, Team=dict(Code=_names[1])) return _team1, _team2 def _reformat_name(self, name): ''' convert country names to (rough) codes ''' name = name.replace('of', '').upper().split() if len(name) > 2: return ''.join(entry[0] for entry in name) return name[0][:3] <file_sep> from .wcf import * from .wcf_scraper import * __version__ = '0.6.2' __author__ = '<NAME>'
5b7579379b38bcca3eccf76cc8f9e9099e4164b7
[ "Python", "reStructuredText" ]
7
Python
mmoran0032/wcf
bb421c63d58f70b16e4297a0421e781c90b6fc51
b643f7dc04eaef544a96881704b558112aaf85ea
refs/heads/master
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.ditto</groupId> <artifactId>cookiez</artifactId> <version>0.0.1-SNAPSHOT</version> <name>cookiez</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 --> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> <version>3.0.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.73</version> </dependency> <!--java.lang.ClassNotFoundException: javax.xml.bind.DatatypeConverter--> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <artifactId>velocity</artifactId> <groupId>org.apache.velocity</groupId> <version>1.7</version> </dependency> <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-s3 --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-s3</artifactId> <version>1.11.871</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> <file_sep>package com.ditto.cookiez.service; import com.ditto.cookiez.entity.NoEat; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * service class * </p> * * @author astupidcoder * @since 2020-08-14 */ public interface INoEatService extends IService<NoEat> { } <file_sep>function getTokenHeader() { let token = getToken(); // token="<KEY>" if (!isTokenNull()) { token = "Bearer-" + token; headers = {Authorization: token}; return headers; } return headers; } function getToken() { let sto = window.sessionStorage; return sto.getItem("accessToken"); } function setToken(token) { let sto = window.sessionStorage; sto.setItem("accessToken", token); } function isTokenNull() { let token = getToken(); return token === null || token === "-1"; } function setTokenNull() { let sto = window.sessionStorage; sto.setItem("accessToken", "-1"); } function isLogged() { return !isTokenNull(); } var headers = getTokenHeader(); var instance = axios.create({ timeout: 10000, headers, }); $('textarea').each(function () { this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;'); }).on('input', function () { this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px'; }).on('change', function () { this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px'; }); $('textarea').change(function () { this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px'; }) function loading(obj) { let html = ` <div class="loader" id="loading"> <div class="loader-inner"> <div class="loader-line-wrap"> <div class="loader-line"></div> </div> <div class="loader-line-wrap"> <div class="loader-line"></div> </div> <div class="loader-line-wrap"> <div class="loader-line"></div> </div> <div class="loader-line-wrap"> <div class="loader-line"></div> </div> </div> </div> ` $("body").append(html) } function completeLoading() { $("#loading").remove(); } function getTagsHtml(tagList) { let tagHtml = '' let ind = 0 for (const tag of tagList) { if (ind > 1) { break } let tagName = tag['tagName']; tagHtml += ` <span class=" iconfont mx-1 "> &#xe612;${tagName}</span> ` ind++ } return tagHtml } function generateRecipeCard(recipes) { let html = '' for (const i in recipes) { let recipe = recipes[i] let title = recipe["recipeName"] let description = recipe['recipeDescription'] let coverPath = recipe['coverPath'] let author = recipe['author'] let link = recipe['url'] let tagList = recipe['tagList'] let tagHtml=getTagsHtml(tagList) let ind = 0 html += ` <div class="col-sm-3 mb-3" > <a href="${link}"> <div class="p-3 d-flex flex-column shadow-sm rounded-10 shadow-0-2-4 "> <img class="rounded-20" src="${coverPath != null ? coverPath : '/images/logo.png'}" alt=""> <span style="font-size: 20px">${title}</span> <p style="font-size: 14px;color: #6b6668; max-width: 10em; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;"> ${description} </p> <span class="d-flex"> ${tagHtml} <span class="ml-auto" style="font-size: 13px" >By ${author}</span> </span> </div> </a> </div> ` } return html }<file_sep>package com.ditto.cookiez.service.impl; import com.ditto.cookiez.entity.TagType; import com.ditto.cookiez.mapper.TagTypeMapper; import com.ditto.cookiez.service.ITagTypeService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * Service Class * </p> * * @author astupidcoder * @since 2020-09-16 */ @Service public class TagTypeServiceImpl extends ServiceImpl<TagTypeMapper, TagType> implements ITagTypeService { } <file_sep>package com.ditto.cookiez.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.ditto.cookiez.entity.*; import com.ditto.cookiez.mapper.IngredientRecipeBridgeMapper; import com.ditto.cookiez.service.IIngredientRecipeBridgeService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.ditto.cookiez.service.IIngredientService; import com.ditto.cookiez.service.IRecipeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * <p> * Service Class * </p> * * @author astupidcoder * @since 2020-09-29 */ @Service public class IngredientRecipeBridgeServiceImpl extends ServiceImpl<IngredientRecipeBridgeMapper, IngredientRecipeBridge> implements IIngredientRecipeBridgeService { @Autowired IIngredientService ingredientService; @Autowired IRecipeService recipeService; @Override public List<Ingredient> getIngredientsByRecipeId(Integer recipeId) { QueryWrapper<IngredientRecipeBridge> qw = new QueryWrapper(); if (recipeId != null) { qw.eq("recipe_id", recipeId); } List<IngredientRecipeBridge> bridges = list(qw); System.out.println("IngredientRecipeBridge"); System.out.println(bridges); List<Integer> ids = new ArrayList<>(); for (IngredientRecipeBridge bridge : bridges ) { ids.add(bridge.getIngredientId()); } if(ids.size()!=0){ return ingredientService.listByIds(ids); }else { return new ArrayList<Ingredient>(); } } @Override public List<Recipe> getRecipesByIngredientId(Integer ingredientId) { QueryWrapper<IngredientRecipeBridge> qw = new QueryWrapper(); if (ingredientId != null) { qw.eq("ingredient_id", ingredientId); } List<IngredientRecipeBridge> bridges = list(qw); List<Integer> ids = new ArrayList<>(); for (IngredientRecipeBridge bridge : bridges ) { ids.add(bridge.getRecipeId()); } if(ids.size()!=0){ return recipeService.listByIds(ids); }else { return new ArrayList<Recipe>(); } } @Override public Boolean deleteByRecipeId(Integer recipeId) { QueryWrapper<IngredientRecipeBridge> qw=new QueryWrapper<>(); qw.eq("recipe_id",recipeId); return remove(qw); } } <file_sep>package com.ditto.cookiez.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.ditto.cookiez.entity.Img; import com.ditto.cookiez.entity.Step; import com.ditto.cookiez.mapper.StepMapper; import com.ditto.cookiez.service.IImgService; import com.ditto.cookiez.service.IStepService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.ditto.cookiez.utils.FileUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; /** * <p> * Service Class * </p> * * @author astupidcoder * @since 2020-09-16 */ @Service public class StepServiceImpl extends ServiceImpl<StepMapper, Step> implements IStepService { @Autowired IImgService imgService; @Override public Step addStep(Step step) { save(step); return step; } @Override public Step getByOrderAndRecipeId(Integer order, Integer recipeId) { QueryWrapper<Step> qw = new QueryWrapper<>(); qw.eq("recipe_id", recipeId); qw.eq("step_order", order); if (list(qw).size() == 0) { return null; } return list(qw).get(0); } @Override public Step addStep(Step step, MultipartFile file) throws IOException { int recipeId = step.getRecipeId(); int order = step.getStepOrder(); String url = FileUtil.uploadStepImgToAws(file, recipeId, order); Img img = new Img(url); imgService.save(img); step.setImgId(img.getImgId()); save(step); return step; } } <file_sep>package com.ditto.cookiez.utils; public enum ResponseMsg { SUCCEED_TO_DELETE("Succeed to delete"), SUCCEED_TO_CREATE("Succeed to create"), SUCCEED_TO_UPDATE("Succeed to update"), FAILED_TO_DELETE("Failed to delete"), FAILED_TO_UPDATE("Failed to update"), FAILED_TO_CREATE("Failed to create"), SUCCEED_TO_GET("Succeed to query"), FAILED_TO_GET("Failed to query"), SUCCEED_TO_LOGIN("Succeed to login"), ; private String value; ResponseMsg(String s) { this.value=s; } public String v() { return this.value; } } <file_sep>package com.ditto.cookiez.mapper; import com.ditto.cookiez.entity.TagType; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author astupidcoder * @since 2020-09-16 */ public interface TagTypeMapper extends BaseMapper<TagType> { } <file_sep>package com.ditto.cookiez.controller; import com.alibaba.fastjson.JSONObject; import com.ditto.cookiez.entity.vo.RecipeResultVo; import com.ditto.cookiez.service.IRecipeService; import com.ditto.cookiez.service.ITagService; import com.ditto.cookiez.utils.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletResponse; import java.util.List; /** * <p> * * </p> * * @author astupidcoder * @since 2020-09-16 */ @RestController public class TagController { private final Logger logger = LoggerFactory.getLogger(TagController.class); @Autowired ITagService service; @Autowired IRecipeService recipeService; // @PutMapping("/tags") // public ResponseEntity<JSONObject> searchPage(@RequestBody JSONObject param) { // String tag_name = param.getString("tag_name"); // ModelAndView mv = new ModelAndView("tag/show"); // if (tag_name == null) { // return Response.ok("Do not have to find"); // // }else{ // List<RecipeResultVo> recipeList = recipeService.search(tag_name); // if (recipeList != null){ // mv.addObject("recipes",recipeList); // return Response.ok("Succeed to find the recipes", recipeList); // }else { // new ModelAndView("/tag/show"); // return Response.bad("Failed to find the recipes"); // } // } // } } <file_sep>package com.ditto.cookiez.service; import com.ditto.cookiez.entity.IngredientTagBridge; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 服务类 * </p> * * @author astupidcoder * @since 2020-09-16 */ public interface IIngredientTagBridgeService extends IService<IngredientTagBridge> { } <file_sep>package com.ditto.cookiez.service; import com.alibaba.fastjson.JSONObject; import com.ditto.cookiez.entity.User; import com.baomidou.mybatisplus.extension.service.IService; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.Map; /** * <p> * service class * </p> * * @author astupidcoder * @since 2020-08-14 */ public interface IUserService extends IService<User> { User getByUsername(String username); User auth(String username, String password); Boolean register(User user); User getUserByToken(String token); User updateProfile(JSONObject jsonObject, Map<String, MultipartFile> fileMap) throws IOException; String getUsernameById(Integer id); } <file_sep>package com.ditto.cookiez.mapper; import com.ditto.cookiez.entity.Img; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author astupidcoder * @since 2020-08-14 */ public interface ImgMapper extends BaseMapper<Img> { } <file_sep>package com.ditto.cookiez.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.extension.activerecord.Model; import lombok.Data; import lombok.EqualsAndHashCode; /** * <p> * * </p> * * @author astupidcoder * @since 2020-08-14 */ @Data @EqualsAndHashCode(callSuper = true) public class Comment extends Model { private static final long serialVersionUID = 1L; @TableId(value = "comment_id") private Integer commentId; private Integer userId; private String commentContent; private Integer recipeId; } <file_sep>package com.ditto.cookiez.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.ditto.cookiez.entity.Recipe; import com.ditto.cookiez.entity.RecipeTagBridge; import com.ditto.cookiez.entity.Tag; import com.ditto.cookiez.mapper.RecipeTagBridgeMapper; import com.ditto.cookiez.service.IRecipeService; import com.ditto.cookiez.service.IRecipeTagBridgeService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.ditto.cookiez.service.ITagService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * <p> * Service Class * </p> * * @author astupidcoder * @since 2020-09-29 */ @Service public class RecipeTagBridgeServiceImpl extends ServiceImpl<RecipeTagBridgeMapper, RecipeTagBridge> implements IRecipeTagBridgeService { @Autowired ITagService tagService; @Autowired IRecipeService recipeService; @Override public List<Tag> getTagsByRecipeId(Integer recipeId) { QueryWrapper<RecipeTagBridge> qw = new QueryWrapper(); if (recipeId != null) { qw.eq("recipe_id", recipeId); } List<RecipeTagBridge> bridges = list(qw); List<Integer> ids = new ArrayList<>(); for (RecipeTagBridge bridge : bridges ) { ids.add(bridge.getTagId()); } if (ids.size() != 0) { return tagService.listByIds(ids); } return new ArrayList<Tag>(); } @Override public Boolean deleteByRecipeId(Integer id) { QueryWrapper<RecipeTagBridge> qw = new QueryWrapper<>(); qw.eq("recipe_id", id); return remove(qw); } @Override public List<Recipe> getRecipesByTagId(Integer tagId) { QueryWrapper<RecipeTagBridge> qw = new QueryWrapper(); if (tagId != null) { qw.eq("tag_id", tagId); } List<RecipeTagBridge> bridges = list(qw); List<Integer> ids = new ArrayList<>(); for (RecipeTagBridge bridge : bridges ) { ids.add(bridge.getRecipeId()); } if (ids.size() != 0) { return recipeService.listByIds(ids); } return new ArrayList<Recipe>(); } public Set<Integer> getRecipesIdByTagId(Integer tagId) { QueryWrapper<RecipeTagBridge> qw = new QueryWrapper(); if (tagId != null) { qw.eq("tag_id", tagId); } List<RecipeTagBridge> bridges = list(qw); Set<Integer> recipeIdSet = new HashSet<>(); for (RecipeTagBridge bridge : bridges ) { recipeIdSet.add(bridge.getRecipeId()); } if (recipeIdSet.size() == 0) { log.error("Cannot find corresponding recipe"); } return recipeIdSet; } } <file_sep>package com.ditto.cookiez.mapper; import com.ditto.cookiez.entity.Comment; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * <p> * Mapper 接口 * </p> * * @author astupidcoder * @since 2020-08-14 */ public interface CommentMapper extends BaseMapper<Comment> { } <file_sep>package com.ditto.cookiez.service.impl; import com.alibaba.fastjson.JSONObject; import com.ditto.cookiez.entity.Pantry; import com.ditto.cookiez.mapper.PantryMapper; import com.ditto.cookiez.service.IIngredientService; import com.ditto.cookiez.service.IPantryService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.ditto.cookiez.service.IRecipeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * <p> * Service Class * </p> * * @author astupidcoder * @since 2020-08-14 */ @Service public class PantryServiceImpl extends ServiceImpl<PantryMapper, Pantry> implements IPantryService { @Autowired IIngredientService ingredientService; @Autowired IRecipeService recipeService; @Override public boolean savePantry(JSONObject param) { List<String> list = JSONObject.parseArray(param.toJSONString(), String.class); // int userId = param.getInteger("userId"); // if (list != null) { // for (String str : list // ) { // int idOr1 =ingredientService.existedReturnId(str); // if(idOr1==-1){ //// ingredientService.save(); // } // } // } recipeService.searchByIngredients(list); return false; } } <file_sep>function getKeywords() { let tags = $("#keywords").val().split(",") let newTags = [] for (let tag of tags) { if (tag.trim().length !== 0) { newTags.push(tag.trim()) } } return newTags } // search tag async function handleSearchBtn() { let request let option = $("#search-option").val() console.log(option) switch (option) { case 'default': request = '/api/search/all' break case 'ingredients': request = '/api/search/ingredients' break case 'tags': request = '/api/search/tags' break case 'title': request = '/api/search/title' break } let keywords = getKeywords() if (keywords.length === 0) { return } loading() await axios.post(request, { keywords: getKeywords(), }).then(res => { completeLoading() console.log(res) let recipes = res['data']['data'] const div = document.getElementById("cardDiv") let html = generateRecipeCard(recipes); if (recipes.length === 0) { html = `<h2>No result...</h2>` } $(div).html(html) cutPic() }).catch(err => { completeLoading() // eslint-disable-next-line no-undef bootbox.alert("Cannot find the corresponding recipe") console.log(err) }) } $('.table_block p span').each(function () { var words = $(this).text().length; if (words > 100) { $(this).text($(this).text().slice(0, 100) + "..."); } }); $("#keywords").keydown(function (e) { if (e.keyCode === 188 || e.key === "Enter") { handleSearchBtn() } }); function cutPic() { $('img.rounded-20').each(function (i) { $(this).jqthumb({ width: '100%',// height: '200px',// zoom: '1',// method: 'auto', after: function (obj) { $(obj).css("border-radius", "20px") } }); }) } <file_sep>package com.ditto.cookiez.mapper; import com.ditto.cookiez.entity.User; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; /** * <p> * Mapper 接口 * </p> * * @author astupidcoder * @since 2020-08-14 */ @Component @Repository public interface UserMapper extends BaseMapper<User> { } <file_sep>package com.ditto.cookiez; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.ditto.cookiez.entity.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.jdbc.core.JdbcTemplate; //@SpringBootTest //class CookiezApplicationTests { // // //} <file_sep>let formData = new FormData(); let coverFile = document.getElementById('cover-input'); function uploadCover(obj) { let reader = new FileReader() reader.readAsDataURL(coverFile.files[0]) reader.onload = function (e) { document.getElementById('cover').src = this.result; } formData.append("coverImg", coverFile.files[0]) } function uploadStepImg(index,obj) { if (index === -1) { index = $(obj).attr('id').split('-')[3] } let stepFile = document.getElementById(`img-input-step-${index}`) let reader = new FileReader() reader.readAsDataURL(stepFile.files[0]) reader.onload = function (e) { document.getElementById(`img-step-${index}`).src = this.result; } formData.append(`stepImg-${index}`, stepFile.files[0]) } function getIngredients() { const div = document.getElementById("div-ingredients") let ingredientsJson = [] for (const ele of div.children) { let ingredient = $(ele.children[0]).val().trim() let amount = $(ele.children[1]).val().trim() if (ingredient.length !== 0 && amount.length !== 0) ingredientsJson.push({ ingredientName: ingredient, amount }) } return ingredientsJson } function delIngredientEle(index,obj) { if(index===-1){ index=$(obj).attr('id').split('-')[2] } const div = document.getElementById("div-ingredients") const size = div.children.length if (size > 1) { $(`#ingred-${index}`).remove() } } $("#btn-addStep").click(function () { const div = document.getElementById("div-steps") const size = div.children.length const html = ` <div class="d-flex mt-5 justify-content-between align-content-between" id="step-${size + 1}"> <div class="d-flex flex-column w-75 mr-3"> <h4 class="font-comic"> Step${size + 1}</h4> <textarea class="h-100 input-area-red" name="textarea" placeholder="Add step here"></textarea> </div> <div class="d-flex flex-column "><img id="img-step-${size + 1}" class="rounded-20 mb-1" src="http://iph.href.lu/1280x1024" alt="" width="300" width="300"> <label class="btn custom-file-upload btn-red"> <input id="img-input-step-${size + 1}" type="file" class="btn-red" ACCEPT="image/*" onchange="uploadStepImg(${size + 1})"> <i class="iconfont icon-LocalUpload"></i> Upload a Step Picture </label></div> </div> ` $(div).append(html) }) $("#btn-removeStep").click(function () { const div = document.getElementById("div-steps") const size = div.children.length if (size > 1) { div.lastElementChild.remove() } }) $("#btn-addIngredient").click(function () { const div = document.getElementById("div-ingredients") const size = div.children.length let newSize = size + 1 let childHtml = ` <div class="d-flex justify-content-between mt-2" id="ingred-${newSize}"><input class="mr-3 input-red" type="text" placeholder="Name"> <input class="input-red" type="text" placeholder="Amount"> <button class="btn iconfont icon-x" onclick="delIngredientEle(${newSize})"> </button> </div>` $("#div-ingredients").append(childHtml) }) function getStepsContent() { const div = document.getElementById("div-steps") let steps = [] let ind = 0; for (const ele of div.children) { ind++; let stepOrder = ind; let stepContent = $(ele).find('textarea').val().trim(); steps.push({ stepOrder, stepContent }) } return steps } function getTags() { let tags = $(".input-tags").val().split(",") let newTags = [] for (let tag of tags) { if (tag.trim().length !== 0) { newTags.push({tagName: tag.trim()}) } } return newTags } function getJsonData() { let errors = [] const title = $("#input-title").val().trim(); const description = $("#input-describe").val().trim(); //poor validate const recipe = { recipeName: title, recipeDescription: description, recipeCreatedTime: moment().format(), recipeAuthorId: userId, }; errors.push(validate(recipe, { recipeName: { length: { minimum: 3, message: "%{value} is too short. Recipe name should be at least 3 characters" } }, recipeDescription: { length: { minimum: 3, message: "%{value} is too short. Recipe description should be at least 3 characters" } } })) const tags = getTags() const steps = getStepsContent() for (const step of steps) { errors.push(validate(step, { stepContent: { length: { minimum: 3, message: "%{value} is too short. Each recipe step should be at least 3 characters" } } })) } const ingredients = getIngredients() for (const ingredient of ingredients) { errors.push(validate(ingredient, { ingredient: { length: { minimum: 3, message: "%{value} is too short. Each ingredient step should be at least 3 characters" } }, amount: { length: { minimum: 3, message: "%{value} is too short. Each amount should be at least 3 characters" } } })) } let data = { recipe, steps, ingredients, tags, } return data } function submit() { let data = getJsonData() formData.append("data", JSON.stringify(data)) bootbox.confirm("Are you sure you want to submit this recipe?", function (result) { if (result) { loading(); axios.post('/api/recipe', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(res => { completeLoading() console.log(res) let recipeId = res['data']['data']['recipeId'] bootbox.alert("Add a recipe Successfully!") window.location.replace('/recipe/' + recipeId) // window.location.replace("/"); }).catch(err => { completeLoading() bootbox.alert("Failed to add") console.log(err) }) formData = new FormData() } }) } function update() { let data = getJsonData() data['recipe']['recipeId'] = recipeId console.log({data}) formData.append("data", JSON.stringify(data)) bootbox.confirm("Are you sure you want to update this recipe?", function (result) { if (result) { loading(); axios.put('/api/recipe', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(res => { completeLoading() console.log(res) bootbox.alert("Update the recipe Successfully!") formData = new FormData() window.location.replace('/recipe/' + recipeId) // window.location.replace("/"); }).catch(err => { completeLoading() bootbox.alert("Failed to add") console.log(err) }) } }) }<file_sep>package com.ditto.cookiez.config; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.*; import com.amazonaws.services.s3.transfer.TransferManager; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.Objects; /** * @author <NAME> * @date 2020/9/30 16:32 * @email <EMAIL> */ public class AwsClient { static AmazonS3 s3; // static TransferManager tx; static final String bucketName = "cookiez-img2"; static { s3 = AmazonS3ClientBuilder.standard() .withRegion(Regions.US_EAST_1) .build(); } /** * @param @param tempFile * @param @param remoteFileName * @param @return * @param @throws IOException * @return String url * @throws * @Title: uploadToS3 * @Description: */ public static String uploadToS3(MultipartFile tempFile, String remoteFileName) throws IOException { try { ObjectMetadata objectMetadata = new ObjectMetadata(); //upload file s3.putObject(new PutObjectRequest(bucketName, remoteFileName, tempFile.getInputStream(),objectMetadata).withCannedAcl(CannedAccessControlList.PublicRead)); //get a request //generate url return s3.getUrl(bucketName, remoteFileName).toString(); } catch (AmazonServiceException ase) { ase.printStackTrace(); } catch (AmazonClientException ace) { ace.printStackTrace(); } return null; } /** * @param @param remoteFileName * @param @throws IOException * @return S3ObjectInputStream * @throws * @Title: getContentFromS3 * @Description: */ public static S3ObjectInputStream getContentFromS3(String remoteFileName) throws IOException { try { GetObjectRequest request = new GetObjectRequest(bucketName, remoteFileName); S3Object object = s3.getObject(request); S3ObjectInputStream inputStream = object.getObjectContent(); return inputStream; } catch (Exception e) { e.printStackTrace(); } return null; } /** * @param @param remoteFileName * @param @param path * @param @throws IOException * @return void * @throws * @Title: downFromS3 * @Description: */ public static void downFromS3(String remoteFileName, String path) throws IOException { try { GetObjectRequest request = new GetObjectRequest(bucketName, remoteFileName); s3.getObject(request, new File(path)); } catch (Exception e) { e.printStackTrace(); } } /** * @param @param remoteFileName * @param @return * @param @throws IOException * @return String * @throws * @Title: getUrlFromS3 * @Description: getFileUrl */ public static String getUrlFromS3(String remoteFileName) throws IOException { try { GeneratePresignedUrlRequest httpRequest = new GeneratePresignedUrlRequest(bucketName, remoteFileName); // temp url String url = s3.generatePresignedUrl(httpRequest).toString(); return url; } catch (Exception e) { e.printStackTrace(); } return null; } /** * * @param s3 * @param bucketName * @return */ public static boolean checkBucketExists(AmazonS3 s3, String bucketName) { List<Bucket> buckets = s3.listBuckets(); for (Bucket bucket : buckets) { if (Objects.equals(bucket.getName(), bucketName)) { return true; } } return false; } public static void delFromS3(String remoteFileName) throws IOException { try { s3.deleteObject(bucketName, remoteFileName); } catch (AmazonServiceException ase) { ase.printStackTrace(); } catch (AmazonClientException ace) { ace.printStackTrace(); } } public static void main(String[] args) throws Exception { // String key = "redisinfo"; // File tempFile = new File("C:\\Users\\guosen\\Desktop\\redis.txt"); // uploadToS3(tempFile, key);//上传文件 // String url = getUrlFromS3(key);//获取文件的url // System.out.println(url); // delFromS3(key);//删除文件 } } <file_sep>/* * @Author: <NAME> * @Date: 2020-07-31 23:14:36 * @LastEditTime: 2020-07-31 23:41:03 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: \BIT-P1\loader.js */ $(document).ready(function () { $("#header").load("header.html"); $("#footer").load("footer.html"); $("#carousel").carousel(); }); <file_sep>let formData = new FormData() function uploadAvatar(obj) { let file = document.getElementById("input-avatar") let reader = new FileReader() reader.readAsDataURL(file.files[0]) reader.onload = function (e) { document.getElementById("img-avatar").src = this.result; } formData.append(`avatar`, file.files[0]) } function saveProfile() { let username = $("#username").val().trim(); let oldPassword = $("#oldPassword").val().trim(); let newPassword = $("#newPassword").val().trim(); if (username.length === 0) { bootbox.alert("Username cannot be blank") return } let data = { userId, username, newPassword, oldPassword } formData.append("data", JSON.stringify(data)) bootbox.confirm("Are you sure you want to update the profile?", function (result) { if (result) { loading() axios.put('/api/profile', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(res => { completeLoading() console.log(res) bootbox.alert("Successfully!") window.location.replace("/user/kitchen"); }).catch(err => { completeLoading() bootbox.alert("Failed") console.log(err) }) formData = new FormData() } }) }<file_sep>package com.ditto.cookiez.service; import com.ditto.cookiez.entity.Img; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * service class * </p> * * @author astupidcoder * @since 2020-08-14 */ public interface IImgService extends IService<Img> { String getPathById(Integer id); } <file_sep>package com.ditto.cookiez.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.extension.activerecord.Model; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; /** * <p> * * </p> * * @author astupidcoder * @since 2020-09-29 */ @Data @EqualsAndHashCode(callSuper = true) public class RecipeTagBridge extends Model { private static final long serialVersionUID = 1L; @TableId(value = "recipe_tag_id", type = IdType.AUTO) private Integer recipeTagId; private Integer tagId; private Integer recipeId; public RecipeTagBridge() { } public RecipeTagBridge( Integer recipeId,Integer tagId) { this.tagId = tagId; this.recipeId = recipeId; } } <file_sep>package com.ditto.cookiez.mapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.ditto.cookiez.entity.Recipe; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import java.util.List; /** * <p> * Mapper 接口 * </p> * * @author astupidcoder * @since 2020-08-14 */ public interface RecipeMapper extends BaseMapper<Recipe> { List<Recipe> selectList(QueryWrapper<List> recipeList); } <file_sep># TR-WE-430-Ditto This is a group project required by course Building IT System. Group Members: 1. <NAME> (<EMAIL>) 2. <NAME> (<EMAIL>) 3. <NAME> (<EMAIL>) 4. <NAME> (<EMAIL>) 5. <NAME> (<EMAIL>) 6. <NAME> (<EMAIL>) Trello workload:https://trello.com/b/9n2h12R1/build-it-systems You can attach the description of the project from branch P1 <file_sep>package com.ditto.cookiez.service; import com.ditto.cookiez.entity.Role; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * service class * </p> * * @author astupidcoder * @since 2020-08-14 */ public interface IRoleService extends IService<Role> { } <file_sep>package com.ditto.cookiez.service.impl; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.ditto.cookiez.entity.*; import com.ditto.cookiez.entity.dto.IngredientDTO; import com.ditto.cookiez.entity.dto.RecipeDTO; import com.ditto.cookiez.entity.dto.StepDTO; import com.ditto.cookiez.entity.vo.RecipeResultVo; import com.ditto.cookiez.mapper.RecipeMapper; import com.ditto.cookiez.service.*; import com.ditto.cookiez.utils.FileUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.*; /** * <p> * Service Class * </p> * * @author astupidcoder * @since 2020-08-14 */ @Slf4j @Service public class RecipeServiceImpl extends ServiceImpl<RecipeMapper, Recipe> implements IRecipeService { @Autowired IImgService imgService; @Autowired IStepService stepService; @Autowired IUserService userService; @Autowired IIngredientService ingredientService; @Autowired IAmountService amountService; @Autowired IIngredientRecipeBridgeService ingredientRecipeBridgeService; @Autowired ITagService tagService; @Autowired IRecipeTagBridgeService recipeTagBridgeService; public static String coverKey = FileUtil.COVER; public static String stepImgPrefix = FileUtil.STEP_PREFIX; // TODO update ingredients @Transactional @Override public Boolean updateRecipe(JSONObject json, Map<String, MultipartFile> fileMap) throws IOException { Recipe recipe = json.getObject("recipe", Recipe.class); Integer recipeId = recipe.getRecipeId(); // get data from json List<Tag> tags = json.getJSONArray("tags").toJavaList(Tag.class); List<IngredientDTO> ingredients = json.getJSONArray("ingredients").toJavaList(IngredientDTO.class); // some magic value recipe.setRecipeCreatedTime(null); setUpCover(fileMap, recipe); // update step List<StepDTO> stepDTOs = json.getJSONArray("steps").toJavaList(StepDTO.class); int index = 0; for (StepDTO stepDTO : stepDTOs ) { index++; Step step = stepService.getByOrderAndRecipeId(stepDTO.getStepOrder(), recipeId); if (step == null) { step = new Step(); step.setRecipeId(recipeId); stepService.save(step); } step.setStepContent(stepDTO.getStepContent()); step.setStepOrder(stepDTO.getStepOrder()); Integer order = stepDTO.getStepOrder(); if (fileMap.containsKey(stepImgPrefix + stepDTO.getStepOrder())) { String nameInFileMap = stepImgPrefix + order; log.info(FileUtil.getRecipeStepRelativePath(recipeId, order, FileUtil.getFileType(fileMap.get(nameInFileMap).getOriginalFilename()))); FileUtil.delete(FileUtil.getRecipeStepRelativePath(recipeId, order, FileUtil.getFileType(fileMap.get(nameInFileMap).getOriginalFilename()))); String url = FileUtil.uploadStepImgToAws(fileMap.get(nameInFileMap), recipeId, order); Img img = new Img(url); if (step.getImgId() != null) { img.setImgId(step.getImgId()); img.updateById(); } else { imgService.save(img); } step.setImgId(img.getImgId()); } step.updateById(); } // delete redundant steps QueryWrapper<Step> stepQueryWrapper = new QueryWrapper<>(); stepQueryWrapper.eq("recipe_id", recipeId); int count = stepService.count(stepQueryWrapper); for (int i = index + 1; i <= count; i++) { stepQueryWrapper.clear(); stepQueryWrapper.eq("recipe_id", recipeId); stepQueryWrapper.eq("step_order", i); stepService.remove(stepQueryWrapper); } // delete previous ingredients and amount ingredientRecipeBridgeService.deleteByRecipeId(recipeId); amountService.deleteByRecipeId(recipeId); // update ingredient saveIngredientAndAmount(ingredients, recipeId); // delete tags recipeTagBridgeService.deleteByRecipeId(recipeId); // update tags saveTag(tags, recipeId); recipe.updateById(); return true; } @Transactional @Override public Recipe addRecipe(JSONObject json, Map<String, MultipartFile> fileMap) throws IOException { // BUG: when upload tow same pictures, one picture will lost. Recipe recipe = json.getObject("recipe", Recipe.class); save(recipe); Integer recipeId = recipe.getRecipeId(); // get data from json List<Tag> tags = json.getJSONArray("tags").toJavaList(Tag.class); List<Step> steps = json.getJSONArray("steps").toJavaList(Step.class); List<IngredientDTO> ingredients = json.getJSONArray("ingredients").toJavaList(IngredientDTO.class); // some magic value // save cover img if (fileMap.containsKey(coverKey)) { MultipartFile file = fileMap.get(coverKey); String url = FileUtil.uploadCoverToAws(file, recipeId); // Img img = new Img(url); imgService.save(img); recipe.setRecipeCoverId(img.getImgId()); } // save ingredients and its amount saveIngredientAndAmount(ingredients, recipeId); // save tag saveTag(tags, recipeId); // save steps for (Step step : steps ) { int order = step.getStepOrder(); step.setRecipeId(recipeId); String nameInFileMap = stepImgPrefix + order; if (fileMap.containsKey(nameInFileMap)) { stepService.addStep(step, fileMap.get(nameInFileMap)); } else { stepService.addStep(step); } } recipe.updateById(); return recipe; } @Override public RecipeDTO getRecipe(int id) { return null; } private void saveTag(List<Tag> tags, Integer recipeId) { for (Tag tag : tags ) { tagService.save(tag); recipeTagBridgeService.save(new RecipeTagBridge(recipeId, tag.getTagId())); } } private void setUpCover(Map<String, MultipartFile> fileMap, Recipe recipe) throws IOException { if (fileMap.containsKey(coverKey)) { MultipartFile file = fileMap.get(coverKey); String url = FileUtil.uploadCoverToAws(file, recipe.getRecipeId()); Img img = new Img(url); imgService.save(img); recipe.setRecipeCoverId(img.getImgId()); } } private void saveIngredientAndAmount(List<IngredientDTO> ingredients, Integer recipeId) { for (IngredientDTO ingredientDTO : ingredients ) { String ingredientName = ingredientDTO.getIngredientName(); String amountContent = ingredientDTO.getAmount(); Amount amount = new Amount(amountContent); Ingredient ingredient = new Ingredient(ingredientName); ingredientService.save(ingredient); amount.setIngredientId(ingredient.getIngredientId()); amount.setRecipeId(recipeId); log.info(amount.toString()); amountService.save(amount); IngredientRecipeBridge bridge = new IngredientRecipeBridge(ingredient.getIngredientId(), recipeId); ingredientRecipeBridgeService.save(bridge); } } // private void setUpStepImg(Map<String, MultipartFile> fileMap, Step step) throws IOException { // if (fileMap.containsKey(coverKey)) { // MultipartFile file = fileMap.get(coverKey); // String url = FileUtil.uploadCoverToAws(file, recipe.getRecipeId()); //// // Img img = new Img(url); // imgService.save(img); // recipe.setRecipeCoverId(img.getImgId()); // } // } @Transactional @Override public RecipeDTO getRecipe(Integer id) { Recipe recipe = getById(id); // get title and description RecipeDTO recipeDTO = new RecipeDTO(recipe); recipeDTO.setId(id); // get cover path if (recipe.getRecipeCoverId() != null) { recipeDTO.setCoverPath(imgService.getPathById(recipe.getRecipeCoverId())); } // TODO add author info User user = userService.getById(recipe.getRecipeAuthorId()); recipeDTO.setAuthor(user.getUsername()); // Get Step List<Step> stepList = stepService.list(new QueryWrapper<Step>().eq("recipe_id", id)); List<StepDTO> stepDTOList = new ArrayList<>(); for (Step step : stepList ) { StepDTO stepDTO = new StepDTO(step); stepDTO.setImgPath(imgService.getPathById(step.getImgId())); stepDTOList.add(stepDTO); stepDTO.setId(step.getStepId()); } recipeDTO.setStepDTOList(stepDTOList); // Get tags List<Tag> tags = recipeTagBridgeService.getTagsByRecipeId(id); recipeDTO.setTagList(tags); // Get ingredients List<IngredientDTO> ingredientDTOS = new ArrayList<>(); List<Ingredient> ingredients = ingredientRecipeBridgeService.getIngredientsByRecipeId(id); log.info(ingredients.toString()); for (Ingredient i : ingredients ) { Amount amount = amountService.getByRecipeIngredientId(id, i.getIngredientId()); log.info(amount.toString()); ingredientDTOS.add(new IngredientDTO(i.getIngredientName(), amount.getAmountContent())); } log.info(ingredientDTOS.toString()); recipeDTO.setIngredientDTOList(ingredientDTOS); return recipeDTO; } @Override public List<RecipeResultVo> search(List<String> keywords) { Set<Integer> recipeIdSet = new HashSet<>(); // title for (String word : keywords ) { recipeIdSet.addAll(searchRecipeIdListByTitle(word)); recipeIdSet.addAll(searchRecipeIdListByTag(word)); recipeIdSet.addAll(searchRecipeIdListByIngredient(word)); } return getResultVoListByIdList(recipeIdSet); } @Override public List<RecipeResultVo> searchByIngredients(List<String> strList) { Set<Integer> recipeIdSet = new HashSet<>(); for (String ingred : strList ) { Set<Integer> idList = searchRecipeIdListByIngredient(ingred); recipeIdSet.addAll(idList); } return getResultVoListByIdList(recipeIdSet); } @Override public List<RecipeResultVo> searchByTitle(List<String> strList) { Set<Integer> recipeIdSet = new HashSet<>(); for (String ingred : strList ) { Set<Integer> idList = searchRecipeIdListByTitle(ingred); recipeIdSet.addAll(idList); } return getResultVoListByIdList(recipeIdSet); } @Override public List<RecipeResultVo> searchByTags(List<String> keywords) { Set<Integer> recipeIdSet = new HashSet<>(); for (String tag : keywords ) { Set<Integer> idList = searchRecipeIdListByTag(tag); recipeIdSet.addAll(idList); } return getResultVoListByIdList(recipeIdSet); } private Set<Integer> searchRecipeIdListByTag(String keyword) { QueryWrapper<Tag> qw = new QueryWrapper<>(); Set<Integer> recipeIdSet = new HashSet<>(); // search tag using "like" qw.like("tag_name", keyword); List<Tag> tags = tagService.list(qw); List<Integer> tagIdList = new ArrayList<>(); for (Tag tag : tags ) { log.info("add by tag:" + tag.getTagName()); tagIdList.add(tag.getTagId()); } List<RecipeTagBridge> recipeTagBridges = new ArrayList<>(); if (tagIdList.size() != 0) { QueryWrapper<RecipeTagBridge> qw2 = new QueryWrapper<>(); qw2.in("tag_id", tagIdList); recipeTagBridges = recipeTagBridgeService.list(qw2); } for (RecipeTagBridge recipeTagBridge : recipeTagBridges ) { recipeIdSet.add(recipeTagBridge.getRecipeId()); } return recipeIdSet; } private Set<Integer> searchRecipeIdListByTitle(String keyword) { QueryWrapper<Recipe> qw = new QueryWrapper<>(); Set<Integer> recipeIdSet = new HashSet<>(); // search tag using "like" qw.like("recipe_name", keyword); List<Recipe> recipes = list(qw); for (Recipe r : recipes ) { recipeIdSet.add(r.getRecipeId()); } return recipeIdSet; } private Set<Integer> searchRecipeIdListByIngredient(String keyword) { QueryWrapper<Ingredient> qw = new QueryWrapper<>(); Set<Integer> recipeIdSet = new HashSet<>(); // search tag using "like" qw.like("ingredient_name", keyword); List<Ingredient> ingredients = ingredientService.list(qw); List<Integer> ingredientIdList = new ArrayList<>(); for (Ingredient ingredient : ingredients ) { log.info("add by ingredient:" + ingredient.getIngredientName()); ingredientIdList.add(ingredient.getIngredientId()); } List<IngredientRecipeBridge> ingredientRecipeBridges = new ArrayList<>(); if (ingredientIdList.size() != 0) { QueryWrapper<IngredientRecipeBridge> qw2 = new QueryWrapper<>(); qw2.in("ingredient_id", ingredientIdList); ingredientRecipeBridges = ingredientRecipeBridgeService.list(qw2); } for (IngredientRecipeBridge ingredientRecipeBridge : ingredientRecipeBridges ) { recipeIdSet.add(ingredientRecipeBridge.getRecipeId()); } return recipeIdSet; } @Override public RecipeResultVo getResultVoById(int id) { Recipe recipe = getById(id); RecipeResultVo vo = new RecipeResultVo(recipe); vo.setId(id); vo.setUrl(generateRecipeUrl(id)); vo.setCoverPath(imgService.getPathById(recipe.getRecipeCoverId())); vo.setAuthor(userService.getUsernameById(recipe.getRecipeAuthorId())); List<Tag> tagList = recipeTagBridgeService.getTagsByRecipeId(recipe.getRecipeId()); vo.setTagList(tagList); return vo; } private List<RecipeResultVo> getResultVoListByIdList(Set<Integer> idList) { List<RecipeResultVo> voList = new ArrayList<>(); for (Integer id : idList ) { voList.add(getResultVoById(id)); } return voList; } private String generateRecipeUrl(int id) { return "/recipe/" + id; } @Override public List<RecipeResultVo> getResultVoListByUserId(int id) { QueryWrapper<Recipe> qw = new QueryWrapper<>(); qw.eq("recipe_author_id", id); List<Recipe> recipes = list(qw); List<RecipeResultVo> voList = new ArrayList<>(); if (recipes == null) { return voList; } for (Recipe r : recipes ) { voList.add(getResultVoById(r.getRecipeId())); } return voList; } } <file_sep>/* Navicat Premium Data Transfer Source Server : liang Source Server Type : MySQL Source Server Version : 80019 Source Host : localhost:3306 Source Schema : cookiez Target Server Type : MySQL Target Server Version : 80019 File Encoding : 65001 Date: 29/09/2020 22:54:47 replace utf8mb4_0900_ai_ci with utf8_general_ci */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for amount -- ---------------------------- DROP TABLE IF EXISTS `amount`; CREATE TABLE `amount` ( `amount_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `amount_content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `ingredient_id` int(0) NULL DEFAULT NULL, `recipe_id` int(0) NULL DEFAULT NULL, PRIMARY KEY (`amount_id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for comment -- ---------------------------- DROP TABLE IF EXISTS `comment`; CREATE TABLE `comment` ( `comment_id` int(0) NOT NULL, `user_id` int(0) UNSIGNED NULL DEFAULT NULL, `comment_content` varchar(2550) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `recipe_id` int(0) UNSIGNED NULL DEFAULT NULL, PRIMARY KEY (`comment_id`) USING BTREE, INDEX `fk_comment_user_1`(`user_id`) USING BTREE, INDEX `fk_comment_recipe_1`(`recipe_id`) USING BTREE, CONSTRAINT `fk_comment_recipe_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipe` (`recipe_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_comment_user_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for favorite -- ---------------------------- DROP TABLE IF EXISTS `favorite`; CREATE TABLE `favorite` ( `favorite_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `recipe_id` int(0) UNSIGNED NULL DEFAULT NULL, `user_id` int(0) UNSIGNED NULL DEFAULT NULL, PRIMARY KEY (`favorite_id`) USING BTREE, INDEX `fk_favorite_recipe_1`(`recipe_id`) USING BTREE, INDEX `fk_favorite_user_1`(`user_id`) USING BTREE, CONSTRAINT `fk_favorite_recipe_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipe` (`recipe_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_favorite_user_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for img -- ---------------------------- DROP TABLE IF EXISTS `img`; CREATE TABLE `img` ( `img_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `img_path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, PRIMARY KEY (`img_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for ingredient -- ---------------------------- DROP TABLE IF EXISTS `ingredient`; CREATE TABLE `ingredient` ( `ingredient_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `ingredient_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, PRIMARY KEY (`ingredient_id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for ingredient_recipe_bridge -- ---------------------------- DROP TABLE IF EXISTS `ingredient_recipe_bridge`; CREATE TABLE `ingredient_recipe_bridge` ( `ingredient_recipe_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `ingredient_id` int(0) UNSIGNED NULL DEFAULT NULL, `recipe_id` int(0) UNSIGNED NULL DEFAULT NULL, PRIMARY KEY (`ingredient_recipe_id`) USING BTREE, INDEX `fk_ingredient_recipe_bridge_ingredient_1`(`ingredient_id`) USING BTREE, INDEX `fk_ingredient_recipe_bridge_recipe_1`(`recipe_id`) USING BTREE, CONSTRAINT `fk_ingredient_recipe_bridge_ingredient_1` FOREIGN KEY (`ingredient_id`) REFERENCES `ingredient` (`ingredient_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_ingredient_recipe_bridge_recipe_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipe` (`recipe_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for ingredient_tag_bridge -- ---------------------------- DROP TABLE IF EXISTS `ingredient_tag_bridge`; CREATE TABLE `ingredient_tag_bridge` ( `ingredient_tag_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `ingredient_id` int(0) UNSIGNED NULL DEFAULT NULL, `tag_id` int(0) UNSIGNED NULL DEFAULT NULL, PRIMARY KEY (`ingredient_tag_id`) USING BTREE, INDEX `fk_ingredient_tag_bridge_ingredient_1`(`ingredient_id`) USING BTREE, INDEX `fk_ingredient_tag_bridge_tag_1`(`tag_id`) USING BTREE, CONSTRAINT `fk_ingredient_tag_bridge_ingredient_1` FOREIGN KEY (`ingredient_id`) REFERENCES `ingredient` (`ingredient_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_ingredient_tag_bridge_tag_1` FOREIGN KEY (`tag_id`) REFERENCES `tag` (`tag_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for like -- ---------------------------- DROP TABLE IF EXISTS `like`; CREATE TABLE `like` ( `like_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `user_id` int(0) UNSIGNED NULL DEFAULT NULL, `like_time` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), `status` int(0) NULL DEFAULT NULL, `recipe_id` int(0) UNSIGNED NULL DEFAULT NULL, PRIMARY KEY (`like_id`) USING BTREE, INDEX `fk_like_user_1`(`user_id`) USING BTREE, INDEX `fk_like_recipe_1`(`recipe_id`) USING BTREE, CONSTRAINT `fk_like_recipe_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipe` (`recipe_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_like_user_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for no_eat -- ---------------------------- DROP TABLE IF EXISTS `no_eat`; CREATE TABLE `no_eat` ( `ingredient_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `user_id` int(0) UNSIGNED NULL DEFAULT NULL, `reason` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, PRIMARY KEY (`ingredient_id`) USING BTREE, INDEX `fk_no_eat_user_1`(`user_id`) USING BTREE, CONSTRAINT `fk_no_eat_user_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for pantry -- ---------------------------- DROP TABLE IF EXISTS `pantry`; CREATE TABLE `pantry` ( `pantry_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `user_id` int(0) UNSIGNED NULL DEFAULT NULL, `ingredient_id` int(0) UNSIGNED NULL DEFAULT NULL, PRIMARY KEY (`pantry_id`) USING BTREE, INDEX `fk_pantry_user_1`(`user_id`) USING BTREE, INDEX `fk_pantry_ingredient_1`(`ingredient_id`) USING BTREE, CONSTRAINT `fk_pantry_ingredient_1` FOREIGN KEY (`ingredient_id`) REFERENCES `ingredient` (`ingredient_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_pantry_user_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for recipe -- ---------------------------- DROP TABLE IF EXISTS `recipe`; CREATE TABLE `recipe` ( `recipe_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `recipe_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `recipe_description` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `recipe_like` int(0) NULL DEFAULT NULL, `recipe_created_time` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), `recipe_cover_id` int(0) NULL DEFAULT NULL, `recipe_author_id` int(0) NULL DEFAULT NULL, PRIMARY KEY (`recipe_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 19 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for recipe_tag_bridge -- ---------------------------- DROP TABLE IF EXISTS `recipe_tag_bridge`; CREATE TABLE `recipe_tag_bridge` ( `recipe_tag_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `tag_id` int(0) UNSIGNED NULL DEFAULT NULL, `recipe_id` int(0) UNSIGNED NULL DEFAULT NULL, PRIMARY KEY (`recipe_tag_id`) USING BTREE, INDEX `fk_recipe_tag_bridge_tag_1`(`tag_id`) USING BTREE, INDEX `fk_recipe_tag_bridge_recipe_1`(`recipe_id`) USING BTREE, CONSTRAINT `fk_recipe_tag_bridge_recipe_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipe` (`recipe_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_recipe_tag_bridge_tag_1` FOREIGN KEY (`tag_id`) REFERENCES `tag` (`tag_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for role -- ---------------------------- DROP TABLE IF EXISTS `role`; CREATE TABLE `role` ( `role_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `role_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, PRIMARY KEY (`role_id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for step -- ---------------------------- DROP TABLE IF EXISTS `step`; CREATE TABLE `step` ( `step_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `step_order` int(0) NULL DEFAULT NULL, `img_id` int(0) UNSIGNED NULL DEFAULT NULL, `recipe_id` int(0) UNSIGNED NULL DEFAULT NULL, `step_content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, PRIMARY KEY (`step_id`) USING BTREE, INDEX `fk_step_img_1`(`img_id`) USING BTREE, INDEX `fk_step_recipe_1`(`recipe_id`) USING BTREE, CONSTRAINT `fk_step_img_1` FOREIGN KEY (`img_id`) REFERENCES `img` (`img_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_step_recipe_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipe` (`recipe_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 21 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for tag -- ---------------------------- DROP TABLE IF EXISTS `tag`; CREATE TABLE `tag` ( `tag_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `tag_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `tag_type_id` int(0) UNSIGNED NULL DEFAULT NULL, PRIMARY KEY (`tag_id`) USING BTREE, INDEX `fk_tag_tag_type_1`(`tag_type_id`) USING BTREE, CONSTRAINT `fk_tag_tag_type_1` FOREIGN KEY (`tag_type_id`) REFERENCES `tag_type` (`tag_type_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for tag_type -- ---------------------------- DROP TABLE IF EXISTS `tag_type`; CREATE TABLE `tag_type` ( `tag_type_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `tag_type_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, PRIMARY KEY (`tag_type_id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `user_id` int(0) UNSIGNED NOT NULL AUTO_INCREMENT, `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `user_pwd` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `role_id` int(0) UNSIGNED NULL DEFAULT NULL, `avatar_id` int(0) UNSIGNED NULL DEFAULT NULL, PRIMARY KEY (`user_id`) USING BTREE, INDEX `fk_user_role_1`(`role_id`) USING BTREE, INDEX `fk_user_img_1`(`avatar_id`) USING BTREE, CONSTRAINT `fk_user_img_1` FOREIGN KEY (`avatar_id`) REFERENCES `img` (`img_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_user_role_1` FOREIGN KEY (`role_id`) REFERENCES `role` (`role_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1; <file_sep>package com.ditto.cookiez.service; import com.alibaba.fastjson.JSONObject; import com.ditto.cookiez.entity.Recipe; import com.baomidou.mybatisplus.extension.service.IService; import com.ditto.cookiez.entity.dto.RecipeDTO; import com.ditto.cookiez.entity.vo.RecipeResultVo; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; /** * <p> * service class * </p> * * @author astupidcoder * @since 2020-08-14 */ public interface IRecipeService extends IService<Recipe> { // TODO update ingredients Boolean updateRecipe(JSONObject json, Map<String, MultipartFile> fileMap) throws IOException; Recipe addRecipe(JSONObject json, Map<String, MultipartFile> fileMap) throws IOException; RecipeDTO getRecipe(int id); RecipeDTO getRecipe(Integer id); List<RecipeResultVo> search(List<String> keyword); List<RecipeResultVo> searchByIngredients(List<String> strList); List<RecipeResultVo> searchByTitle(List<String> strList); List<RecipeResultVo> searchByTags(List<String> keywords); RecipeResultVo getResultVoById(int id); List<RecipeResultVo> getResultVoListByUserId(int id); } <file_sep>package com.ditto.cookiez.service; import com.ditto.cookiez.entity.Ingredient; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; /** * <p> * 服务类 * </p> * * @author astupidcoder * @since 2020-09-16 */ public interface IIngredientService extends IService<Ingredient> { List<Ingredient> getIngredientsByTagId(Integer tagId); } <file_sep>package com.ditto.cookiez.service.impl; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.ditto.cookiez.WebLogAspect; import com.ditto.cookiez.auth.JwtTokenUtil; import com.ditto.cookiez.entity.Img; import com.ditto.cookiez.entity.Ingredient; import com.ditto.cookiez.entity.User; import com.ditto.cookiez.mapper.UserMapper; import com.ditto.cookiez.service.IImgService; import com.ditto.cookiez.service.IUserService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.ditto.cookiez.utils.FileUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; /** * <p> * Service Class * </p> * * @author astupidcoder * @since 2020-08-14 */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { @Autowired private UserMapper userMapper; @Autowired private IImgService imgService; private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); private final QueryWrapper<User> queryWrapper = new QueryWrapper<>(); @Autowired @Qualifier("jwtUserDetailsService") private UserDetailsService userDetailsService; @Autowired private JwtTokenUtil jwtTokenUtil; @Override public User getByUsername(String username) { QueryWrapper<User> wrapper = new QueryWrapper(); wrapper.eq("username", username); List<User> list = userMapper.selectList(wrapper); if (list.size() != 0) { return list.get(0); } return null; } @Override public User auth(String username, String password) { User user = getByUsername(username); if (user != null && user.getUserPwd().equals(password)) { final UserDetails userDetails = userDetailsService.loadUserByUsername(username); final String token = jwtTokenUtil.generateToken(userDetails); user.setAccessToken(token); return user; } return null; } @Override public User getUserByToken(String token) { String username = jwtTokenUtil.getUsernameFromToken(token); User user = null; if (username != null) { user = getByUsername(username); if (user.getAvatarId() != null) { user.setAvatarPath(imgService.getPathById(user.getAvatarId())); } } return user; } @Override public Boolean register(User user) { // Has existed the user? User qUser = getByUsername(user.getUsername()); if (qUser == null) { save(user); return true; } return false; } @Transactional @Override public User updateProfile(JSONObject jsonObject, Map<String, MultipartFile> fileMap) throws IOException { String avatarKey = "avatar"; Integer userId = jsonObject.getInteger("userId"); String username = jsonObject.getString("username"); String oldPwd = jsonObject.getString("oldPassword"); String newPwd = jsonObject.getString("newPassword"); logger.info(username); User user = getById(userId); user.setUsername(username); if (!"".equals(newPwd)) { user.setUserPwd(newPwd); } if (fileMap.containsKey(avatarKey)) { MultipartFile file = fileMap.get("avatar"); String url = FileUtil.uploadAvatarToAws(file, userId); Img img = new Img(url); imgService.save(img); user.setAvatarId(img.getImgId()); } user.updateById(); // After user update the profile, cookie also need update final UserDetails userDetails = userDetailsService.loadUserByUsername(username); final String token = jwtTokenUtil.generateToken(userDetails); user.setAccessToken(token); return user; } @Override public String getUsernameById(Integer id) { if (id != null) { User user = getById(id); return user.getUsername(); } return null; } } <file_sep>package com.ditto.cookiez.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.extension.activerecord.Model; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; /** * <p> * * </p> * * @author astupidcoder * @since 2020-08-14 */ @Data @EqualsAndHashCode(callSuper = true) public class Pantry extends Model { private static final long serialVersionUID = 1L; @TableId(value = "pantry_id", type = IdType.AUTO) private Integer pantryId; private Integer userId; private Integer ingredientId; } <file_sep>package com.ditto.cookiez.service; import com.ditto.cookiez.entity.TagType; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 服务类 * </p> * * @author astupidcoder * @since 2020-09-16 */ public interface ITagTypeService extends IService<TagType> { } <file_sep>function signUp() { bootbox.dialog({ message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>', closeButton: false }) axios.post("/api/register", { username: $("#username").val(), password: <PASSWORD>").val() }).then(res => { console.log(res) window.location.replace("/login") }).catch(err => { bootbox.alert("Register Failed") console.log(err) }) }<file_sep>package com.ditto.cookiez.service.impl; import com.ditto.cookiez.entity.Img; import com.ditto.cookiez.mapper.ImgMapper; import com.ditto.cookiez.service.IImgService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * Service Class * </p> * * @author astupidcoder * @since 2020-08-14 */ @Service public class ImgServiceImpl extends ServiceImpl<ImgMapper, Img> implements IImgService { @Override public String getPathById(Integer id) { Img img = getById(id); if (img != null) { return img.getImgPath(); } return null; } // @Override // public boolean save() } <file_sep>package com.ditto.cookiez.service; import com.ditto.cookiez.entity.Like; import com.baomidou.mybatisplus.extension.service.IService; import com.ditto.cookiez.entity.User; /** * <p> * 服务类 * </p> * * @author astupidcoder * @since 2020-09-16 */ public interface ILikeService extends IService<Like> { Like getByUserID(String userId); } <file_sep>package com.ditto.cookiez.entity.dto; import com.ditto.cookiez.entity.Recipe; import com.ditto.cookiez.entity.Tag; import lombok.Data; import java.util.ArrayList; import java.util.List; /** * @author <NAME> * @date 2020/9/23 18:12 * @email <EMAIL> */ @Data public class RecipeDTO { private Integer id; private String recipeName; private String recipeDescription; private String author; private String coverPath; private List<IngredientDTO> ingredientDTOList; private List<StepDTO> stepDTOList; private List<Tag> tagList; public RecipeDTO(Recipe recipe) { this.recipeName = recipe.getRecipeName(); this.recipeDescription = recipe.getRecipeDescription(); } public String getTagsString() { StringBuilder str = new StringBuilder(); for (Tag tag : this.getTagList()) { str.append(tag.getTagName()); str.append(","); } if(str.length()!=0){ str = new StringBuilder(str.substring(0, str.length() - 1)); } return str.toString(); } } <file_sep>//package com.ditto.cookiez.service.impl; // //import com.alibaba.fastjson.JSONObject; //import com.ditto.cookiez.entity.vo.RecipeResultVo; //import com.ditto.cookiez.service.IRecipeService; //import lombok.extern.slf4j.Slf4j; //import org.junit.jupiter.api.Test; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.test.context.SpringBootTest; // //import java.util.ArrayList; //import java.util.List; // //import static org.junit.jupiter.api.Assertions.*; // ///** // * @author <NAME> // * @date 2020/9/23 20:12 // * @email <EMAIL> // */ //@SpringBootTest //@Slf4j //class RecipeServiceImplTest { // @Autowired // IRecipeService service; // // @Test // void updateRecipe() { // } // // @Test // void addRecipe() { // JSONObject jsonObject = (JSONObject) JSONObject.parse("{\n" + // " \"recipe\": {\n" + // " \"recipeDescription\": \"s#Fv97ONnFjE4S7jqAYWDhEnLBpLzIbQGktzPRuGME3D[lXHOrwT@7gzm9@[z[NCxQvDo\",\n" + // " \"recipeName\": \"Rx@4\",\n" + // " \"recipeCreatedTime\": \"2018-04-24\"\n" + // " },\n" + // " \"steps\": [\n" + // " {\n" + // " \"stepOrder\": 7,\n" + // " \"stepContent\": \"t@s0kGoLOctE8PifwmTUo0jhTY9bylgwKOv6e@I9DA[k@S0ReLfO9OqDmfzc7j1!3AtUoPIpBU171qx@[C0jMi7JL08Vp)]tDhBaRS79pIjaMynL63MDcQKhHr3[z68&jF)h%ju!n9HI8Z^OVjG)Hd(I#qv8V#4m(dnE0fty[DZ)i]r9oe]Ajo\",\n" + // " \"imgPath\": \"RUV%QBYSfKlI^f6k32wp$NSnn*iMOckKo4VpuJQZ7R&CIx2s57HS&ItAHZ7ioR%$xDJAui87AvNHZoyJF4Non*9\"\n" + // " },\n" + // " {\n" + // " \"stepOrder\": 2,\n" + // " \"stepContent\": \"G[0yoVmGhFZzcM6hbmchE@BkDhvxV]@u3G0NpQzcqoS!%VyL!e3l4KGgdQ3eHdd#k78Fy(QgbLnnPEn7VnGmbK(Wh&kQfE2#^fc5QL[8Cd%0M7AZV7&kSB(dIhj2B2%wD2IT#QQIHkxG9iBYNyCITKxuzLc[U%%bs#0F9ayuTk50m8\",\n" + // " \"imgPath\": \"rsPwwJIsN*O3bryJAqJZtrd\"\n" + // " },\n" + // " {\n" + // " \"stepOrder\": 4,\n" + // " \"stepContent\": \"IfbxY2RSk33uY4F&m5&b3XUe\",\n" + // " \"imgPath\": \"klrQc&PFYfJAC4M3wjRsw&KmrI4&^KxGXC!C7n@3JepX]0$Lqmgo3kM4Ty$B!#vOYXo]K(IdQajxddF8tA!Xu&QbKDO@rEamfNvSecsk%kjH#$(5f&cOXqDw!Q66LjokkOf\"\n" + // " },\n" + // " {\n" + // " \"stepOrder\": 5,\n" + // " \"stepContent\": \"122KHtqWkFJeozqvzkTn2)9Smeif^XUInhKTnW2nrALl)ZS0\",\n" + // " \"imgPath\": \"U%CF3wZ#!)iXQ7&dOA%pV$FQ[CJFH5#0cJY(NfYQdQml6B7VkATOibvMts37LxpKhSv8$P1TLY6&%ClCW\"\n" + // " },\n" + // " {\n" + // " \"stepOrder\": 3,\n" + // " \"stepContent\": \"Rgl%hmK5xP!%9ci!)r8@!hs525t0Sd*Vq5haS!P%j515qRi38l78vXocT4js&1P2t3OO96okdTBkjD0H#*JnR(jtLhNdT*![4I#$Vf@ogHOd7$gca\",\n" + // " \"imgPath\": \"M0!lpzS&byjFS%7kUai(ewuo(!@U5fF]Wm]Cm!o^0XH7bI@sZT#dvju9yAEwuvB5[(SrjIVfUGsVCfn$xbZD0v^lycLuknos[yUeXJ0X&ZQKR1yL2R#3wX2WI@I[\"\n" + // " }\n" + // " ]\n" + // "}"); // System.out.println(jsonObject.toJSONString()); //// servic.addRecipe(jsonObject); // } // // @Test // void testUpdateRecipe() { // } // // @Test // void testAddRecipe() { // } // // @Test // void getRecipe() { // // // } // // @Test // void search() { // List<String> str=new ArrayList<>(); // str.add("chicken"); // List<RecipeResultVo> vo = service.search(str); // System.out.println(vo.toString()); // log.info(vo.size() + ""); // } // // @Test // void getResultVoById() { // System.out.println(service.getResultVoById(20)); // } // // @Test // void searchByIngredients() { // List<String> stringList = new ArrayList<>(); // stringList.add("divided"); // List<RecipeResultVo> list= service.searchByIngredients(stringList); // log.info(list.toString()); // // // } // // @Test // void searchByTags() { // List<String> stringList = new ArrayList<>(); // stringList.add("shit"); // List<RecipeResultVo> list= service.searchByTags(stringList); // assert list.size()==1; // } // // // @Test // void searchByTitle() { // List<String> stringList = new ArrayList<>(); // stringList.add("shit"); // List<RecipeResultVo> list= service.searchByTitle(stringList); // assert list.size()==0; // } //}<file_sep>package com.ditto.cookiez.mapper; import com.ditto.cookiez.entity.Like; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author astupidcoder * @since 2020-09-16 */ public interface LikeMapper extends BaseMapper<Like> { } <file_sep>package com.ditto.cookiez.service.impl; import com.ditto.cookiez.entity.Like; import com.ditto.cookiez.mapper.LikeMapper; import com.ditto.cookiez.service.ILikeService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * Service Class * </p> * * @author astupidcoder * @since 2020-09-16 */ @Service public abstract class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements ILikeService { @Override public Like getByUserID(String userId) { return null; } } <file_sep>package com.ditto.cookiez.service; import com.ditto.cookiez.entity.Recipe; import com.ditto.cookiez.entity.Tag; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; import java.util.Set; /** * <p> * 服务类 * </p> * * @author astupidcoder * @since 2020-09-16 */ public interface ITagService extends IService<Tag> { }
5ec717e0916a46ae43fe4d6611de8cf3f347889e
[ "SQL", "JavaScript", "Markdown", "Maven POM", "Java" ]
43
Maven POM
zhihao-liang/TR-WE-430-Ditto
857a79bae466f541fcd0b12e069fec185deba86c
fef3a5466db3d390b444a2e7626244fcb19f3d41
refs/heads/master
<file_sep><?php /** * @Author: 王金龙 * @Date: 2017-11-30 16:25:36 * @Last Modified by: 王金龙 * @Last Modified time: 2017-11-30 18:36:21 */ // header(string:'cont ent-type:text/html;charset=utf8'); $user=$_GET['user']; $pass=$_GET['pass']; if($user=='admin'){ if ($pass=='<PASSWORD>') { echo "登录成功"; }else{ echo "密码失败"; } }else{ echo "账号不存在"; }
5551b1c53b9328911cefa6f4117c79e0a562e201
[ "PHP" ]
1
PHP
wang123jin/kuang
8464fe94db88cfc3c41acd7c25449d09a35e5d15
8948d538eb0c4e4e531a9fc31f7384e49d3adb6b
refs/heads/master
<repo_name>NominationP/go-DelegationMode<file_sep>/v2/UndoDelegationModeV2.go package v2 import ( "errors" "fmt" ) /** UndoDelegationMode.go 中的数据容器平淡无奇,我们想给它加一个Undo功能 */ type UndoableIntSet struct { IntSet // Embedding (delegation) functions []func() } func NewUndoableIntSet() UndoableIntSet { return UndoableIntSet{NewIntSet(), nil} } func (set *UndoableIntSet) Add(x int) { // Override if !set.Contains(x) { set.data[x] = true set.functions = append(set.functions, func() { set.Delete(x) }) } else { set.functions = append(set.functions, nil) } } func (set *UndoableIntSet) Delete(x int) { //Overried if set.Contains(x) { delete(set.data, x) set.functions = append(set.functions, func() { set.Add(x) }) } else { set.functions = append(set.functions, nil) } } func (set *UndoableIntSet) Undo() error { if len(set.functions) == 0 { return errors.New("No functions to undo") } index := len(set.functions) - 1 if function := set.functions[index]; function != nil { function() set.functions[index] = nil // Free closure for garbage collection } set.functions = set.functions[:index] return nil } func main() { ints := NewUndoableIntSet() for _, i := range []int{1, 3, 5, 7} { ints.Add(i) fmt.Println(ints) } for _, i := range []int{1, 2, 3, 4, 5, 6, 7} { fmt.Println(i, ints.Contains(i), " ") ints.Delete(i) fmt.Println(ints) } fmt.Println() for { if err := ints.Undo(); err != nil { break } fmt.Println(ints) } } <file_sep>/v2/UndoDelegationMode.go package v2 import ( "fmt" . "sort" "strings" ) /** 声明一个数据容器,其中有Add(), Delete() Contains(), 还有一个转字符串的方法 */ type IntSet struct { data map[int]bool } func NewIntSet() IntSet { return IntSet{make(map[int]bool)} } func (set *IntSet) Add(x int) { set.data[x] = true } func (set *IntSet) Delete(x int) { delete(set.data, x) } func (set *IntSet) Contains(x int) bool { return set.data[x] } func (set *IntSet) String() string { // Staisfies fmt.Stringer interface if len(set.data) == 0 { return "{}" } ints := make([]int, 0, len(set.data)) for i := range set.data { ints = append(ints, i) } Ints(ints) parts := make([]string, 0, len(ints)) for _, i := range ints { parts = append(parts, fmt.Sprint(i)) } return "{" + strings.Join(parts, ",") + "}" } //func main() { // ints := NewIntSet() // for _, i := range []int{1, 3, 5, 7} { // ints.Add(i) // fmt.Println(ints) // } // // for _, i := range []int{1, 2, 3, 4, 5, 6, 7} { // fmt.Print(i, ints.Contains(i), " ") // ints.Delete(i) // fmt.Println(ints) // } //} <file_sep>/example1.go /** 这个是 Go 语中的委托和接口多态的编程方式,其实是面向对象和原型编程的综合玩法 https://time.geekbang.org/column/article/2748 */ package main import ( "fmt" ) type Widget struct { X, Y int } /** Label */ type Label struct { Widget Text string X int } func (label Label) Paint() { // fmt.Printf("[%p] - Label.Paint(%q)\n", &label, label.Text) } /** Button */ type Button struct { Label } func NewButton(x, y int, text string) Button { return Button{Label{Widget{x, y}, text, x}} } func (button Button) Paint() { fmt.Printf("[%p] - Button.Paint(%q)\n", &button, button.Text) } func (button Button) Click() { fmt.Printf("[%p] - Button.Click()\n", &button) } /** ListBox */ type ListBox struct { Widget Texts []string Index int } func (listBox ListBox) Paint() { fmt.Printf("[%p] - ListBox.Paint(%q)\n", &listBox, listBox.Texts) } func (listBox ListBox) Click() { fmt.Printf("[%p] - ListBox.Click()\n", &listBox) } /** interface */ type Painter interface { Paint() } type Clicker interface { Click() } func main() { /** example1 output */ label := Label{Widget{10, 10}, "State", 100} //fmt.Printf("X=%d, Y=%d, Text=%s Widget.X=%d\n", // label.X, label.Y, label.Text, // label.Widget.X) //fmt.Println() //fmt.Printf("%+v\n%v\n", label, label) //label.Paint() /** example2 output */ button1 := Button{Label{Widget{10, 70}, "ok", 10}} button2 := NewButton(50, 70, "Cancel") listBox := ListBox{Widget{10, 10}, []string{"AL", "AK", "AZ", "AR"}, 0} fmt.Println() for _, painter := range []Painter{label, listBox, button1, button2} { painter.Paint() } fmt.Println() for _, widget := range []interface{}{label, listBox, button1, button2} { if clicker, ok := widget.(Clicker); ok { clicker.Click() } } } <file_sep>/README.md # go-DelegationMode Go 委托模式 -- 理解反转控制IOC - example1.go 简单介绍go的委托和多态接口的编程方式 - v1~v3 逐步演化一个undo功能的需求,来体现反转控制IOC编程思想 参见[极客时间-左耳听风专栏](https://time.geekbang.org/column/article/2723)
161b69fc152996858dd96e21836cec92dadf6d93
[ "Markdown", "Go" ]
4
Go
NominationP/go-DelegationMode
ce02c3f112d95c20dc29bb1cf0be78a0c66de9c3
e1b1a44ca4903ea177d852c079208a2d7d63725c
refs/heads/master
<repo_name>damienmartindarcy/Recommender<file_sep>/DL Recommender.py # Deep Learning recommender # https://github.com/khanhnamle1994/movielens/blob/master/Deep_Learning_Model.ipynb # Import libraries %matplotlib inline import math import numpy as np import pandas as pd import matplotlib.pyplot as plt # Reading ratings file ratings = pd.read_csv('ratings.csv', sep='\t', encoding='latin-1', usecols=['user_id', 'movie_id', 'user_emb_id', 'movie_emb_id', 'rating']) max_userid = ratings['user_id'].drop_duplicates().max() max_movieid = ratings['movie_id'].drop_duplicates().max() # Reading ratings file users = pd.read_csv('users.csv', sep='\t', encoding='latin-1', usecols=['user_id', 'gender', 'zipcode', 'age_desc', 'occ_desc']) # Reading ratings file movies = pd.read_csv('movies.csv', sep='\t', encoding='latin-1', usecols=['movie_id', 'title', 'genres']) # Create training set shuffled_ratings = ratings.sample(frac=1., random_state=RNG_SEED) # Shuffling users Users = shuffled_ratings['user_emb_id'].values print 'Users:', Users, ', shape =', Users.shape # Shuffling movies Movies = shuffled_ratings['movie_emb_id'].values print 'Movies:', Movies, ', shape =', Movies.shape # Shuffling ratings Ratings = shuffled_ratings['rating'].values print 'Ratings:', Ratings, ', shape =', Ratings.shape # Import Keras libraries from keras.callbacks import Callback, EarlyStopping, ModelCheckpoint # Import CF Model Architecture from CFModel import CFModel # Define constants K_FACTORS = 100 # The number of dimensional embeddings for movies and users TEST_USER = 2000 # A random test user (user_id = 2000) # Define model model = CFModel(max_userid, max_movieid, K_FACTORS) # Compile the model using MSE as the loss function and the AdaMax learning algorithm model.compile(loss='mse', optimizer='adamax') # Train the model # Callbacks monitor the validation loss # Save the model weights each time the validation loss has improved callbacks = [EarlyStopping('val_loss', patience=2), ModelCheckpoint('weights.h5', save_best_only=True)] # Use 30 epochs, 90% training data, 10% validation data history = model.fit([Users, Movies], Ratings, nb_epoch=30, validation_split=.1, verbose=2, callbacks=callbacks) # Evaluate # Show the best validation RMSE min_val_loss, idx = min((val, idx) for (idx, val) in enumerate(history.history['val_loss'])) print 'Minimum RMSE at epoch', '{:d}'.format(idx+1), '=', '{:.4f}'.format(math.sqrt(min_val_loss)) # Use the pre-trained model trained_model = CFModel(max_userid, max_movieid, K_FACTORS) # Load weights trained_model.load_weights('weights.h5') # Pick a random test user users[users['user_id'] == TEST_USER] # Function to predict the ratings given User ID and Movie ID def predict_rating(user_id, movie_id): return trained_model.rate(user_id - 1, movie_id - 1) user_ratings = ratings[ratings['user_id'] == TEST_USER][['user_id', 'movie_id', 'rating']] user_ratings['prediction'] = user_ratings.apply(lambda x: predict_rating(TEST_USER, x['movie_id']), axis=1) user_ratings.sort_values(by='rating', ascending=False).merge(movies, on='movie_id', how='inner', suffixes=['_u', '_m']).head(20) # Recommend recommendations = ratings[ratings['movie_id'].isin(user_ratings['movie_id']) == False][['movie_id']].drop_duplicates() recommendations['prediction'] = recommendations.apply(lambda x: predict_rating(TEST_USER, x['movie_id']), axis=1) recommendations.sort_values(by='prediction', ascending=False).merge(movies, on='movie_id', how='inner', suffixes=['_u', '_m']).head(20)<file_sep>/Model based collaborative filtering.py # Model based collaborative filtering also known as Matrix Factorization recommender # https://github.com/khanhnamle1994/movielens/blob/master/SVD_Model.ipynb # Import libraries import numpy as np import pandas as pd # Reading ratings file ratings = pd.read_csv('ratings.csv', sep='\t', encoding='latin-1', usecols=['user_id', 'movie_id', 'rating', 'timestamp']) # Reading users file users = pd.read_csv('users.csv', sep='\t', encoding='latin-1', usecols=['user_id', 'gender', 'zipcode', 'age_desc', 'occ_desc']) # Reading movies file movies = pd.read_csv('movies.csv', sep='\t', encoding='latin-1', usecols=['movie_id', 'title', 'genres']) movies.head() ratings.head() n_users = ratings.user_id.unique().shape[0] n_movies = ratings.movie_id.unique().shape[0] print 'Number of users = ' + str(n_users) + ' | Number of movies = ' + str(n_movies) Ratings = ratings.pivot(index = 'user_id', columns ='movie_id', values = 'rating').fillna(0) Ratings.head() R = Ratings.as_matrix() user_ratings_mean = np.mean(R, axis = 1) Ratings_demeaned = R - user_ratings_mean.reshape(-1, 1) sparsity = round(1.0 - len(ratings) / float(n_users * n_movies), 3) print 'The sparsity level of MovieLens1M dataset is ' + str(sparsity * 100) + '%' from scipy.sparse.linalg import svds U, sigma, Vt = svds(Ratings_demeaned, k = 50) sigma = np.diag(sigma) all_user_predicted_ratings = np.dot(np.dot(U, sigma), Vt) + user_ratings_mean.reshape(-1, 1) preds = pd.DataFrame(all_user_predicted_ratings, columns = Ratings.columns) preds.head() def recommend_movies(predictions, userID, movies, original_ratings, num_recommendations): # Get and sort the user's predictions user_row_number = userID - 1 # User ID starts at 1, not 0 sorted_user_predictions = preds.iloc[user_row_number].sort_values(ascending=False) # User ID starts at 1 # Get the user's data and merge in the movie information. user_data = original_ratings[original_ratings.user_id == (userID)] user_full = (user_data.merge(movies, how = 'left', left_on = 'movie_id', right_on = 'movie_id'). sort_values(['rating'], ascending=False) ) print 'User {0} has already rated {1} movies.'.format(userID, user_full.shape[0]) print 'Recommending highest {0} predicted ratings movies not already rated.'.format(num_recommendations) # Recommend the highest predicted rating movies that the user hasn't seen yet. recommendations = (movies[~movies['movie_id'].isin(user_full['movie_id'])]. merge(pd.DataFrame(sorted_user_predictions).reset_index(), how = 'left', left_on = 'movie_id', right_on = 'movie_id'). rename(columns = {user_row_number: 'Predictions'}). sort_values('Predictions', ascending = False). iloc[:num_recommendations, :-1] ) return user_full, recommendations already_rated, predictions = recommend_movies(preds, 1310, movies, ratings, 20) # Top 20 movies that User 1310 has rated already_rated.head(20) # Top 20 movies that User 1310 hopefully will enjoy predictions # Import libraries from Surprise package from surprise import Reader, Dataset, SVD, evaluate # Load Reader library reader = Reader() # Load ratings dataset with Dataset library data = Dataset.load_from_df(ratings[['user_id', 'movie_id', 'rating']], reader) # Split the dataset for 5-fold evaluation data.split(n_folds=5) # Use the SVD algorithm. svd = SVD() # Compute the RMSE of the SVD algorithm. evaluate(svd, data, measures=['RMSE']) trainset = data.build_full_trainset() svd.train(trainset) ratings[ratings['user_id'] == 1310] svd.predict(1310, 1994) <file_sep>/README.md # Recommender Recommender Systems
4f800245bc7864a537b36f6e2875d12bc4b9a6b0
[ "Markdown", "Python" ]
3
Python
damienmartindarcy/Recommender
676acb5d2a3beaec57282edddf1a8a0222ec9a01
e803c12b2c65041850e325ed1ac0ff260fb9e975
refs/heads/master
<repo_name>emilytsherwood/liri-node-app<file_sep>/liri.js var keyFile = require('./keys.js'); //grabbing data from keys.js file var Twitter = require('twitter'); var spotify = require('spotify'); var request = require('request'); var fs = require('fs'); var tweets = ''; //empty string to hold the tweets var liriSwitch = process.argv[2]; //Grabbing the API keys from the keys.js file var client = new Twitter(keyFile.twitterKeys); //Function that displays the last 20 tweets of mine function myTweets() { var params = { screen_name: 'emilyturner88', count: 20 }; client.get('statuses/user_timeline', params, function(error, tweets, response) { if (error) { console.log(error); } else { console.log(tweets); } for (var i = 0; i < tweets.length; i++) { console.log(tweets[i].text); console.log(tweets[i].created_at); } }); } //Spotify var songName = process.argv[3]; console.log(songName); function spotifySong(songName) { // var songSpotify = process.argv[3]; //user has to type in song name var song = songName; console.log(song); if (song === undefined){ song = 'The Sign'; } spotify.search({ type: 'track', query: song }, function(err, data) { if (err) { console.log('Error occurred: ' + err); return; } else { console.log("The song name is: " + data.tracks.items[0].name); console.log("The artist is: " + data.tracks.items[0].artists[0].name); console.log("The album is: " + data.tracks.items[0].album.name); console.log("Preview link of song: " + data.tracks.items[0].preview_url); //'data' is coming from the function on line 34 } }); } //Movies/OMDB function movieThis() { var movieName = process.argv[3]; //user has to type in movie name request('http://www.omdbapi.com/?t=' + movieName + '&y=&plot=short&r=json&tomatoes=true', function(error, response, body) { if (!error && response.statusCode == 200) { } var movies = JSON.parse(body); // if (movies.Title === undefined);{ // movies.Title = 'Mr. Nobody'; console.log("Title: " + movies.Title); console.log("Year: " + movies.Year); console.log("IMDB Rating: " + movies.imdbRating); console.log("Country: " + movies.Country); console.log("Language: " + movies.Language); console.log("Plot: " + movies.Plot); console.log("Actors: " + movies.Actors); console.log("Rotten Tomato Rating: " + movies.tomatoUserRating); console.log("Rotton Tomato Link: " + movies.tomatoURL); }); } function doSays() { fs.readFile('random.txt', 'utf8', function(err, data){ console.log(data); var dataArr = data.split(','); spotifySong(dataArr[1]); }); } switch (liriSwitch) { case 'my-tweets': myTweets(); break; case 'spotify-this-song': spotifySong(songName); break; case 'movie-this': movieThis(); break; case 'do-what-it-says': doSays(); break; }
672d0bd4306bf694fe80c1379e5c8c45a3466731
[ "JavaScript" ]
1
JavaScript
emilytsherwood/liri-node-app
31aacdd699a027c8a496ea74e89b716f6d8fc249
b2df5577c7fea9b786058f522a7027c6a20bb027
refs/heads/master
<repo_name>ANKIT9263/freETarget<file_sep>/Software/Arduino/freETarget/freETarget.ino /*---------------------------------------------------------------- * * freETarget * * Software to run the Air-Rifle / Small Bore Electronic Target * *-------------------------------------------------------------*/ #include "freETarget.h" #include "gpio.h" #include "compute_hit.h" #include "analog_io.h" #include "json.h" #include "EEPROM.h" #include "nonvol.h" #include "mechanical.h" #include "diag_tools.h" #include "esp-01.h" this_shot record; double s_of_sound; // Speed of sound unsigned int shot = 0; // Shot counter bool face_strike = false; // Miss indicator bool is_trace = false; // TRUE if trace is enabled const char* names[] = { "TARGET", // 0 "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", // 1 "DOC", "DOPEY", "HAPPY", "GRUMPY", "BASHFUL", "SNEEZEY", "SLEEPY", // 11 "RUDOLF", "DONNER", "BLITZEN", "DASHER", "PRANCER", "VIXEN", "COMET", "CUPID", "DUNDER", // 18 "ODIN", "WODEN", "THOR", "BALDAR", // 26 0}; const char nesw[] = "NESW"; // Cardinal Points const char to_hex[] = "0123456789ABCDEF"; // Quick Hex to ASCII static long tabata(bool reset_time, bool reset_cycles); // Tabata state machine /*---------------------------------------------------------------- * * function: setup() * * brief: Initialize the board and prepare to run * * return: None * *--------------------------------------------------------------*/ void setup(void) { /* * Setup the serial port */ Serial.begin(115200); AUX_SERIAL.begin(115200); DISPLAY_SERIAL.begin(115200); /* * Set up the port pins */ init_gpio(); init_sensors(); init_analog_io(); switch ( read_DIP() & 0x0f ) // Execute a power up routine if we have to { case 1: set_trip_point(0); // Calibrate break; case 0x0f: factory_nonvol(false); // Force a factory nonvol reset break; default: break; } randomSeed( analogRead(V_REFERENCE)); // Seed the random number generator is_trace = VERBOSE_TRACE; // Set the trace based on the DIP switch /* * Initialize the WiFi if available */ esp01_init(); // Prepare the WiFi channel if installed /* * Initialize variables */ read_nonvol(); tabata(true, true); // Reset the Tabata timers /* * Run the power on self test */ POST_version(PORT_ALL); // Show the version string on all ports show_echo(0); POST_LEDs(); // Cycle the LEDs while ( (POST_counters() == false) // If the timers fail && !is_trace) // and not in trace mode (DIAG jumper installed) { Serial.print(T("\r\nPOST_2 Failed\r\n"));// Blink the LEDs blink_fault(POST_COUNT_FAILED); // and try again } POST_trip_point(); // Show the trip point /* * Ready to go */ set_LED_PWM(json_LED_PWM); return; } /*---------------------------------------------------------------- * * function: loop() * * brief: Main control loop * * return: None * *---------------------------------------------------------------- */ #define SET_MODE 0 // Set the operating mode #define ARM (SET_MODE+1) // State is ready to ARM #define WAIT (ARM+1) // ARM the circuit #define AQUIRE (WAIT+1) // Aquire the shot #define REDUCE (AQUIRE+1) // Reduce the data #define WASTE (REDUCE+1) // Wait for the shot to end #define SEND_MISS (WASTE+1) // Got a trigger, but was defective unsigned int state = SET_MODE; unsigned long now; // Interval timer unsigned long power_save; // Power save timer unsigned int sensor_status; // Record which sensors contain valid data unsigned int location; // Sensor location unsigned int i, j; // Iteration Counter int ch; unsigned int shot_number; unsigned int shot_time; // Shot time captured from Tabata timer void loop() { /* * First thing, handle polled devices */ esp01_receive(); // Accumulate input from the IP port. multifunction_switch(0); // Read the switches tabata(false, false); /* * Take care of any commands coming through */ if ( read_JSON() ) { now = micros(); // Reset the power down timer if something comes in set_LED_PWM(json_LED_PWM); // Put the LED back on if it was off } /* * Cycle through the state machine */ switch (state) { /* * Check for special operating modes */ default: case SET_MODE: is_trace |= VERBOSE_TRACE; // Turn on tracing if the DIP switch is in place if ( CALIBRATE ) { set_trip_point(0); // Are we calibrating? } state = ARM; // Carry on to the target break; /* * Arm the circuit */ case ARM: arm_counters(); enable_interrupt(json_send_miss); // Turn on the face strike interrupt face_strike = false; // Reset the face strike count set_LED_PWM(json_LED_PWM); // Keep the LEDs ON if ( json_tabata_on != 0 ) // Show that Tabata is ON { set_LED(-1,1,-1); // Just turn on X } sensor_status = is_running(); power_save = micros(); // Start the power saver time if ( sensor_status == 0 ) { if ( is_trace ) { Serial.print(T("\r\n\nWaiting...")); } state = WAIT; // Fall through to WAIT } else { if ( is_trace == false ) { if ( sensor_status & TRIP_NORTH ) { Serial.print(T("\r\n{ \"Fault\": \"NORTH\" }")); set_LED(NORTH_FAILED); // Fault code North delay(ONE_SECOND); } if ( sensor_status & TRIP_EAST ) { Serial.print(T("\r\n{ \"Fault\": \"EAST\" }")); set_LED(EAST_FAILED); // Fault code East delay(ONE_SECOND); } if ( sensor_status & TRIP_SOUTH ) { Serial.print(T("\r\n{ \"Fault\": \"SOUTH\" }")); set_LED(SOUTH_FAILED); // Fault code South delay(ONE_SECOND); } if ( sensor_status & TRIP_WEST ) { Serial.print(T("\r\n{ \"Fault\": \"WEST\" }")); set_LED(WEST_FAILED); // Fault code West delay(ONE_SECOND); } } } break; /* * Wait for the shot */ case WAIT: if ( (esp01_is_present() == false) || esp01_connected() ) // If the ESP01 is not present, or connected { set_LED(1, -1, -1); // to a client, then the RDY light is steady on } else { if ( (micros() / 1000000) & 1 ) // Otherwise blink the RDY light { set_LED(1, -1, -1); } else { set_LED(0, -1, -1); } } if ( (json_power_save != 0 ) && (((micros()-power_save) / 1000000 / 60) >= json_power_save) ) { set_LED_PWM(0); // Dim the lights? } sensor_status = is_running(); if ( face_strike ) // Something hit the front { state = SEND_MISS; // Show it's a miss break; } if ( sensor_status != 0 ) // Shot detected { now = micros(); // Remember the starting time record.shot_time = tabata(false, false); // Capture the time into the shot set_LED(L('-', '*', '-')); // No longer waiting state = AQUIRE; } break; /* * Aquire the shot */ case AQUIRE: if ( (micros() - now) > (SHOT_TIME) ) // Enough time already { stop_counters(); state = REDUCE; // 3, 4 Have enough data to performe the calculations } break; /* * Reduce the data to a score */ case REDUCE: if ( is_trace ) { Serial.print(T("\r\nTrigger: ")); show_sensor_status(sensor_status); Serial.print(T("\r\nReducing...")); } set_LED(L('*', '*', '*')); // Light All location = compute_hit(sensor_status, &record, false); if ( ((json_tabata_cycles != 0) && ( record.shot_time == 0 )) // Are we out of the tabata cycle time? || (timer_value[N] == 0) || (timer_value[E] == 0) || (timer_value[S] == 0) || (timer_value[W] == 0) ) // If any one of the timers is 0, that's a miss { state = SEND_MISS; break; } send_score(&record, shot_number, sensor_status); state = WASTE; shot_number++; break; /* * Wait here to make sure the RUN lines are no longer set */ case WASTE: if ( (json_paper_time + json_step_time) != 0 ) // Has the witness paper been enabled { if ( (json_paper_eco == 0) // ECO turned off || ( sqrt(sq(record.x) + sq(record.y)) < json_paper_eco ) ) // And inside the black { drive_paper(); } } state = SET_MODE; break; /* * Show an error occured */ case SEND_MISS: state = SET_MODE; // Next time go to waste time if ( is_trace ) { Serial.print(T("\r\nFace Strike...\r\n")); } face_strike = false; blink_fault(SHOT_MISS); if ( json_send_miss != 0) { send_miss(shot); } break; } /* * All done, exit for now */ return; } /*---------------------------------------------------------------- * * function: tabata * * brief: Implement a Tabata timer for training * * return: Time that the current TABATA state == TABATA_ON * *---------------------------------------------------------------- * * A Tabata timer is used to train for specific durations or time * of events. For example in shooting the target should be aquired * and shot within a TBD seconds. * * This function turns on the LEDs for a configured time and * then turns them off for another configured time and repeated * for a configured number of cycles * * OFF - 2 Second Warning - 2 Second Off - ON * * Test JSON {"TABATA_ON":7, "TABATA_REST":45, "TABATA_CYCLES":60} * *--------------------------------------------------------------*/ static long tabata_time; // Internal timern in milliseconds static uint16_t tabata_cycles; #define TABATA_IDLE 0 #define TABATA_WARNING 1 #define TABATA_DARK 2 #define TABATA_ON 3 #define TABATA_DONE_OFF 4 #define TABATA_DONE_ON 5 #define TABATA_BLINK_ON 20 // Warning blink 20 x 100ms = 2 second #define TABATA_BLINK_OFF 20 // Warning blink 20 x 100ms = 2 second static uint16_t tabata_state = TABATA_IDLE; static long tabata ( bool reset_time, // TRUE if starting timer bool reset_cycles // TRUE if cycles the cycles ) { unsigned long now; // Current time in seconds now = millis()/100; // Now in 10ms increments if ( json_tabata_on == 0 ) // Exit if no cycles are enabled { return now; // Just return the current time } /* * Reset the variables based on the arguements */ if ( reset_time ) // Reset the timer { tabata_time = now; tabata_state = TABATA_IDLE; set_LED_PWM_now(0); } if ( reset_cycles ) // Reset the number of cycles { tabata_cycles = 0; tabata_state = TABATA_IDLE; } /* * Execute the state machine */ switch (tabata_state) { case (TABATA_IDLE): // OFF, wait for the time to expire if ( (now - tabata_time)/10 > (json_tabata_rest - ((TABATA_BLINK_ON + TABATA_BLINK_OFF)/10)) ) { tabata_state = TABATA_WARNING; tabata_time = now;; tabata_cycles++; set_LED_PWM_now(json_LED_PWM); // Turn on the lights } break; case (TABATA_WARNING): // 1 second warning if ( (now - tabata_time) > TABATA_BLINK_ON ) { tabata_state = TABATA_DARK; tabata_time = now; set_LED_PWM_now(0); // Turn off the lights } break; case (TABATA_DARK): // 2 second dark if ( (now - tabata_time) > TABATA_BLINK_OFF ) { tabata_state = TABATA_ON; tabata_time = now; set_LED_PWM_now(json_LED_PWM); // Turn on the lights if ( is_trace ) { Serial.print(T("\r\nTabata ON")); } } break; case (TABATA_ON): // Keep the LEDs on for the tabata time if ( (now - tabata_time) > json_tabata_on ) { if ( (json_tabata_cycles != 0) && (tabata_cycles >= json_tabata_cycles) ) { tabata_state = TABATA_DONE_OFF; } else { tabata_state = TABATA_IDLE; if ( is_trace ) { Serial.print(T("\r\nTabata OFF")); } } tabata_time = now; set_LED_PWM_now(0); // Turn off the LEDs } break; /* * We have run out of cycles. Sit there and blink the LEDs */ case (TABATA_DONE_OFF): //Finished. Stop the game if ( (now - tabata_time) > TABATA_BLINK_OFF ) { tabata_state = TABATA_DONE_ON; tabata_time = now; set_LED_PWM(json_LED_PWM); // Turn off the LEDs } break; case (TABATA_DONE_ON): //Finished. Stop the game if ( (now - tabata_time) > TABATA_BLINK_ON ) { tabata_state = TABATA_DONE_OFF; tabata_time = now; set_LED_PWM(0); // Turn off the LEDs } break; } /* * All done. Return the current time if in the TABATA_ON state */ if ( tabata_state == TABATA_ON ) { return now-tabata_time; } else return 0; } <file_sep>/Software/Arduino/freETarget/analog_io.h #ifndef _ANALOG_IO_H_ #define _ANALOG_IO_H_ /* * Global functions */ void init_analog_io(void); // Setup the analog hardware unsigned int read_reference(void); // Read the feedback channel void show_analog(int v); // Display the analog values double temperature_C(void); // Temperature in degrees C unsigned int revision(void); // Return the board revision void set_LED_PWM(int percent); // Ramp the PWM duty cycle void set_LED_PWM_now(int percent); // Set the PWM duty cycle /* * Port Definitions */ #define NORTH_ANA 1 // North Analog Input #define EAST_ANA 2 // East Analog Input #define SOUTH_ANA 3 // South Analog Input #define WEST_ANA 4 // West Analog Input #define SPARE_2A 7 // Not Used #define V_REFERENCE 0 // Reference Input #define ANALOG_VERSION 5 // Analog Version Input #define LED_PWM 5 // PWM Port #define MAX_ANALOG 0x3ff // Largest analog input #define TO_VOLTS(x) ( ((double)(x) * 5.0) / 1024.0 ) #define TEMP_IC (0x9E >> 1) #endif <file_sep>/Software/Arduino/freETarget/esp-01.ino /*---------------------------------------------------------------- * * esp-01.ino * * WiFi Driver for ESP-01 * *----------------------------------------------------------------- * * Refer to the command set which can be found at * * https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf * * The WiFi software somewhat convoluted. * * In order to simplify operation in the field, each freETarget * is a WiFi station. The target is assigned an SSID corresponding * to the name of the target, ex FET-WODEN. This helps to link up * the WiFI to the target. * * Each ESP-01 is a server so that the PC connects to it over * IP address 192.168.10.9:1090 * * Unfortunatly as a server, each ESP expects to see more than one * connection, so a transparent or passthrought mode is not possible. * Instead the incoming messages are tagged with a channel number * and outgoign messages are prepended with a channel number. * * Thus the function esp01_receive constantly listens on the serial * port, parses the input and saves only the message to a * circular buffer that is used later on by the application. * * On output, the function esp01_send tells the ESP-01 to expect a * very long null-terminated message. The regular Serial.send() * messages are then used to send the body of the message and at * the end esp01_send() inserts the null and kicks off the * transmission. * *---------------------------------------------------------------*/ /* * Function Prototypes */ static bool esp01_esp01_waitOK(void); // Wait for an OK to come back static void esp01_flush(void); // Flush any pending messages /* * Local Variables */ static bool esp01_present = false; // TRUE if the esp 01 is installed static char esp01_in_queue[32]; // Place to store incoming characters static int esp01_in_ptr; // Queue in pointer static int esp01_out_ptr; // Queue out pointer static bool esp01_connect[] = {false, false, false}; // Set to true when a channel (0-2) connects /*---------------------------------------------------------------- * * function: void esp01_init * * brief: Initialize the ESP-01 * * return: esp_present - set to TRUE if an ESP-01 is on the board * *---------------------------------------------------------------- * * The function outputs a series of AT commands to the port to * * Set the part as a WiFi Server * The SSID is set up as FET-<name> * The freETarget IP address is 172.16.58.3 * The freETarget port is 1090 * The connecting PC will be assigned address 192.168.10.8 * * Open a port for connection * * IMPORTANT * * The init function does not set the pass through mode. This * is done by a separate call to esp01_passthrough(); * *--------------------------------------------------------------*/ void esp01_init(void) { if ( is_trace ) { Serial.print(T("\r\nInitializing ESP-01")); } /* * Determine if the ESP-01 is attached to the Accessory Connector */ if (esp01_is_present() == false ) { if ( is_trace ) { Serial.print(T("\r\nESP-01 Not Found")); } return; // No hardware installed, nothing to do } if ( is_trace ) { Serial.print(T("\r\nESP-01 Present")); } esp01_restart(); delay(ONE_SECOND); esp01_flush(); /* * There is an ESP-01 on the freETarget. We need to program it */ WIFI_SERIAL.print(T("ATE0\r\n")); // Turn off echo (don't use it) if ( (esp01_waitOK() == false) && is_trace ) { Serial.print(T("\r\nESP-01: Failed ATE0")); } WIFI_SERIAL.print(T("AT+RFPOWER=80\r\n")); // Set almost max power if ( (esp01_waitOK() == false) && ( is_trace ) ) { Serial.print(T("\r\nESP-01: Failed AT+RFPOWER=80")); } WIFI_SERIAL.print(T("AT+CWMODE_DEF=2\r\n")); // We want to be an access point if ( (esp01_waitOK() == false) && (is_trace) ) { Serial.print(T("\r\nESP-01: Failed AT+CWMODE_DEF=2")); } WIFI_SERIAL.print(T("AT+CWSAP_DEF=\"FET-")); WIFI_SERIAL.print(names[json_name_id]); WIFI_SERIAL.print(T("\",\"NA\",5,0\r\n")); if ( (esp01_waitOK() == false) && (is_trace) ) { Serial.print(T("\r\nESP-01: AT+CWSAP_DEF=\"FET-")); Serial.print(names[json_name_id]); Serial.print(T("\",\"NA\",5,0\r\n")); } WIFI_SERIAL.print(T("AT+CWDHCP_DEF=0,1\r\n")); // DHCP turned on if ( (esp01_waitOK() == false) && (is_trace) ) { Serial.print(T("\r\nESP-01: Failed AT+CWDHCP_DEF=0,1")); } WIFI_SERIAL.print(T("AT+CIPAP_DEF=\"192.168.10.9\",\"192.168.10.9\"\r\n")); // Set the freETarget IP to 192.168.10.9 if ( (esp01_waitOK() == false) && (is_trace) ) { Serial.print(T("\r\nESP-01: Failed AT+CIPAP_DEF=\"192.168.10.9\",\"192.168.10.9\"")); } WIFI_SERIAL.print(T("AT+CWDHCPS_DEF=1,2800,\"192.168.10.0\",\"192.168.10.8\"\r\n")); // Set the PC IP to 192.168.10.0. Lease Time 2800 minutes if ( (esp01_waitOK() == false) && (is_trace) ) { Serial.print(T("\r\nESP-01: Failed AT+CWDHCPS_DEF=1,2800,\"192.168.10.0\",\"192.168.10.8\"")); } WIFI_SERIAL.print(T("AT+CIPMUX=1\r\n")); // Allow a single connection if ( (esp01_waitOK() == false) && (is_trace) ) { Serial.print(T("\r\nESP-01: Failed AT+CIPMUX=1")); } WIFI_SERIAL.print(T("AT+CIPSERVER=1,1090\r\n")); // Turn on the server and listen on port 1090 if ( (esp01_waitOK() == false) && (is_trace) ) { Serial.print(T("\r\nESP-01: Failed AT+CIPSERVER=1,1090")); } WIFI_SERIAL.print(T("AT+CIPSTO=7000\r\n")); // Set the server time out if ( (esp01_waitOK() == false) && (is_trace) ) { Serial.print(T("\r\nESP-01: Failed AT+CIPSTO=7000")); } /* * All done, return */ if ( is_trace ) { Serial.print(T("\r\nESP-01 Initialization complete")); } return; } /*---------------------------------------------------------------- * * function: void esp01_restart * * brief: Take control of the ESP and issue a reset * * return: TRUE if the module acknowleges the command and restarts * *---------------------------------------------------------------- * * We don't know what state the ESP is in, so this function * isses +++AT to get contol of the device and reset it to * factory defaults. * *--------------------------------------------------------------*/ bool esp01_restart(void) { char ch; /* * Determine if the ESP-01 is attached to the Accessory Connector */ if (esp01_is_present() == false ) { return false; // No hardware installed, nothing to do } /* * Send out the break then restart the module */ WIFI_SERIAL.print(T("+++")); delay(ONE_SECOND); WIFI_SERIAL.print(T("AT+RST\r\n")); /* * All done, */ esp01_connect[0] = false; esp01_connect[1] = false; esp01_connect[2] = false; return true; } /*---------------------------------------------------------------- * * function: bool esp01_is_present * * brief: Determines if an ESP-01 is installed * * return: TRUE if the ESO-01 is installed * *---------------------------------------------------------------- * * The function outputs an AT<entere> to the auxilarry port and * waits to see if an OK is returned within one second. * * This function can only be executed once after a reset. After * that time, the device may be in pass through mode and will not * do anything with the AT command * *--------------------------------------------------------------*/ bool esp01_is_present(void) { static bool esp01_first = true; // Remember if we have results /* * If the function has been exectued once, return the old results */ if ( esp01_first == false ) { return esp01_present; } /* * Determine if the ESP-01 is attached to the Accessory Connector */ esp01_present = false; // Assume that the ESP-01 is not installed esp01_flush(); // Eat any garbage that might be on the port WIFI_SERIAL.print(T("AT\r\n")); // Send out an AT command to the port esp01_present = esp01_waitOK(); // and wait for the OK to come back /* * All done, return the esp-01 present state */ esp01_first = false; // Done it once. return esp01_present; } /*---------------------------------------------------------------- * * function: bool esp01_test * * brief: Tests to see if the WiFi responds to ATs * * return: Displayed on screen * *---------------------------------------------------------------- * * The function outputs an AT<entere> to the auxilarry port and * waits to see if an OK is returned within one second. * * This function can only be executed once after a reset. After * that time, the device may be in pass through mode and will not * do anything with the AT command * *--------------------------------------------------------------*/ #define LONG_TIME (1000000 * 30) void esp01_test(void) { char ch; // Character read from ESP-01 long unsigned int start; // Start time esp01_flush(); // Eat any garbage that might be on the port WIFI_SERIAL.print("+++"); delay(ONE_SECOND); WIFI_SERIAL.print("AT+RST\r\n"); Serial.print(T("\r\nSending AT\r\n")); WIFI_SERIAL.print("AT\r\n"); // Send out an AT command to the port start = micros(); while ( (micros() - start) < LONG_TIME ) { if ( WIFI_SERIAL.available() != 0 ) { ch = WIFI_SERIAL.read(); Serial.print(ch); } } /* * All done, return the esp-01 present state */ Serial.print(T("\r\nTest Over")); return; } /*---------------------------------------------------------------- * * function: void esp01_flush * * brief: Flush any characters waiting in the buffer * * return: None * *---------------------------------------------------------------- * * Just read the port and return when nothing is left * *--------------------------------------------------------------*/ static void esp01_flush(void) { while ( WIFI_SERIAL.available() != 0 ) { WIFI_SERIAL.read(); } /* * The buffer is empty, go home */ return; } /*---------------------------------------------------------------- * * function: bool esp01_waitOK() * * brief: Wait for the OK to come back * * return: FALSE if no OK came back * *---------------------------------------------------------------- * * Loop for a second to see if OK is returned. * * The state machine ensures that OK is parsed * *--------------------------------------------------------------*/ #define MAX_esp01_waitOK 1000000 // 1M microseconds #define GOT_NUTHN 0 // Decoding states #define GOT_O 1 static bool esp01_waitOK(void) { char ch; // Character from port unsigned int state; // OK decoding state long start; // Timer start start = micros(); // Remember the starting time state = GOT_NUTHN; // Start off empty /* * Loop for a second and see if OK comes back */ while ( (micros() - start) < MAX_esp01_waitOK ) { if ( WIFI_SERIAL.available() != 0 ) { ch = WIFI_SERIAL.read(); switch (state) { default: case GOT_NUTHN: if ( ch == 'O' ) // Got an O, wait for the K { state = GOT_O; } break; case GOT_O: if ( ch == 'K' ) // Got O then K { return true; // Done } else // Got O but no K { state = GOT_NUTHN; // Start over } break; } } } /* * Time ran out without getting an OK. */ return false; } /*---------------------------------------------------------------- * * function: char esp01_read() * * brief: Return a character from the Accessory port * * return: Next character waiting * *---------------------------------------------------------------- * * The function checks to see if an ESP-01 is attached to the * board. * * Not attached - Perform regular WIFI_SERIAL.read() * Attached - Take a character from the IP queue * *--------------------------------------------------------------*/ char esp01_read(void) { char ch; // Working character /* * Determine which source will be used to get the next character */ if ( esp01_is_present() == false ) { return WIFI_SERIAL.read(); // Just do a regular read from the aux port } /* * We have an ESP-01 attached, Get the character from the queue */ if ( esp01_in_ptr == esp01_out_ptr ) // Is the queue empty? { ch = -1; // Return an error } else { ch = esp01_in_queue[esp01_out_ptr]; // Get the character out of the queueu esp01_out_ptr++; // Bump up the output pointer esp01_out_ptr %= sizeof(esp01_in_queue);// and wrap around } /* * All done, return the next character */ return ch; } /*---------------------------------------------------------------- * * function: unsigned int esp01_available() * * brief: Determine ihow many characters are available * * return: Number of characters in the input queue * *---------------------------------------------------------------- * * The function checks to see if an ESP-01 is attached to the * board. * * Not attached - Perform regular WIFI_SERIAL.gavailable() * Attached - Return the queue size * *--------------------------------------------------------------*/ unsigned int esp01_available(void) { unsigned int x; // Working character /* * Determine which source will be used to get return the input size */ if ( esp01_is_present() == false ) { return WIFI_SERIAL.available(); // Just do a regular read fromthe aux port } /* * We have an ESP-01 attached, Figure out the bytes in the queueu */ if ( esp01_in_ptr < esp01_out_ptr ) // Have we wrapped around? { x = sizeof(esp01_in_queue) + esp01_in_ptr; // add in the size offset } else { x = esp01_in_ptr; } x -= esp01_out_ptr; // Subtract the output pointer /* * All done, return */ return x; } /*---------------------------------------------------------------- * * function: char esp01_send() * * brief: Send a string over the IP port * * return: TRUE if the channel is active * *---------------------------------------------------------------- * * The function checks to see if an ESP-01 is attached to the * board. * * Not attached - Do nothing * Attached - Output the control bytes to begin IP transmission * * The function operates on a bit of a kluge. The ESP-01 has a * command AT+CIPSENDEX which will transmit the next N bytes * over the IP channel. The ESP-01 will also stop collecting * bytes and send the data if a NULL is received. * * The function uses a state machine * * Not ready to send out characters * Filling the transmit buffer * Kicking out the transmit buffer. * * This lets the application fill the tranmsit buffer as * quickly as possible until the buffer is full. * *--------------------------------------------------------------*/ #define MAX_RETRY 10 // Allow for 10 attempts to start #define ESP_BUFFER 2048 // The ESP buffer size #define SEND_OFF 1 // The send function is off #define SEND_READY 2 // The send is ready to send #define SEND_NOW 3 // Send the buffer now #define SEND_BUSY 4 // The buffer is being sent. #define SEND_ERROR 5 // The send is in error, do nothing static unsigned int send_used[3] = {0, 0, 0}; // How much of the send buffer is used static unsigned int send_state[3] = {SEND_OFF, SEND_OFF, SEND_OFF}; // State of each channel static unsigned int miss_count = 0; bool esp01_send_ch // Send a character ( char ch, // Character to send int index // Which index (connection) to send on ) { char str[2]; str[0] = ch; str[1] = 0; esp01_send(str, index); } bool esp01_send ( char* str, // String to send int index // Which index (connection) to send on ) { long timer; // Timer start unsigned int retry_count; // Number of times to try again char AT_command[64]; // Place to store a string bool not_sent; // TRUE if still busy sending char ch; // Character read back /* * Determine if we actually have to do anything */ if ( (esp01_is_present() == false) // No ESP at all || ( esp01_connect[index] == false )) // No connection on this channel { send_used[index] = 0; return false; } /* * Loop here until the string has been output */ not_sent = true; while ( not_sent ) { switch ( send_state[index] ) { case SEND_OFF: // The ESP is not ready to send, for (retry_count = 0; retry_count != MAX_RETRY; retry_count++) { sprintf(AT_command, "AT+CIPSENDEX=%d,%d\r\n", index, ESP_BUFFER); // Start and lie that we will send 2K of data WIFI_SERIAL.print(AT_command); send_used[index] = 0; // The buffer is completely empty timer = micros(); // Remember the starting time while ( (micros() - timer) < MAX_esp01_waitOK ) // Wait for the > to come back within a second { if ( WIFI_SERIAL.available() != 0 ) // Something available? { ch = WIFI_SERIAL.read(); Serial.print(ch); if ( ch == '>' ) // Is it the prompt? { send_state[index] = SEND_READY; // Ready to send break; } } } if ( send_state[index] == SEND_READY ) { break; } WIFI_SERIAL.print(T("+++")); // Command not acted on Serial.print(T(" missed:")); Serial.print(str); Serial.print(T(":"));Serial.print(index); delay(ONE_SECOND + (ONE_SECOND/10)); // Go into AT command mode } if ( send_state[index] == SEND_READY ) { break; } send_state[index] = SEND_ERROR; break; case SEND_READY: // Ready to send a string if ( str == 0 ) { send_state[index] = SEND_NOW; // A null string starts transmission break; } if ( (send_used[index] + strlen(str)) >= ESP_BUFFER)// Is there space to send it? { send_state[index] = SEND_NOW; // And reset the AT command break; } WIFI_SERIAL.print(str); // Space left to send send_used[index] += strlen(str); // Keep track of how much is waiting to go not_sent = false; // Send and done break; case SEND_NOW: WIFI_SERIAL.print("\\0"); // The buffer is ready to send out. Kick it off send_state[index] = SEND_BUSY; // Wait for the buffer to be sent break; // case SEND_BUSY: // Wait for the buffer to be sent timer = micros(); // Remember the starting time while ( (micros() - timer) < MAX_esp01_waitOK ) // Wait for the OK to come back within a second { if ( WIFI_SERIAL.available() != 0 ) // Something available { ch = WIFI_SERIAL.read(); // (Make sure we only read on char at a time) if ( ch == 'K' ) // Is it OK? { send_state[index] = SEND_OFF; // Ready to next time return; } } } send_state[index] = SEND_OFF; // Ran out of time, nothing we can do to return; // Fix it. case SEND_ERROR: // An error occured. send_state[index] = SEND_OFF; // Go back to the off state not_sent = false; break; // And bail out } } /* * All done, return */ return true; } /*---------------------------------------------------------------- * * function: char esp01_receive() * * brief: Receive a string over the IP port * * return: Incoming characters saved to a queueu * *---------------------------------------------------------------- * * The ESP-01 receives incoming characters on the IP channel, * parses the frame, and informs the application of what * channel received data, the length, and the contents * * ex * * +IPD,0,1:b // Data comes in from the target * 0,CONNECT // The target connects to the PC * * As with any IP type communications, there is a disconnect * between what is sent and what is received. In many cases * the sent data may be broken up over several received frames * * This function is a state machine that parses the incoming * message and then buffers only the 'real' data so that it * can be extracted later on. * *--------------------------------------------------------------*/ #define WAIT_IDLE 0 // Wait for the + or channel,CONNECT to come along #define WAIT_MESSAGE 1 // Wait for the a message to come along #define WAIT_CONNECT 2 // The for the CONNECT message to appear #define WAIT_CHANNEL 3 // Throw away the channel information #define WAIT_SIZE 4 // Pull in the size buffer #define WAIT_DATA 5 // Pull in the rest of the buffer #define IS_UNKNOWN 0 // As yet the message is unknown #define IS_CONNECT 1 // Message appears to be CONNECT #define IS_CLOSED 2 // The message appears to be CLOSED #define IS_IPD 4 // The message appears to be IPD static char s_ipd[] = "IPD,"; // IPC message static char s_connect[] = "CONNECT\r\n"; // Connect message static char s_closed[] = "CLOSED\r\n"; // Disconnect message void esp01_receive(void) { char ch; // Working character static unsigned int state = WAIT_IDLE;// Receiver State static unsigned int count; // Expected number of characters static unsigned int i; // Itration counter static unsigned int channel; // Channel contained in CONNECT or CLOSED message static unsigned int message_type; // Mesages is one of CONNECT, CLOSED, or IPD /* * Determine if we actually have to do anything */ if ( esp01_is_present() == false ) { return; // Nope } /* * Loop here while we have characters waiting for us */ while ( WIFI_SERIAL.available() != 0 ) // Nothing is waiting for us { ch = WIFI_SERIAL.read(); // Pull in the next byte switch (state) // What do we do with it? { case WAIT_IDLE: // Stay here until we see a + or , if ( (ch == '+') || (ch == ',' ) )// Synchronized and ready for the next state { i = 0; message_type = IS_CONNECT + IS_CLOSED + IS_IPD; // Message could be anything state = WAIT_CONNECT; } else { channel = ch - '0'; // Nothing, pretend it is a CONNECT channel identifier (ex 0,CONNECT) } break; case WAIT_CONNECT: // If the next character is NOT if ( ch != s_connect[i] ) // from CONNECT { message_type &= ~IS_CONNECT; } if ( ch != s_closed[i] ) // from CLOSED { message_type &= ~IS_CLOSED; } if ( ch != s_ipd[i] ) // from IPD { message_type &= ~IS_IPD; } if ( message_type == IS_UNKNOWN ) // not from IPD { state = WAIT_IDLE; // then, go back to the idle state } i++; // Yes, wait for the next character if ( (message_type & IS_CONNECT) && (s_connect[i] == 0) ) // Reached the end of CONNECT? { esp01_connect[channel] = true;// Record the channel POST_version(PORT_AUX); // Send out the software version to keep the PC happy show_echo(0); // Send out the settings state = WAIT_IDLE; // and go back to waiting } if ( (message_type & IS_CLOSED) && (s_closed[i] == 0) ) // Reached the end of CLOSED? { esp01_connect[channel] = false;// No longer a valid channel state = WAIT_IDLE; // Go back to waiting } if ( (message_type & IS_IPD) && (s_ipd[i] == 0) ) // Reached the end of IPD? { state = WAIT_CHANNEL; // Go and pick up the channel number } break; case WAIT_CHANNEL: // Throw away the CHANNEL if ( ch == ',' ) // Don't do anything until you see a comma { state = WAIT_SIZE; count = 0; // Reset the count field } break; case WAIT_SIZE: // Scoop up the message size if ( ch == ':' ) // Stay here until you see a colin { state = WAIT_DATA; // Then jump to the next state } else { count *= 10; count += ch -'0'; // Accumulate the count } break; case WAIT_DATA: esp01_in_queue[esp01_in_ptr] = ch; // Save the data esp01_in_ptr++; // and bump up the pointer esp01_in_ptr %= sizeof(esp01_in_queue); count--; // One less to read if ( count == 0 ) // No more? { state = WAIT_IDLE; // Wait for the next message } break; } } /* * That's it for this call */ return; } /*---------------------------------------------------------------- * * function: bool esp01_connected() * * brief: Return the connection status * * return: TRUE if any channel is connected * *---------------------------------------------------------------- * * *--------------------------------------------------------------*/ bool esp01_connected(void) { return esp01_connect[0] || esp01_connect[1] || esp01_connect[2]; } <file_sep>/Software/Arduino/freETarget/gpio.h /* * Global functions */ void init_gpio(void); // Initialize the GPIO ports void arm_counters(void); // Make the board ready unsigned int is_running(void); // Return a bit mask of running sensors void set_LED(int state_RDY, int state_X, int state_y); // Manage the LEDs unsigned int read_DIP(void); // Read the DIP switch register unsigned int read_counter(unsigned int direction); void stop_counters(void); // Turn off the counter registers void trip_counters(void); bool read_in(unsigned int port); // Read the selected port void read_timers(void); // Read and return the counter registers void drive_paper(void); // Turn on the paper motor void enable_interrupt(unsigned int active); // Turn on the face strike interrupt if active void disable_interrupt(void); // Turn off the face strike interrupt unsigned int multifunction_switch(unsigned int new_state);// Handle the actions of the DIP Switch signal void output_to_all(char* s); // Multipurpose driver void char_to_all(char ch); // Output a single character /* * Port Definitions */ #define D0 37 // Byte Port bit locations #define D1 36 // #define D2 35 // #define D3 34 // #define D4 33 // #define D5 32 // #define D6 31 // #define D7 30 // #define NORTH_HI 50 // Address port but locations #define NORTH_LO 51 #define EAST_HI 48 #define EAST_LO 49 #define SOUTH_HI 43 // Address port but locations #define SOUTH_LO 47 #define WEST_HI 41 #define WEST_LO 42 #define RUN_NORTH 25 #define RUN_EAST 26 #define RUN_SOUTH 27 #define RUN_WEST 28 #define QUIET 29 #define RCLK 40 #define CLR_N 39 #define STOP_N 52 #define CLOCK_START 53 #define DIP_0 9 // #define DIP_1 10 #define DIP_2 11 #define DIP_3 12 /* * DIP Switch Use. */ // From DIP From Software #define CALIBRATE ((digitalRead(DIP_3) == 0) + 0) // 1 Go to Calibration Mode #define DIP_SW_A ((digitalRead(DIP_2) == 0) + 0) // 2 When CALIBRATE is asserted, use lower trip point #define CAL_LOW (DIP_SW_A) #define DIP_SW_B ((digitalRead(DIP_1) == 0) + 0) // 4 When CALIBRATE is asserted, use higher trip point #define CAL_HIGH (DIP_SW_B) #define VERBOSE_TRACE ((digitalRead(DIP_0) == 0) + 0) // 8 Show the verbose software trace #define CTS_U 7 #define RTS_U 6 #define LED_PWM 5 // PWM Port #define LED_RDY 4 #define LED_X 3 #define LED_Y 2 #define LON 1 // Turn the LED on #define LOF 0 // Turn the LED off #define LXX -1 // Leave the LED alone #define L(A, B, C) ((A) == '*'), ((B) == '*'), ((C) == '*') #define NORTH 0 #define EAST 1 #define SOUTH 2 #define WEST 3 #define TRIP_NORTH 0x01 #define TRIP_EAST 0x02 #define TRIP_SOUTH 0x04 #define TRIP_WEST 0x08 #define PAPER 18 // Paper advance drive active low (TX1) #define PAPER_ON 0 #define PAPER_OFF 1 #define PAPER_ON_300 1 #define PAPER_OFF_300 0 #define FACE_SENSOR 19 #define SPARE_1 22 #define PAPER_FEED 1 // DIP A/B used as a paper feed #define GPIO_IN 2 // DIP A/B used as a GPIO in #define GPIO_OUT 3 // DIP A/B used as a GPIO out #define PC_TEST 4 // DIP A/B used to trigger fake shot #define J10_1 VCC #define J10_2 14 // TX3 #define J10_3 15 // RX3 #define J10_4 19 // RX1 #define J10_5 18 // TX1 #define J10_6 GND #define EOF 0xFF <file_sep>/Software/Arduino/freETarget/nonvol.h #ifndef _NONVOL_H #define _NONVOL_H void factory_nonvol(bool new_serial_number); // Factory reset nonvol void init_nonvol(int v); // Reset to defaults void read_nonvol(void); // Read in the locations void gen_position(int v); // Reset the position values void dump_nonvol(int v); /* * NON Vol Storage */ #define NONVOL_INIT 0x0 #define NONVOL_SENSOR_DIA (NONVOL_INIT + sizeof(int) + 2) // Sensor diameter #define NONVOL_DIP_SWITCH (NONVOL_SENSOR_DIA + sizeof(double) + 2) // DIP switch setting #define NONVOL_PAPER_TIME (NONVOL_DIP_SWITCH + sizeof(int) + 2) // Paper advance time #define NONVOL_TEST_MODE (NONVOL_PAPER_TIME + sizeof(int) + 2) // Self stest #define NONVOL_CALIBRE_X10 (NONVOL_TEST_MODE + sizeof(int) + 2) // Pellet Calibre #define NONVOL_SENSOR_ANGLE (NONVOL_CALIBRE_X10 + sizeof(int) + 2) // Angular displacement of sensors #define NONVOL_NORTH_X (NONVOL_SENSOR_ANGLE + sizeof(int) + 2) // Offset applied to North sensor #define NONVOL_NORTH_Y (NONVOL_NORTH_X + sizeof(int) + 2) #define NONVOL_EAST_X (NONVOL_NORTH_Y + sizeof(int) + 2) // Offset applied to East sensor #define NONVOL_EAST_Y (NONVOL_EAST_X + sizeof(int) + 2) #define NONVOL_SOUTH_X (NONVOL_EAST_Y + sizeof(int) + 2) // Offset applied to South sensor #define NONVOL_SOUTH_Y (NONVOL_SOUTH_X + sizeof(int) + 2) #define NONVOL_WEST_X (NONVOL_SOUTH_Y + sizeof(int) + 2) // Offset applied to West sensor #define NONVOL_WEST_Y (NONVOL_WEST_X + sizeof(int) + 2) #define NONVOL_POWER_SAVE (NONVOL_WEST_Y + sizeof(int) + 2) // Power saver time #define NONVOL_NAME_ID (NONVOL_POWER_SAVE + sizeof(int) + 2) // Name Identifier #define NONVOL_1_RINGx10 (NONVOL_NAME_ID + sizeof(int) + 2) // Size of the 1 ring in mm #define NONVOL_LED_PWM (NONVOL_1_RINGx10 + sizeof(int) + 2) // LED PWM value #define NONVOL_SEND_MISS (NONVOL_LED_PWM + sizeof(int) + 2) // Send the MISS message when true #define NONVOL_SERIAL_NO (NONVOL_SEND_MISS + sizeof(int) + 2) // EIN #define NONVOL_STEP_COUNT (NONVOL_SERIAL_NO + sizeof(int) + 2) // Number of paper pulse steps #define NONVOL_MFS (NONVOL_STEP_COUNT + sizeof(int) + 2) // Multifunction switch operation #define NONVOL_STEP_TIME (NONVOL_MFS + sizeof(int) + 2) // Stepper motor pulse duration #define NONVOL_Z_OFFSET (NONVOL_STEP_TIME + sizeof(int) + 2) // Distance from sensor plane to paper plane #define NONVOL_PAPER_ECO (NONVOL_Z_OFFSET + sizeof(int) + 2) // Advance witness paper if the shot is less than paper_eco #define NONVOL_TARGET_TYPE (NONVOL_PAPER_ECO + sizeof(int) + 2) // Modify the target processing (0 == Regular single bull) #define NONVOL_TABATA_ENBL (NONVOL_TARGET_TYPE + sizeof(int) + 2) // Disable Tabata from the switches #define NONVOL_TABATA_ON (NONVOL_TABATA_ENBL + sizeof(int) + 2) // Time that the Tabata timer is on #define NONVOL_TABATA_REST (NONVOL_TABATA_ON + sizeof(int) + 2) // Time that the Tabata timer is OFF #define NONVOL_TABATA_CYCLES (NONVOL_TABATA_REST + sizeof(int) +2) // Number of cycles in an event #define NEXT_NONVOL ((NONVOL_TABATA_CYCLES + sizeof(int) + 2) - NONVOL_INIT) #define NONVOL_SIZE 4096 // 4K available #if (((45-13) * 4) > NONVOL_SIZE ) #error NEXT_NONVOL OUT OF NONVOL #endif #endif <file_sep>/Software/Arduino/freETarget/analog_io.ino /*------------------------------------------------------- * * analog_io.ino * * General purpose Analog driver * * ----------------------------------------------------*/ #include "freETarget.h" #include "Wire.h" /*---------------------------------------------------------------- * * function: init_analog() * * brief: Initialize the analog I/O * * return: None * *--------------------------------------------------------------*/ void init_analog_io(void) { pinMode(LED_PWM, OUTPUT); Wire.begin(); /* * All done, begin the program */ return; } /*---------------------------------------------------------------- * * function: set_LED_PWM() * function: set_LED_PWM_now() * * brief: Program the PWM value * * return: None * *---------------------------------------------------------------- * * json_LED_PWM is a number 0-100 % It must be scaled 0-255 * * The function ramps the level between the current and desired * *--------------------------------------------------------------*/ static unsigned int old_LED_percent = 0; void set_LED_PWM_now ( int new_LED_percent // Desired LED level (0-100%) ) { if ( new_LED_percent == old_LED_percent ) { return; } if ( is_trace ) { Serial.print(T("\r\nnew_LED_percent:")); Serial.print(new_LED_percent); Serial.print(T(" old_LED_percent:")); Serial.print(old_LED_percent); } old_LED_percent = new_LED_percent; analogWrite(LED_PWM, old_LED_percent * 256 / 100); // Write the value out return; } void set_LED_PWM // Theatre lighting ( int new_LED_percent // Desired LED level (0-100%) ) { if ( new_LED_percent == old_LED_percent ) { return; } if ( is_trace ) { Serial.print(T("\r\nnew_LED_percent:")); Serial.print(new_LED_percent); Serial.print(T(" old_LED_percent:")); Serial.print(old_LED_percent); } while ( new_LED_percent != old_LED_percent ) // Change in the brightness level? { analogWrite(LED_PWM, old_LED_percent * 256 / 100); // Write the value out if ( new_LED_percent < old_LED_percent ) { old_LED_percent--; // Ramp the value down } else { old_LED_percent++; // Ramp the value up } delay(ONE_SECOND/50); // Worst case, take 2 seconds to get there } /* * All done, begin the program */ if ( new_LED_percent == 0 ) { digitalWrite(LED_PWM, 0); } return; } /*---------------------------------------------------------------- * * function: read_feedback(void) * * brief: return the reference voltage * * return: ADC value of the reference voltage * *--------------------------------------------------------------*/ unsigned int read_reference(void) { return analogRead(V_REFERENCE); } /*---------------------------------------------------------------- * * function: revision(void) * * brief: Return the board revision * * return: Board revision level * *-------------------------------------------------------------- * * Read the analog value from the resistor divider, keep only * the top 4 bits, and return the version number. * * The analog input is a number 0-1024 which is banded and * used to look up a table of revision numbers. * * To accomodate unknown hardware builds, if the revision is * undefined (< 100) then the last 'good' revision is returned * *--------------------------------------------------------------*/ // 0 1 2 3 4 5 6 7 8 9 A B C D E F const static unsigned int version[] = {REV_210, 1, 2, 3, REV_300, 5, 6, REV_220, 8, 9, 10, REV_310, 12, 13, 14, 15}; unsigned int revision(void) { unsigned int revision; /* * Read the resistors and determine the board revision */ revision = version[analogRead(ANALOG_VERSION) * 16 / 1024]; /* * Fake the revision if it is undefined */ if ( revision <= REV_100 ) { revision = REV_300; } /* * Nothing more to do, return the board revision */ return revision; } /*---------------------------------------------------------------- * * function: max_analog * * brief: Return the value of the largest analog input * * return: Largest analog voltage from the sensor channels * *--------------------------------------------------------------*/ uint16_t max_analog(void) { uint16_t return_value; return_value = analogRead(NORTH_ANA); if ( analogRead(EAST_ANA) > return_value ) return_value = analogRead(EAST_ANA); if ( analogRead(SOUTH_ANA) > return_value ) return_value = analogRead(SOUTH_ANA); if ( analogRead(WEST_ANA) > return_value ) return_value = analogRead(WEST_ANA); return return_value; } /*---------------------------------------------------------------- * * funciton: temperature_C() * * brief: Read the temperature sensor and return temperature in degrees C * *---------------------------------------------------------------- * * See TI Documentation for LM75 * *--------------------------------------------------------------*/ #define RTD_SCALE (0.5) // 1/2C / LSB double temperature_C(void) { double return_value; int raw; // Allow for negative temperatures int i; raw = 0xffff; /* * Point to the temperature register */ Wire.beginTransmission(TEMP_IC); Wire.write(0), Wire.endTransmission(); /* * Read in the temperature register */ Wire.requestFrom(TEMP_IC, 2); raw = Wire.read(); raw <<= 8; raw += Wire.read(); raw >>= 7; if ( raw & 0x0100 ) { raw |= 0xFF00; // Sign extend } /* * Return the temperature in C */ return_value = (double)(raw) * RTD_SCALE ; #if (SAMPLE_CALCULATIONS ) return_value = 23.0; #endif return return_value; } <file_sep>/Software/Arduino/freETarget/freETarget.h /*---------------------------------------------------------------- * * freETarget.h * * Software to run the Air-Rifle / Small Bore Electronic Target * *---------------------------------------------------------------- * * */ #ifndef _FREETARGET_H #define _FREETARGET_H #include "esp-01.h" #include "json.h" #define SOFTWARE_VERSION "\"3.05.3 November 11, 2021\"" #define REV_100 100 #define REV_210 210 #define REV_220 220 #define REV_290 290 #define REV_300 300 #define REV_310 310 #define INIT_DONE 0xabcd // Initialization complete signature #define T(s) F(s) // Move text string to the flash segment /* * Three way Serial Port */ #define SAMPLE_CALCULATIONS false // Trace the COUNTER values #define AUX_SERIAL Serial3 // Auxilary Connector #define WIFI_SERIAL Serial3 // WiFi Port #define DISPLAY_SERIAL Serial2 // Serial port for slave display char GET (void) { if ( Serial.available() ) { return Serial.read(); } if ( esp01_available() ) { return esp01_read(); } if ( DISPLAY_SERIAL.available() ) { return DISPLAY_SERIAL.read(); } return 0; } #define AVAILABLE ( Serial.available() | esp01_available() | DISPLAY_SERIAL.available() ) #define PORT_SERIAL 1 #define PORT_AUX 2 #define PORT_DISPLAY 4 #define PORT_ALL (PORT_SERIAL + PORT_AUX + PORT_DISPLAY) /* * Oscillator Features */ #define OSCILLATOR_MHZ 8.0 // 8000 cycles in 1 ms #define CLOCK_PERIOD (1.0/OSCILLATOR_MHZ) // Seconds per bit #define ONE_SECOND 1000 // 1000 ms delay #define SHOT_TIME ((int)(json_sensor_dia / 0.33)) // Worst case delay Sensor diameter / speed of sound) #define HI(x) (((x) >> 8 ) & 0x00ff) // High nibble #define LO(x) ((x) & 0x00ff) // Low nibble #define HI10(x) (((x) / 10 ) % 10) // High digit #define LO10(x) ((x) % 10) // Low digit #define N 0 #define E 1 #define S 2 #define W 3 struct record { unsigned int shot; // Current shot number double x; // X location of shot double y; // Y location of shot long shot_time; // Shot time after tabata start }; typedef struct record this_shot; struct GPIO { byte port; char* gpio_name; byte in_or_out; byte value; }; typedef struct GPIO GPIO_t; extern const GPIO init_table[]; extern double s_of_sound; extern const char* names[]; extern const char to_hex[]; extern bool face_strike; extern bool is_trace; // True if tracing is enabled extern const char nesw[]; // Cardinal Points /* * Factory settings via Arduino monitor */ /* #define FACTORY {"NAME_ID":1, "TRGT_1_RINGx10":1550, "ECHO":2} #define FACTORY_BOSS {"NAME_ID":1, "TRGT_1_RINGx10":1550, "ECHO":2} #define FACTORY_MINION {"NAME_ID":2, "TRGT_1_RINGx10":1550, "ECHO":2} #define SERIAL_NUMBER {"NAME_ID":1, "TRGT_1_RINGx10":1550, "SN":1234, "ECHO":2} #define LONG_TEST {"SENSOR":231, "Z_OFFSET":5, "STEP_TIME":50, "STEP_COUNT":0, "NORTH_X":0, "NORTH_Y":0, "EAST_X":0, "EAST_Y":0, "SOUTH_X":0, "SOUTH_Y":0, "WEST_X":0, "WEST_Y":0, "LED_BRIGHT":50, "NAME_ID":0, "ECHO":9} */ #endif <file_sep>/Software/Arduino/freETarget/nonvol.ino /*------------------------------------------------------- * * nonvol.ino * * Nonvol storage managment * * ----------------------------------------------------*/ /*---------------------------------------------------------------- * * function: factory_nonvol * * brief: Initialize the NONVOL back to factory settings * * return: None *--------------------------------------------------------------- * * If the init_nonvol location is not set to INIT_DONE then * initilze the memory * *------------------------------------------------------------*/ void factory_nonvol ( bool new_serial_number ) { unsigned int nonvol_init; // Initialization token int serial_number; // Board serial number char ch; unsigned int x; // Temporary Value double dx; // Temporarty Value /* * Fill up all of memory with a known (bogus) value */ Serial.print(T("\r\nReset to factory defaults. This may take a while\r\n")); ch = 0xAB; for ( i=0; i != NONVOL_SIZE; i++) { if ( (i < NONVOL_SERIAL_NO) || (i >= NONVOL_SERIAL_NO + sizeof(int) + 2) ) // Bypass the serial number { EEPROM.put(i, ch); // Fill up with a bogus value if ( (i % 64) == 0 ) { Serial.print(T(".")); } } } gen_position(0); /* * Use the JSON table to initialize the local variables */ i=0; while ( JSON[i].token != 0 ) { switch ( JSON[i].convert ) { case IS_VOID: // Variable does not contain anything case IS_FIXED: // Variable cannot be overwritten break; case IS_INT16: x = JSON[i].init_value; // Read in the value Serial.print(T("\r\n")); Serial.print(JSON[i].token); Serial.print(T(" ")); Serial.print(x); EEPROM.put(JSON[i].non_vol, x); // Read in the value break; case IS_FLOAT: case IS_DOUBLE: dx = (double)JSON[i].init_value; Serial.print(T("\r\n")); Serial.print(JSON[i].token); Serial.print(T(" ")); Serial.print(dx); EEPROM.put(JSON[i].non_vol, dx); // Read in the value break; } i++; } Serial.print(T("\r\nDone\r\n")); /* * Ask for the serial number. Exit when you get ! */ if ( new_serial_number ) { ch = 0; serial_number = 0; while ( Serial.available() ) // Eat any pending junk { Serial.read(); } Serial.print(T("\r\nSerial Number? (ex 223! or x))")); while (i) { if ( Serial.available() != 0 ) { ch = Serial.read(); if ( ch == '!' ) { EEPROM.put(NONVOL_SERIAL_NO, serial_number); Serial.print(T(" Setting Serial Number to: ")); Serial.print(serial_number); break; } if ( ch == 'x' ) { break; } serial_number *= 10; serial_number += ch - '0'; } } } /* * Initialization complete. Mark the init done */ nonvol_init = INIT_DONE; EEPROM.put(NONVOL_INIT, nonvol_init); /* * Read the NONVOL and print the results */ read_nonvol(); // Read back the new values show_echo(0); // Display these settings set_trip_point(0); // And stay forever in the set trip mode /* * All done, return */ return; } /*---------------------------------------------------------------- * * function: init_nonvol * * brief: Initialize the NONVOL back to factory settings * * return: None *--------------------------------------------------------------- * * init_nonvol requires an arguement == 1234 before the * initialization command will be executed. * * The variable NONVOL_INIT is corrupted. and the values * copied out of the JSON[] table. If the serial number has * not been initialized before, the user is prompted to enter * a serial number. * * The function then continues to display the current trip * point value. * *------------------------------------------------------------*/ void init_nonvol(int v) { unsigned int nonvol_init; // Initialization token int serial_number; // Board serial number char ch; unsigned int x; // Temporary Value double dx; // Temporarty Value /* * Ensure that the user wants to init the unit */ if ( v != 1234 ) { Serial.print(T("\r\nUse {\"INIT\":1234}\r\n")); return; } factory_nonvol(false); /* * Read the NONVOL and print the results */ read_nonvol(); // Read back the new values show_echo(0); // Display these settings /* * All done, return */ return; } /*---------------------------------------------------------------- * * funciton: read_nonvol * * brief: Read nonvol and set up variables * * return: Nonvol values copied to RAM * *--------------------------------------------------------------- * * Read the nonvol into RAM. * * If the results is uninitalized then force the factory default. * Then check for out of bounds and reset those values * *------------------------------------------------------------*/ void read_nonvol(void) { unsigned int nonvol_init; unsigned int i; // Iteration Counter unsigned int x; // 16 bit number double dx; // Floating point number if ( is_trace ) { Serial.print(T("\r\nReading NONVOL")); } /* * Read the nonvol marker and if uninitialized then set up values */ EEPROM.get(NONVOL_INIT, nonvol_init); if ( nonvol_init != INIT_DONE) // EEPROM never programmed { factory_nonvol(true); // Force in good values } EEPROM.get(NONVOL_SERIAL_NO, nonvol_init); if ( nonvol_init == (-1) ) // Serial Number never programmed { factory_nonvol(true); // Force in good values } /* * Use the JSON table to initialize the local variables */ i=0; while ( JSON[i].token != 0 ) { if ( (JSON[i].value != 0) || (JSON[i].d_value != 0) ) // There is a value stored in memory { switch ( JSON[i].convert ) { case IS_VOID: break; case IS_INT16: case IS_FIXED: EEPROM.get(JSON[i].non_vol, x); // Read in the value if ( x == 0xABAB ) // Is it uninitialized? { x = JSON[i].init_value; // Yes, overwrite with the default EEPROM.put(JSON[i].non_vol, x); } *JSON[i].value = x; break; case IS_FLOAT: case IS_DOUBLE: EEPROM.get(JSON[i].non_vol, dx); // Read in the value *JSON[i].d_value = dx; break; } } i++; } /* * Go through and verify that the special cases are taken care of */ EEPROM.get(NONVOL_TABATA_ENBL, x); // Override the Tabata if ( x == 0 ) { json_tabata_on = 0; // and turn it off } /* * All done, begin the program */ return; } /*---------------------------------------------------------------- * * function: gen_postion * * brief: Generate new position varibles based on new sensor diameter * * return: Position values stored in NONVOL * *--------------------------------------------------------------- * * This function resets the offsets to 0 whenever a new * sensor diameter is entered. * *------------------------------------------------------------*/ void gen_position(int v) { /* * Work out the geometry of the sensors */ json_north_x = 0; json_north_y = 0; json_east_x = 0; json_east_y = 0; json_south_x = 0; json_south_y = 0; json_west_x = 0; json_west_y = 0; /* * Save to persistent storage */ EEPROM.put(NONVOL_NORTH_X, json_north_x); EEPROM.put(NONVOL_NORTH_Y, json_north_y); EEPROM.put(NONVOL_EAST_X, json_east_x); EEPROM.put(NONVOL_EAST_Y, json_east_y); EEPROM.put(NONVOL_SOUTH_X, json_south_x); EEPROM.put(NONVOL_SOUTH_Y, json_south_y); EEPROM.put(NONVOL_WEST_X, json_west_x); EEPROM.put(NONVOL_WEST_Y, json_west_y); /* * All done, return */ return; } /*---------------------------------------------------------------- * * function: dump_nonvol * * brief: Core dumo the nonvol memory * * return: Nothing * *--------------------------------------------------------------- * * This function resets the offsets to 0 whenever a new * sensor diameter is entered. * *------------------------------------------------------------*/ void print_hex(unsigned int x) { int i; i = (x >> 4) & 0x0f; Serial.print(to_hex[i]); i = x & 0x0f; Serial.print(to_hex[i]); return; } void dump_nonvol(void) { int i; char x; char line[128]; /* * Loop and print out the nonvol */ for (i=0; i != NONVOL_SIZE; i++) { if ( (i % 16) == 0 ) { sprintf(line, "\r\n%04X: ", i); Serial.print(line); } EEPROM.get(i, x); print_hex(x); if ( ((i+1) % 2) == 0 ) { Serial.print(" "); } } Serial.print("\n\r"); /* * All done, return */ return; } <file_sep>/Software/Arduino/freETarget/esp-01.h /*---------------------------------------------------------------- * * esp-01.h * * WiFi Driver for esp-01 * *---------------------------------------------------------------*/ #ifndef _ESP_01_H_ #define _ESP_01_H_ /* * Function Prototypes */ void esp01_init(void); // Initialize the device bool esp01_restart(void); // Take control and reset the device char esp01_read(void); // Read a character from the queuue unsigned int esp01_available(void); // Return the number of available characters bool esp01_send(char* str, int index); // Send out a string void esp01_receive(void); // Take care of receiving characters from the IP channel bool esp01_connected(void); // TRUE if the channel is connected. bool esp01_is_present(void); // TRUE if an ESP-01 was found void esp01_test(void); // Diagnostic self test /* * Definitions */ #define MAX_CONNECTIONS 3 // Allow up to 3 connections #endif <file_sep>/Software/Arduino/freETarget/json.h /* * Global functions */ #ifndef _JSON_H_ #define _JSON_H_ typedef struct { char* token; // JSON token string, ex "RADIUS": int* value; // Where value is stored double* d_value; // Where value is stored byte convert; // Conversion type void (*f)(int x); // Function to execute with message unsigned int non_vol; // Storage in NON-VOL unsigned int init_value; // Initial Value } json_message; #define IS_VOID 0 // Value is a void #define IS_INT16 1 // Value is a 16 bit int #define IS_FLOAT 2 // Value is a floating point number #define IS_DOUBLE 3 // Value is a double #define IS_FIXED 4 // The value cannot be changed bool read_JSON(void); // Scan the serial port looking for JSON input void show_echo(int v); // Display the settings extern int json_dip_switch; // DIP switch overwritten by JSON message extern double json_sensor_dia; // Sensor radius overwitten by JSON message extern int json_sensor_angle; // Angle sensors are rotated through extern int json_paper_time; // Time to turn on paper backer motor extern int json_echo; // Value to ech extern int json_calibre_x10; // Pellet Calibre extern int json_north_x; // North Adjustment extern int json_north_y; extern int json_east_x; // East Adjustment extern int json_east_y; extern int json_south_x; // South Adjustment extern int json_south_y; extern int json_west_x; // WestAdjustment extern int json_west_y; extern int json_spare_1; // Not used extern int json_name_id; // Name Identifier extern int json_1_ring_x10; // Size of 1 ring in mmx10 extern int json_LED_PWM; // PWM Setting (%) extern int json_power_save; // How long to run target before turning off LEDs extern int json_send_miss; // Sent the miss message when TRUE extern int json_serial_number; // EIN extern int json_step_count; // Number of times paper motor is stepped extern int json_step_time; // Duration of step pulse extern int json_multifunction; // Multifunction switch operation extern int json_z_offset; // Distance between paper and sensor plane (1mm / LSB) extern int json_paper_eco; // Do not advance witness paper if shot is greater than json_paper_eco extern int json_target_type; // Modify the location based on a target type (0 == regular 1 bull target) #define FIVE_BULL_AIR_RIFLE 1 // Target is a five bull air rifle target extern int json_tabata_on; // Tabata ON timer extern int json_tabata_rest; // Tabata OFF timer extern int json_tabata_cycles; // Number of Tabata cycles #endif _JSON_H_ <file_sep>/Software/Arduino/freETarget/gpio.ino /*------------------------------------------------------- * * gpio.ino * * General purpose GPIO driver * * ----------------------------------------------------*/ const GPIO init_table[] = { {D0, "\"D0\":", INPUT_PULLUP, 0 }, {D1, "\"D1\":", INPUT_PULLUP, 0 }, {D2, "\"D2\":", INPUT_PULLUP, 0 }, {D3, "\"D3\":", INPUT_PULLUP, 0 }, {D4, "\"D4\":", INPUT_PULLUP, 0 }, {D5, "\"D5\":", INPUT_PULLUP, 0 }, {D6, "\"D6\":", INPUT_PULLUP, 0 }, {NORTH_HI, "\"N_HI\":", OUTPUT, 1}, {NORTH_LO, "\"N_LO\":", OUTPUT, 1}, {EAST_HI, "\"E_HI\":", OUTPUT, 1}, {EAST_LO, "\"E_LO\":", OUTPUT, 1}, {SOUTH_HI, "\"S_HI\":", OUTPUT, 1}, {SOUTH_LO, "\"S_LO\":", OUTPUT, 1}, {WEST_HI, "\"W_HI\":", OUTPUT, 1}, {WEST_LO, "\"W_LO\":", OUTPUT, 1}, {RUN_NORTH, "\"RUN_N\":", INPUT_PULLUP, 0}, {RUN_EAST, "\"RUN_E\":", INPUT_PULLUP, 0}, {RUN_SOUTH, "\"RUN_S\":", INPUT_PULLUP, 0}, {RUN_WEST, "\"RUN_W\":", INPUT_PULLUP, 0}, {QUIET, "\"QUIET\":", OUTPUT, 1}, {RCLK, "\"RCLK\":", OUTPUT, 1}, {CLR_N, "\"CLR_N\":", OUTPUT, 1}, {STOP_N, "\"STOP_N\":", OUTPUT, 1}, {CLOCK_START, "\"CLK_ST\":", OUTPUT, 0}, {DIP_0, "\"DIP_0\":", INPUT_PULLUP, 0}, {DIP_1, "\"DIP_1\":", INPUT_PULLUP, 0}, {DIP_2, "\"DIP_2\":", INPUT_PULLUP, 0}, {DIP_3, "\"DIP_3\":", INPUT_PULLUP, 0}, {LED_RDY, "\"RDY\":", OUTPUT, 1}, {LED_X, "\"X\":", OUTPUT, 1}, {LED_Y, "\"Y\":", OUTPUT, 1}, {LED_PWM, "\"LED_PWM\":", OUTPUT, 0}, {RTS_U, "\"RTS_U\":", OUTPUT, 1}, {CTS_U, "\"CTS_U\":", INPUT_PULLUP, 0}, {FACE_SENSOR, "\"FACE\":", INPUT_PULLUP, 0}, {PAPER, "\"PAPER\":", OUTPUT, 1}, // 18-Paper drive active low {EOF, EOF, EOF, EOF} }; void face_ISR(void); static void paper_on_off(bool on); // Turn the motor on or off static bool fcn_DIP_SW_A(void); // Function to read DIP_SW_A static bool fcn_DIP_SW_B(void); // Function to read DIP_SW_B static void sw_state (bool* (fcn_state)(void), unsigned long* which_timer, void* (fcn_action)(void)); // Do something with the switches static void send_fake_score(void); // Send a fake score to the PC /*----------------------------------------------------- * * function: gpio_init * * brief: Initalize the various GPIO ports * * return: None * *----------------------------------------------------- * * The GPIO programming is held in a stgrucutre and * copied out to the hardware on power up. *-----------------------------------------------------*/ void init_gpio(void) { int i; i = 0; while (init_table[i].port != 0xff ) { pinMode(init_table[i].port, init_table[i].in_or_out); if ( init_table[i].in_or_out == OUTPUT ) { digitalWrite(init_table[i].port, init_table[i].value); } i++; } disable_interrupt(); set_LED_PWM(0); // Turn off the illumination for now /* * Special case of the witness paper */ pinMode(PAPER, OUTPUT); paper_on_off(false); // Turn it off multifunction_init(); // Program the multifunction switch /* * All done, return */ return; } /*----------------------------------------------------- * * function: read_port * * brief: Read 8 bits from a port * * return: Eight bits returned from the port * *----------------------------------------------------- * * To make the byte I/O platform independent, this * function reads the bits in one-at-a-time and collates * them into a single byte for return * *-----------------------------------------------------*/ int port_list[] = {D7, D6, D5, D4, D3, D2, D1, D0}; unsigned int read_port(void) { int i; int return_value = 0; /* * Loop and read in all of the bits */ for (i=0; i != 8; i++) { return_value <<= 1; return_value |= digitalRead(port_list[i]) & 1; } /* * Return the result */ return (return_value & 0x00ff); } /*----------------------------------------------------- * * function: read_counter * * brief: Read specified counter register * * return: 16 bit counter register * *----------------------------------------------------- * * Set the address bits and read in 16 bits * *-----------------------------------------------------*/ int direction_register[] = {NORTH_HI, NORTH_LO, EAST_HI, EAST_LO, SOUTH_HI, SOUTH_LO, WEST_HI, WEST_LO}; unsigned int read_counter ( unsigned int direction // What direction are we reading? ) { int i; unsigned int return_value_LO, return_value_HI; // 16 bit port value /* * Reset all of the address bits */ for (i=0; i != 8; i++) { digitalWrite(direction_register[i], 1); } digitalWrite(RCLK, 1); // Prepare to read /* * Set the direction line to low */ digitalWrite(direction_register[direction * 2 + 0], 0); return_value_HI = read_port(); digitalWrite(direction_register[direction * 2 + 0], 1); digitalWrite(direction_register[direction * 2 + 1], 0); return_value_LO = read_port(); digitalWrite(direction_register[direction * 2 + 1], 1); /* * All done, return */ return (return_value_HI << 8) + return_value_LO; } /*----------------------------------------------------- * * function: is_running * * brief: Determine if the clocks are running * * return: TRUE if any of the counters are running * *----------------------------------------------------- * * Read in the running registers, and return a 1 for every * register that is running. * *-----------------------------------------------------*/ unsigned int is_running (void) { unsigned int i; i = 0; if ( digitalRead(RUN_NORTH) == 1 ) i += 1; if ( digitalRead(RUN_EAST) == 1 ) i += 2; if ( digitalRead(RUN_SOUTH) == 1 ) i += 4; if ( digitalRead(RUN_WEST) == 1 ) i += 8; /* * Return the running mask */ return i; } /*----------------------------------------------------- * * function: arm_counters * * brief: Strobe the control lines to start a new cycle * * return: NONE * *----------------------------------------------------- * * The counters are armed by * * Stopping the current cycle * Taking the counters out of read * Making sure the oscillator is running * Clearing the counters * Enabling the counters to run again * *-----------------------------------------------------*/ void arm_counters(void) { digitalWrite(CLOCK_START, 0); // Make sure Clock start is OFF digitalWrite(STOP_N, 0); // Cycle the stop just to make sure digitalWrite(RCLK, 0); // Set READ CLOCK to LOW digitalWrite(QUIET, 1); // Arm the counter digitalWrite(CLR_N, 0); // Reset the counters digitalWrite(CLR_N, 1); // Remove the counter reset digitalWrite(STOP_N, 1); // Let the counters run return; } /* * Stop the oscillator */ void stop_counters(void) { digitalWrite(STOP_N,0); // Stop the counters digitalWrite(QUIET, 0); // Kill the oscillator return; } /* * Trip the counters for a self test */ void trip_counters(void) { digitalWrite(CLOCK_START, 0); digitalWrite(CLOCK_START, 1); // Trigger the clocks from the D input of the FF digitalWrite(CLOCK_START, 0); return; } /*----------------------------------------------------- * * function: enable_interrupt * function: disable_interrupt * * brief: Turn on the face interrupt * * return: NONE * *----------------------------------------------------- * * If send_miss is turned on, then enable the * interrutps. Enable interrupts works by attaching an * interrupt * *-----------------------------------------------------*/ void enable_interrupt(unsigned int active) { if ( active ) // Only enable if send_miss is turned on { if ( revision() >= REV_300 ) { attachInterrupt(digitalPinToInterrupt(FACE_SENSOR), face_ISR, CHANGE); } } else // Otherwise turn it off { disable_interrupt(); } return; } void disable_interrupt(void) { if ( revision() >= REV_300 ) { detachInterrupt(digitalPinToInterrupt(FACE_SENSOR)); } return; } /*----------------------------------------------------- * * function: read_DIP * * brief: READ the jumper block setting * * return: TRUE for every position with a jumper installed * *----------------------------------------------------- * * The DIP register is read and formed into a word. * The word is complimented to return a 1 for every * jumper that is installed. * * OR in the json_dip_switch to allow remote testing * OR in 0xF0 to allow for compile time testing *-----------------------------------------------------*/ unsigned int read_DIP(void) { unsigned int return_value; if ( revision() < REV_300 ) // The silkscreen was reversed in Version 3.0 oops { return_value = (~((digitalRead(DIP_0) << 0) + (digitalRead(DIP_1) << 1) + (digitalRead(DIP_2) << 2) + (digitalRead(DIP_3) << 3))) & 0x0F; // DIP Switch } else { return_value = (~((digitalRead(DIP_3) << 0) + (digitalRead(DIP_2) << 1) + (digitalRead(DIP_1) << 2) + (digitalRead(DIP_0) << 3))) & 0x0F; // DIP Switch } return_value |= json_dip_switch; // JSON message return_value |= 0xF0; // COMPILE TIME return return_value; } /*----------------------------------------------------- * * function: set_LED * * brief: Set the state of all the LEDs * * return: None * *----------------------------------------------------- * * The state of the LEDs can be turned on or off * * -1 Leave alone * 0 Turn LED off * 1 Turn LED on * *-----------------------------------------------------*/ void set_LED ( int state_RDY, // State of the Rdy LED int state_X, // State of the X LED int state_Y // State of the Y LED ) { if ( state_RDY >= 0 ) { digitalWrite(LED_RDY, state_RDY == 0 ); } if ( state_X >= 0 ) { digitalWrite(LED_X, state_X == 0); } if ( state_Y >= 0 ) { digitalWrite(LED_Y, state_Y == 0); } return; } /* * HAL Discrete IN */ bool read_in(unsigned int port) { return digitalRead(port); } /*----------------------------------------------------- * * function: read_timers * * brief: Read the timer registers * * return: All four timer registers read and stored * *----------------------------------------------------- * * Force read each of the timers * *-----------------------------------------------------*/ void read_timers(void) { timer_value[N] = read_counter(N); timer_value[E] = read_counter(E); timer_value[S] = read_counter(S); timer_value[W] = read_counter(W); return; } /*----------------------------------------------------- * * function: drive_paper * * brief: Turn on the witness paper motor for json_paper_time * * return: None * *----------------------------------------------------- * * The function turns on the motor for the specified * time. The motor is cycled json_paper_step times * to drive a stepper motor using the same circuit. * * Use an A4988 to drive te stepper in place of a DC * motor * * There is a hardare change between Version 2.2 which * used a transistor and 3.0 that uses a FET. * The driving circuit is reversed in the two boards. * * DC Motor * Step Count = 0 * Step Time = 0 * Paper Time = Motor ON time * * Stepper * Paper Time = 0 * Step Count = X * Step Time = Step On time * *-----------------------------------------------------*/ void drive_paper(void) { unsigned int i, j, k; // Iteration Counters unsigned int s_count, s_time; /* * Set up the count or times based on whether a DC or stepper motor is used */ s_time = json_paper_time; // On time. if ( json_step_time != 0 ) // Non-zero means it's a stepper motor { s_time = json_step_time; // the one we use } s_count = 1; // Default to one cycle (DC or Stepper Motor) if ( json_step_count != 0 ) // Non-zero means it's a stepper motor { s_count = json_step_count; // the one we use } if ( s_time == 0 ) // Nothing to do if the time is zero. { return; } if ( is_trace ) { Serial.print(T("\r\nAdvancing paper ")); } /* * Drive the motor on and off for the number of cycles * at duration */ for (i=0; i != s_count; i++) // Number of steps { paper_on_off(true); // Turn the motor on if ( is_trace ) { Serial.print(T("On ")); Serial.print(s_time); } delay(PAPER_STEP * s_time); // in 10ms increments paper_on_off(false); // Turn the motor off if ( is_trace ) { Serial.print(T(" Off ")); } delay(PAPER_STEP); // Let the A4988 catch ujp } /* * All done, return */ return; } /*----------------------------------------------------- * * function: paper_on_off * * brief: Turn the withness paper motor on or off * * return: None * *----------------------------------------------------- * * The witness paper motor changed polarity between 2.2 * and Version 3.0. * * This function reads the board revision and controls * the FET accordingly * *-----------------------------------------------------*/ static void paper_on_off // Function to turn the motor on and off ( bool on // on == true, turn on motor drive ) { if ( on == true ) { if ( revision() < REV_300 ) // Rev 3.0 changed the motor sense { digitalWrite(PAPER, PAPER_ON); // Turn it on } else { digitalWrite(PAPER, PAPER_ON_300); // } } else { if ( revision() < REV_300 ) // Rev 3.0 changed the motor sense { digitalWrite(PAPER, PAPER_OFF); // Turn it off } else { digitalWrite(PAPER, PAPER_OFF_300); // } } /* * No more, return */ return; } /*----------------------------------------------------- * * function: face_ISR * * brief: Face Strike Interrupt Service Routint * * return: None * *----------------------------------------------------- * * Sensor #5 is attached to the digital input #19 and * is used to generate an interrrupt whenever a face * strike has been detected. * * The ISR simply counts the number of cycles. Anything * above 0 is an indication that sound was picked up * on the front face. * *-----------------------------------------------------*/ void face_ISR(void) { face_strike = true; // Got a face strike if ( is_trace ) { Serial.print(T("\r\nface_ISR()")); } noInterrupts(); return; } /* * Common function to indicate a fault // Cycle LEDs 5x */ void blink_fault ( unsigned int fault_code // Fault code to blink ) { unsigned int i; for (i=0; i != 3; i++) { set_LED(fault_code & 4, fault_code & 2, fault_code & 1); // Blink the LEDs to show an error delay(ONE_SECOND/4); fault_code = ~fault_code; set_LED(fault_code & 4, fault_code & 2, fault_code & 1); // Blink the LEDs to show an error delay(ONE_SECOND/4); fault_code = ~fault_code; } /* * Finished */ return; } /*----------------------------------------------------- * * function: multifunction_init * * brief: Initialize the direction of the MFS on the DIP switch * * return: None * *----------------------------------------------------- * * SPARE_1 is an unassigned GPIO that will change * function based on the software configuration. * * This function uses a switch statement to determine * the settings of the GPIO * *-----------------------------------------------------*/ void multifunction_init(void) { switch (LO10(json_multifunction)) { case PAPER_FEED: case PC_TEST: case GPIO_IN: pinMode(DIP_1,INPUT_PULLUP); break; case GPIO_OUT: // The switch is a general purpose output pinMode(DIP_1,OUTPUT); break; default: break; } switch (HI10(json_multifunction)) { case PAPER_FEED: case PC_TEST: case GPIO_IN: pinMode(DIP_2,INPUT_PULLUP); break; case GPIO_OUT: // The switch is a general purpose output pinMode(DIP_1,OUTPUT); break; default: break; } /* * The GPIO has been programmed per the multifunction mode */ return; } /*----------------------------------------------------- * * function: multifunction_switch * * brief: Carry out the functions of the multifunction switch * * return: Switch state * *----------------------------------------------------- * * The actions of the DIP switch will change depending on the * mode that is programmed into it. * * For some of the DIP switches, tapping the switch * turns the LEDs on, and holding it will carry out * the alternate activity. * *-----------------------------------------------------*/ static unsigned long hold_time_LO; static unsigned long hold_time_HI; unsigned int multifunction_switch ( unsigned int new_state // If output, drive to a new state ) { unsigned int return_value; // Value returned to caller if ( CALIBRATE ) { return; // Not used if in calibration mode } /* * Look for the special case of both switches pressed */ if ( DIP_SW_A && DIP_SW_B ) // Both pressed? { if ( json_tabata_on != 0 ) // Tabata ON? { json_tabata_on = 0; // Turn it Off } else // Turn it ON { EEPROM.get(NONVOL_TABATA_ON, json_tabata_on); } while ( DIP_SW_A || DIP_SW_B ) // Wait for both switches released { if ( json_tabata_on != 0 ) // Flash three LEDs if Tabata { // is enabled set_LED_PWM(0); // Turn off the illumination set_LED(L('*', '.', '*')); delay(ONE_SECOND/4); set_LED(L('.', '*', '.')); delay(ONE_SECOND/4); } else { set_LED_PWM(json_LED_PWM); // Turn on the LED illumination set_LED(L('.', '.', '.')); // Flash one LED if disabled delay(ONE_SECOND/4); set_LED(L('.', '*', '.')); delay(ONE_SECOND/4); EEPROM.put(NONVOL_TABATA_ENBL, (int)0); } set_LED(SHOT_READY); } return; // Bail out now } /* * Manage the GPIO based on the configuration */ switch (LO10(json_multifunction)) { case PAPER_FEED: // The switch acts as paper feed control return_value = DIP_SW_A; // Use DIP_SW_A as a paper feed sw_state(&fcn_DIP_SW_A, &hold_time_LO, &drive_paper); break; case GPIO_IN: // The switch is a general purpose input return_value = digitalRead(DIP_SW_A); break; case GPIO_OUT: // The switch is a general purpose output return_value = new_state; digitalWrite(DIP_1, new_state); break; case PC_TEST: // Send a fake score to the PC return_value = DIP_SW_A; // Use DIP_SW_B as a paper feed sw_state(&fcn_DIP_SW_A, &hold_time_LO, &send_fake_score); break; default: break; } switch (HI10(json_multifunction)) { case PAPER_FEED: // The switch acts as paper feed control return_value = DIP_SW_B; // Use DIP_SW_B as a paper feed sw_state(&fcn_DIP_SW_B, &hold_time_HI, &drive_paper); break; case GPIO_IN: // The switch is a general purpose input return_value = digitalRead(DIP_SW_B); break; case GPIO_OUT: // The switch is a general purpose output return_value = new_state; digitalWrite(DIP_1, new_state); break; case PC_TEST: // Send a fake score to the PC return_value = DIP_SW_B; // Use DIP_SW_B as a paper feed sw_state(&fcn_DIP_SW_B, &hold_time_HI, &send_fake_score); break; default: break; } /* * All done, return the GPIO state */ return return_value; } /*----------------------------------------------------- * * function: multifunction_switch helper functions * * brief: Small functioins to work with the MFC * * return: Switch state * *----------------------------------------------------- * * The MFC software above has been organized to use helper * functions to simplify the construction and provide * consistency in the operation. * *-----------------------------------------------------*/ static bool fcn_DIP_SW_A(void){return DIP_SW_A;} static bool fcn_DIP_SW_B(void){return DIP_SW_B;} /* * Carry out an action based on the switch state */ static void sw_state ( bool* (fcn_state)(void), // Input signal state unsigned long* which_timer, // What timer are we using? void* (fcn_action)(void) // Action to take ) { unsigned long now; // Current time in seconds now = millis() / 100; if ( (fcn_state)() == 0 ) // Switch is open, do nothing { *which_timer = now; // But remember the current time return; } /* * The switch is pressed for more than 1/2 second, carry out the action */ set_LED_PWM(json_LED_PWM); // Switch is pressed, turn on the LEDs tabata(true, true); // Reset the tabata counts if ( (now - *which_timer) > 5 ) // Held for 1/2 second { (fcn_action)(); // execute the function delay(200); } return; } /* * Send a fake score to the PC for testing */ static void send_fake_score(void) { static this_shot h; static int shot; h.x = random(-json_sensor_dia/2.0, json_sensor_dia/2.0); h.y = 0; send_score(&h, shot++, 0); return; } /*----------------------------------------------------- * * function: output_to_all * * brief: Send a string to the available serial ports * * return: None * *----------------------------------------------------- * * Send a string to all of the serial devices that are * in use. * *-----------------------------------------------------*/ void char_to_all(char ch) { char str_a[2]; str_a[0] = ch; str_a[1] = 0; output_to_all(str_a); } void output_to_all(char *str) { Serial.print(str); // Main USB port if ( esp01_is_present() ) { for (i=0; i != MAX_CONNECTIONS; i++ ) { esp01_send(str, i); } } else { AUX_SERIAL.print(str); // No ESP-01, then use just the AUX port } DISPLAY_SERIAL.print(str); // Aux Serial Port /* * All done, return */ return; } <file_sep>/Software/Arduino/freETarget/diag_tools.ino /*---------------------------------------------------------------- * * diag_tools.ino * * Debug and test tools * *---------------------------------------------------------------*/ #include "freETarget.h" #include "gpio.h" const char* which_one[4] = {"North:", "East:", "South:", "West:"}; #define TICK(x) (((x) / 0.33) * OSCILLATOR_MHZ) // Distance in clock ticks #define RX(Z,X,Y) (16000 - (sqrt(sq(TICK(x)-s[(Z)].x) + sq(TICK(y)-s[(Z)].y)))) #define GRID_SIDE 25 // Should be an odd number #define TEST_SAMPLES ((GRID_SIDE)*(GRID_SIDE)) static void show_analog_on_PC(int v); static void unit_test(unsigned int mode); static bool sample_calculations(unsigned int mode, unsigned int sample); /*---------------------------------------------------------------- * * function: void self_test * * brief: Execute self tests based on the jumper settings * * return: None * *---------------------------------------------------------------- * * This function is a large case statement with each element * of the case statement *--------------------------------------------------------------*/ unsigned int tick; void self_test(uint16_t test) { double volts; // Reference Voltage unsigned int i; char ch; unsigned int sensor_status; // Sensor running inputs unsigned long sample; // Sample used for comparison unsigned int random_delay; // Random sampe time bool pass; unsigned long start_time; // Running time /* * Update the timer */ tick++; volts = TO_VOLTS(analogRead(V_REFERENCE)); /* * Figure out what test to run */ switch (test) { /* * Test 0, Display the help */ default: // Undefined, show the tests case T_HELP: Serial.print(T("\r\n 1 - Digital inputs")); Serial.print(T("\r\n 2 - Counter values (external trigger)")); if ( revision() >= REV_220 ) { Serial.print(T("\r\n 3 - Counter values (internal trigger)")); } Serial.print(T("\r\n 4 - Oscilloscope")); Serial.print(T("\r\n 5 - Oscilloscope (PC)")); Serial.print(T("\r\n 6 - Advance paper backer")); Serial.print(T("\r\n 7 - Spiral Unit Test")); Serial.print(T("\r\n 8 - Grid calibration pattern")); Serial.print(T("\r\n 9 - One time calibration pattern")); Serial.print(T("\r\n 8 - Grid calibration pattern")); if ( revision() >= REV_220 ) { Serial.print(T("\r\n 10 - Aux port passthrough")); } Serial.print(T("\r\n11 - Calibrate")); Serial.print(T("\r\n12 - Transfer loopback")); Serial.print(T("\r\n13 - Serial port test")); Serial.print(T("\r\n14 - LED brightness test")); Serial.print(T("\r\n15 - Face strike test")); Serial.print(T("\r\n16 - WiFi test")); Serial.print(T("\r\n17 - Dump NonVol")); Serial.print(T("\r\n")); break; /* * Test 1, Display GPIO inputs */ case T_DIGITAL: Serial.print(T("\r\nTime:")); Serial.print(micros()/1000000); Serial.print("."); Serial.print(micros()%1000000); Serial.print(T("s")); Serial.print(T("\r\nBD Rev:")); Serial.print(revision()); Serial.print(T("\r\nDIP: 0x")); Serial.print(read_DIP(), HEX); digitalWrite(STOP_N, 0); digitalWrite(STOP_N, 1); // Reset the fun flip flop Serial.print(T("\r\nRUN FlipFlop: 0x")); Serial.print(is_running(), HEX); Serial.print(T("\r\nTemperature: ")); Serial.print(temperature_C()); Serial.print(T("'C ")); Serial.print(speed_of_sound(temperature_C(), RH_50)); Serial.print(T("mm/us")); Serial.print(T("\r\nV_REF: ")); Serial.print(volts); Serial.print(T(" Volts")); Serial.print(T("\r\n")); i=0; while (init_table[i].port != 0xff) { if ( init_table[i].in_or_out == OUTPUT ) { Serial.print(T("\r\n OUT >> ")); } else { Serial.print(T("\r\n IN << ")); } Serial.print(init_table[i].gpio_name); Serial.print(digitalRead(init_table[i].port)); i++; } POST_LEDs(); break; /* * Test 2, 3, Test the timing circuit */ case T_TRIGGER: // Show the timer values (Wait for analog input) Serial.print(T("\r\nWaiting for Trigger\r\n")); case T_CLOCK: // Show the timer values (Trigger input) stop_counters(); arm_counters(); set_LED(L('*', '-', '-')); if ( test == T_CLOCK ) { if ( revision() >= REV_220 ) { random_delay = random(1, 6000); // Pick a random delay time in us Serial.print(T("\r\nRandom clock test: ")); Serial.print(random_delay); Serial.print(T("us. All outputs must be the same. ")); trip_counters(); delayMicroseconds(random_delay); // Delay a random time } else { Serial.print(T("\r\nThis test not supported on this hardware revision")); break; } } while ( !is_running() ) { continue; } sensor_status = is_running(); // Remember all of the running timers stop_counters(); timer_value[N] = read_counter(N); timer_value[E] = read_counter(E); timer_value[S] = read_counter(S); timer_value[W] = read_counter(W); // Read the counters if ( test == T_CLOCK ) // Test the results { sample = timer_value[N]; pass = true; for(i=N; i<=W; i++) { if ( timer_value[i] != sample ) { pass = false; // Make sure they all match } } if ( pass == true ) { Serial.print(T(" PASS\r\n")); } else { Serial.print(T(" FAIL\r\n")); } } send_timer(sensor_status); set_LED(L('-', '-', '-')); delay(ONE_SECOND); break; /* * Test 4, 5, Simple O'Scope */ case T_OSCOPE: // Show the analog input show_analog(0); break; case T_OSCOPE_PC: show_analog_on_PC(0); break; /* * Test 6, Advance the paper */ case T_PAPER: Serial.print(T("\r\nAdvancing backer paper ")); Serial.print(((json_paper_time) + (json_step_time)) * 10); Serial.print(T(" ms ")); Serial.print(json_step_count); Serial.print(T(" steps")); drive_paper(); Serial.print(T("\r\nDone")); break; /* * Test 7, 8, 9, Generate test pattern for diagnosing software problems */ case T_SPIRAL: Serial.print(T("\r\nSpiral Calculation\r\n")); unit_test( T_SPIRAL ); // Generate a spiral break; case T_GRID: Serial.print(T("\r\nGrid Calculation\r\n")); unit_test( T_GRID); // Generate a grid break; case T_ONCE: Serial.print(T("\r\nSingle Calculation\r\n")); unit_test( T_ONCE); // Generate a SINGLE calculation break; /* * Test 10, Test the pass through connector */ case T_PASS_THRU: Serial.print(T("\r\nPass through active. Cycle power to exit\r\n")); while (1) { if ( Serial.available() ) { ch = Serial.read(); AUX_SERIAL.print(ch); } if ( AUX_SERIAL.available() ) { ch = AUX_SERIAL.read(); Serial.print(ch); } } break; /* * Test 11 */ case T_SET_TRIP: set_trip_point(0); // Stay in the trip point loop break; /* * Test 13 */ case T_SERIAL_PORT: Serial.print(T("\r\nArduino Serial Port: Hello World\r\n")); AUX_SERIAL.print(T("\r\nAux Serial Port: Hello World\r\n")); DISPLAY_SERIAL.print(T("\r\nDisplay Serial Port: Hello World\r\n")); break; /* * Test 14 */ case T_LED: Serial.print(T("\r\nRamping the LED")); for (i=0; i != 256; i++) { analogWrite(LED_PWM, i); delay(ONE_SECOND/50); } for (i=255; i != -1; i--) { analogWrite(LED_PWM, i); delay(ONE_SECOND/50); } analogWrite(LED_PWM, 0); Serial.print(T(" Done\r\n")); break; /* * Test 15 */ case T_FACE: Serial.print(T("\r\nFace strike test")); enable_interrupt(1); face_strike = 0; EEPROM.put(NONVOL_TEST_MODE, T_HELP); // Stop the test on the next boot cycle while (1) { if ( face_strike != 0 ) { set_LED(L('*', '*', '*')); // If something comes in, turn on all of the LEDs Serial.print(T("\n\rStrike")); delay(ONE_SECOND/4); face_strike = 0; enable_interrupt(1); } else { set_LED(L('-', '-', '-')); } delay(ONE_SECOND/2); } break; /* * TEST 16 WiFI */ case T_WIFI: esp01_test(); break; /* * TEST 17 Dump NonVol */ case T_NONVOL: dump_nonvol(); break; } /* * All done, return; */ return; } /*---------------------------------------------------------------- * * function: POST_version() * * brief: Show the Version String * * return: None * *---------------------------------------------------------------- * * Common function to show the version. Routed to the selected * port(s) * *--------------------------------------------------------------*/ void POST_version ( int port // Port to display output on ) { int i; char str_a[256]; sprintf(str_a, "\r\nfreETarget %s\r\n", SOFTWARE_VERSION); /* * Display the version on the default serial port */ if ( (port == 0) || (port & PORT_SERIAL) ) // No port or Serial port selected { Serial.print(str_a); } /* * Display the version on the AUX port, taking care of the WiFi if present */ if ( port & PORT_AUX ) { if ( esp01_is_present() ) { for (i=0; i != MAX_CONNECTIONS; i++ ) { esp01_send(str_a, i); esp01_send(0, i); } } else { AUX_SERIAL.print(str_a); // No ESP-01, then use just the AUX port } } /* * Output to the spare USB serial port */ if ( port & PORT_DISPLAY ) { DISPLAY_SERIAL.print(str_a); } /* * All done, return */ return; } /*---------------------------------------------------------------- * * function: POST_LEDs() * * brief: Show the LEDs are working * * return: None * *---------------------------------------------------------------- * * Cycle the LEDs to show that the board has woken up and has * freETarget software in it. * *--------------------------------------------------------------*/ void POST_LEDs(void) { if ( is_trace ) { Serial.print(T("\r\nPOST LEDs")); } set_LED(L('*', '.', '.')); delay(ONE_SECOND/4); set_LED(L('.', '*', '.')); delay(ONE_SECOND/4); set_LED(L('.', '.', '*')); delay(ONE_SECOND/4); set_LED(L('.', '.', '.')); return; } /*---------------------------------------------------------------- * * function: void POST_counters() * * brief: Verify the counter circuit operation * * return: None * *---------------------------------------------------------------- * * Trigger the counters from inside the circuit board and * read back the results and look for an expected value. * * Return TRUE if the complete circuit is working * * Test 1, Arm the circuit and make sure there are no random trips * This test will fail if the sensor cable harness is not attached * Test 2, Arm the circuit amd make sure it is off (No running counters * Test 3: Trigger the counter and make sure that all sensors are triggered * Test 4: Stop the clock and make sure that the counts have stopped * Test 5: Verify that the counts are correctia * *--------------------------------------------------------------*/ #define POST_counters_cycles 10 // Repeat the test 10x #define CLOCK_TEST_LIMIT 500 // Clock should be within 500 ticks bool POST_counters(void) { unsigned int i, j; // Iteration counter unsigned int random_delay; // Delay duration unsigned int sensor_status; // Sensor status int x; // Time difference (signed) bool test_passed; // Record if the test failed long now; // Current time /* * The test only works on V2.2 and higher */ if ( revision() < REV_300 ) { return true; // Fake a positive response } if ( is_trace ) { Serial.print(T("\r\nPOST counters")); } test_passed = true; // And assume that it will pass /* * Test 1, Arm the circuit and see if there are any random trips */ stop_counters(); // Get the circuit ready arm_counters(); // Arm it. delay(1); // Wait a millisecond sensor_status = is_running(); // Remember all of the running timers if ( sensor_status != 0 ) { Serial.print(T("\r\nFailed Clock Test. Spurious trigger:")); show_sensor_status(sensor_status); return false; // No point in any more tests } /* * Loop and verify the opertion of the clock circuit using random times */ for (i=0; i!= POST_counters_cycles; i++) { if ( is_trace ) { Serial.print(T("\r\nCycle:")); Serial.print(i); } /* * Test 2, Arm the circuit amd make sure it is off */ stop_counters(); // Get the circuit ready arm_counters(); delay(1); // Wait for a bit for (j=N; j <= W; j++ ) // Check all of the counters { if ( read_counter(j) != 0 ) // Make sure they stay at zero { Serial.print(T("\r\nFailed Clock Test. Counter free running:")); Serial.print(nesw[j]); test_passed = false; // return a failed test } } /* * Test 3: Trigger the counter and make sure that all sensors are triggered */ stop_counters(); // Get the circuit ready arm_counters(); delay(1); random_delay = random(1, 6000); // Pick a random delay time in us now = micros(); // Grab the current time trip_counters(); sensor_status = is_running(); // Remember all of the running timers while ( micros() < (now + random_delay ) ) { continue; } stop_counters(); if ( sensor_status != 0x0F ) // The circuit was triggered but not all { // FFs latched Serial.print(T("\r\nFailed Clock Test. sensor_status:")); show_sensor_status(sensor_status); test_passed = false; } /* * Test 4: Stop the clock and make sure that the counts have stopped */ random_delay *= 8; // Convert to clock ticks for (j=N; j <= W; j++ ) // Check all of the counters { x = read_counter(j); if ( read_counter(j) != x ) { Serial.print(T("\r\nFailed Clock Test. Counter did not stop:")); Serial.print(nesw[j]); show_sensor_status(sensor_status); test_passed = false; // since there is delay in } // Turning off the counters /* * Test 5: Verify that the counts are correct */ x =x - random_delay; if( x < 0 ) { x = -x; } if ( x > CLOCK_TEST_LIMIT ) // The time should be positive and within limits { Serial.print(T("\r\nFailed Clock Test. Counter:")); Serial.print(nesw[j]); Serial.print(T(" Is:")); Serial.print(read_counter(j)); Serial.print(T(" Should be:")); Serial.print(random_delay); Serial.print(T(" Delta:")); Serial.print(x); test_passed = false; // since there is delay in } // Turning off the counters else { if ( is_trace ) { Serial.print(T("\r\nClock Pass. Counter:")); Serial.print(nesw[j]); Serial.print(T(" Is:")); Serial.print(read_counter(j)); Serial.print(T(" Should be:")); Serial.print(random_delay); Serial.print(T(" Delta:")); Serial.print(x); } } } } /* * Got here, the test completed successfully */ set_LED(L('.', '.', '.')); return test_passed; } /*---------------------------------------------------------------- * * function: void POST_trip_point() * * brief: Display the trip point * * return: None *---------------------------------------------------------------- * * Run the set_trip_point function once * *--------------------------------------------------------------*/ void POST_trip_point(void) { if ( is_trace ) { Serial.print(T("\r\nPOST trip point")); } set_trip_point(20); // Show the trip point once (20 cycles used for blinking values) set_LED(L('.', '.', '.')); // Show test test Ending return; } /*---------------------------------------------------------------- * * function: set_trip_point * * brief: Read the pot and display the voltage on the LEDs as a grey code * * return: Potentiometer set for the desired trip point *---------------------------------------------------------------- * * The reference voltage is divided into 8 bands from 0.5 volt * to 1.5 volts in 1/8 volt increments. * * This function averages the voltage over 1/2 second and * determines what band the reference belongs in and displays * it on the LEDs as a Grey code. * * The function will remain here * If started by a CAL jumper until the jumper is removed * If the voltage is out of spec on power up * If started by a {TEST} forever * * Calibration Display * * V_REF S X Y * 0.350 . . . * 0.400 . . * * 0.450 . . B * 0.500 . * . * 0.550 . B . * 0.600 . * * * 0.650 . B B * 0.700 * . . * 0.750 B . . * 0.800 * . * * 0.900 B . B * 1.000 * * . * 1.100 B B . * 1.200 * * * * 1.3^^ B B B * * Calibration Modes * No Jumpers Regular Range * CAL_LOW Reduced Detection * CAL_HI Increased Detetion * *--------------------------------------------------------------*/ #define CT(x) (1023l * (long)(x+25) / 5000l ) // 1/16 volt = 12.8 counts #define SPEC_RANGE 50 // Out of spec if within 50 couts of the rail #define BLINK 0x80 #define NOT_IN_SPEC 0x40 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 const unsigned int volts_to_LED[] = { NOT_IN_SPEC, 1, BLINK+1, 2, BLINK+2, 3, BLINK+3, 4, BLINK+4, 5, BLINK+5, 6, BLINK+6, 7, BLINK+7, NOT_IN_SPEC, 0 }; const unsigned int mv_to_counts[] = { CT(350), CT(400), CT(450), CT(500), CT(550), CT(600), CT(650), CT(700), CT(750), CT(800), CT(900), CT(1000), CT(1100), CT(1200), CT(1300), CT(5000), 0 }; void set_trip_point ( int pass_count // Number of passes to allow before exiting (0==infinite) ) { unsigned long start_time; // Starting time of average loop unsigned long sample; // Counts read from ADC bool blinky; // Blink the LEDs on an over flow bool not_in_spec; // Set to true if the input is close to the limits bool stay_forever; // Stay forever if called with pass_count == 0; unsigned int sensor_status; // OR of the sensor bits that have tripped if ( is_trace ) // Infinite number of passes? { Serial.print(T("\r\nSetting trip point. Type ! of cycle power to exit\r\n")); } blinky = 0; not_in_spec = true; // Start off by assuming out of spec sensor_status = 0; // No sensors have tripped stay_forever = false; if (pass_count == 0 ) // A pass count of 0 means stay { stay_forever = true; // For a long time } arm_counters(); // Arm the flip flops for later enable_interrupt(true); // Arm the face sensor face_strike = false; /* * Loop if not in spec, passes to display, or the CAL jumper is in */ while ( not_in_spec // Out of tolerance || ( stay_forever ) // Passes to go || ( CALIBRATE ) // Held in place by DIP switch || (pass_count != 0)) // Wait here for N cycles { start_time = millis(); sample = 0; i=0; while ( millis() - start_time < (ONE_SECOND/10) ) // Read voltage for 1/10 second { sample += analogRead(V_REFERENCE); // Read the ADC. 0-1023V i++; // and keep a running total } sample /= i; // Get the average /* * See if we are on one of the limits and out of spec. */ if ( (sample < SPEC_RANGE) // Close to 0 || ( sample > (MAX_ANALOG - SPEC_RANGE)) ) // Near VCC { // Blink the LEDs * - x - * if ( is_trace ) { Serial.print(T("\r\nOut Of Spec: ")); Serial.print(TO_VOLTS(analogRead(V_REFERENCE))); } blink_fault(VREF_OVER_UNDER); pass_count = 0; // Stay in this function forever not_in_spec = true; // Show we are out of spec continue; } /* * In spec, display the trip level on the LEDs */ if ( CAL_LOW ) // Low Calibration { sample *= 3; sample /= 2; } if ( CAL_HIGH ) // Set scale if the high range { sample *= 2; sample /= 3; } /* * Determine what band it belongs to */ i = 0; while (volts_to_LED[i] != 0) { if ( sample <= mv_to_counts[i] ) { break; } i++; } /* * Use the band to find the LEDs and if they should blink */ blinky = !blinky; // Toggle the blink ch = volts_to_LED[i]; if ( ch & BLINK ) // Blink bit on? { if ( blinky ) // Time to blink? { ch = 0; // No, then off } ch &= ~BLINK; // Keep only the LED state } not_in_spec = ch & NOT_IN_SPEC; if ( not_in_spec ) // Out of spec? { ch = 0b010; // Flash x - * - x if ( blinky ) // or * - x - * { ch = 0b101; } } set_LED(ch & 4, ch & 2, ch & 1); /* * Got to the end. See if we are going to do this for a fixed time or forever */ switch (Serial.read()) { case '!': // ! waiting in the serial port Serial.print(T("\r\nExiting calibration\r\n")); return; case 'X': case 'x': // X Cancel sensor_status = 0; arm_counters(); // Reset the latch state enable_interrupt(1); // Turn on the face strike interrupt face_strike = false; // Reset the face strike count enable_interrupt(1); // Turning it on above creates a fake interrupt with a disable break; default: break; } if ( stay_forever ) { show_sensor_status(is_running()); Serial.print(T("\n\r")); } else { if ( pass_count != 0 ) // Set for a finite loop? { pass_count--; // Decriment count remaining if ( pass_count == 0 ) // And bail out when zero { return; } } } delay(ONE_SECOND/5); } /* * Return */ return; } /*---------------------------------------------------------------- * * function: show_analog * * brief: Read and display as a 4 channel scope trace * * return: None *---------------------------------------------------------------- * * The output appears as a 1 channel O'scope with all four * sensors shown on the display. * * Tapping the microphone will be enough to trigger a response * * To make catching the trace easier, the input has a peak * detection and decay * *--------------------------------------------------------------*/ unsigned int channel[] = {NORTH_ANA, EAST_ANA, SOUTH_ANA, WEST_ANA}; unsigned int cycle = 0; unsigned int max_input[4]; #define FULL_SCALE 128 // Max full scale is 128 (128 = 5V) #define SCALE 128/128 // Gain applied to analog input #define DECAY_RATE 16 // Decay rate for peak detection #define SAMPLE_TIME (500000U) // 500 x 1000 us void show_analog(int v) { unsigned int i, sample; char o_scope[FULL_SCALE]; unsigned long now; set_LED((1 << cycle) & 1, (1 << cycle) & 2, (1 << cycle) & 4); cycle = (cycle+1) % 4; /* * Clear the oscope line */ for ( i=0; i != FULL_SCALE; i++) // Clear the oscope { o_scope[i] = ' '; } o_scope[FULL_SCALE-1] = 0; // Null terminate /* * Draw in the trip point */ i = analogRead(V_REFERENCE) * SCALE; o_scope[i] = '|'; /* * Sample the input for 250ms */ max_input[N] = 0; max_input[E] = 0; // Forget the maxium max_input[S] = 0; max_input[W] = 0; now = micros(); while ((micros() - now) <= SAMPLE_TIME ) // Enough time already { for (i=N; i <= W; i++) { sample = analogRead(channel[i]) * SCALE; // Read and scale the input if ( sample >= FULL_SCALE -1 ) { sample = FULL_SCALE-2; } if ( sample > max_input[i] ) // Remember the max { max_input[i] = sample; } } } /* * Put the values into the line */ for (i=N; i <= W; i++) { o_scope[max_input[i]] = nesw[i]; } Serial.print(T("{\"OSCOPE\": ")); Serial.print(o_scope); Serial.print(T("\"}\r\n")); // Display the trace as JSON /* * All done. */ return; } /*---------------------------------------------------------------- * * function: show_analog_on_PC * * brief: Four channel scope shown on the PC * * return: None *---------------------------------------------------------------- * * Special purpose version of the software for use on the PC test * .program *--------------------------------------------------------------*/ static void show_analog_on_PC(int v) { unsigned int i, j, k; char o_scope[FULL_SCALE]; /* * Output as a scope trace */ Serial.print(T("\n{Ref:")); Serial.print(TO_VOLTS(analogRead(V_REFERENCE))); Serial.print(T(" ")); for (i=N; i != W + 1; i++) { Serial.print(which_one[i]); if ( max_input[i] != 0 ) { max_input[i]--; } j = analogRead(channel[i]) * SCALE; // Read and scale the input if ( (j * DECAY_RATE) > max_input[i] ) // Remember the max { max_input[i] = j * DECAY_RATE; } if ( j > FULL_SCALE-1 ) { j = FULL_SCALE-1; } for ( k=0; k != FULL_SCALE; k++) // Clear the oscope { o_scope[k] = ' '; } o_scope[j] = '*'; // Put in the trace o_scope[(max_input[i]) / DECAY_RATE] = '#'; o_scope[FULL_SCALE-1] = 0; Serial.print(o_scope); // Display this channel } Serial.print(T("}")); /* * All done. */ return; } /*---------------------------------------------------------------- * * function: unit_test * * brief: Setup a known target for sample calculations * * return: None * *---------------------------------------------------------------- * * See excel spread sheet sample calculations.xls * * Estimate 0.02mm / delta count * --> 400 counts -> 8mm * *--------------------------------------------------------------*/ /* * Prompt the user for a test number and execute the test. */ static void unit_test(unsigned int mode) { unsigned int i; unsigned int location; unsigned int shot_number; /* * Auto Generate spiral */ init_sensors(); shot_number = 1; for ( i = 0; i != TEST_SAMPLES; i++) { if ( sample_calculations(mode, i) ) { location = compute_hit(0x0F, &record, true); sensor_status = 0xF; // Fake all sensors good send_score(&record, shot_number, sensor_status); shot_number++; delay(ONE_SECOND/2); // Give the PC program some time to catch up } if ( mode == T_ONCE ) { break; } } /* * All done, return */ return; } /*---------------------------------------------------------------- * * function: sample_calculations * * brief: Work out the clock values to generate a particular pattern * * return: TRUE to be compatable with other calcuation functions * *---------------------------------------------------------------- * * This function is used to generate a test pattern that the * PC or Arduino software is compared to. * *--------------------------------------------------------------*/ /* * Fill up counters with sample values. Return false if the sample does not exist */ static bool sample_calculations ( unsigned int mode, // What test mode are we generating unsigned int sample // Current sample number ) { double x, y; // Resulting target position double angle; // Polar coordinates double radius; double polar; int ix, iy; double step_size; // Rectangular coordinates double grid_step; switch (mode) { /* * Generate a single calculation */ case T_ONCE: angle = 0; radius =json_sensor_dia / sqrt(2.0d) / 2.0d; x = radius * cos(angle); y = radius * sin(angle); timer_value[N] = RX(N, x, y); timer_value[E] = RX(E, x, y); timer_value[S] = RX(S, x, y); timer_value[W] = RX(W, x, y); timer_value[W] -= 200; // Inject an error into the West sensor Serial.print(T("\r\nResult should be: ")); Serial.print(T("x:")); Serial.print(x); Serial.print(T(" y:")); Serial.print(y); Serial.print(T(" radius:")); Serial.print(radius); Serial.print(T(" angle:")); Serial.print(angle * 180.0d / PI); break; /* * Generate a spiral pattern */ default: case T_SPIRAL: angle = (PI_ON_4) / 5.0 * ((double)sample); radius = 0.99d * (json_sensor_dia/2.0) / sqrt(2.0d) * (double)sample / TEST_SAMPLES; x = radius * cos(angle); y = radius * sin(angle); timer_value[N] = RX(N, x, y); timer_value[E] = RX(E, x, y); timer_value[S] = RX(S, x, y); timer_value[W] = RX(W, x, y); break; /* * Generate a grid */ case T_GRID: radius = 0.99d * (json_sensor_dia / 2.0d / sqrt(2.0d)); grid_step = radius * 2.0d / (double)GRID_SIDE; ix = -GRID_SIDE/2 + (sample % GRID_SIDE); // How many steps iy = GRID_SIDE/2 - (sample / GRID_SIDE); x = (double)ix * grid_step; // Compute the ideal X-Y location y = (double)iy * grid_step; polar = sqrt(sq(x) + sq(y)); angle = atan2(y, x) - (PI * json_sensor_angle / 180.0d); x = polar * cos(angle); y = polar * sin(angle); // Rotate it through the sensor position. if ( sqrt(sq(x) + sq(y)) > radius ) { return false; } timer_value[N] = RX(N, x, y); timer_value[E] = RX(E, x, y); timer_value[S] = RX(S, x, y); timer_value[W] = RX(W, x, y); break; } /* * All done, return */ return true; } /*---------------------------------------------------------------- * * function: show_sensor_status() * * brief: Show which sensor flip flops were latched * * return: Nothing * *---------------------------------------------------------------- * * The sensor state NESW or .... is shown for each latch * The clock values are also printed * *--------------------------------------------------------------*/ void show_sensor_status(unsigned int sensor_status) { unsigned int i; Serial.print(T(" Latch:")); for (i=N; i<=W; i++) { if ( sensor_status & (1<<i) ) Serial.print(nesw[i]); else Serial.print(T(".")); } Serial.print(" Timers:"); for (i=N; i<=W; i++) { if ( timer_value[i] != 0 ) Serial.print(nesw[i]); else Serial.print(T(".")); } Serial.print(T(" Face Strike:")); Serial.print(face_strike); Serial.print(T(" V_Ref:")); Serial.print(TO_VOLTS(analogRead(V_REFERENCE))); if ( ((sensor_status & 0x0f) == 0x0f) && (face_strike) ) { Serial.print(T(" PASS")); } /* * All done, return */ return; } <file_sep>/Software/Arduino/freETarget/json.ino /*------------------------------------------------------- * * JSON.ino * * JSON driver * * ----------------------------------------------------*/ #include <EEPROM.h> static char input_JSON[256]; int json_dip_switch; // DIP switch overwritten by JSON message double json_sensor_dia = DIAMETER; // Sensor daiamter overwitten by JSON message int json_sensor_angle; // Angle sensors are rotated through int json_paper_time = 0; // Time paper motor is applied int json_echo; // Test String double json_d_echo; // Test String int json_calibre_x10; // Pellet Calibre int json_north_x; // North Adjustment int json_north_y; int json_east_x; // East Adjustment int json_east_y; int json_south_x; // South Adjustment int json_south_y; int json_west_x; // WestAdjustment int json_west_y; int json_name_id; // Name identifier int json_1_ring_x10; // Size of the 1 ring in mm int json_LED_PWM; // LED control value int json_power_save; // Power down time int json_send_miss; // Send a miss message int json_serial_number; // Electonic serial number int json_step_count; // Number of steps ouput to motor int json_step_time; // Duration of each step int json_multifunction; // Multifunction switch operation int json_z_offset; // Distance between paper and sensor plane in 0.1mm int json_paper_eco; // Do not advance paper if outside of the black int json_target_type; // Modify target type (0 == single bull) int json_tabata_on; // Tabata ON timer int json_tabata_rest; // Tabata resting timer int json_tabata_cycles; // Number of Tabata cycles #define JSON_DEBUG false // TRUE to echo DEBUG messages void show_echo(int v); // Display the current settings static void show_test(int v); // Execute the self test once static void show_test0(int v); // Help Menu static void show_names(int v); static void nop(void); static void set_trace(int v); // Set the trace on and off const json_message JSON[] = { // token value stored in RAM double stored in RAM convert service fcn() NONVOL location Initial Value {"\"ANGLE\":", &json_sensor_angle, 0, IS_INT16, 0, NONVOL_SENSOR_ANGLE, 45 }, // Locate the sensor angles {"\"CAL\":", 0, 0, IS_VOID, &set_trip_point, 0, 0 }, // Enter calibration mode {"\"CALIBREx10\":", &json_calibre_x10, 0, IS_INT16, 0, NONVOL_CALIBRE_X10, 45 }, // Enter the projectile calibre (mm x 10) {"\"DIP\":", &json_dip_switch, 0, IS_INT16, 0, NONVOL_DIP_SWITCH, 0 }, // Remotely set the DIP switch {"\"ECHO\":", 0, 0, IS_VOID, &show_echo, 0, 0 }, // Echo test {"\"INIT\":", 0, 0, IS_INT16, &init_nonvol, NONVOL_INIT, 0 }, // Initialize the NONVOL memory {"\"LED_BRIGHT\":", &json_LED_PWM, 0, IS_INT16, &set_LED_PWM_now, NONVOL_LED_PWM, 50 }, // Set the LED brightness {"\"MFS\":", &json_multifunction, 0, IS_INT16, 0, NONVOL_MFS, 0 }, // Multifunction switch action {"\"NAME_ID\":", &json_name_id, 0, IS_INT16, &show_names, NONVOL_NAME_ID, 0 }, // Give the board a name {"\"PAPER_ECO\":", &json_paper_eco, 0, IS_INT16, 0, NONVOL_PAPER_ECO, 0 }, // Ony advance the paper is in the black {"\"PAPER_TIME\":", &json_paper_time, 0, IS_INT16, 0, NONVOL_PAPER_TIME, 0 }, // Set the paper advance time {"\"POWER_SAVE\":", &json_power_save, 0, IS_INT16, 0, NONVOL_POWER_SAVE, 30 }, // Set the power saver time {"\"SEND_MISS\":", &json_send_miss, 0, IS_INT16, 0, NONVOL_SEND_MISS, 0 }, // Enable / Disable sending miss messages {"\"SENSOR\":", 0, &json_sensor_dia, IS_FLOAT, &gen_position, NONVOL_SENSOR_DIA, 230 }, // Generate the sensor postion array {"\"SN\":", &json_serial_number, 0, IS_FIXED, 0, NONVOL_SERIAL_NO, 0xffff }, // Board serial number {"\"STEP_COUNT\":", &json_step_count, 0, IS_INT16, 0, NONVOL_STEP_COUNT, 0 }, // Set the duration of the stepper motor ON time {"\"STEP_TIME\":", &json_step_time, 0, IS_INT16, 0, NONVOL_STEP_TIME, 0 }, // Set the number of times stepper motor is stepped {"\"TABATA_CYCLES\":", &json_tabata_cycles, 0, IS_INT16, 0, NONVOL_TABATA_CYCLES, 0 }, // Number of cycles to use for the Tabata timer {"\"TABATA_REST\":", &json_tabata_rest, 0, IS_INT16, 0, NONVOL_TABATA_REST, 0 }, // Time that the LEDs are OFF for a Tabata timer {"\"TABATA_ON\":", &json_tabata_on, 0, IS_INT16, 0, NONVOL_TABATA_ON, 0 }, // Time that the LEDs are ON for a Tabata timer (1/10 seconds) {"\"TARGET_TYPE\":", &json_target_type, 0, IS_INT16, 0, NONVOL_TARGET_TYPE, 0 }, // Marify shot location (0 == Single Bull) {"\"TEST\":", 0, 0, IS_INT16, &show_test, NONVOL_TEST_MODE, 0 }, // Execute a self test {"\"TRACE\":", 0, 0, IS_INT16, &set_trace, 0, 0 }, // Enter / exit diagnostic trace {"\"VERSION\":", 0, 0, IS_INT16, &POST_version, 0, 0 }, // Return the version string {"\"Z_OFFSET\":", &json_z_offset , 0, IS_INT16, 0, NONVOL_Z_OFFSET, 0 }, // Distance from paper to sensor plane (mm) {"\"NORTH_X\":", &json_north_x, 0, IS_INT16, 0, NONVOL_NORTH_X, 0 }, // {"\"NORTH_Y\":", &json_north_y, 0, IS_INT16, 0, NONVOL_NORTH_Y, 0 }, // {"\"EAST_X\":", &json_east_x, 0, IS_INT16, 0, NONVOL_EAST_X, 0 }, // {"\"EAST_Y\":", &json_east_y, 0, IS_INT16, 0, NONVOL_EAST_Y, 0 }, // {"\"SOUTH_X\":", &json_south_x, 0, IS_INT16, 0, NONVOL_SOUTH_X, 0 }, // {"\"SOUTH_Y\":", &json_south_y, 0, IS_INT16, 0, NONVOL_SOUTH_Y, 0 }, // {"\"WEST_X\":", &json_west_x, 0, IS_INT16, 0, NONVOL_WEST_X, 0 }, // {"\"WEST_Y\":", &json_west_y, 0, IS_INT16, 0, NONVOL_WEST_Y, 0 }, // { 0, 0, 0, 0, 0, 0} }; int instr(char* s1, char* s2); /*----------------------------------------------------- * * function: read_JSON() * * brief: Accumulate input from the serial port * * return: None * *----------------------------------------------------- * * The format of the JSON stings used here is * * { "LABLE":value } * * {"ECHO":23"} * {"ECHO":12, "DIP":8} * {"DIP":9, "SENSOR":230.0, "ECHO":32} * {"TEST":7, "ECHO":5} * * Find the lable, ex "DIP": and save in the * corresponding memory location * *-----------------------------------------------------*/ static uint16_t in_JSON = 0; static bool not_found; bool read_JSON(void) { static int16_t got_right; unsigned int i, j, x; int k; char ch; double y; bool return_value; return_value = false; /* * See if anything is waiting and if so, add it in */ while ( AVAILABLE != 0) { return_value = true; ch = GET(); #if ( JSON_DEBUG == true ) char_to_all(ch); #endif /* * Parse the stream */ switch (ch) { case ' ': // Ignore spaces break; case '%': self_test(T_XFR_LOOP); // Transfer self test break; case '^': drive_paper(); // Page Feed break; case '{': in_JSON = 0; input_JSON[0] = 0; got_right = 0; break; case '}': if ( in_JSON != 0 ) { got_right = in_JSON; } break; default: input_JSON[in_JSON] = ch; // Add in the latest if ( in_JSON < (sizeof(input_JSON)-1) ) { in_JSON++; } input_JSON[in_JSON] = 0; // Null terminate break; } } if ( got_right == 0 ) { return return_value; } /* * Found out where the braces are, extract the contents. */ not_found = true; for ( i=0; i != got_right; i++) // Go across the JSON input { j = 0; while ( JSON[j].token != 0 ) // Cycle through the tokens { k = instr(&input_JSON[i], JSON[j].token ); // Compare the input against the list of JSON tags if ( k > 0 ) // Non zero, found something { not_found = false; // Read and convert the JSON value switch ( JSON[j].convert ) { default: case IS_VOID: // Void, default to zero case IS_FIXED: // Fixed cannot be changed x = 0; y = 0; break; case IS_INT16: // Convert an integer x = atoi(&input_JSON[i+k]); if ( JSON[j].value != 0 ) { *JSON[j].value = x; // Save the value } if ( JSON[j].non_vol != 0 ) { EEPROM.put(JSON[j].non_vol, x); // Store into NON-VOL } break; case IS_FLOAT: // Convert a floating point number case IS_DOUBLE: y = atof(&input_JSON[i+k]); if ( JSON[j].d_value != 0 ) { *JSON[j].d_value = y; // Save the value } if ( JSON[j].non_vol != 0 ) { EEPROM.put(JSON[j].non_vol, y); // Store into NON-VOL } break; } if ( JSON[j].f != 0 ) // Call the handler if it is available { JSON[j].f(x); } } j++; } } /* * Check for an alternate GPIO test */ for ( i=0; i != got_right; i++) // Go across the JSON input { j = 0; while ( init_table[j].port != 0xff ) // Cycle through the tokens { k = instr(&input_JSON[i], init_table[j].gpio_name ); // Compare the input against the list of JSON tags if ( k > 0 ) // Non zero, found something { not_found = false; // Read and convert the JSON value Serial.print(T("\r\n")); Serial.print(init_table[j].gpio_name); if ( init_table[j].in_or_out == INPUT_PULLUP ) { Serial.print(T(" is input only")); break; } if ( instr("LED_PWM", init_table[j].gpio_name ) != 0 ) // Special case analog output { x = atoi(&input_JSON[i+k]); analogWrite(LED_PWM, x); Serial.print(x); } else { x = atoi(&input_JSON[i+k]); digitalWrite(init_table[j].port, x); Serial.print(x); Serial.print(T(" Verify:")); Serial.print(digitalRead(init_table[j].port)); } } j++; } } /* * Report an error if input not found */ if ( not_found == true ) { Serial.print(T("\r\n\r\nCannot decode: {")); Serial.print(input_JSON); Serial.print(T("}. Use")); j = 0; while ( JSON[j].token != 0 ) { Serial.print(T("\r\n")); Serial.print(JSON[j].token); j++; if ( (j%4) == 0 ) { Serial.print(T("\r\n")); } } Serial.print(T("\r\n\r\n *** GPIO ***")); j=0; while ( init_table[j].port != 0xff ) { if ( init_table[j].in_or_out == OUTPUT ) { Serial.print(T("\r\n")); Serial.print(init_table[j].gpio_name); if ( (j%4) == 0 ) { Serial.print(T("\r\n")); } } j++; } } /* * All done */ in_JSON = 0; // Start Over got_right = 0; // Neet to wait for a new Right Bracket input_JSON[in_JSON] = 0; // Clear the input return return_value; } // Compare two strings. Return -1 if not equal, length of string if equal // S1 Long String, S2 Short String . if ( instr("CAT Sam", "CAT") == 3) int instr(char* s1, char* s2) { int i; i=0; while ( (*s1 != 0) && (*s2 != 0) ) { if ( *s1 != *s2 ) { return -1; } s1++; s2++; i++; } /* * Reached the end of the comparison string. Check that we arrived at a NULL */ if ( *s2 == 0 ) // Both strings are the same { return i; } return -1; // The strings are different } /*----------------------------------------------------- * * function: show_echo * * brief: Display the current settings * * return: None * *----------------------------------------------------- * * Loop and display the settings * *-----------------------------------------------------*/ void show_echo(int v) { unsigned int i, j; char s[512], str_c[10]; // String holding buffers sprintf(s, "\r\n{\r\n\"NAME\":\"%s\", \r\n", names[json_name_id]); output_to_all(s); /* * Loop through all of the JSON tokens */ i=0; j=1; while ( JSON[i].token != 0 ) // Still more to go? { if ( (JSON[i].value != NULL) || (JSON[i].d_value != NULL) ) // It has a value ? { switch ( JSON[i].convert ) // Display based on it's type { default: case IS_VOID: break; case IS_INT16: case IS_FIXED: sprintf(s, "%s %d, \r\n", JSON[i].token, *JSON[i].value); break; case IS_FLOAT: case IS_DOUBLE: dtostrf(*JSON[i].d_value, 4, 2, str_c ); sprintf(s, "%s %s, \r\n", JSON[i].token, str_c); break; } output_to_all(s); } i++; } /* * Finish up with the special cases */ sprintf(s, "\"IS_TRACE\": %d, \n\r", is_trace); // TRUE to if trace is enabled output_to_all(s); dtostrf(temperature_C(), 4, 2, str_c ); sprintf(s, "\"TEMPERATURE\": %s, \n\r", str_c); // Temperature in degrees C output_to_all(s); dtostrf(speed_of_sound(temperature_C(), RH_50), 4, 2, str_c ); sprintf(s, "\"SPEED_SOUND\": %s, \n\r", str_c); // Speed of Sound output_to_all(s); dtostrf(TO_VOLTS(analogRead(V_REFERENCE)), 4, 2, str_c ); sprintf(s, "\"V_REF\": %s, \n\r", str_c); // Trip point reference output_to_all(s); sprintf(s, "\"TIMER_COUNT\":%d, \n\r", (int)(SHOT_TIME * OSCILLATOR_MHZ)); // Maximum number of clock cycles to record shot (target dependent) output_to_all(s); sprintf(s, "\"DIP_HEX\": 0x0%c, \n\r", to_hex[0x0F & read_DIP()]); // DIP switch status output_to_all(s); sprintf(s, "\"WiFi\": %d, \n\r", esp01_is_present()); // TRUE if WiFi is available output_to_all(s); sprintf(s, "\"VERSION\": %s, \n\r", SOFTWARE_VERSION); // Current software version output_to_all(s); dtostrf(revision()/100.0, 4, 2, str_c ); sprintf(s, "\"BD_REV\": %s \n\r", str_c); // Current board versoin output_to_all(s); sprintf(s, "}\r\n"); output_to_all(s); output_to_all(0); /* * All done, return */ return; } /*----------------------------------------------------- * * function: show_names * * brief: Display the list of names * * return: None * *----------------------------------------------------- * * If the name is Loop and display the settings * *-----------------------------------------------------*/ static void show_names(int v) { unsigned int i; if ( v != 0 ) { return; } Serial.print(T("\r\nNames\r\n")); i=0; while (names[i] != 0 ) { Serial.print(i); Serial.print(T(": \"")); Serial.print(names[i]); Serial.print(T("\", \r\n")); i++; } /* * All done, return */ return; } /*----------------------------------------------------- * * function: show_test * * brief: Execute one iteration of the self test * * return: None67! * *----------------------------------------------------*/ static void show_test(int test_number) { Serial.print(T("\r\nSelf Test:")); Serial.print(test_number); Serial.print(T("\r\n")); self_test(test_number); return; } /*----------------------------------------------------- * * function: set_trace * * brief: Turn the software trace on and off * * return: None * *----------------------------------------------------- * * Uset the trace to set the DIP switch * *-----------------------------------------------------*/ static void set_trace ( int trace // Trace on or off ) { char s[32]; sprintf(s, "\r\nTrace:"); if ( trace == 0 ) { is_trace = 0; strcat(s, "OFF\r\n"); } else { is_trace = 1; strcat(s,"ON\r\n"); } output_to_all(s); /* * The DIP switch has been remotely set */ return; }
58e093ff4f3f3ac182c74df39ca19601cf2acdc8
[ "C", "C++" ]
13
C++
ANKIT9263/freETarget
a6561440abe9a5721fd7a1b3cb4facf813abfdd9
36ca74bc81119865edf1a917202d8b2542bc3dce
refs/heads/master
<file_sep>helo hello world readme <file_sep>//hello testing git //adding something new to the codew #include<iostream> #include<vector> #include<math.h> #include <cstdlib> #include <cmath> #include <limits> #define E 2.7182818284 #define LAMBDA 3 using namespace std; // mean = mu variance = sigma^2 double generateGaussianNoise(double mu, double sigma) { const double epsilon = std::numeric_limits<double>::min(); const double two_pi = 2.0*3.14159265358979323846; static double z0, z1; static bool generate; generate = !generate; if (!generate) return z1 * sigma + mu; double u1, u2; do { u1 = rand() * (1.0 / RAND_MAX); u2 = rand() * (1.0 / RAND_MAX); } while (u1 <= epsilon); z0 = sqrt(-2.0 * log(u1)) * cos(two_pi * u2); z1 = sqrt(-2.0 * log(u1)) * sin(two_pi * u2); return z0 * sigma + mu; } int poissonRandom(double expectedValue) { int n = 0; //counter of iteration double limit; double x; //pseudo random number limit = exp(-expectedValue); x = rand() / INT_MAX; while (x > limit) { n++; x *= rand() / RAND_MAX; } return x; } void hammersley(int num) { float u, p, v; int kk; for (int k = 0; k < num; k++) { u = 0.0; p = 0.5; kk = k; while (kk > 0) { if (kk & 1) { u += p; } p *= 0.5; kk >>= 1; } v = (k + 0.5) / num; cout << "(" << u << "," << v << ")" << endl; } } void halton(int num, int p2) { // vector<double> myvec; int a, kk; float u, v, p, ip; int k = 0; while (k + 1 != num) { u = 0.0; p = .5; kk = k; while (kk > 0) { if (kk & 1) { u += p; } p *= .5; kk >>= 1; } v = 0.0; ip = (1.0 / p2); p = ip; kk = k; while (kk > 0) { a = kk % p2; if (a != 0) { v += a*p; } p *= ip; kk = (kk / p2); } cout << "(" << u << "," << v << ")" << endl; k++; } //return myvec; } int main() { halton(100, 3); hammersley(100); vector<int> x; for (size_t i = 0; i < 1000; i++) { cout << poissonRandom(20) << endl; x.push_back(poissonRandom(20)); } int sum = 0; for (int i = 0; i < x.size(); i++) { sum += x[i]; } cout << "AVG = " << sum / x.size() << endl; getchar(); return 0; }
f7f6f7edb2a7c4e44b2a743c8219736635159568
[ "Text", "C++" ]
2
Text
shantoeee/youtube.demo
0ad97627a07a77f0ab46114cd34968da38c41f48
055a961918c9aa487ba7e6149308a4252846992c
refs/heads/master
<file_sep># Simple Quiz Using JavaScript - [GitHub Pages Link - Go ahead and try it out](https://anshikag0219.github.io/js-quiz/) - [Repl Link - for terminal execution](https://replit.com/@AnshikaG0219/js-quiz) ## Challenges #### I have multiple challenges for you this time, So go ahead and try implementing any of the following: - Add time limit for the quiz - Implement pagination (i.e. displaying one question at a time) - Add different styles for results, Quiz presentation or for wrong and correct answer. - Adding Progress Bar - Create custom message for each level of results. For eg. 1-5 better luck next time ------------- Happy Learning ---------------------- ## Resources - [JS Array by mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) - [JS Objects by mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) - [All the event listeners by mdn](https://developer.mozilla.org/en-US/docs/Web/Events) - [Quiz video tutorial by Thapa Technical](https://youtu.be/rGhH70KUTuk) - [Quiz video tutorial by <NAME> (Advanced)](https://youtu.be/f4fB9Xg2JEY)<file_sep>const quizContainer = document.getElementById("quiz"); const resultsContainer = document.getElementById("results"); const submitButton = document.getElementById("submit"); const userName = document.getElementById("userName"); const welcomeText = document.querySelector("span"); const restartGame = document.getElementById("newGame"); const questions = [ { question: "Which character has a twin? ", options: { a: "Monica", b: "Chandler", c: "Phoebe", }, answer: "c", }, { question: "How many sisters does Joey have? ", options: { a: "8", b: "7", c: "9", }, answer: "b", }, { question: "What nickname did Monica’s dad give her? ", options: { a: "<NAME>", b: "Little Electronica", c: "Little Harmoica", }, answer: "c", }, { question: "What's the name of the dancer Joey lived with? ", options: { a: "Janice", b: "Janine", c: "Chandler", }, answer: "b", }, { question: "What’s Phoebe’s sister’s name? ", options: { a: "Ariel", b: "Ursula", c: "Janine", }, answer: "b", }, ]; function buildQuiz() { // variable to store the HTML output const output = []; // for each question... questions.forEach((currentQuestion, questionNumber) => { // variable to store the list of possible answers const answers = []; // and for each available answer... for (key in currentQuestion.options) { // ...add an HTML radio button answers.push( `<label> <input type="radio" name="question${questionNumber}" value="${key}"> ${key} : ${currentQuestion.options[key]} </label>` ); } console.log(answers); // add this question and its answers to the output output.push( `<div class="question"> ${currentQuestion.question} </div> <div class="answers"> ${answers.join("")} </div>` ); }); // finally combine our output list into one string of HTML and put it on the page quizContainer.innerHTML = output.join(""); console.log(output); } function showResults() { // gather answer containers from our quiz resultsContainer.style.height = "20vh"; const answerContainers = quizContainer.querySelectorAll(".answers"); // keep track of user's answers let score = 0; // for each question... questions.forEach((currentQuestion, questionNumber) => { // find selected answer const answerContainer = answerContainers[questionNumber]; const selector = `input[name=question${questionNumber}]:checked`; const userAnswer = (answerContainer.querySelector(selector) || {}).value; // if answer is correct if (userAnswer === currentQuestion.answer) { // add to the number of correct answers score++; // color the answers green answerContainers[questionNumber].style.color = "lightgreen"; } // if answer is wrong or blank else { // color the answers red answerContainers[questionNumber].style.color = "red"; } }); // show number of correct answers out of total resultsContainer.innerHTML = `Wooho! You got ${score} out of ${questions.length} correct!`; } buildQuiz(); // Event listeners submitButton.addEventListener("click", showResults); userName.addEventListener("input", () => { welcomeText.innerText = userName.value; }); restartGame.addEventListener("click", () => { window.location.reload(); });<file_sep>var readlineSync = require("readline-sync"); function welcome() { var userName = readlineSync.question("What's your name? "); console.log("Welcome "+ userName + " to F.R.I.E.N.D.S. Quiz "); game(userName); } var score = 0; var highScores = { name: "Anshika", score: 3, } // array of objects var questions = [{ question: "Which character has a twin? ", options: { a: "Monica", b: "Chandler", c: "Phoebe" }, answer: "c" }, { question: "How many sisters does Joey have? ", options: { a: "8", b: "7", c: "9" }, answer: "b" }, { question: "What nickname did Monica’s dad give her? ", options: { a: "<NAME>monica", b: "Little Electronica", c: "Little Harmoica" }, answer: "c" }, { question: "What's the name of the dancer Joey lived with? ", options: { a: "Janice", b: "Janine", c: "Chandler" }, answer: "b" }, { question: "What’s Phoebe’s sister’s name? ", options: { a: "Ariel", b: "Ursula", c: "Janine" }, answer: "b" }, ]; // play function function play(question, answer, options) { console.log(question); for(const key in options){ console.log(`${key} : ${options[key]}`); } var userAnswer = readlineSync.question("Choose you option: "); if (userAnswer.toUpperCase() === answer.toUpperCase()) { console.log("right!"); score = score + 1; } else { console.log("wrong!"); } console.log("*--------------------------*") console.log("current score: ", score); console.log("*--------------------------*") } function game(userName) { for (var i=0; i<questions.length; i++) { var currentQuestion = questions[i]; play(currentQuestion.question, currentQuestion.answer, currentQuestion.options) } showScores(userName); } function showScores(userName) { console.log("YAY! You SCORED: ", score); if(highScores.score <= score) { highScores.name = userName; highScores.score = score; } console.log("Check out the high scores!"); console.log(highScores.name, " : ", highScores.score); } welcome();
2d0a8abdbb0337b9d7d5eb9a1e1a487f0c00be6e
[ "Markdown", "JavaScript" ]
3
Markdown
AnshikaG0219/js-quiz
ec00f5e15f7ac9ac51f070c657691411e97a8b9e
2e35613c161d5fc480f490ede99b1428b275ad36
refs/heads/master
<repo_name>stasbanned/BookingHairdresser<file_sep>/Hairs/AuthorizationVC.swift // // AuthorizationVC.swift // Hairs // // Created by <NAME> on 27.05.2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import QuartzCore class AuthorizationVC: UIViewController, AuthorizationProtocol { var user: [User]? = nil var master: [Master]? = nil var event: [Event]? = nil var isShowNavigationBar = true lazy var authorization = Authorization(delegate: self) @IBOutlet weak var loginText: UITextField! @IBOutlet weak var passwordText: UITextField! @IBOutlet weak var userOrMasterControl: UISegmentedControl! @IBAction func logInButton(_ sender: Any) { authorization.authNewUserOrMaster(performSegue: performSegue(withIdentifier:sender:), withIdentifierforUser: "toListOfMasters", withIdentifierforMaster: "toListOfUsers", sender: self) } override func viewDidLoad() { super.viewDidLoad() user = User.fetchObject() master = Master.fetchObject() event = Event.fetchObject() passwordText.isSecureTextEntry = true if isShowNavigationBar { self.navigationController?.isNavigationBarHidden = false } else { self.navigationController?.isNavigationBarHidden = true } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toListOfMasters" { let destination = segue.destination as! ListOfMasterTableVC if userOrMasterControl.selectedSegmentIndex == 0 { for i in user! { if i.login == loginText.text && i.password == passwordText.text { destination.userName = i.name! } } } } if segue.identifier == "toListOfUsers" { let destination = segue.destination as! ListOfUsersTableVC if userOrMasterControl.selectedSegmentIndex == 1 { for i in master! { if i.login == loginText.text && i.password == <PASSWORD>Text.text { destination.masterName = i.name! } } } } } func getSegmentControlValue() -> Int { if userOrMasterControl.selectedSegmentIndex == 0 { return 0 } return 1 } func getLoginText() -> String { return loginText.text! } func getPasswordText() -> String { return passwordText.text! } func changeColorOfPasswodField() { if passwordText.text == "" { passwordText.layer.borderWidth = 1.0 passwordText.layer.borderColor = UIColor.red.cgColor } else { passwordText.layer.borderWidth = 0 passwordText.layer.borderColor = nil } } } <file_sep>/Hairs/Registration.swift // // Registration.swift // Hairs // // Created by <NAME> on 30.05.2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit protocol RegistrationProtocol { func getSegmentControlValue() -> Int func getLoginText() -> String func getPasswordText() -> String func getConfirmText() -> String func getNameText() -> String } class Registration { var delegate: RegistrationProtocol? init(delegate: RegistrationProtocol) { self.delegate = delegate } func regNewUserOrMaster(performSegue: (String, Any?) -> (), withIdentifier: String, sender: Any?) { var user: [User]? = nil var master: [Master]? = nil user = User.fetchObject() master = Master.fetchObject() var invalidInput = false if delegate?.getSegmentControlValue() == 0 { if delegate?.getPasswordText() == delegate?.getConfirmText() && delegate?.getLoginText() != "" && delegate?.getPasswordText() != "" && delegate?.getNameText() != ""{ for i in user! { if i.login == delegate?.getLoginText() { invalidInput = true print("Invalid input") break } } if invalidInput == false { User.saveObject(login: (delegate?.getLoginText())!, password: (delegate?.getPasswordText())!, name: (delegate?.getNameText())!) user = User.fetchObject() print("Successful registration") performSegue(withIdentifier, sender) } } } else { if delegate?.getPasswordText() == delegate?.getConfirmText() && delegate?.getLoginText() != "" && delegate?.getPasswordText() != "" && delegate?.getNameText() != ""{ for i in master! { if i.login == delegate?.getLoginText() { invalidInput = true print("Invalid input") break } } if invalidInput == false { //print((delegate?.getLoginText())!) Master.saveObject(login: (delegate?.getLoginText())!, password: (delegate?.getPasswordText())!, name: (delegate?.getNameText())!) master = Master.fetchObject() print("Successful registration") performSegue(withIdentifier, sender) } } } } } <file_sep>/Hairs/infoAboutUserVC.swift // // infoAboutUserVC.swift // Hairs // // Created by <NAME> on 28.05.2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class infoAboutUserVC: UIViewController { var masterName = "" var userName = "" var event: [Event]? = nil @IBOutlet weak var nameOfUserLabel: UILabel! @IBOutlet weak var dateOfUserLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() event = Event.fetchObject() for i in event! { if i.date != nil && i.master != nil && i.user != nil { if i.user?.name == userName && i.master?.name == masterName{ nameOfUserLabel.text = i.user?.name let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy-hh-mm" let stringDate: String = dateFormatter.string(from: i.date! as Date) dateOfUserLabel.text = stringDate } } } } } <file_sep>/Hairs/RegistrationVC.swift // // RegistrationVC.swift // Hairs // // Created by <NAME> on 27.05.2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class RegistrationVC: UIViewController, RegistrationProtocol { var user: [User]? = nil var master: [Master]? = nil lazy var registration = Registration(delegate: self) @IBOutlet weak var loginText: UITextField! @IBOutlet weak var passwordText: UITextField! @IBOutlet weak var confirmText: UITextField! @IBOutlet weak var nameText: UITextField! @IBOutlet weak var userOrMasterController: UISegmentedControl! @IBAction func signUpButton(_ sender: Any) { registration.regNewUserOrMaster(performSegue: performSegue(withIdentifier:sender:), withIdentifier: "toAuthorization", sender: self) } override func viewDidLoad() { super.viewDidLoad() user = User.fetchObject() master = Master.fetchObject() passwordText.isSecureTextEntry = true confirmText.isSecureTextEntry = true } func getSegmentControlValue() -> Int { if userOrMasterController.selectedSegmentIndex == 0 { return 0 } return 1 } func getLoginText() -> String { return loginText.text! } func getPasswordText() -> String { return passwordText.text! } func getConfirmText() -> String { return confirmText.text! } func getNameText() -> String { return nameText.text! } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let destination = segue.destination as! AuthorizationVC destination.isShowNavigationBar = false } } <file_sep>/Hairs/InfoAboutMasterVC.swift // // InfoAboutMasterVC.swift // Hairs // // Created by <NAME> on 28.05.2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class InfoAboutMasterVC: UIViewController { var masterName = "" var userName = "" var event: [Event]? = nil var master: [Master]? = nil var infoAboutMaster = InfoAboutMaster() @IBOutlet weak var nameOfMasterLabel: UILabel! @IBOutlet weak var datePicker: UIDatePicker! @IBAction func bookingButton(_ sender: Any) { infoAboutMaster.getInfoAboutMaster(datePicker: datePicker, userName: userName) } override func viewDidLoad() { super.viewDidLoad() nameOfMasterLabel.text = masterName event = Event.fetchObject() master = Master.fetchObject() } } <file_sep>/Hairs/ListOfUsersTableVC.swift // // ListOfUsersTableVC.swift // Hairs // // Created by <NAME> on 28.05.2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class ListOfUsersTableVC: UITableViewController { var user: [User]? = nil var event: [Event]? = nil var master: [Master]? = nil var masterName = "" var userName = "" var indexOfSelectedRow = 0 var arrayOfUsers: [String] = [] override func viewDidLoad() { super.viewDidLoad() indexOfSelectedRow = 0 master = Master.fetchObject() user = User.fetchObject() event = Event.fetchObject() tableView.tableFooterView = UIView() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { event = Event.fetchObject() var k = 0 for i in event! { if i.date != nil && i.master != nil && i.user != nil { if i.master?.name == masterName { k += 1 arrayOfUsers.append((i.user?.name)!) } } } return k } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = arrayOfUsers[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { indexOfSelectedRow = indexPath.row performSegue(withIdentifier: "toUserInfo", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let destination = segue.destination as! infoAboutUserVC destination.userName = arrayOfUsers[indexOfSelectedRow] destination.masterName = masterName for i in event! { if i.date != nil && i.user != nil && i.master != nil || i.date == nil && i.user != nil && i.master == nil && i.user?.name == userName { } else { Event.deleteObject(event: i) event = Event.fetchObject() } } } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ // Override to support editing the table view. /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>/Hairs/Authorization.swift // // Authorization.swift // Hairs // // Created by <NAME> on 30.05.2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit protocol AuthorizationProtocol { func getSegmentControlValue() -> Int func getLoginText() -> String func getPasswordText() -> String func changeColorOfPasswodField() } class Authorization { var delegate: AuthorizationProtocol? init(delegate: AuthorizationProtocol) { self.delegate = delegate } func authNewUserOrMaster(performSegue: (String, Any?) -> (), withIdentifierforUser: String, withIdentifierforMaster: String, sender: Any?) { var user: [User]? = nil var master: [Master]? = nil var event: [Event]? = nil user = User.fetchObject() master = Master.fetchObject() event = Event.fetchObject() if delegate?.getSegmentControlValue() == 0 { for i in user! { if i.login == delegate?.getLoginText() && i.password == delegate?.getPasswordText() { print("Login successful as user") Event.saveObject(date: nil, userName: i, masterName: nil) event = Event.fetchObject() performSegue(withIdentifierforUser, sender) } } } else { for i in master! { if i.login == delegate?.getLoginText() && i.password == delegate?.getPasswordText() { print("Login successful as master") performSegue(withIdentifierforMaster, sender) } } } delegate?.changeColorOfPasswodField() } }
8f95ed24eee30cccc0417f8e9badc1a1cb04cdfa
[ "Swift" ]
7
Swift
stasbanned/BookingHairdresser
5bcdd163473fcffb6fbb43bb233d0c85a6b7519c
359ed145888099495cccd1c23fdd06bd24b52409
refs/heads/master
<file_sep>class Post < ActiveRecord::Base validates :title, presence: true validates :content, length: { minimum: 250 } validates :summary, length: { maximum: 250 } validates :category, inclusion: { in: %w(Fiction Non-Fiction), message: "%{value} is not a valid category" } validate :click_bait, if: :title CLICK_BAIT_WORDS = ["Won't Believe", "Secret", "Top", "Guess"] def click_bait if !CLICK_BAIT_WORDS.find {|click_bait| title.match(click_bait)} errors.add(:title, "can't be click bait") end end end
61488a376ca993b45766a040ca7ab26e85f2f259
[ "Ruby" ]
1
Ruby
esmeryjose/activerecord-validations-lab-wdf-000
24bba1f10b7ecbf79d19f55a2be9e1bddaefe3c3
01c7c09d1de9ace55e724aa51a4eedea61f65429
refs/heads/main
<repo_name>crvvasconcellos/Golang<file_sep>/src/calculadora/calculator/calculator.go // Package calculator provides a library for simple calculations in Go. package calculator import ( "errors" "math" ) var ErrExpected = errors.New("É impossivel dividir por ZERO - Resultado Indefinido") var ErrExpected1 = errors.New("Resultado Indefinido") /*type Calc struct { a, b float64 }*/ // Add takes two numbers and returns the result of adding them together. func Add(a, b float64, c ...float64) float64 { result := a + b for _, i := range c { result += i } return result } // Subtract takes two numbers and returns the result of subtracting the second // from the first. func Subtract(a, b float64, c ...float64) float64 { result := a - b for _, i := range c { result -= i } return result } func Multiply(a, b float64, c ...float64) float64 { result := a * b for _, i := range c { result *= i } return result } func Divide(a, b float64, c ...float64) (float64, error) { if b == 0 { return 0, ErrExpected } result := a / b for _, i := range c { result /= i if i == 0 { return 0, ErrExpected } } return result, nil } func Sqrt(a float64) (float64, error) { if a < 0 { return 0, ErrExpected1 } return sqrt(a), nil } func sqrt(a float64) float64 { //fmt.Println(math.Pow(a, 0.5)) return math.Pow(a, 0.5) } /*func main() { fmt.Println(Sqrt(0)) }*/ <file_sep>/src/go_udy/2_variaveis/variaveis.go package main import "fmt" func main() { var variavel1 string = "varriavel1" variavel2 := "variavel2" var ( variavel3 string = "3" variavel4 string = "4" ) variavel5, variavel6 := "5", "6" fmt.Printf("%v, %v", variavel1, variavel2) fmt.Println(variavel3) fmt.Println(variavel4) fmt.Println(variavel5) fmt.Println(variavel6) } <file_sep>/src/aulas_nache/aprenda_go_com_testes/maps/maps_test.go package maps import ( "testing" ) func TestBusca2(t *testing.T) { dicionario := Dicionario{"teste": "isso é apenas um teste"} t.Run("palavra conhecida", func(t *testing.T) { got, _ := dicionario.Busca("teste") want := "isso é apenas um teste" if got != want { t.Errorf("got '%s', want '%s', dado '%s'", got, want, "test") } }) t.Run("palavra desconhecida", func(t *testing.T) { _, err := dicionario.Busca("desconhecida") if err == nil { t.Fatal("é esperado que um erro seja obtido.") } }) } func TestAdiciona(t *testing.T) { dicionario := Dicionario{} dicionario.Adiciona1("teste", "isso é apenas um teste") got := "isso é apenas um teste" want, err := dicionario.Busca("teste") if err != nil { t.Fatal("não foi possível encontrar a palavra adicionada:", err) } if got != want { t.Errorf("want '%s', got '%s'", want, got) } } func TestUpdate(t *testing.T) { palavra := "teste" definicao := "isso é apenas um teste" dicionario := Dicionario{palavra: definicao} novaDefinicao := "nova definição" dicionario.Atualiza(palavra, novaDefinicao) } func TestDeleta(t *testing.T) { palavra := "teste" dicionario := Dicionario{palavra: "definição de teste"} dicionario.Deleta(palavra) _, err := dicionario.Busca(palavra) if err != ErroNew { t.Errorf("espera-se que '%s' seja deletado", palavra) } } <file_sep>/src/aulas_nache/aprenda_go_com_testes/maps/maps.go package maps import ( "errors" ) type Dicionario map[string]string var ErroNew = errors.New("Erro") func (d Dicionario) Busca(key string) (string, error) { _, ok := d[key] if !ok { return "", ErroNew } return d[key], nil } func (d Dicionario) Adiciona1(key, value string) { d[key] = value } func (d Dicionario) Atualiza(key, value string) { d[key] = value } func (d *Dicionario) Deleta(key string) { delete(*d, key) } <file_sep>/src/aulas_youtube/estruturas_metodos_interfaces/est_met_interf.go package main import "fmt" //Struct: type Pessoa struct { Nome string Idade int Veiculo Veiculo } type Carro struct { Fabricante string Modelo string Ano int } type Moto struct { Fabricante string Ano int } // Método: func (p Pessoa) Andou() { fmt.Println(p.Nome, "Andou a mais de 200 km/h no", p.Veiculo) } //Interface: type Veiculo interface { buzina() } func (c Carro) buzina() { fmt.Println("Andou a mais de 200 km/h no", c.Modelo) } func main() { carro := Carro{ Fabricante: "Honda", Modelo: "Civic 1.7", Ano: 2002, } /*moto := Moto{ Fabricante: "Ducati", Ano: 2015, }*/ cyro := Pessoa{ Nome: "Cyro", Idade: 32, Veiculo: carro, } fmt.Println("Nome: ", cyro.Nome) fmt.Println("Idade: ", cyro.Idade) //fmt.Println("Carro: ", cyro.Carro.Modelo) fmt.Println("Carro: ", cyro.Veiculo) cyro.Andou() carro.buzina() } <file_sep>/src/go_udy/12_switch/switch.go package main import "fmt" func DiaDaSemana(n int) string { switch n { case 1: return "Domingo" case 2: return "Segunda_Feira" default: return "numero invalido" } } func DiaDaSemana2(n int) string { switch { case n == 1: return "Domingo" default: return "Erroooouuu" } } func DiaDaSemana3(n int) string { var dia string switch { case n == 1: dia = "Domingo" default: dia = "Erroooouuu" } return dia } func main() { fmt.Println(DiaDaSemana(20)) fmt.Println(DiaDaSemana2(20)) fmt.Println(DiaDaSemana3(20)) } <file_sep>/src/aula_nache_youtube/go_tour/rot13_rightway/rot13.go package main import ( "io" "os" "strings" ) type rot13Reader struct { r io.Reader } func (rot rot13Reader) Read(bytes []byte) (int, error) { count := 0 n, err := rot.r.Read(bytes) if err != nil { return 0, err } for i := 0; i < n; i++ { count++ if bytes[i] >= 97 && bytes[i] <= 122 { if bytes[i]+13 > 122 { bytes[i] = bytes[i] + 13 - 26 continue } bytes[i] = bytes[i] + 13 } if bytes[i] >= 65 && bytes[i] <= 90 { if bytes[i]+13 > 90 { bytes[i] = bytes[i] + 13 - 26 continue } bytes[i] = bytes[i] + 13 } } return count, nil } func main() { s := strings.NewReader("Lbh penpxrq gur pbqr!") r := rot13Reader{s} io.Copy(os.Stdout, &r) } <file_sep>/src/aula_nache_youtube/README.md - Gerar cartelas - Estrutura de dados da cartela - Sorteio - Armazenar números já sorteados - Imprime a cartela com valores sorteados<file_sep>/src/go_udy/13_loops/loops.go package main import ( "fmt" "time" ) func main() { i := 0 for i < 10 { i++ time.Sleep(time.Millisecond) fmt.Println(i) } fmt.Println(i) for j := 0; j < 10; j++ { fmt.Println(j) time.Sleep(time.Millisecond) } nomes := [3]string{"Jonas", "Caio", "Carla"} for _, nome := range nomes { fmt.Println(nome) } for ind, letra := range "palavra" { fmt.Println(ind, string(letra)) } usuario := map[string]string{ "nome": "Josias", "sobrenome": "boneco", } for chave, name := range usuario { fmt.Println(chave, name) } } <file_sep>/src/calculadora/calculator/calculator_test.go package calculator_test import ( "calculator" "math/rand" "testing" ) func TestSubtract1(t *testing.T) { t.Parallel() var want float64 = -4 got := calculator.Subtract(4, 8) if want != got { t.Errorf("want %f, got %f", want, got) } } func TestAdd(t *testing.T) { testCases := []struct { desc string want, a, b float64 c []float64 }{ {desc: "adicao 2 + 2 = 4", want: 4, a: 2, b: 2}, {desc: "adicao 1 + 1.25 = 2.25", want: 2.25, a: 1, b: 1.25}, {"adicao 1 + 1.25 = 2.25", 10.25, 1, 1.25, []float64{5.0, 3.0}}, } for _, tC := range testCases { t.Run(tC.desc, func(t *testing.T) { got := calculator.Add(tC.a, tC.b, tC.c...) if tC.want != got { t.Errorf("want %f, got %f", tC.want, got) } }) } } func TestSubstract(t *testing.T) { testCases := []struct { desc string want, a, b float64 c []float64 }{ { desc: "subtracao 2 - 16 = -14", want: -14, a: 2, b: 16, }, { desc: "subtracao 0.15 - (-1) = 1.15", want: 1.15, a: 0.15, b: -1, }, { desc: "subtracao 0.15 - (-1) - (-100) = 101.15", want: 101.15, a: 0.15, b: -1, c: []float64{-100.0}, }, } for _, tC := range testCases { t.Run(tC.desc, func(t *testing.T) { got := calculator.Subtract(tC.a, tC.b, tC.c...) if tC.want != got { t.Errorf("want %f, got %f", tC.want, got) } }) } } func TestMultiply(t *testing.T) { testCases := []struct { desc string want float64 a float64 b float64 c []float64 }{ { desc: "multiplicacao -0.5 * -0.75 = 0.375", want: 0.375, a: -0.5, b: -0.75, }, { desc: "multiplicacao 900 * 1500 = 1350000", want: 1350000, a: 900, b: 1500, }, { desc: "multiplicacao 1 * 2 * 3 = 6", want: 6, a: 1.0, b: 2.0, c: []float64{3.0}, }, { desc: "multiplicacao 3 * 3 * 3 * 3 = 81", want: 81, a: 3.0, b: 3.0, c: []float64{3.0, 3.0}, }, } for _, tC := range testCases { t.Run(tC.desc, func(t *testing.T) { got := calculator.Multiply(tC.a, tC.b, tC.c...) if tC.want != got { t.Errorf("want %f, got %f", tC.want, got) } }) } } func TestDivide(t *testing.T) { testCases := []struct { desc string want, a, b float64 c []float64 }{ { desc: "divisao -0.5 / -2 = 0.25", want: 0.25, a: -0.5, b: -2, }, { desc: "divisao por 0", want: 0, a: 100, b: 0, }, { desc: "divisao 100 / 10 / 5 / 2 = 1", want: 1, a: 100, b: 10, c: []float64{5.0, 2.0}, }, { desc: "divisao 100 / 10 / 5 / 2 / 1 / 0 = erro", want: 0, a: 100, b: 10, c: []float64{5.0, 2.0, 1.0, 0.0}, }, { desc: "divisao 100 / 10 / 0 = erro", want: 0, a: 100, b: 10, c: []float64{0.0}, }, } for _, tC := range testCases { t.Run(tC.desc, func(t *testing.T) { got, err := calculator.Divide(tC.a, tC.b, tC.c...) c := 0 for _, i := range tC.c { if i == 0 { if err != calculator.ErrExpected { t.Fatalf("Esperava-se um erro %v, mas recebeu o %v", calculator.ErrExpected, err) } } else { c += 1 } } if tC.b != 0 && c == len(tC.c) { if err != nil { t.Fatalf("Não era esperado um erro %v, porém ele ocorreu!", err) } } if tC.b == 0 { if err != calculator.ErrExpected { t.Fatalf("Esperava-se um erro %v, mas recebeu o %v", calculator.ErrExpected, err) } } if tC.want != got { t.Errorf("want %f, got %f", tC.want, got) } }) } } func TestSqrt(t *testing.T) { testCases := []struct { desc string want, a float64 }{ {desc: "raiz quadrada 7 = 49", want: 7, a: 49}, {"Raiz negativa - Erro", 1.4142135623730951, 2}, {"Raiz quadrada 0 = 0", 0, 0}, {"Raiz quadrada 144 = 12", 12, 144}, } for _, tC := range testCases { t.Run(tC.desc, func(t *testing.T) { got, err := calculator.Sqrt(tC.a) if tC.a < 0 { if err != calculator.ErrExpected1 { t.Fatalf("Esperava-se um erro %v, mas recebeu o %v", calculator.ErrExpected1, err) } } if tC.a >= 0 { if err != nil { t.Fatalf("Não era esperado um erro %v, porém ele ocorreu!", err) } } if tC.want != got { t.Errorf("want %f, got %f", tC.want, got) } }) } } func TestAddRandom(t *testing.T) { t.Parallel() for i := 0; i < 100; i++ { a := rand.NormFloat64() b := rand.NormFloat64() c := rand.NormFloat64() var want float64 = a + b + c got := calculator.Add(a, b, c) if want != got { t.Errorf("want %f, got %f", want, got) } } } <file_sep>/src/aulas_nache/aprenda_go_com_testes/iteracao/for_test.go package iteracao_test import ( "iteracao" "testing" ) func TestRepetir(t *testing.T) { got := iteracao.Repetir("a") want := "aaaaa" if got != want { t.Errorf("got '%s' but want '%s'", got, want) } } func BenchmarkRepetir(b *testing.B) { for i := 0; i < b.N; i++ { iteracao.Repetir("a") } } <file_sep>/src/go_udy/11_estruturas_controle/if_else.go package main import "fmt" func main() { n := 10 p := &n *p = 50 if n > 15 { fmt.Println("Maior que 15") } else { fmt.Println("Menor que 15") } if n2 := n; n2 > 0 { fmt.Println("Maior que 0") } fmt.Println(n) } <file_sep>/src/aulas_nache/aprenda_go_com_testes/iteracao/for.go package iteracao const quantidadeRepetcoes = 5 func Repetir(caractere string) string { var repeticoes string for i := 0; i < quantidadeRepetcoes; i++ { repeticoes += caractere } return repeticoes } /* func Repetir(caractere string) string { return "" } */ <file_sep>/src/aulas_nache/aprenda_go_com_testes/iteracao/go.mod module iteracao go 1.15 <file_sep>/src/go_udy/8_ponteiros/ponteiros.go package main import "fmt" func main() { var v1 int = 10 var v2 int = v1 fmt.Println(v1, v2) v1++ fmt.Println(v1, v2) // Ponteiro é uma referência de memória var v3 int = 100 var ponteiro *int ponteiro = &v3 fmt.Println(v3, ponteiro) fmt.Println(v3, *ponteiro) // desreferenciamento } <file_sep>/src/go_udy/14_funcoes_avancadas/14.2_funcoes_variaticas/funcoes_variaticas.go package main import "fmt" func soma(n ...int) int { result := 0 for _, i := range n { result += i } return result } func main() { fmt.Println(soma(1, 2, 3, 4)) } <file_sep>/src/aulas_nache/aprenda_go_com_testes/inteiros/adicionador.go package inteiros import "fmt" func Adiciona(x, y int) int { return x + y } func inteiros() { fmt.Println(Adiciona(2, 3)) } <file_sep>/src/aulas_youtube/ponteiros/ponteiros.go package main import "fmt" func main() { //memória---0xc0000120a0(50), <----- a <----- 50 a := 50 ponteiros := &a *ponteiros = 100 b := &a *b = 200 fmt.Println(a) } <file_sep>/src/go_udy/14_funcoes_avancadas/14.3_funcoes_anonimas/funcoes_anonimas.go package main import "fmt" func main() { func() { fmt.Println("Hello!") }() func(texto string) { fmt.Println(texto) }("Hello!") } <file_sep>/src/go_udy/14_funcoes_avancadas/14.5_defer/defer.go package main import "fmt" func f1() { fmt.Println("Executando a f1") } func f2() { fmt.Println("Executando a f2") } func AlunoAprovado(n1, n2 float64) bool { defer fmt.Println("Média calculada. Resultado retornado!") fmt.Println("Entrando na função para verificar se o aluno está aprovado") if (n1+n2)/2 > 6 { return true } return false } func main() { /*defer f1() // DEFER = adiar f2()*/ fmt.Println(AlunoAprovado(7, 8)) } <file_sep>/src/aulas_nache/aprenda_go_com_testes/estruturas_met_intef/estruturas.go package estruturas const Pi = 3.14159265 type Circle struct { Raio float64 } type Retangulo struct { Largura, Altura float64 } type Triangulo struct { Base, Altura float64 } type Forma interface { Area() float64 } func Perimetro(retangulo Retangulo) float64 { return 2 * (retangulo.Largura + retangulo.Altura) } /*func Area(retangulo Retangulo) float64 { return (retangulo.Largura * retangulo.Altura) }*/ func AreaCircle(circle Circle) float64 { return (Pi * (circle.Raio * circle.Raio)) } func (r Retangulo) Area() float64 { return r.Altura * r.Largura } func (c Circle) Area() float64 { return Pi * c.Raio * c.Raio } func (t Triangulo) Area() float64 { return (t.Base * t.Altura) / 2 } <file_sep>/src/aula_nache_youtube/aula_nache_youtube.go package main import ( "fmt" "math/rand" "time" ) const cols, rows, totalCardNumber, totalBalls = 5, 5, 24, 75 var card [totalCardNumber]int func main() { fmt.Println("Bem vindo, jogador") rand.Seed(time.Now().UnixNano()) for i := 1; i <= totalCardNumber; i++ { n := rand.Intn(totalBalls-1) + 1 card[i-1] = n } fmt.Println(card) } <file_sep>/src/aulas_nache/aprenda_go_com_testes/inteiros/go.mod module inteiros go 1.15 <file_sep>/src/go_udy/10_maps/maps.go package main import "fmt" func main() { usuario := map[string]string{ "nome": "Paulo", "sobrenome": "Silva", } fmt.Println(usuario) fmt.Println(usuario["sobrenome"]) usuario2 := map[string]map[string]string{ "nome": { "primeiro_nome": "Jonas", "ultimo_nome": "Santos", }, } fmt.Println(usuario2) } <file_sep>/src/go_udy/90_teste/teste.go package main import ( "errors" "fmt" ) var ErrExpected = errors.New("É impossivel dividir por ZERO - Resultado Indefinido") var count int = 0 func Divide(a, b float64, c ...float64) (float64, error) { if b == 0 { return 0, ErrExpected } //count := 0 result := a / b for _, i := range c { result /= i if i == 0 { return 0, ErrExpected } else { count += 1 } } return result, nil } func main() { /*var value string fmt.Println("Enter values: ") fmt.Scan(&value) fmt.Println(value) for _, valor := range value { fmt.Println(string(valor)) }*/ fmt.Println(Divide(100.0, 0.1, 2.0, 1.0, 0.1)) fmt.Println(count) } <file_sep>/src/aulas_nache/aprenda_go_com_testes/estruturas_met_intef/estruturas_test.go package estruturas_test import ( "estruturas" "testing" ) func TestPerimetro(t *testing.T) { retangulo := estruturas.Retangulo{10.0, 10.0} want := 40.0 got := estruturas.Perimetro(retangulo) if want != got { t.Errorf("want %.2f got %.2f", want, got) } } func TestArea(t *testing.T) { retangulo := estruturas.Retangulo{12.0, 6.0} want := 72.0 got := retangulo.Area() if want != got { t.Errorf("want %.2f got %.2f", want, got) } } func TestCircle(t *testing.T) { circle := estruturas.Circle{10.0} want := 314.159265 got := estruturas.AreaCircle(circle) if want != got { t.Errorf("want %.2f got %.2f", want, got) } } func TestAreaNovo(t *testing.T) { t.Run("retângulos", func(t *testing.T) { retangulo := estruturas.Retangulo{12.0, 6.0} want := 72.0 got := retangulo.Area() if want != got { t.Errorf("want %.2f got %.2f", want, got) } }) t.Run("círculos", func(t *testing.T) { circulo := estruturas.Circle{10.0} want := 314.159265 got := circulo.Area() if want != got { t.Errorf("want %.2f got %.2f", want, got) } }) } func TestAreaNovo2(t *testing.T) { verificaArea := func(t *testing.T, forma estruturas.Forma, want float64) { t.Helper() got := forma.Area() if want != got { t.Errorf("want %.2f got %.2f", want, got) } } t.Run("retângulos", func(t *testing.T) { retangulo := estruturas.Retangulo{12.0, 6.0} verificaArea(t, retangulo, 72.0) }) t.Run("círculos", func(t *testing.T) { circulo := estruturas.Circle{10} verificaArea(t, circulo, 314.159265) }) } func TestAreaNovo3(t *testing.T) { testesArea := []struct { forma estruturas.Forma want float64 }{ {estruturas.Retangulo{12, 6}, 72.0}, {estruturas.Circle{10}, 314.159265}, } for _, tt := range testesArea { got := tt.forma.Area() if got != tt.want { t.Errorf("want %.2f, got %.2f", tt.want, got) } } } func TestAreaNovo4(t *testing.T) { testesArea := []struct { forma estruturas.Forma want float64 }{ {estruturas.Retangulo{12, 6}, 72.0}, {estruturas.Circle{10}, 314.159265}, {estruturas.Triangulo{12, 6}, 36.0}, } for _, tt := range testesArea { got := tt.forma.Area() if got != tt.want { t.Errorf("want %.2f, got %.2f", tt.want, got) } } } func TestAreaNovo5(t *testing.T) { testesArea := []struct { forma estruturas.Forma want float64 }{ {forma: estruturas.Retangulo{Largura: 12, Altura: 6}, want: 72.0}, {forma: estruturas.Circle{Raio: 10}, want: 314.159265}, {forma: estruturas.Triangulo{Base: 12, Altura: 6}, want: 36.0}, } for _, tt := range testesArea { got := tt.forma.Area() if got != tt.want { t.Errorf("want %.2f, got %.2f", tt.want, got) } } } func TestAreaNovo6(t *testing.T) { testesArea := []struct { nome string forma estruturas.Forma temArea float64 }{ {nome: "Retângulo", forma: estruturas.Retangulo{Largura: 12, Altura: 6}, temArea: 72.0}, {nome: "Círculo", forma: estruturas.Circle{Raio: 10}, temArea: 314.159265}, {nome: "Triângulo", forma: estruturas.Triangulo{Base: 12, Altura: 6}, temArea: 36.0}, } for _, tt := range testesArea { t.Run(tt.nome, func(t *testing.T) { got := tt.forma.Area() if got != tt.temArea { t.Errorf("%#v got %.2f, want %.2f", tt.forma, got, tt.temArea) } }) } } <file_sep>/src/go_udy/15_metodos/metodos.go package main import "fmt" type usuario struct { nome string idade int } func (u usuario) salvar() { fmt.Printf("Salvando os dados do usuário %q no banco de dados \n", u.nome) } func (u *usuario) fazerNiver() { u.idade++ } func main() { usuario1 := usuario{"Jonas", 17} fmt.Println(usuario1) usuario1.salvar() usuario1.fazerNiver() fmt.Println(usuario1.idade) } <file_sep>/src/aulas_nache/aprenda_go_com_testes/arrays_slices/arrays.go package arrays func Soma(numbers []int) int { sum := 0 for _, number := range numbers { sum += number } return sum } func SomaTudo(numeroParaSomar ...[]int) []int { var somas []int for _, numeros := range numeroParaSomar { somas = append(somas, Soma(numeros)) } return somas } func SomaTodoOResto(numeroParaSomar ...[]int) []int { var somas []int for _, numeros := range numeroParaSomar { if len(numeros) == 0 { somas = append(somas, 0) continue } somas = append(somas, Soma(numeros[1:])) } return somas } <file_sep>/src/go_udy/3_tipos_de_dados/tipos_de_dados.go package main func main() { // int8, int16, int32, int64 // uint8, uint16, uint32, uint64 // float32, float64 // string // boolean // error } <file_sep>/src/go_udy/9_arrays_slices/arrays_slices.go package main import "fmt" func main() { var ar1 [5]int ar1[0] = 2 fmt.Println(ar1) ar2 := [5]int{1, 2, 3, 4, 5} fmt.Println(ar2) sl1 := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11} fmt.Println(sl1) fmt.Printf("%T, %T", ar2, sl1) fmt.Println("---------") sl1 = append(sl1, 57) fmt.Println(sl1) // Arrays Internos sl2 := make([]float64, 10, 11) // 2º valor = tamanho(lenght) // 3º valor = capacidade(cap) fmt.Println(sl2) fmt.Println(len(sl2)) fmt.Println(cap(sl2)) sl3 := append(sl2, 57) sl3 = append(sl3, 59) fmt.Println("---------") fmt.Println(sl3) fmt.Println(len(sl3)) fmt.Println(cap(sl3)) } <file_sep>/src/go_udy/14_funcoes_avancadas/14.8_funcoes_ponteiros/funcoes_ponteiros.go package main import "fmt" func inverterSinal(n int) int { return n * -1 } func inverterSinalComPonteiro(n *int) { *n = *n * -1 } func main() { n := 20 nInvertido := inverterSinal(n) fmt.Println(nInvertido) novo_n := 40 fmt.Println(novo_n) inverterSinalComPonteiro(&novo_n) fmt.Println(novo_n) novo_n = 50 inverterSinalComPonteiro(&novo_n) fmt.Println(novo_n) } <file_sep>/src/aulas_nache/aprenda_go_com_testes/ponteiros_erros/ponteiros_erros.go package ponteiros_erros import ( "errors" "fmt" ) type Bitcoin int type Stringer interface { String() string } type Carteira struct { saldo Bitcoin } func (c *Carteira) Depositar(qtde Bitcoin) { //fmt.Printf("O enderço do saldo no Depositar é %v \n", &c.saldo) c.saldo += qtde } func (c *Carteira) Saldo() Bitcoin { return c.saldo } func (b Bitcoin) String() string { return fmt.Sprintf("%d BTC", b) } /*func (c *Carteira) Retirar(qtde Bitcoin) { c.saldo -= qtde } func (c *Carteira) Retirar(qtde Bitcoin) error { if qtde > c.saldo { return errors.New("não é possível retirar: saldo insuficiente") } c.saldo -= qtde return nil }*/ var ErroSaldoInsuficiente = errors.New("não é possível retirar: saldo insuficiente") func (c *Carteira) Retirar(qtde Bitcoin) error { if qtde > c.saldo { return ErroSaldoInsuficiente } c.saldo -= qtde return nil } <file_sep>/src/go_udy/7_heranca/heranca.go package main import "fmt" type pessoa struct { nome string idade int altura float64 } type estudante struct { pessoa curso string reg int } func main() { p1 := pessoa{"Jonas", 20, 1.78} fmt.Println(p1) est1 := estudante{p1, "engenharia", 123454} fmt.Println(est1.altura) } <file_sep>/src/go_udy/14_funcoes_avancadas/14.1_retorno_nomeado/retorno_nomeado.go package main import "fmt" func CalcMatematico(a, b float64) (soma float64, subtracao float64) { soma = a + b subtracao = a - b return } func main() { fmt.Println(CalcMatematico(2, 4)) } <file_sep>/src/go_udy/14_funcoes_avancadas/14.6_panic_recover/panic_recover.go package main import "fmt" func recover1() { if r := recover(); r != nil { fmt.Println("Execução recuperada!") } } func AlunoAprovado(n1, n2 float64) bool { defer recover1() //fmt.Println("Entrando na função para verificar se o aluno está aprovado") if (n1+n2)/2 > 6 { return true } else if (n1+n2)/2 < 6 { return false } panic("A média é exatamente 6") } func main() { fmt.Println(AlunoAprovado(8, 4)) } <file_sep>/src/aulas_nache/aprenda_go_com_testes/estruturas_met_intef/go.mod module estruturas go 1.15 <file_sep>/src/aulas_nache/aprenda_go_com_testes/ola/ola_test.go package main import "testing" func TestOla(t *testing.T) { verificarMensagemCorreta := func(t *testing.T, got, want string) { t.Helper() if got != want { t.Errorf("got %q, want %q", got, want) } } t.Run("em frances", func(t *testing.T) { got := Ola("teste ", "frances") want := "<NAME>" verificarMensagemCorreta(t, got, want) }) } //t.Run("diz '<NAME>' quando uma string vazia for passada", func(t *testing.T) { //got := Ola("") //want := "<NAME>" //if got != want { //t.Errorf("got %q, want %q", got, want) //} //}) <file_sep>/src/go_udy/4_funcoes/funcoes.go package main import "fmt" func Somar(a, b float64) float64 { return a + b } func CalculosMatematicos(a, b float64) (float64, float64, float64, float64) { soma := a + b subtracao := a - b divisao := a / b multiplicacao := a * b return soma, subtracao, divisao, multiplicacao } func main() { fmt.Println(Somar(1, 5)) fmt.Println(CalculosMatematicos(1, 5)) } <file_sep>/src/aulas_nache/rand_test/rand.py import random print(random.randrange(0, 100))<file_sep>/src/aulas_nache/aprenda_go_com_testes/inteiros/adicionador_test.go package inteiros_test import ( "fmt" "inteiros" "testing" ) func TestAdicionador(t *testing.T) { got := inteiros.Adiciona(2, 2) want := 4 if got != want { t.Errorf("esperado '%d', resultado '%d'", got, want) } } func ExampleAdiciona() { soma := inteiros.Adiciona(2, 5) fmt.Println(soma) // Output: 7 } <file_sep>/src/go_udy/5_operadores/operadores.go package main import "fmt" func main() { // Aritimeticos soma := 1 + 2 subtracao := 1 - 2 divisao := 10 / 4 multiplicacao := 10 * 5 restoDaDivisao := 10 % 2 fmt.Println(soma, subtracao, divisao, multiplicacao, restoDaDivisao) // Atribuicao var variavel1 string = "string" variavel2 := "string2" fmt.Println(variavel1, variavel2) // Operadores Relacionais fmt.Println(1 > 2) fmt.Println(1 <= 2) fmt.Println(2 == 2) fmt.Println(2 != 2) // Operadores Logicos fmt.Println(true && true) fmt.Println(true || false) fmt.Println(!true) // Operadores Unários n := 10 n++ // n = n + 1 n += 1 // n = n + 1 n-- // n = n - 1 n -= 2 // n = n - 2 n *= 3 // n = n * 3 fmt.Println(n) } <file_sep>/src/aula_nache_youtube/go_tour/rot13_readers/rot13.go package main import ( "io" "os" "strings" ) type rot13Reader struct { r io.Reader } var alphabetUpper = map[byte]byte{ 'A': 'N', 'L': 'Y', } var alphabetLower = map[byte]byte{ 'a': 'n', 'b': 'o', 'l': 'y', } func (rot rot13Reader) Read(bytes []byte) (int, error) { count := 0 n, err := rot.r.Read(bytes) if err != nil { return 0, err } for i := 0; i < n; i++ { count++ v, ok := alphabetUpper[bytes[i]] if ok { bytes[i] = v continue } v, ok = alphabetLower[bytes[i]] if ok { bytes[i] = v continue } } return count, nil } func main() { s := strings.NewReader("Lbh penpxrq gur pbqr!") r := rot13Reader{s} io.Copy(os.Stdout, &r) } <file_sep>/src/aulas_nache/aprenda_go_com_testes/ponteiros_erros/ponteiros_erros_test.go package ponteiros_erros import ( "fmt" "testing" ) /*func TestCarteira(t *testing.T) { carteira := Carteira{} carteira.Depositar(10) resultado := carteira.Saldo() esperado := 10 if resultado != esperado { t.Errorf("resultado %d, esperado %d", resultado, esperado) } } func TestCarteira2(t *testing.T) { carteira := Carteira{} carteira.Depositar(10) got := carteira.Saldo() //fmt.Printf("O endereço do saldo no teste é %v \n", &carteira.saldo) want := 10 if got != want { t.Errorf("want %d, got %d", want, got) } }*/ func TestCarteira3(t *testing.T) { carteira := Carteira{} carteira.Depositar(Bitcoin(10)) got := carteira.Saldo() fmt.Printf("O endereço do saldo no teste é %v \n", &carteira.saldo) want := Bitcoin(10) if got != want { t.Errorf("want %d, got %d", want, got) } } func TestCarteira4(t *testing.T) { carteira := Carteira{} carteira.Depositar(Bitcoin(10)) got := carteira.Saldo() want := Bitcoin(10) if got != want { t.Errorf("want %s, got %s", want, got) } } func TestCarteira5(t *testing.T) { t.Run("depositar", func(t *testing.T) { carteira := Carteira{} carteira.Depositar(Bitcoin(10)) got := carteira.Saldo() want := Bitcoin(10) if got != want { t.Errorf("got %s, want %s", got, want) } }) t.Run("Retirar", func(t *testing.T) { carteira := Carteira{saldo: Bitcoin(20)} carteira.Retirar(Bitcoin(10)) got := carteira.Saldo() want := Bitcoin(10) if got != want { t.Errorf("got %s, want %s", got, want) } }) } func TestCarteira6(t *testing.T) { confirmaSaldo := func(t *testing.T, carteira Carteira, want Bitcoin) { t.Helper() got := carteira.Saldo() if got != want { t.Errorf("got %s, want %s", got, want) } } t.Run("depositar", func(t *testing.T) { carteira := Carteira{} carteira.Depositar(Bitcoin(10)) confirmaSaldo(t, carteira, Bitcoin(10)) }) t.Run("Retirar", func(t *testing.T) { carteira := Carteira{saldo: Bitcoin(20)} carteira.Retirar(Bitcoin(10)) confirmaSaldo(t, carteira, Bitcoin(10)) }) } func TestCarteira7(t *testing.T) { confirmaSaldo := func(t *testing.T, carteira Carteira, want Bitcoin) { t.Helper() got := carteira.Saldo() if got != want { t.Errorf("got %s, want %s", got, want) } } t.Run("depositar", func(t *testing.T) { carteira := Carteira{} carteira.Depositar(Bitcoin(10)) confirmaSaldo(t, carteira, Bitcoin(10)) }) t.Run("Retirar", func(t *testing.T) { carteira := Carteira{saldo: Bitcoin(20)} carteira.Retirar(Bitcoin(10)) confirmaSaldo(t, carteira, Bitcoin(10)) }) t.Run("Retirar com saldo insuficiente", func(t *testing.T) { saldoInicial := Bitcoin(20) carteira := Carteira{saldoInicial} erro := carteira.Retirar(Bitcoin(100)) confirmaSaldo(t, carteira, saldoInicial) if erro == nil { t.Error("esperava um erro, mas nenhum ocorreu") } }) } func TestCarteira8(t *testing.T) { confirmaSaldo := func(t *testing.T, carteira Carteira, want Bitcoin) { t.Helper() got := carteira.Saldo() if got != want { t.Errorf("got %s, want %s", got, want) } } t.Run("depositar", func(t *testing.T) { carteira := Carteira{} carteira.Depositar(Bitcoin(10)) confirmaSaldo(t, carteira, Bitcoin(10)) }) t.Run("Retirar", func(t *testing.T) { carteira := Carteira{saldo: Bitcoin(20)} carteira.Retirar(Bitcoin(10)) confirmaSaldo(t, carteira, Bitcoin(10)) }) confirmaErro := func(t *testing.T, valor error, want string) { t.Helper() if valor == nil { t.Fatal("esperava um erro, mas nenhum ocorreu") } got := valor.Error() if got != want { t.Errorf("got %s, want %s", got, want) } } t.Run("Retirar com saldo insuficiente", func(t *testing.T) { saldoInicial := Bitcoin(20) carteira := Carteira{saldoInicial} erro := carteira.Retirar(Bitcoin(100)) confirmaSaldo(t, carteira, saldoInicial) confirmaErro(t, erro, "não é possível retirar: saldo insuficiente") }) } func TestCarteira9(t *testing.T) { t.Run("Depositar", func(t *testing.T) { carteira := Carteira{} carteira.Depositar(Bitcoin(10)) confirmaSaldo(t, carteira, Bitcoin(10)) }) t.Run("Retirar com saldo suficiente", func(t *testing.T) { carteira := Carteira{Bitcoin(20)} erro := carteira.Retirar(Bitcoin(10)) confirmaSaldo(t, carteira, Bitcoin(10)) confirmaErroInexistente(t, erro) }) t.Run("Retirar com saldo insuficiente", func(t *testing.T) { saldoInicial := Bitcoin(20) carteira := Carteira{saldoInicial} erro := carteira.Retirar(Bitcoin(100)) confirmaSaldo(t, carteira, saldoInicial) confirmaErro(t, erro, ErroSaldoInsuficiente) }) } func confirmaSaldo(t *testing.T, carteira Carteira, want Bitcoin) { t.Helper() got := carteira.Saldo() if got != want { t.Errorf("got %s, want %s", got, want) } } func confirmaErroInexistente(t *testing.T, got error) { t.Helper() if got != nil { t.Fatal("erro inesperado recebido") } } func confirmaErro(t *testing.T, got error, want error) { t.Helper() if got == nil { t.Fatal("esperava um erro, mas nenhum ocorreu") } if got != want { t.Errorf("erro got %s, erro want %s", got, want) } } <file_sep>/src/aulas_nache/aprenda_go_com_testes/arrays_slices/arrays_test.go package arrays_test import ( "arrays" "reflect" "testing" ) func TestSoma(t *testing.T) { t.Run("coleção de 5 números", func(t *testing.T) { numbers := []int{1, 2, 3, 4, 5} got := arrays.Soma(numbers) want := 15 if got != want { t.Errorf("got %d, want %d, dado %v", got, want, numbers) } }) } func TestSomaTudo(t *testing.T) { want := []int{3, 9} got := arrays.SomaTudo([]int{1, 2}, []int{0, 9}) if !reflect.DeepEqual(got, want) { t.Errorf("want %v got %v", want, got) } } func TestSomaTodoOResto(t *testing.T) { t.Run("faz as somas de alguns slices", func(t *testing.T) { want := []int{2, 9} got := arrays.SomaTodoOResto([]int{1, 2}, []int{0, 9}) if !reflect.DeepEqual(got, want) { t.Errorf("want %v, got %v", want, got) } }) t.Run("soma slices vazios de forma segura", func(t *testing.T) { want := []int{0, 9} got := arrays.SomaTodoOResto([]int{}, []int{3, 4, 5}) if !reflect.DeepEqual(got, want) { t.Errorf("want %v, got %v", want, got) } }) } /*func TestSomaTodoOResto(t *testing.T) { verificaSomas := func(t *testing.T, got, want []int) { t.Helper() if !reflect.DeepEqual(got, want) { t.Errorf("want %v, got %v", want, got) } } t.Run("faz a soma do resto", func(t *testing.T) { want := []int{2,9} got := SomaTodoOResto([]int{1,2}, []int{0,9}) if !reflect.DeepEqual(got, want) { t.Errorf("want %v, got %v", want, got) } }) t.Run("soma slices vazios de forma segura", func(t *testing.T) { want := []int{0,9} got := SomaTodoOResto([]int{}, []int{3,4,5}) if !reflect.DeepEqual(got, want) { t.Errorf("want %v, got %v", want, got) } }) }*/
7f3db692e1c0d4d81a6d49589cf44110b1317126
[ "Markdown", "Python", "Go Module", "Go" ]
44
Go
crvvasconcellos/Golang
7fb84809f0367f430c4d2c3b4297dc50e59e910c
382d85da8108bf2a1c4f2d20073d01ccf70dbdd9
refs/heads/master
<file_sep>import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /** * This class give users to game mode selection view, which has two buttons, one is single player * mode and one is double player mode that user can choose * * @author Dongbo * */ public class ModeView implements ActionListener { private JButton singlePlayerModeButton; private JButton doublePlayerModeButton; private JFrame selectionModeFrame; public ModeView() { singlePlayerModeButton = new JButton("Single Player Mode"); doublePlayerModeButton = new JButton("Double Players Mode"); selectionModeFrame = new JFrame("Connect 4"); singlePlayerModeButton.addActionListener(this); doublePlayerModeButton.addActionListener(this); setView(); } /** * This method give users to game mode selection view, which has two buttons, one is single player * mode and one is double player mode that user can choose */ public void setView() { JPanel selectionPanel = new JPanel(); singlePlayerModeButton.setPreferredSize(new Dimension(150, 50)); doublePlayerModeButton.setPreferredSize(new Dimension(150, 50)); selectionPanel.add(singlePlayerModeButton); selectionPanel.add(doublePlayerModeButton); selectionModeFrame.add(selectionPanel, BorderLayout.SOUTH); selectionModeFrame.setVisible(true); selectionModeFrame.setSize(320, 90); selectionModeFrame.setLocationRelativeTo(null); selectionModeFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == singlePlayerModeButton) { GameLogic gameLogic = GameLogic.getModelInstance(); new GameView(gameLogic, Color.red); gameLogic.createPlayers(GameMode.SINGLE); selectionModeFrame.dispose(); } if (e.getSource() == doublePlayerModeButton) { GameLogic gameLogic = GameLogic.getModelInstance(); new GameView(gameLogic, Color.red); new GameView(gameLogic, Color.black); gameLogic.createPlayers(GameMode.DOUBLE); selectionModeFrame.dispose(); } } } <file_sep>import java.awt.Color; /** * This class create a human player that player the game. * * @author Dongbo * */ public class HumanPlayer implements Player { private Color playerColor; private int dropCol; public HumanPlayer(Color color) { this.playerColor = color; } /** * This method is used by the gameLogic to denote to the player object where the drop column move * has to be made. */ @Override public void setMoveCol(int col) { this.dropCol = col; } /** * This method returns the column of the last move made by the Human player */ @Override public int getMoveCol() { return this.dropCol; } /** * make the move. */ @Override public void move(GameLogic gameLogic) { if (gameLogic == null) { throw new IllegalArgumentException("gameLogic is null!"); } gameLogic.makeMove(playerColor, dropCol); } /** * This method returns the Color for this player */ @Override public Color getColor() { return playerColor; } /** * This method returns the type of the player which is HUMAN */ @Override public PlayerType getPlayerType() { return PlayerType.HUMAN; } @Override public String toString() { String outColor = ""; if (this.playerColor == Color.red) { outColor = "red"; } else { outColor = "black"; } return "HumanPlayer Color: " + outColor + " Column: " + this.dropCol; } @Override public int hashCode() { final int prime = 31; int result = 17; result = prime * result + ((playerColor == null) ? 0 : playerColor.hashCode()); result = prime * result + dropCol; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof HumanPlayer)) { return false; } HumanPlayer other = (HumanPlayer) obj; if (playerColor == null) { if (other.playerColor != null) { return false; } } else { if (!playerColor.equals(other.playerColor)) { return false; } } if (dropCol != other.dropCol) { return false; } return true; } } <file_sep>import static org.junit.Assert.*; import java.awt.Color; import org.junit.Test; public class HumanPlayerTest { @Test public void testGetColorRed() { HumanPlayer humanPlayer = new HumanPlayer(Color.red); Color expectedColor = Color.red; Color actualColor = humanPlayer.getColor(); assertEquals(expectedColor, actualColor); } @Test public void testGetColorBlack() { HumanPlayer humanPlayer = new HumanPlayer(Color.black); Color expectedColor = Color.black; Color actualColor = humanPlayer.getColor(); assertEquals(expectedColor, actualColor); } @Test public void testGetPlayerType() { HumanPlayer humanPlayer = new HumanPlayer(Color.red); PlayerType expectedType = PlayerType.HUMAN; PlayerType actualType = humanPlayer.getPlayerType(); assertEquals(expectedType, actualType); } @Test public void testSetAndGetMoveCol() { HumanPlayer humanPlayer = new HumanPlayer(Color.red); humanPlayer.setMoveCol(2); int expectedCol = 2; int actualCol = humanPlayer.getMoveCol(); assertEquals(expectedCol, actualCol); } @Test public void testToStringRed() { HumanPlayer humanPlayer = new HumanPlayer(Color.red); humanPlayer.setMoveCol(1); String expected = "HumanPlayer Color: red Column: 1"; String actual = humanPlayer.toString(); assertEquals(expected, actual); } @Test public void testToStringBlack() { HumanPlayer humanPlayer = new HumanPlayer(Color.black); humanPlayer.setMoveCol(3); String expected = "HumanPlayer Color: black Column: 3"; String actual = humanPlayer.toString(); assertEquals(expected, actual); } @Test public void testEquals() { HumanPlayer humanPlayer1 = new HumanPlayer(Color.red); HumanPlayer humanPlayer2 = new HumanPlayer(Color.red); humanPlayer1.setMoveCol(3); humanPlayer2.setMoveCol(3); assertTrue(humanPlayer1.equals(humanPlayer2) && humanPlayer2.equals(humanPlayer1)); } @Test public void testNotEqualsColor() { HumanPlayer humanPlayer1 = new HumanPlayer(Color.red); HumanPlayer humanPlayer2 = new HumanPlayer(Color.black); humanPlayer1.setMoveCol(3); humanPlayer2.setMoveCol(3); assertTrue(!humanPlayer1.equals(humanPlayer2) && !humanPlayer2.equals(humanPlayer1)); } @Test public void testNotEqualsCol() { HumanPlayer humanPlayer1 = new HumanPlayer(Color.red); HumanPlayer humanPlayer2 = new HumanPlayer(Color.red); humanPlayer1.setMoveCol(3); humanPlayer2.setMoveCol(4); assertTrue(!humanPlayer1.equals(humanPlayer2) && !humanPlayer2.equals(humanPlayer1)); } @Test public void testNotEqualsNull() { HumanPlayer humanPlayer1 = new HumanPlayer(Color.red); HumanPlayer humanPlayer2 = new HumanPlayer(null); humanPlayer1.setMoveCol(3); humanPlayer2.setMoveCol(4); assertTrue(!humanPlayer1.equals(humanPlayer2) && !humanPlayer2.equals(humanPlayer1)); } @Test public void testEqualsHashCode() { HumanPlayer humanPlayer1 = new HumanPlayer(Color.red); HumanPlayer humanPlayer2 = new HumanPlayer(Color.red); humanPlayer1.setMoveCol(3); humanPlayer2.setMoveCol(3); assertTrue(humanPlayer1.hashCode() == humanPlayer2.hashCode()); } @Test public void testNotEqualsHashCodeColor() { HumanPlayer humanPlayer1 = new HumanPlayer(Color.red); HumanPlayer humanPlayer2 = new HumanPlayer(Color.black); humanPlayer1.setMoveCol(3); humanPlayer2.setMoveCol(3); assertTrue(humanPlayer1.hashCode() != humanPlayer2.hashCode()); } @Test public void testNotEqualsHashCodeCol() { HumanPlayer humanPlayer1 = new HumanPlayer(Color.red); HumanPlayer humanPlayer2 = new HumanPlayer(Color.red); humanPlayer1.setMoveCol(3); humanPlayer2.setMoveCol(4); assertTrue(humanPlayer1.hashCode() != humanPlayer2.hashCode()); } @Test(expected = IllegalArgumentException.class) public void testMoveWithNull() { HumanPlayer humanPlayer = new HumanPlayer(Color.red); humanPlayer.setMoveCol(3); humanPlayer.move(null); } } <file_sep># ConnectFour Simple Connect Four game wrote by java with design patterns and used Swing for UI. Run Game.java for start the game. <file_sep>import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.border.Border; /** * This Class is the GameView of the game, which include a start/restart view and the board view * * @author Dongbo * */ public class GameView implements Listener, ActionListener { private GameLogic gameLogic; private Color playerColor; private int row; private int col; private JFrame startFrame; private JFrame gameFrame; private JPanel startFrameButtonPanel; private JPanel gameFrameBoardPanel; private JPanel gameFrameButtonPanel; private JPanel[][] gameFrameBoardPanels; private JButton startFrameStartButton; private JButton startFrameRestartButton; private JButton startFrameExitButton; private JButton[] gameFrameDropButtons; private JTextArea startFrameWelcomeText; private JTextArea startFrameResultText; private JTextArea gameFrameTurnText; private Border line; public GameView(GameLogic gameLogic, Color color) { this.gameLogic = gameLogic; this.gameLogic.addListener(this); row = 6; col = 7; startFrame = new JFrame("Connect 4"); gameFrame = new JFrame("Connect 4"); gameFrameBoardPanel = new JPanel(new GridLayout(row, col)); gameFrameButtonPanel = new JPanel(); startFrameStartButton = new JButton("Start"); startFrameRestartButton = new JButton("Restart"); startFrameExitButton = new JButton("Exit"); startFrameButtonPanel = new JPanel(); gameFrameDropButtons = new JButton[col]; gameFrameBoardPanels = new JPanel[row][col]; line = BorderFactory.createLineBorder(Color.blue); startFrameWelcomeText = new JTextArea(); startFrameResultText = new JTextArea(); gameFrameTurnText = new JTextArea(); this.playerColor = color; startFrameStartButton.addActionListener(this); startFrameRestartButton.addActionListener(this); startFrameExitButton.addActionListener(this); setStartBoard(); } /** * it shows a view with a startFrameWelcomeText view has the welcome/result info, start/restart * and exit. */ @Override public void setStartBoard() { startFrameWelcomeText.setText("Welcome!"); gameFrameDropButtons = new JButton[col]; startFrameStartButton.setPreferredSize(new Dimension(150, 50)); startFrameRestartButton.setPreferredSize(new Dimension(150, 50)); startFrameExitButton.setPreferredSize(new Dimension(150, 50)); startFrameButtonPanel.add(startFrameStartButton); startFrameButtonPanel.add(startFrameExitButton); startFrame.add(startFrameWelcomeText, BorderLayout.CENTER); startFrame.add(startFrameButtonPanel, BorderLayout.SOUTH); startFrame.setVisible(true); startFrame.setSize(320, 110); startFrame.setLocationRelativeTo(null); startFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == startFrameStartButton) { gameLogic.fireGameStartEvent(); } else if (e.getSource() == startFrameRestartButton) { gameLogic.fireGameRestartEvent(); } else if (e.getSource() == startFrameExitButton) { gameLogic.fireGameExitEvent(); } else { for (int i = 0; i < col; i++) { if (e.getSource() == gameFrameDropButtons[i]) { gameLogic.drop(i); } } } } /** * start the game, called when user clicked start/restart button, generate the game board */ @Override public void gameStart() { startFrame.dispose(); gameFrameButtonPanel.setLayout(new GridLayout(0, col)); for (int i = 0; i < col; i++) { JButton dropButton = new JButton("X"); dropButton.addActionListener(this); gameFrameButtonPanel.add(dropButton); gameFrameDropButtons[i] = dropButton; } gameFrameBoardPanels = new JPanel[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { JPanel panel = new JPanel(); panel.setBorder(line); gameFrameBoardPanels[i][j] = panel; gameFrameBoardPanel.add(gameFrameBoardPanels[i][j]); } } if (this.playerColor == Color.red) { gameFrame.setTitle("Red Player Window"); } else { gameFrame.setTitle("Black Player Window"); } gameFrameTurnText.setText("Red Turn!"); gameFrame.add(gameFrameTurnText, BorderLayout.SOUTH); gameFrame.add(gameFrameBoardPanel, BorderLayout.CENTER); gameFrame.setVisible(true); gameFrame.setSize(230, 230); gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gameFrame.add(gameFrameButtonPanel, BorderLayout.NORTH); gameFrame.setVisible(true); if (this.playerColor == Color.red) { gameFrame.setEnabled(true); } else { gameFrame.setEnabled(false); } } /** * Move piece show in the UI */ @Override public void gameMove(int row, int col, Color color) { gameFrameBoardPanels[this.row - row - 1][col].setBackground(color); if (color == Color.black) { gameFrameTurnText.setText("Red Turn!"); if (this.playerColor == Color.black) { gameFrame.setEnabled(false); } else { gameFrame.setEnabled(true); } } else { gameFrameTurnText.setText("Black Turn!"); if (this.playerColor == Color.red) { gameFrame.setEnabled(false); } else { gameFrame.setEnabled(true); } } if (row >= 5) { gameFrameDropButtons[col].removeActionListener(this); } } /** * show UI when game is tie */ @Override public void gameTie() { String result = "Tie!"; setGameEndUI(result); } /** * show UI when game is not tie, red or black wins. */ @Override public void gameWin(Color color) { String result = ""; if (color == Color.black) { result = "Black Wins!"; } else { result = "Red Wins!"; } setGameEndUI(result); } /** * set up the UI when Game end: remove the drop buttons listener, show result and restart screen * * @param result */ public void setGameEndUI(String result) { for (JButton button : gameFrameDropButtons) { button.removeActionListener(this); } startFrameResultText.setText(result); startFrameButtonPanel.remove(startFrameStartButton); startFrameButtonPanel.add(startFrameRestartButton); startFrame.remove(startFrameWelcomeText); startFrame.add(startFrameResultText, BorderLayout.CENTER); startFrame.setVisible(true); } /** * Restart the game. */ @Override public void gameRestart() { gameFrame.dispose(); gameFrameButtonPanel.removeAll(); gameFrameBoardPanel.removeAll(); } /** * Exit the game. */ @Override public void gameExit() { gameLogic.deleteListener(this); System.exit(0); } }
6d826af9e1638903e333bdb5c8c431587a94a4c4
[ "Markdown", "Java" ]
5
Java
DependingOnMood/ConnectFour
ecea4c957bc54730a8053c19ec901999f9c9409f
989a6f0a701a119ea2d6a8d370fcc028bb36f76c
refs/heads/master
<file_sep>original_password = "<PASSWORD>" user_password = input("Введите пароль >>") if original_password == user_password: print("OK") else: print("FAIL") <file_sep>hour_cost = int(input("Укажите стоимость часа >>")) day_quantity = int(input("Укажите количество дней >>")) total = (hour_cost * 8) * day_quantity final = total - (total*.13) print(total)<file_sep>class Person: name: str surname: str age: int user = Person() user.name = "John" user.surname = "Doe" user.age = 30 print(user)<file_sep>def salary(hour_cost, day_quantity): total = (hour_cost * 8) * day_quantity final = total - (total*.13) return final a = salary(600, 2) b = salary(1200, 6) print(a, b)<file_sep>def user_hello(user): print(f"Привет,{user}") clients = ['John','David', 'Kate', 'Alex'] for user in clients: user_hello(user) new_user = "Artur" clients.append(new_user) print(f"Привет,{clients[-1]}")<file_sep>number_1 = int(input("Укажите число 1 >>")) number_2 = int(input("Укажите число 2 >>")) result = number_1 > number_2 print(result)<file_sep> numbers = [4, 8, 15, 16, 23, 42] print(numbers) numbers.append(108) print(numbers) numbers.remove(15) print(numbers) print(len(numbers)) print(sum(numbers)) print(numbers[-1]) print(numbers[2:4]) print(numbers[2:4:2])<file_sep>clients = ['John','David', 'Kate', 'Alex'] for user in clients: print(f"Привет,{user}") clients.append("Artur")
cf5ed6d254a7422980631d971ec4d02082428156
[ "Python" ]
8
Python
netraf/skillbox-phyton
f1c2893e4d22e84856f2dd7f38683f2a33eb97e1
fa79d093066f57d9b09b821f7e7618cab93955c0
refs/heads/main
<repo_name>maylcf/learning-go<file_sep>/Pluralsight/Creating-Web-Services-Go/webservice/go.mod module github.com/maylcf/learning-go go 1.16 require ( github.com/go-sql-driver/mysql v1.5.0 // indirect golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 ) <file_sep>/Pluralsight/Creating-Web-Services-Go/webservice/receipt/receipt.go package receipt import ( "io/ioutil" "path/filepath" "time" ) var ReceiptDirectory string = filepath.Join("uploads") type Receipt struct { ReceiptName string `json:"name"` UploadDate time.Time `json:"uploadDate"` } func GetReceipts() ([]Receipt, error) { receipts := make([]Receipt, 0) files, err := ioutil.ReadDir(ReceiptDirectory) if err != nil { return nil, err } for _,f := range files { receipts = append(receipts, Receipt{ReceiptName: f.Name(), UploadDate: f.ModTime()}) } return receipts, nil }<file_sep>/Pluralsight/Creating-Web-Services-Go/webservice/main.go package main import ( "net/http" "github.com/maylcf/learning-go/product" "github.com/maylcf/learning-go/database" "github.com/maylcf/learning-go/receipt" _ "github.com/go-sql-driver/mysql" ) const apiBasePath = "/api" func main() { database.SetupDatabase() receipt.SetupRoutes(apiBasePath) product.SetupRoutes(apiBasePath) http.ListenAndServe(":5000", nil) } <file_sep>/README.md # course-web-service-with-go Creating Web Services with Go
0af6024d0281a0818b635a7608baaa4ca5720933
[ "Go", "Go Module", "Markdown" ]
4
Go Module
maylcf/learning-go
329153a7c3343bcb89ebca2252a2a1863491f458
9d87e98327da53dd0183624b6af7cce021e6511e
refs/heads/master
<repo_name>geeklimit/Beacon<file_sep>/README.md ![beacon header image of a lambo on a lighthouse island](https://github.com/geeklimit/Beacon/blob/master/backtestEngine/web/vue/assets/beacon-header.png) ## What does Beacon do? Beacon uses a hive of minimalistic linux virtual machines (nodes) to find patterns of success across multiple strategies and strategy configurations for cryptocurrency trading pairs. ## Does Beacon work? Beacon's effectiveness and accuracy are functions of how many nodes are used, how much time is given to the backtesting research process, and how much data the nodes are given to process. These factors are multipliers with each other and you are encouraged to use at least 5 nodes and 3 months of backtesting data, running a total of at least 5000 (5x1000) tests per trading pair per strategy. In testing with single-core 2.2Ghz VMs running 2GB of RAM each, this takes about 5 hours. This number changes dramatically when using multiple trading pairs and/or multiple strategies. See the [usage directions](https://github.com/geeklimit/Beacon/blob/master/USAGE.md) for more information on how to properly estimate the number of tests needed to provide a satisfactory result set. ## How do I install and use Beacon? See the [install directions](https://github.com/geeklimit/Beacon/blob/master/INSTALL.md) to install Beacon's primary and worker nodes. Once *n* number of nodes are installed, see the [usage directions](https://github.com/geeklimit/Beacon/blob/master/USAGE.md) to install Beacon's primary and worker nodes. on how to configure and run a Beacon cluster. ## How can I help Beacon? Many hours have gone into creating, maintaining and improving Beacon, and many more will only make it better. If Beacon helps you acheive crypto-trading success, please consider donating 1% of your Beacon-assisted success to: **(BTC) 1NvwuUHbp3WgACVo5b495RoJ3KpoypZK8k** These funds will also be used in part to create developer bounties for [improvements or new features](https://github.com/geeklimit/Beacon/projects/1) commented-up as being especially helpful by the community. ## Can I help improve Beacon? Yes! See the [current list of to-do items](https://github.com/geeklimit/Beacon/projects/1) or add one of your own. If you're a developer, post how you'd like to help, make your contributions and create a pull request when done. ## Warning and Indemnity Use Beacon at your own risk. Beacon is an exploratory tool for research purposes only, and is not intended for use as financial advice. Consult a qualified, independant financial advisor before utilizing the information Beacon provides to craft your personal trading strategies. You are solely responsible for any negative outcome from your trading decisions, whether they are based on information Beacon supplies or otherwise. ## Attributions *Beacon is a modified form of [Gekko](https://github.com/askmike/gekko) v0.5.14, a Bitcoin TA trading and backtesting platform that connects to popular Bitcoin exchanges. Beacon incorporates components of [Bruteforce](https://github.com/gekkowarez/bruteforce), a nodejs brute force backtester for Gekko trading bot, which is in turn built from components of [GAB](https://github.com/tommiehansen/gab), an automated backtesting tool for Gekko. By using Beacon, you may be agreeing to certain statements and terms in these projects, and should ensure you understand and agree before using Beacon.* <file_sep>/import/importer.js const async = require('async'); //const sqlite3 = require('sqlite3').verbose(); const moment = require('moment'); // http://momentjs.com/docs const Binance = require('binance-api-node').default // https://github.com/binance-exchange/binance-api-node const binance = Binance(); // Public client const auth_binance = Binance({ apiKey: 'xxx', apiSecret: 'xxx' }); // Authenticated client, can make signed calls console.log("In declarations"); // ##### SETTINGS ##### const apiLimit = 500; // Max 500 JSON objects per request var rateLimit = 100; // Milliseconds to wait per API call, max 1200 requests per minute. 1200/m = 20/s = 1 per 50ms (0.050s) candleTime = "1h"; // Intervals: 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w (1M available in Binance API but not used) historyDays = 1; // Number of days to collect history /* tradingPairs = [ "BNBBTC", "BNBETH", "VETBNB", "EOSBNB", "NANOBNB", "NEOBNB", "ADABNB", "XLMBNB", "XRPBNB", "IOTABNB", "LTCBNB", "BCCBNB", "ONTBNB", "ZILBNB", "GTOBNB", "ICXBNB", "BCNBNB", "TUSDBNB", "BATBNB", "MFTBNB", "LOOMBNB", "ETCBNB", "SCBNB", "WANBNB", "NCASHBNB", "NULSBNB"]; // These are BNB-traded coins in global top 300 as of 05SEP2018 https://coinmarketcap.com/exchanges/binance/ */ const tradingPairs = ["BNBBTC", "BNBETH"]; console.log("Researching " + tradingPairs); // ##### SYSTEM VARIABLES ##### var endTime = moment().day(-1).hour(23).minute(59).second(59).millisecond(999).valueOf(); // 1 second before today started var startTime = moment(endTime).subtract(historyDays, 'days').valueOf(); var diffTime = endTime - startTime; const rateIncrement = rateLimit; // ##### SQLITE SETUP ##### /* const candleData = new sqlite3.Database('/home/tc/Beacon/data/candleData.db', (err) => { if (err) { console.error(err.message); } else { console.log("\nConnected to candleData.db \n"); }; }); */ var candleData = []; // ##### IMPORT PREP ##### if (candleTime === "1m") candleMilli = (1000 * 60 * 1); if (candleTime === "3m") candleMilli = (1000 * 60 * 3); if (candleTime === "5m") candleMilli = (1000 * 60 * 5); if (candleTime === "15m") candleMilli = (1000 * 60 * 15); if (candleTime === "30m") candleMilli = (1000 * 60 * 30); if (candleTime === "1h") candleMilli = (1 * (1000 * 60 * 60)); if (candleTime === "2h") candleMilli = (2 * (1000 * 60 * 60)); if (candleTime === "4h") candleMilli = (4 * (1000 * 60 * 60)); if (candleTime === "6h") candleMilli = (6 * (1000 * 60 * 60)); if (candleTime === "8h") candleMilli = (8 * (1000 * 60 * 60)); if (candleTime === "12h") candleMilli = (12 * (1000 * 60 * 60)); if (candleTime === "1d") candleMilli = (24 * (1000 * 60 * 60)); if (candleTime === "3d") candleMilli = (3 * (24 * (1000 * 60 * 60))); if (candleTime === "1w") candleMilli = (7 * (24 * (1000 * 60 * 60))); var callsNeeded = diffTime / (candleMilli * apiLimit); console.log("in main"); var callStart = startTime; var callEnd = endTime; for (tpCount = 0; tpCount <= tradingPairs.length; tpCount++) { let pair = tradingPairs[tpCount]; console.log("Working on " + tradingPairs[tpCount]); /* sql = "CREATE TABLE IF NOT EXISTS " + pair + " (openTime REAL NOT NULL UNIQUE PRIMARY KEY, open REAL NOT NULL, high REAL NOT NULL, low REAL NOT NULL, close REAL NOT NULL, " + "volume REAL NOT NULL, closeTime REAL NOT NULL, quoteVolume REAL NOT NULL, trades REAL NOT NULL, baseAssetVolume REAL NOT NULL, quoteAssetVolume REAL NOT NULL) WITHOUT ROWID"; console.log("\nAttempting: " + sql); candleData.run(sql); // for troubleshooting, clears all rows for each table before starting sql = "DELETE FROM " + pair; console.log("\nAttempting: " + sql); candleData.run(sql); */ callStart = startTime; // moving start time for each call (call is start time + <apiLimit> candles) if (callsNeeded > 1) { // the number of candles needed exceeds the limit of a single API call: multiple calls needed setTimeout(function () { while (callStart < endTime) { // loop through needed number of max-apiLimit calls per tradingPair if (callStart + (candleMilli * apiLimit) > endTime) { // last call in series requiring multiple calls callEnd = endTime; console.log("Scheduling remaining " + candleTime + " " + pair + " candles at " + rateLimit + "ms: " + moment(callStart).format("D MMM YYYY H:mm") + " to " + moment(callEnd).format("D MMM YYYY H:mm (UTC+0)") + "\n"); binance.candles({ symbol: pair, interval: candleTime, limit: apiLimit, startTime: callStart, endTime: callEnd }).then(candles => saveCandles(candles, pair, candleData, callStart, callEnd)); } else { // calls asking for full <apiLimit> candle count callEnd = callStart + (candleMilli * apiLimit); console.log("Scheduling request for " + apiLimit + " " + candleTime + " " + pair + " candles at " + rateLimit + "ms: " + moment(callStart).format("D MMM YYYY H:mm") + " to " + moment(callEnd).format("D MMM YYYY H:mm (UTC+0)")); binance.candles({ symbol: pair, interval: candleTime, limit: apiLimit, startTime: callStart, endTime: callEnd }).then(candles => saveCandles(candles, pair, candleData, callStart, callEnd)); }; // end if rateLimit = rateLimit + rateIncrement; // delay each API call by the previous call's delay + rateIncrement (seperates each call by rateIncrement) callStart = callStart + (candleMilli * apiLimit); }; // end while }, rateLimit); } else { // the number of candles needed can fit within a single API call console.log("Scheduling " + pair + " candle data request for " + rateLimit + "ms: " + moment(startTime).format("D MMM YYYY H:mm") + " to " + moment(endTime).format("D MMM YYYY H:mm (UTC+0)")); binance.candles({ symbol: pair, interval: candleTime, limit: apiLimit, startTime: callStart, endTime: callEnd }).then(candles => saveCandles(candles, pair, candleData, callStart, callEnd)); rateLimit = rateLimit + rateIncrement; // delay each API call by the previous call's delay + rateIncrement (seperates each call by rateIncrement) }; // end if-else console.log("Done researching" + tradingPairs[tpCount]); }; // end if /* console.log("In tableCheck"); // table dump checks while (dumpCount=0, dumpCount<tradingPairs.length, dumpCount++) { sql = "SELECT * FROM " + tradingPairs[dumpCount] + " ORDER BY openTime ASC"; console.log("Attempting: " + sql); candleData.all(sql, [], (err, rows) => { if (err) { console.error(err) } else { rows.forEach((row) => { console.log(moment(row.openTime).format("D MMM YYYY H:mm (UTC+0)") + ": " + row.trades + " trades") }) } }); }; */ function saveCandles(candles, pair, candleData, callStart, callEnd) { // saves a result from callBinance to SQLite //console.log(candles); // for troubleshooting console.log("saveCandles eceived " + candles.length + " records of " + candleTime + " " + pair + " candle data for " + moment(callStart).format("D MMM YYYY H:mm") + " to " + moment(callEnd).format("D MMM YYYY H:mm (UTC+0)")); for (candle in candles) { // candle // console.log(moment(candles[candle]['openTime']).format("D MMM YYYY H:mm") + " to " + moment(candles[candle]['closeTime']).format("D MMM YYYY H:mm (UTC+0)")); // build command and insert candle data as row in table <pair> let sql = "INSERT INTO " + pair + " VALUES(" + candles[candle]['openTime'] + "," + candles[candle]['open'] + "," + candles[candle]['high'] + "," + candles[candle]['low'] + "," + candles[candle]['close'] + "," + candles[candle]['volume'] + "," + candles[candle]['closeTime'] + "," + candles[candle]['quoteVolume'] + "," + candles[candle]['trades'] + "," + candles[candle]['baseAssetVolume'] + "," + candles[candle]['quoteAssetVolume'] + ")"; /* $openTime: candles[candle]['openTime'] $open: candles[candle]['open']," $high: candles[candle]['high']," $low: candles[candle]['low']," $close: candles[candle]['close']," $volume: candles[candle]['volume']," $closeTime: candles[candle]['closeTime']," $quoteVolume: candles[candle]['quoteVolume']," $trades: candles[candle]['trades']," $baseAssetVolume: candles[candle]['baseAssetVolume']," $quoteAssetVolume: candles[candle]['quoteAssetVolume']" */ console.log("Attempting: " + sql); // candleData.run(sql); // candleData.run }; // for candle return; }; // function saveCandles <file_sep>/install/tinycore90.sh #!/bin/bash # do not run this shell script with sudo - multiple commands require local user permissions ## VM HOST PREREQUISITES # Full install of VirtualBox, including network adapters # File - Preferences - Network # Add a network with default name of NatNetwork if not already listed # no port forwarding ## VM PREREQUISITES # VirtualBox VM, named 'beacon_0n' where n is the client number # Linux, 'Linux 2.6 / 3.x / 4.x (32-bit)' # at least 2048 MB RAM allocated, create disk now # 2GB VDI disk dynamically allocated, named same as client ## VM SETTINGS # System - Motherboard - Boot Order - move Hard Disk to the top # Storage - Optical Drive - click small icon next to 'Optical Drive' under 'Attributes' # Choose virtual optical disk file - find CorePlus installer iso on host # tested: http://tinycorelinux.net/9.x/x86/release/CorePlus-current.iso # Network # Network Adapter 1: Host-Only Adapter, Virtualbox Host-Only Ethernet Adapter # Network adapter 2: NAT Network, NatNetwork # note: the order of the adapters above is required for DNS via NAT to work, # the VM uses last adapter configured for DNS, and host is not a DNS resolver. ## VM INSTALL # Start - Normal Start # Boot into FLWM topside (default) # Tray icon 'install' # Install Frugal - Whole Disk - sda - Install boot loader # ext4 # Use defaults / blank boot options # Core Only (Text Based Interface) - Proceed, wait for 'Installation has completed' # Close virtual machine window - Power Off # Start - Normal Start ## INSTALL # Download this script and its support files tce-load -wi openssh wget tiny.cc/install-beacon # If you don't want to use this short URL, use the actual link: https://raw.githubusercontent.com/geeklimit/Beacon/master/nodeUtils/nodeInstall.sh #### From the console / SSH, do the following. #### # # # sh install-beacon # # # ################################################### ### PROCEED FROM THIS POINT ONLY IF INSTALLING MANUALLY sudo /usr/local/etc/init.d/openssh start clear sudo echo '/etc/shadow' >> /opt/.filetool.lst # Set user passwords to be persistent, tab-complete works echo "Set a password for user 'tc' so you can log in later via SSH if needed" passwd # <PASSWORD> or something, needed for SSH # Set up SSH so copy-paste works via PuTTY - using the console to work with Beacon is difficult is cop-paste is needed echo /usr/local/etc/ssh >> /opt/.filetool.lst cp /opt/bootlocal.sh myboot echo '/usr/local/etc/init.d/openssh start' >> myboot mv -f myboot /opt/bootlocal.sh # Get the Host Adapter IP address # We already know this, but it is needed programmatically ip=$(/sbin/ifconfig eth0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}') # this node's IP on the node network hostip=$(/sbin/ifconfig eth1 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}') clear echo "What is the name of this node? (beacon_0x)" read hostname # Enter the hostname: beacon_0x (where x is the node number you're installing) sed -i "s/box/$hostname/g" /opt/bootsync.sh # Install Node LTS and npm cd ~ mkdir ~/.nvm export NVM_DIR="$HOME/.nvm" wget https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh && mv install.sh install-node.sh sleep 10 sh install-node.sh [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm sleep 10 nvm install 8.12.0 # get Beacon tce-load -wi git cd ~ && git clone https://github.com/geeklimit/Beacon.git cd Beacon && npm install # hard-code Binance's load-balancer address to hosts file # (avoids DNS lookup issues / delays, can be checked here: https://mxtoolbox.com/SuperTool.aspx?action=a%3aapi.binance.com&run=toolpage) echo /etc/hosts >> /opt/.filetool.lst cp /etc/hosts hosts echo d3h36i1mno13q3.cloudfront.net api.binance.com >> hosts sudo mv -f hosts /etc/hosts # install SQLite tce-load -wi python compiletc cd ~/Beacon && npm install sqlite3 --build-from-source # Make sure work is saved to permanent disk filetool.sh -b echo Rebooting, SSH to node at $ip sleep 10 # reboot to use machine in its production config sudo reboot <file_sep>/data/README.md This is where the data tables are held<file_sep>/INSTALL.md ## Installing Beacon nodes ## Running Beacon nodes ## Consolidating node reports ## Automated analysis of node reports
4aeba83d09a17423503627c5e1dc3aa8d4b086fa
[ "Markdown", "JavaScript", "Shell" ]
5
Markdown
geeklimit/Beacon
06746567d5feb5d2faecee56119a6bb6ac4738a0
4df8d2186827c121a70ff9efe793998e5f1950ed
refs/heads/master
<file_sep>#! /bin/bash chmod +x build/wificonfig.py rm gcwconnect.opk mksquashfs build/* gcwconnect.opk -noappend -comp gzip -all-root scp gcwconnect.opk zero:/media/data/apps/<file_sep>#!/usr/bin/env python # wificonfig.py # # Requires: pygame # # Copyright (c) 2013 <NAME> # # Licensed under the GNU General Public License, Version 3.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.gnu.org/copyleft/gpl.html # # 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. import subprocess as SU import sys, time, os, shutil, re import pygame from pygame.locals import * # What is our wireless interface? wlan = "wlan0" # How many times do you want to try to # connect to a network before we give up? timeout = 3 ## That's it for options. Everything else below shouldn't be edited. confdir = os.environ['HOME'] + "/.gcwconnect/" sysconfdir = "/usr/local/etc/network/" surface = pygame.display.set_mode((320,240)) keyboard = '' selected_key = '' maxrows = '' maxcolumns = '' passphrase = '' wirelessmenuexists = '' go = '' ## Initialize the dispaly, for pygame if not pygame.display.get_init(): pygame.display.init() if not pygame.font.get_init(): pygame.font.init() surface.fill((41,41,41)) pygame.mouse.set_visible(False) pygame.key.set_repeat(199,69) #(delay,interval) ## File management def createpaths(): # Create paths, if necessary if not os.path.exists(confdir): os.makedirs(confdir) if not os.path.exists(sysconfdir): os.makedirs(sysconfdir) ## Interface management def ifdown(): command = ['ifdown', wlan] output = SU.Popen(command, stdout=SU.PIPE).stdout.readlines() def ifup(): def fixmetrics(): # This is stupid and I shouldn't have to do this. command = ['route', 'del', 'default', 'gw', '10.1.1.1', 'netmask', '0.0.0.0'] output = SU.Popen(command, stdout=SU.PIPE).stdout.readlines() command = ['route', 'add', '-net', 'default', 'gw', '10.1.1.1', 'netmask', '0.0.0.0', 'dev', 'usb0', 'metric', '2'] output = SU.Popen(command, stdout=SU.PIPE).stdout.readlines() fixmetrics() oldssid = '' if getcurrentssid(): oldssid = getcurrentssid() counter = 0 while checkinterfacestatus() == '' and counter < timeout: if counter > 0: modal('Connection failed. Retrying...'+str(counter),"false") command = ['ifup', wlan] output = SU.Popen(command, stdout=SU.PIPE).stdout.readlines() counter += 1 if counter >= timeout: modal('Connection failed!',wait="true") else: wlanstatus = "" currentssid = getcurrentssid() if not checkinterfacestatus() == "offline": if not currentssid == "unassociated" and not oldssid == currentssid: modal("Connected!","false","true") def getwlanip(): ip = "" command = ['ifconfig', wlan] output = SU.Popen(command, stdout=SU.PIPE).stdout.readlines() for line in output: if line.strip().startswith("inet addr"): ip = str.strip(line[line.find('inet addr')+len('inet addr"'):line.find('Bcast')+len('Bcast')].rstrip('Bcast')) return ip def checkinterfacestatus(): interface = "" # set default assumption of interface status ip = "" command = ['ifconfig'] output = SU.Popen(command, stdout=SU.PIPE).stdout.readlines() for line in output: if line.strip().startswith(wlan): ip = getwlanip() if ip: interface = ip return interface def getnetworks(): # Run iwlist to get a list of networks in range modal("Scanning...","false") command = ['ifconfig', wlan, 'up'] output = SU.Popen(command, stdout=SU.PIPE).stdout.readlines() drawinterfacestatus() command = ['iwlist', wlan, 'scan'] output = SU.Popen(command, stdout=SU.PIPE).stdout.readlines() for item in output: if item.strip().startswith('Cell'): # network is the current list corresponding to a MAC address {MAC:[]} network = networks.setdefault(parsemac(item), dict()) elif item.strip().startswith('ESSID:'): network["ESSID"] = (parseessid(item)) elif item.strip().startswith('IE:') and not item.strip().startswith('IE: Unknown') or item.strip().startswith('Encryption key:'): network["Encryption"] = (parseencryption(item)) elif item.strip().startswith('Quality='): network["Quality"] = (parsequality(item)) # Now the loop is over, we will probably find a MAC address and a new "network" will be created. redraw() return networks def listuniqssids(): menuposition = 0 uniqssid = {} uniqssids = {} for network, detail in networks.iteritems(): if detail['ESSID'] not in uniqssids and detail['ESSID']: uniqssid = uniqssids.setdefault(detail['ESSID'], {}) uniqssid["Network"] = detail uniqssid["Network"]["menu"] = menuposition uniqssid["Network"]["Encryption"] = detail['Encryption'] menuposition += 1 return uniqssids ## Parsing iwlist output for various components def parsemac(macin): mac = str.strip(macin[macin.find("Address:")+len("Address: "):macin.find("\n")+len("\n")]) return mac def parseessid(essid): essid = str.strip(essid[essid.find('ESSID:"')+len('ESSID:"'):essid.find('"\n')+len('"\n')].rstrip('"\n')) return essid def parsequality(quality): quality = quality[quality.find("Quality=")+len("Quality="):quality.find(" S")+len(" S")].rstrip(" S") return quality def parseencryption(encryption): encryption = str.strip(encryption) if encryption.startswith('Encryption key:off'): encryption = "none" elif encryption.startswith('Encryption key:on'): encryption = "wep" elif encryption.startswith("IE: WPA"): encryption = "wpa" elif encryption.startswith("IE: IEEE 802.11i/WPA2"): encryption = "wpa2" else: encryption = "Encrypted (unknown)" return encryption ## Draw interface elements def drawlogobar(): # Set up the menu bar pygame.draw.rect(surface, (84,84,84), (0,0,320,32)) pygame.draw.line(surface, (255, 255, 255), (0, 33), (320, 33)) def drawlogo(): gcw = "GCW" zero = "Connect" # wireless = "Wireless" # configuration = "configuration" gcw_font = pygame.font.Font('./data/gcwzero.ttf', 24) text1 = gcw_font.render(gcw, True, (255, 255, 255), (84,84,84)) text2 = gcw_font.render(zero, True, (153, 0, 0), (84,84,84)) # text3 = pygame.font.SysFont(None, 16).render(wireless, True, (255, 255, 255), (84,84,84)) # text4 = pygame.font.SysFont(None, 16).render(configuration, True, (255, 255, 255), (84,84,84)) logo_text = text1.get_rect() logo_text.topleft = (8, 6) surface.blit(text1, logo_text) logo_text = text2.get_rect() logo_text.topleft = (98, 6) surface.blit(text2, logo_text) # logo_text = text3.get_rect() # logo_text.topleft = (272, 5) # surface.blit(text3, logo_text) # logo_text = text4.get_rect() # logo_text.topleft = (245, 18) # surface.blit(text4, logo_text) def drawstatusbar(): # Set up the status bar pygame.draw.rect(surface, (84,84,84), (0,224,320,16)) pygame.draw.line(surface, (255, 255, 255), (0, 223), (320, 223)) def drawinterfacestatus(): # Interface status badge wlanstatus = "" currentssid = getcurrentssid() if not checkinterfacestatus() == '': if currentssid == "unassociated": wlanstatus = wlan+" is disconnected." elif not currentssid == "unassociated": wlanstatus = currentssid else: wlanstatus = wlan+" is off." wlantext = pygame.font.SysFont(None, 16).render(wlanstatus, True, (255, 255, 255), (84,84,84)) wlan_text = wlantext.get_rect() wlan_text.topleft = (4, 227) surface.blit(wlantext, wlan_text) if not checkinterfacestatus() == "not connected": text = pygame.font.SysFont(None, 16).render(checkinterfacestatus(), True, (153, 0, 0), (84,84,84)) interfacestatus_text = text.get_rect() interfacestatus_text.topright = (315, 227) surface.blit(text, interfacestatus_text) def getcurrentssid(): # What network are we connected to? command = ['iwconfig', wlan] output = SU.Popen(command, stdout=SU.PIPE).stdout.readlines() for line in output: if line.strip().startswith(wlan): ssid = str.strip(line[line.find('ESSID')+len('ESSID:"'):line.find('Nickname:')+len('Nickname:')].rstrip(' Nickname:').rstrip('"')) return ssid def wifilistedit(): yellow = (128, 128, 0) blue = (0, 0, 128) red = (128, 0, 0) green = (0, 128, 0) black = (0, 0, 0) # Draw the edit icon labelblock = pygame.draw.rect(surface, (41,41,41), (35,207,25,14)) labeltext = pygame.font.SysFont(None, 12).render("Edit", True, (255, 255, 255), (41,41,41)) label = labeltext.get_rect() label.center = labelblock.center surface.blit(labeltext, label) pygame.draw.rect(surface, black, (4, 209, 34, 5)) pygame.draw.circle(surface, black, (9, 214), 5) pygame.draw.circle(surface, black, (33, 214), 5) startbutton = pygame.draw.rect(surface, black, (9, 209, 25, 10)) start = pygame.font.SysFont(None, 10).render("SELECT", True, (255, 255, 255), black) starttext = start.get_rect() starttext.center = startbutton.center surface.blit(start, starttext) # Draw the connect icon labelblock = pygame.draw.rect(surface, (41,41,41), (80,207,35,14)) labeltext = pygame.font.SysFont(None, 12).render("Connect", True, (255, 255, 255), (41,41,41)) label = labeltext.get_rect() label.center = labelblock.center surface.blit(labeltext, label) abutton = pygame.draw.circle(surface, green, (70,214), 5) # (x, y) a = pygame.font.SysFont(None, 10).render("A", True, (255, 255, 255), green) atext = a.get_rect() atext.center = abutton.center surface.blit(a, atext) def redraw(): surface.fill((41,41,41)) drawlogobar() drawlogo() mainmenu() if wirelessmenuexists == "true": wirelessmenu.draw() wifilistedit() drawstatusbar() drawinterfacestatus() pygame.display.update() def modal(text,wait="true",timeout="false"): # Draw a modal dialog = pygame.draw.rect(surface, (84,84,84), (64,88,192,72)) pygame.draw.rect(surface, (255,255,255), (62,86,194,74), 2) text = pygame.font.SysFont(None, 16).render(text, True, (255, 255, 255), (84,84,84)) modal_text = text.get_rect() modal_text.center = dialog.center def drawcontinue(): abutton = pygame.draw.circle(surface, (0, 0, 128), (208,151), 5) # (x, y) a = pygame.font.SysFont(None, 10).render("A", True, (255, 255, 255), (0,0,128)) atext = a.get_rect() atext.center = abutton.center surface.blit(a, atext) labelblock = pygame.draw.rect(surface, (84,84,84), (218,144,32,14)) labeltext = pygame.font.SysFont(None, 12).render("Continue", True, (255, 255, 255), (84,84,84)) label = labeltext.get_rect() label.center = labelblock.center surface.blit(labeltext, label) pygame.display.update() surface.blit(text, modal_text) pygame.display.update() if not wait == "true" and timeout == "true": time.sleep(2.5) redraw() while wait == "true": drawcontinue() for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_LCTRL: redraw() wait = "false" ## Connect to a network def writeconfig(mode="a"): # Write wireless configuration to disk global passphrase if passphrase: if passphrase == "none": passphrase = "" f = open(ssidconfig, mode) f.write('WLAN_ESSID="'+ssid+'"\n') f.write('WLAN_MODE="managed"\n') f.write('WLAN_ENCRYPTION="'+uniq[ssid]['Network']['Encryption']+'"\n') f.write('WLAN_PASSPHRASE="'+passphrase+'"\n') f.write('WLAN_DRIVER="wext"\n') f.write('WLAN_DHCP_RETRIES=20\n') f.close() def connect(): # Connect to a network global go if go == "true": modal("Connecting...","false") oldconf = re.escape(ssidconfig) newconf = sysconfdir +"config-wlan0.conf" shutil.copy2(ssidconfig, newconf) ifdown() ifup() ## Keyboard def getkeys(board): def qwertyNormal(): keyarray = {} keyboard = {} global maxrows global maxcolumns maxrows = 4 maxcolumns = 13 keys = '`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=',\ 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\\',\ 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', '', '',\ 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', '', '', '' row = 0 column = 0 keyid = 0 for k in keys: keyarray = keyboard.setdefault(keyid, {}) keyarray["key"] = k if column <= 12: keyarray["column"] = column keyarray["row"] = row column += 1 else: row += 1 column = 0 keyarray["column"] = column keyarray["row"] = row column += 1 keyid += 1 return keyboard def qwertyShift(): keyarray = {} keyboard = {} global maxrows global maxcolumns maxrows = 4 maxcolumns = 13 keys = '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+',\ 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '|',\ 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"', '', '',\ 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?', '', '', '' row = 0 column = 0 keyid = 0 for k in keys: keyarray = keyboard.setdefault(keyid, {}) keyarray["key"] = k if column <= 12: keyarray["column"] = column keyarray["row"] = row column += 1 else: row += 1 column = 0 keyarray["column"] = column keyarray["row"] = row column += 1 keyid += 1 return keyboard def wep(): keyarray = {} keyboard = {} global maxrows global maxcolumns maxrows = 4 maxcolumns = 4 keys = '1', '2', '3', '4', \ '5', '6', '7', '8', \ '9', '0', 'A', 'B', \ 'C', 'D', 'E', 'F' row = 0 column = 0 keyid = 0 for k in keys: keyarray = keyboard.setdefault(keyid, {}) keyarray["key"] = k if column <= 3: keyarray["column"] = column keyarray["row"] = row column += 1 else: row += 1 column = 0 keyarray["column"] = column keyarray["row"] = row column += 1 keyid += 1 return keyboard if board == "qwertyNormal": k = qwertyNormal() elif board == "qwertyShift": k = qwertyShift() elif board == "wep": k = wep() return k class key: def __init__(self): self.key = [] self.selection_color = (153,0,0) self.text_color = (255,255,255) self.selection_position = (0,0) self.selected_item = 0 def init(self, key, row, column): self.key = key self.row = row self.column = column self.drawkey() def drawkey(self): key_width = 16 key_height = 16 top = '' left = '' if self.row == 0: top = 136 elif self.row == 1: top = 156 elif self.row == 2: top = 176 elif self.row == 3: top = 196 elif self.row == 4: top = 216 if self.column == 0: left = 32 elif self.column == 1: left = 52 elif self.column == 2: left = 72 elif self.column == 3: left = 92 elif self.column == 4: left = 112 elif self.column == 5: left = 132 elif self.column == 6: left = 152 elif self.column == 7: left = 172 elif self.column == 8: left = 192 elif self.column == 9: left = 212 elif self.column == 10: left = 232 elif self.column == 11: left = 252 elif self.column == 12: left = 272 if len(self.key) > 1: key_width = 36 keybox = pygame.draw.rect(surface, (50,50,50), (left,top,key_width,key_height)) text = pygame.font.SysFont(None, 16).render(self.key, True, (255, 255, 255), (50,50,50)) label = text.get_rect() label.center = keybox.center surface.blit(text, label) def drawkeyboard(board): yellow = (128, 128, 0) blue = (0, 0, 128) red = (128, 0, 0) green = (0, 128, 0) black = (0, 0, 0) # Draw keyboard background pygame.draw.rect(surface, (84,84,84), (0,100,320,140)) # Draw the cancel icon pygame.draw.rect(surface, black, (4, 225, 34, 5)) pygame.draw.circle(surface, black, (9, 230), 5) pygame.draw.circle(surface, black, (33, 230), 5) startbutton = pygame.draw.rect(surface, black, (9, 225, 25, 10)) start = pygame.font.SysFont(None, 10).render("SELECT", True, (255, 255, 255), black) starttext = start.get_rect() starttext.center = startbutton.center surface.blit(start, starttext) labelblock = pygame.draw.rect(surface, (84,84,84), (42,223,25,14)) labeltext = pygame.font.SysFont(None, 12).render("Cancel", True, (255, 255, 255), (84,84,84)) label = labeltext.get_rect() label.center = labelblock.center surface.blit(labeltext, label) # Draw the finish icon pygame.draw.rect(surface, black, (75, 225, 35, 5)) pygame.draw.circle(surface, black, (80, 230), 5) pygame.draw.circle(surface, black, (105, 230), 5) startbutton = pygame.draw.rect(surface, black, (80, 225, 25, 10)) start = pygame.font.SysFont(None, 10).render("START", True, (255, 255, 255), black) starttext = start.get_rect() starttext.center = startbutton.center surface.blit(start, starttext) labelblock = pygame.draw.rect(surface, (84,84,84), (113,223,25,14)) labeltext = pygame.font.SysFont(None, 12).render("Finish", True, (255, 255, 255), (84,84,84)) label = labeltext.get_rect() label.center = labelblock.center surface.blit(labeltext, label) # Draw the delete icon xbutton = pygame.draw.circle(surface, red, (160,230), 5) # (x, y) x = pygame.font.SysFont(None, 10).render("X", True, (255, 255, 255), red) xtext = x.get_rect() xtext.center = xbutton.center surface.blit(x, xtext) labelblock = pygame.draw.rect(surface, (84,84,84), (170,223,20,14)) labeltext = pygame.font.SysFont(None, 12).render("Delete", True, (255, 255, 255), (84,84,84)) label = labeltext.get_rect() label.center = labelblock.center surface.blit(labeltext, label) if not board == "wep": # Draw the shift icon ybutton = pygame.draw.circle(surface, yellow, (205,230), 5) # (x, y) y = pygame.font.SysFont(None, 10).render("Y", True, (255, 255, 255), yellow) ytext = y.get_rect() ytext.center = ybutton.center surface.blit(y, ytext) labelblock = pygame.draw.rect(surface, (84,84,84), (210,223,25,14)) labeltext = pygame.font.SysFont(None, 12).render("Shift", True, (255, 255, 255), (84,84,84)) label = labeltext.get_rect() label.center = labelblock.center surface.blit(labeltext, label) # Draw the space icon labelblock = pygame.draw.rect(surface, (84,84,84), (245,223,35,14)) labeltext = pygame.font.SysFont(None, 12).render("Space", True, (255, 255, 255), (84,84,84)) label = labeltext.get_rect() label.center = labelblock.center surface.blit(labeltext, label) bbutton = pygame.draw.circle(surface, blue, (243,230), 5) # (x, y) b = pygame.font.SysFont(None, 10).render("B", True, (255, 255, 255), blue) btext = b.get_rect() btext.center = bbutton.center surface.blit(b, btext) # Draw the enter icon labelblock = pygame.draw.rect(surface, (84,84,84), (290,223,35,14)) labeltext = pygame.font.SysFont(None, 12).render("Enter", True, (255, 255, 255), (84,84,84)) label = labeltext.get_rect() label.center = labelblock.center surface.blit(labeltext, label) abutton = pygame.draw.circle(surface, green, (285,230), 5) # (x, y) a = pygame.font.SysFont(None, 10).render("A", True, (255, 255, 255), green) atext = a.get_rect() atext.center = abutton.center surface.blit(a, atext) # Draw the keys k = getkeys(board) z = key() for x, y in k.iteritems(): if y['key']: z.init(y['key'],y['row'],y['column']) pygame.display.update() return keyboard def getinput(board): selectkey(board) security = softkeyinput(board) return security def softkeyinput(keyboard): global passphrase global go wait = "true" while wait == "true": for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_RETURN: # finish input selectkey(keyboard, "enter") wait = "false" if event.key == K_UP: # Move cursor up selectkey(keyboard, "up") if event.key == K_DOWN: # Move cursor down selectkey(keyboard, "down") if event.key == K_LEFT: # Move cursor left selectkey(keyboard, "left") if event.key == K_RIGHT: # Move cursor right selectkey(keyboard, "right") if event.key == K_LCTRL: # A button selectkey(keyboard, "select") if event.key == K_LALT: # B button selectkey(keyboard, "space") if event.key == K_SPACE: # # B button (shift) if keyboard == "qwertyNormal": keyboard = "qwertyShift" elif keyboard == "qwertyShift": keyboard = "qwertyNormal" drawkeyboard(keyboard) selectkey(keyboard, "swap") if event.key == K_LSHIFT: # X button selectkey(keyboard, "delete") if event.key == K_ESCAPE: # Select key passphrase = '' wait = "false" if event.key == K_RETURN: # Start key redraw() writeconfig("w") go = "true" modal("Connecting...","false") connect() drawinterfacestatus() wait = "false" passphrase = '' redraw() return go def displaypassphrase(passphrase, size=24): # Display passphrase on screen bg = pygame.draw.rect(surface, (255, 255, 255), (0, 35, 320, 65)) text = "[ " text += passphrase text += " ]" pw = pygame.font.SysFont(None, size).render(text, True, (0, 0, 0), (255, 255, 255)) pwtext = pw.get_rect() pwtext.center = bg.center surface.blit(pw, pwtext) pygame.display.update() def selectkey(keyboard, direction="none"): def getcurrentkey(keyboard, pos): keys = getkeys(keyboard) for item in keys.iteritems(): if item[1]['row'] == pos[1] and item[1]['column'] == pos[0]: currentkey = item[1]['key'] return currentkey def highlightkey(keyboard, pos): drawkeyboard(keyboard) pygame.display.update() left_margin = 32 top_margin = 136 if pos[0] > left_margin: x = left_margin + (16 * (pos[0])) else: x = left_margin + (16 * pos[0]) + (pos[0] * 4) if pos[1] > top_margin: y = top_margin + (16 * (pos[1])) else: y = top_margin + (16 * pos[1]) + (pos[1] * 4) list = [ \ (x, y), \ (x + 16, y), \ (x + 16, y + 16), \ (x, y + 16), \ (x, y) \ ] lines = pygame.draw.lines(surface, (255,255,255), True, list, 1) pygame.display.update() global maxrows global maxcolumns global selected_key global passphrase if not selected_key: selected_key = [0,0] highlightkey(keyboard, selected_key) if direction == "swap": highlightkey(keyboard, selected_key) else: if direction == "up": if selected_key[1] <= 0: selected_key[1] = 0 else: selected_key[1] -= 1 elif direction == "down": if selected_key[1] >= maxrows - 1: selected_key[1] = maxrows - 1 elif not getcurrentkey(keyboard, (selected_key[0], selected_key[1] + 1)): selected_key[1] = selected_key[1] else: selected_key[1] = selected_key[1] + 1 elif direction == "left": if selected_key[0] <= 0: selected_key[0] = 0 else: selected_key[0] = selected_key[0] - 1 elif direction == "right": if selected_key[0] >= maxcolumns - 1: selected_key[0] = maxcolumns - 1 elif not getcurrentkey(keyboard, (selected_key[0] + 1, selected_key[1])): selected_key[0] = selected_key[0] else: selected_key[0] = selected_key[0] + 1 elif direction == "select": passphrase += getcurrentkey(keyboard, selected_key) if len(passphrase) > 20: drawlogobar() drawlogo() displaypassphrase(passphrase, 12) else: displaypassphrase(passphrase) elif direction == "space": passphrase += ' ' if len(passphrase) > 20: drawlogobar() drawlogo() displaypassphrase(passphrase, 12) else: displaypassphrase(passphrase) elif direction == "delete": if len(passphrase) > 0: passphrase = passphrase[:-1] drawlogobar() drawlogo() if len(passphrase) > 20: displaypassphrase(passphrase, 12) else: displaypassphrase(passphrase) highlightkey(keyboard, selected_key) class Menu: font_size = 24 font = pygame.font.SysFont dest_surface = pygame.Surface canvas_color = (41,41,41) def __init__(self): self.menu = [] self.field = [] self.selected_item = 0 self.selection_position = (0,0) self.menu_width = 0 self.menu_height = 0 self.number_of_fields = 0 self.selection_color = (153,0,0) self.text_color = (255,255,255) class Pole: text = '' pole = pygame.Surface pole_rect = pygame.Rect selection_rect = pygame.Rect def move_menu(self, top, left): self.selection_position = (top,left) def set_colors(self, text, selection, background): self.canvas_color = background self.text_color = text self.selection_color = selection def set_fontsize(self,font_size): self.font_size = font_size def set_font(self, path): self.font_path = path def get_position(self): return self.selected_item def init(self, menu, dest_surface): self.menu = menu self.dest_surface = dest_surface self.number_of_fields = len(self.menu) self.create_structure() def draw(self,move=0): if move: self.selected_item += move if self.selected_item == -1: self.selected_item = self.number_of_fields - 1 self.selected_item %= self.number_of_fields menu = pygame.Surface((self.menu_width, self.menu_height)) menu.fill(self.canvas_color) selection_rect = self.field[self.selected_item].selection_rect pygame.draw.rect(menu,self.selection_color,selection_rect) for i in xrange(self.number_of_fields): menu.blit(self.field[i].pole,self.field[i].pole_rect) self.dest_surface.blit(menu,self.selection_position) return self.selected_item def create_structure(self): shift = 0 self.menu_height = 0 self.font = pygame.font.SysFont('Arial', self.font_size) for i in xrange(self.number_of_fields): self.field.append(self.Pole()) self.field[i].text = self.menu[i] self.field[i].pole = self.font.render(self.field[i].text, 1, self.text_color) self.field[i].pole_rect = self.field[i].pole.get_rect() shift = int(self.font_size * 0.2) height = round(self.field[i].pole_rect.height/5.)*5 self.field[i].pole_rect.left = shift self.field[i].pole_rect.top = shift+(shift*2+height)*i width = self.field[i].pole_rect.width+shift*2 height = self.field[i].pole_rect.height+shift*2 left = self.field[i].pole_rect.left-shift top = self.field[i].pole_rect.top-shift self.field[i].selection_rect = (left,top ,width, height) if width > self.menu_width: self.menu_width = width self.menu_height += height x = self.dest_surface.get_rect().centerx - self.menu_width / 2 y = self.dest_surface.get_rect().centery - self.menu_height / 2 mx, my = self.selection_position self.selection_position = (x+mx, y+my) def swapmenu(active_menu): if active_menu == "main": active_menu = "ssid" menu.set_colors((128,128,128), (84,84,84), (41,41,41)) wirelessmenu.set_colors((128,128,128), (153,0,0), (41,41,41)) redraw() elif active_menu == "ssid": active_menu = "main" menu.set_colors((255,255,255), (153,0,0), (41,41,41)) wirelessmenu.set_colors((255,255,255), (84,84,84), (41,41,41)) redraw() pygame.draw.rect(surface, (41,41,41), (0,207,120,14)) return active_menu wirelessmenu = Menu() menu = Menu() def mainmenu(): def wlan(): wlanstatus = '' try: with open('/media/data/local/etc/network/config-wlan0.conf'): currentssid = getcurrentssid() if not checkinterfacestatus() == '': if currentssid: wlanstatus = "Turn off wifi" else: wlanstatus = "Reconnect" except IOError: pass return wlanstatus wlan = wlan() if wlan: menu.init(['Scan for APs', wlan, "Quit"], surface) else: menu.init(['Scan for APs', "Reconnect", "Quit"], surface) menu.move_menu(16, 96) menu.draw() if __name__ == "__main__": # Persistent variables networks = {} uniqssids = {} currentssid = "" createpaths() redraw() active_menu = "main" while 1: for event in pygame.event.get(): ## GCW-Zero keycodes: # A = K_LCTRL # B = K_LALT # X = K_LSHIFT # Y = K_SPACE # L = K_TAB # R = K_BACKSPACE # start = K_RETURN # select = K_ESCAPE # power up = K_KP0 # power down = K_PAUSE # left shoulder = K_TAB # right shoulder = K_BACKSPACE if event.type == QUIT: pygame.display.quit() sys.exit() elif event.type == KEYDOWN: if event.key == K_PAUSE: # Power down pass if event.key == K_TAB: # Left shoulder button pass if event.key == K_BACKSPACE: # Right shoulder button pass if event.key == K_KP0: # Power up pass if event.key == K_UP: # Arrow up the menu if active_menu == "main": menu.draw(-1) if active_menu == "ssid": wirelessmenu.draw(-1) if event.key == K_DOWN: # Arrow down the menu if active_menu == "main": menu.draw(1) if active_menu == "ssid": wirelessmenu.draw(1) if event.key == K_LEFT or event.key == K_RIGHT: if wirelessmenuexists == "true": active_menu = swapmenu(active_menu) if event.key == K_LCTRL: # Main menu if active_menu == "main": if menu.get_position() == 0: # Scan menu wirelessmenuexists = '' getnetworks() uniq = listuniqssids() wirelessitems = [] wirelessmenu.set_fontsize(14) for item in sorted(uniq.iterkeys(), key=lambda x: uniq[x]['Network']['menu']): for network, detail in uniq.iteritems(): if network == item: menuitem = "[" menuitem += str(detail['Network']['Encryption']) menuitem += "] " menuitem += str(detail['Network']['ESSID']) wirelessitems.append(menuitem) wirelessmenu.init(wirelessitems, surface) wirelessmenu.move_menu(128, 36) wirelessmenu.draw() if not wirelessmenuexists == "true": wirelessmenuexists = "true" active_menu = swapmenu('main') redraw() if menu.get_position() == 1: # Toggle wifi if not checkinterfacestatus(): modal("Connecting...","false") ifup() redraw() else: wirelessmenuexists = "false" ifdown() redraw() if menu.get_position() == 2: # Quit menu pygame.display.quit() sys.exit() # SSID menu elif active_menu == "ssid": ssid = "" netconfdir = confdir+"networks/" if not os.path.exists(netconfdir): os.makedirs(netconfdir) for network, detail in uniq.iteritems(): position = str(wirelessmenu.get_position()) if str(detail['Network']['menu']) == position: ssid = network ssidconfig = netconfdir +ssid +".conf" if not os.path.exists(ssidconfig): if detail['Network']['Encryption'] == "none": passphrase = "none" elif detail['Network']['Encryption'] == "wep": displaypassphrase(passphrase) drawkeyboard("wep") getinput("wep") else: displaypassphrase(passphrase) drawkeyboard("qwertyNormal") getinput("qwertyNormal") writeconfig() go = "true" connect() redraw() if event.key == K_ESCAPE and active_menu == "ssid": # Allow us to edit the existing key ssid = "" netconfdir = confdir+"networks/" if not os.path.exists(netconfdir): os.makedirs(netconfdir) for network, detail in uniq.iteritems(): position = str(wirelessmenu.get_position()) if str(detail['Network']['menu']) == position: ssid = network ssidconfig = netconfdir +ssid +".conf" if detail['Network']['Encryption'] == "none": pass elif detail['Network']['Encryption'] == "wep": displaypassphrase(passphrase) drawkeyboard("wep") getinput("wep") else: displaypassphrase(passphrase) drawkeyboard("qwertyNormal") getinput("qwertyNormal") pygame.display.update()
9a9bbc2d1b3c36cfc7cfca242c4afad3fd67cfe8
[ "Python", "Shell" ]
2
Shell
andmatand/gcwconnect
817e36cf0f7b99b9990e0747c30d7edb040a36a1
7052071430843741874d69c7ff9e09b86df62378
refs/heads/main
<file_sep>import React from "react"; import { useMoralis } from "react-moralis"; import { FlatList, View, Text, Image, StyleSheet, Pressable, } from "react-native"; // import { Flex } from "../../uikit/Flex/Flex"; import { getEllipsisTxt } from "../../utils/formatters"; import useERC20Balance from "./hooks/useERC20balance"; import { List, Card, Divider } from "react-native-paper"; const Item = ({ name, logo, balance, symbol }) => ( <View style={styles.itemContainer}> <View style={styles.itemView}> <View style={{ flex: 1 }}> {logo ? ( <Image source={{ uri: logo }} style={styles.logo} /> ) : ( <Image source={{ uri: "https://etherscan.io/images/main/empty-token.png" }} style={styles.logo} /> )} </View> <View style={{ flex: 2, justifyContent: "center" }}> <Text style={styles.name}>{name}</Text> </View> <View style={{ flex: 2, justifyContent: "center", alignItems: "flex-end" }}> <Text style={styles.balance}> {balance} {symbol} </Text> </View> </View> <Divider /> </View> ); function ERC20Balance(props) { const { assets } = useERC20Balance(props); const { Moralis } = useMoralis(); console.log(assets, "assets"); const renderItem = ({ item }) => { return ( <Pressable onPress={() => (props.setToken ? props.setToken(item) : null)}> <Item name={item.name} logo={item.logo} balance={parseFloat( Moralis.Units.FromWei(item.balance, item.decimals).toFixed(6) )} symbol={item.symbol} /> </Pressable> ); }; return ( <FlatList data={assets} renderItem={renderItem} keyExtractor={(item, index) => index.toString()} /> ); } const styles = StyleSheet.create({ itemContainer: { flex: 1, flexDirection: "column", backgroundColor: "white", }, itemView: { backgroundColor: "white", padding: 20, // marginVertical: 8, marginHorizontal: 2, flex: 1, flexDirection: "row", }, balance: { fontSize: 18, color: "black", fontWeight: "400", }, name: { fontSize: 15, color: "black", fontWeight: "500", }, logo: { height: 50, width: 50, }, }); export default ERC20Balance;
3ac3bc43e587319b022240db267b66633e5ca9da
[ "JavaScript" ]
1
JavaScript
allnim/ethereum-react-native-boilerplate
17a6dd4c093b36f2a56da912b1d58051206fb2a3
588d2d7f3723d577b4d422324d37998b9cbfd5ae
refs/heads/master
<repo_name>MaciejSwiderski/Find-The-Closest-Points<file_sep>/FindTheClosest.java package org.java2.maciej.swiderski.zadania011algorytmy.zadanie5; public class FindTheClosest { public String[][] findTwoPoints(int x, int y) { String[][] myGridsField = new String[x][y]; for (int i = 0; i < myGridsField.length; i++) { System.out.println(); for (int j = 0; j < myGridsField[i].length; j++) { myGridsField[i][j] = " " + "\t"; } } return myGridsField; } } <file_sep>/Points.java package org.java2.maciej.swiderski.zadania011algorytmy.zadanie5; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Points { int x; int y; public Points(int x, int y) { this.x = x; this.y = y; } public double compare(Points p1, Points p2, Points p3, Points p4, Points p5, Points p6, Points p7) { Points[] myNew = new Points[7]; myNew[0] = p1; myNew[1] = p2; myNew[2] = p3; myNew[3] = p4; myNew[4] = p5; myNew[5] = p6; myNew[6] = p7; System.out.println(); List<Double> myNewTableNew = new ArrayList<>(); int a = 0; int b = 0; for (int i = 0; i < myNew.length; i++) { for (int j = 0; j < myNew.length; j++) { if (i == j) break; double finalResult1 = Math.sqrt((myNew[i].x - myNew[j].x) * (myNew[i].x - myNew[j].x) + (myNew[i].y - myNew[j].y) * (myNew[i].y - myNew[j].y)); if (finalResult1 == 0) continue; myNewTableNew.add(finalResult1); double min = i; if ((Collections.min(myNewTableNew) <= min)) { min = Collections.min(myNewTableNew); } if ((finalResult1 == min)) { b = j; a = i; } } } double min = Collections.min(myNewTableNew); System.out.println("(*p" + (b + 1) + " and *p" + (a + 1) + ")- are the closests points on the Grid"); System.out.println("The grids of the Points are: (" + myNew[b].x + "," + myNew[b].y + ")(" + myNew[a].x + "," + myNew[a].y + ")"); return min; } } <file_sep>/RunFindTheClosest.java package org.java2.maciej.swiderski.zadania011algorytmy.zadanie5; import java.util.Random; public class RunFindTheClosest { public static void main(String[] args) { Random random = new Random(); Points point1 = new Points(random.nextInt(15), random.nextInt(15)); Points point2 = new Points(random.nextInt(15), random.nextInt(15)); Points point3 = new Points(random.nextInt(15), random.nextInt(15)); Points point4 = new Points(random.nextInt(15), random.nextInt(15)); Points point5 = new Points(random.nextInt(15), random.nextInt(15)); Points point6 = new Points(random.nextInt(15), random.nextInt(15)); Points point7 = new Points(random.nextInt(15), random.nextInt(15)); Points[] points = new Points[7]; points[0] = point1; points[1] = point2; points[2] = point3; points[3] = point4; points[4] = point5; points[5] = point6; points[6] = point7; for (int i = 0; i < points.length; i++) { System.out.println("*p" + (i + 1) + " : (" + points[i].x + "," + points[i].y + ")"); } FindTheClosest findTheClosest = new FindTheClosest(); String[][] result = findTheClosest.findTwoPoints(18, 18); for (int i = 0; i < result.length; i++) { System.out.println(); for (int j = 0; j < result[i].length; j++) { result[point1.x][point1.y] = "p*1"; result[point2.x][point2.y] = "p*2"; result[point3.x][point3.y] = "p*3"; result[point4.x][point4.y] = "p*4"; result[point5.x][point5.y] = "p*5"; result[point6.x][point6.y] = "p*6"; result[point7.x][point7.y] = "p*7"; System.out.print(result[i][j] + "\t"); } } Points point = new Points(0, 0); double minDistance = point.compare(point1, point2, point3, point4, point5, point6, point7); System.out.println("The distance between those two Point is " + minDistance); } } <file_sep>/README.md # Find-The-Closest-Points The algorithm compares all the points on the coordinate system and finds the pair placed the nearest to each other.
e99dcdc60ef7dab8bad9119694fbe1c24a76287d
[ "Markdown", "Java" ]
4
Java
MaciejSwiderski/Find-The-Closest-Points
d84fdc23c30c32853caddfc6bf65805f3e42bd0f
23bc1d31290c3cabd343c7f67e2271cee7c1ba48
refs/heads/master
<file_sep>import styled from 'styled-components'; export const Button = styled.button` color: #5f76f3; `; <file_sep>import styled from 'styled-components'; interface InputPropsType { error?: String; } export const CreateTeamWrap = styled.div` padding: 60px 1.375rem 0; flex-direction: column; align-items: center; display: flex; `; export const Container = styled.div` width: 62%; border: 1px solid #fff; background-color: #fff; padding: 2%; box-shadow: 4px 4px 4px 4px rgba(40, 50, 60, 0.06); margin: 1%; border-radius: 5px; `; export const Form = styled.form``; export const SubTitle = styled.label` font-size: 1.2rem; font-weight: 400; `; export const ItemWrap = styled.div``; export const Title = styled.h1` font-size: 1.5rem; font-weight: 800; `; export const Input = styled.input<InputPropsType>` width: 100%; height: 40px; padding-right: 15px; padding-left: 15px; border-radius: 5px; border: 1px solid #f7f8fb; font-size: 15px; color: #333; background-color: #f7f8fb; margin: 10px 0; border-color: ${(props: InputPropsType) => (props.error ? 'red' : '')}; `; export const NumberInputWrap = styled.div` width: 80%; `; export const NumberInput = styled.input<InputPropsType>` width: 90%; height: 40px; padding: 10px; border-radius: 5px; border: 1px solid #f7f8fb; font-size: 15px; color: #333; background-color: #f7f8fb; margin: 10px 0; border-color: ${(props: InputPropsType) => (props.error ? 'red' : '')}; `; export const TextArea = styled.textarea<InputPropsType>` display: block; width: 100%; height: 150px; padding: 15px; border-radius: 5px; border: 1px solid #f7f8fb; font-size: 15px; color: #333; background-color: #f7f8fb; margin: 10px 0; border-color: ${(props: InputPropsType) => (props.error ? 'red' : '')}; `; export const FieldWrap = styled.div` justify-content: space-between; display: flex; `; export const SelectArea = styled.select` display: block; width: 25%; height: 40px; padding-right: 15px; padding-left: 15px; border-radius: 5px; border: 1px solid #f7f8fb; font-size: 15px; color: #333; background-color: #f7f8fb; margin: 10px 0; `; export const CreateButton = styled.button` width: 14%; height: 30px; border-radius: 15px; border: 0px solid; font-size: 12px; font-weight: 600; background-color: #3562ff; color: #ffffff; text-align: center; cursor: pointer; display: block; margin-left: auto; margin-top: 5%; margin-bottom: 5%; `; <file_sep>import { createEntity } from '../../utils/redux'; import * as authApi from '../../api/auth'; export const REGISTER = 'REGISTER'; export const LOGIN = 'LOGIN'; export const EMAIL_CHECK = 'EMAIL_CHECK'; export const RESET = 'RESET'; export const ME = 'ME'; export const registerEntity = createEntity(REGISTER, authApi.postRigster); export const register = (params: authApi.RegisterParams) => ({ type: REGISTER, params, }); export const reset = () => ({ type: RESET, }); export const loginEntity = createEntity(LOGIN, authApi.postLogin); export const login = (params: authApi.LoginParams) => ({ type: LOGIN, params, }); export const emailCheckEntity = createEntity(EMAIL_CHECK, authApi.emailCheck); export const emailCheck = (params: authApi.EmailCheckParams) => ({ type: EMAIL_CHECK, params, }); export const meEntity = createEntity(ME, authApi.getUser); export const me = (token?: string) => ({ type: ME, token }); export type Register = ReturnType<typeof register>; export type Login = ReturnType<typeof login>; export type EmailCheck = ReturnType<typeof emailCheck>; export type Me = ReturnType<typeof me>; <file_sep>import { call, put } from 'redux-saga/effects'; // entity fetch export const fetchEntity = ({ request, success, failure, api, }: EntitySchema) => { return function*(...args: any[]) { yield put(request()); try { const response = yield call(api, ...args); yield put(success(response)); } catch (err) { yield put(failure()); } }; }; <file_sep>import styled from 'styled-components'; export const NavLayout = styled.div` position: fixed; left: 0; top: 0; padding: 10px; width: 300px; height: 100vh; background-color: #f7f8fb; border-right: 1px solid #efefef; `; export const NavTopWrap = styled.div` height: 10%; padding: 10px; display: flex; justify-content: space-between; flex-direction: row; `; export const NavLogo = styled.div` font-size: 2rem; font-weight: 800; color: #3562ff; `; export const NavContainer = styled.div` height: 90%; display: flex; justify-content: space-between; flex-direction: column; `; export const NavGlobalMenu = styled.div` padding: 10px; font-size: 1rem; `; export const NavFirstLevelWrap = styled.div` padding-bottom: 40px; font-size: 14px; `; export const NavSecondMenuWarp = styled.div` color: #9e9fa2; font-size: 0.875rem; `; export const NavMenu = styled.ul` line-height: 28px; color: #5b5c5f; font-size: 0.875rem; padding: 0; `; export const NavUserWrap = styled.ul` cursor: pointer; padding: 10px; `; export const NavUserName = styled.li` font-size: 0.875rem; `; export const NavUserLogin = styled.li` font-size: 0.75rem; color: #9e9fa2; `; export const CreateButton = styled.button` min-width: 170px; height: 50px; border-radius: 30px; border: 0px solid; font-size: 0.75rem; background-color: #3562ff; color: #fff; text-align: center; cursor: pointer; a { color: #fff; } `; <file_sep>import { produce } from 'immer'; import { combineReducers } from 'redux'; import { IComment } from 'models/comment'; export type CommentState = { getComments: { list: { parent_comments: IComment[]; }; status: string; }; }; const initialState: CommentState = { getComments: { list: { parent_comments: [], }, status: 'INIT', }, }; const getCommentsReducer = ( state = initialState.getComments, action: any, ): CommentState['getComments'] => { return produce(state, draft => { switch (action.type) { case 'GET_COMMENTS_REQUEST': console.log('555'); draft.status = 'FETCHING'; return draft; case 'GET_COMMENTS_SUCCESS': draft.list = { ...action.payload, }; draft.status = 'SUCCESS'; return draft; case 'GET_COMMENTS_FAILTURE': draft.status = 'FAILTURE'; return draft; default: return draft; } }); }; export default combineReducers({ getComments: getCommentsReducer, }); <file_sep>import { all, fork, call, take } from 'redux-saga/effects'; import { fetchEntity } from 'utils/saga'; import { registerEntity, REGISTER, Register, loginEntity, LOGIN, Login, EMAIL_CHECK, EmailCheck, emailCheckEntity, meEntity, ME, Me, } from 'store/auth/action'; const fetchRegister = fetchEntity(registerEntity); const fetchLogin = fetchEntity(loginEntity); const fetchEmail = fetchEntity(emailCheckEntity); const fetchMe = fetchEntity(meEntity); function* watchRegister() { while (true) { const { params }: Register = yield take(REGISTER); yield call(fetchRegister, params); } } function* watchLogin() { while (true) { const { params }: Login = yield take(LOGIN); yield call(fetchLogin, params); } } function* watchEmailCheck() { while (true) { const { params }: EmailCheck = yield take(EMAIL_CHECK); yield call(fetchEmail, params); } } function* watchMe() { while (true) { const { token }: Me = yield take(ME); yield call(fetchMe, token); } } export default function* root() { yield all([ fork(watchLogin), fork(watchRegister), fork(watchEmailCheck), fork(watchMe), ]); } <file_sep>import styled from 'styled-components'; export const LoginWrap = styled.div` display: flex; flex-direction: column; justify-content: center; min-height: 450px; `; export const LoginTitle = styled.p` font-size: 2rem; margin: 4% 0; font-weight: 800; margin-bottom: 10px; `; export const LoginContent = styled.p` padding-top: 3%; font-size: 0.88rem; color: #777777; font-weight: 800; padding-bottom: 3%; `; <file_sep>import { all, fork, call, take } from 'redux-saga/effects'; import { fetchEntity } from 'utils/saga'; import { myPageEntity, MY_PAGE, getMyApplicationListEntity, GET_MY_APPLICATION_LIST, getMyTeamListEntity, GET_MY_TEAM_LIST, } from 'store/mypage/action'; const fetchMyPage = fetchEntity(myPageEntity); const fetchGetMyApplicationList = fetchEntity(getMyApplicationListEntity); const fetchGetMyTeamList = fetchEntity(getMyTeamListEntity); function* watchMyPage() { while (true) { yield take(MY_PAGE); yield call(fetchMyPage); } } function* watchGetMyApplicationList() { while (true) { yield take(GET_MY_APPLICATION_LIST); yield call(fetchGetMyApplicationList); } } function* watchGetMyTeamList() { while (true) { yield take(GET_MY_TEAM_LIST); yield call(fetchGetMyTeamList); } } export default function* root() { yield all([ fork(watchMyPage), fork(watchGetMyApplicationList), fork(watchGetMyTeamList), ]); } <file_sep>type APIEndpoint<P extends any[], R> = (...p: P) => Promise<R>; <file_sep>import styled from 'styled-components'; interface Props { show: boolean; } export const ApplicantItemContainer = styled.div` display: flex; flex-direction: column; background-color: #f7f8fb; margin: 3% 0; border-radius: 10px; `; export const ApplicantItemWrap = styled.div` display: flex; flex-direction: row; justify-content: space-between; width: 100%; border-radius: 10px; `; export const ApplicantName = styled.span` font-size: 1.25rem; margin: 5% 1%; display: inline-block; `; export const ApplicantImage = styled.div` width: 62px; height: 62px; background-color: #fff; border-radius: 100%; display: inline-block; `; export const ApplyButton = styled.button` width: 20%; height: 30px; border-radius: 15px; border: 0px solid; font-size: 0.75rem; font-weight: 600; background-color: #3562ff; color: #fff; text-align: center; cursor: pointer; display: block; margin: 5% 1%; a { color: #fff; } `; export const ApplicantContent = styled.div<Props>` display: ${({ show }: Props) => (show ? 'show' : 'none')}; `; export const QnAWrap = styled.div` border: 1px solid #fff; border-radius: 10px; margin: 10px 4%; box-shadow: 4px 4px 4px 4px rgba(40, 50, 60, 0.06); `; export const Question = styled.div` border-bottom: 1px solid #bdbdbd; text-align: left; min-height: 30px; margin: 10px; font-size: 1.25rem; `; export const Answer = styled.div` text-align: left; min-height: 30px; margin: 10px; font-size: 1rem; `; <file_sep>import { produce } from 'immer'; import { combineReducers } from 'redux'; import { User } from 'models/user'; import { setAuthToken } from 'utils/auth'; export type AuthState = { register: { status: string; }; login: { loginStatus: string; }; emailCheck: { email: string; status: string; }; me: User & { isLoggedIn: boolean; }; }; const initialState: AuthState = { register: { status: 'INIT', }, login: { loginStatus: 'INIT', }, emailCheck: { email: '', status: 'INIT', }, me: { id: -1, username: '', email: '', phone: '', livingArea: '', isLoggedIn: false, }, }; const loginReducer = ( state = initialState.login, action: any, ): AuthState['login'] => { return produce(state, draft => { switch (action.type) { case 'LOGIN_REQUEST': draft.loginStatus = 'FETCHING'; return draft; case 'LOGIN_SUCCESS': draft.loginStatus = 'SUCCESS'; setAuthToken(action.payload.token); return draft; case 'LOGIN_FAILURE': draft.loginStatus = 'FAILTURE'; return draft; case 'RESET': draft = initialState.login; default: return draft; } }); }; const registerReducer = ( state: AuthState['register'] = initialState.register, action: any, ): AuthState['register'] => { return produce(state, draft => { switch (action.type) { case 'REGISTER_REQUEST': draft.status = 'REQUEST'; return draft; case 'REGISTER_SUCCESS': draft.status = 'SUCCESS'; return draft; case 'REGISTER_FAILURE': draft.status = 'FAILURE'; return draft; case 'RESET': draft = initialState.register; default: return draft; } }); }; const emailCheckReducer = ( state = initialState.emailCheck, action: any, ): AuthState['emailCheck'] => { return produce(state, draft => { switch (action.type) { case 'EMAIL_CHECK_REQUEST': draft.status = 'FETCHING'; return draft; case 'EMAIL_CHECK_SUCCESS': draft.email = action.payload.email; draft.status = action.payload.message; return draft; case 'EMAIL_CHECK_FAILURE': draft.status = 'FAILTURE'; return draft; case 'RESET': draft = initialState.emailCheck; default: return draft; } }); }; const meReducer = ( state: AuthState['me'] = initialState.me, action: any, ): AuthState['me'] => { return produce(state, draft => { switch (action.type) { case 'ME_REQUEST': return draft; case 'ME_SUCCESS': draft = { ...action.payload.profile, isLoggedIn: true, }; return draft; case 'ME_FAILURE': draft = { ...initialState.me, isLoggedIn: false, }; return draft; default: return draft; } }); }; export default combineReducers({ register: registerReducer, login: loginReducer, emailCheck: emailCheckReducer, me: meReducer, }); <file_sep>import styled from 'styled-components'; export const ApplicantCheckWrap = styled.div` display: flex; flex-direction: column; min-height: 450px; overflow-y: scroll; `; export const ApplicantCheckTitle = styled.p` font-size: 2rem; margin: 4% 0; font-weight: 800; margin-bottom: 10px; `; <file_sep>import { produce } from 'immer'; import { combineReducers } from 'redux'; import { User } from 'models/user'; import { Team } from 'models/team'; export type MyPageState = { profile: User; getMyApplicationList: { list: Team[]; status: string; }; }; const initialState: MyPageState = { profile: { id: -1, username: '', email: '', phone: '', livingArea: '', }, getMyApplicationList: { list: [], status: 'INIT', }, }; const myPageReducer = ( state = initialState.profile, action: any, ): MyPageState['profile'] => { return produce(state, draft => { switch (action.type) { case 'MY_PAGE_REQUEST': return draft; case 'MY_PAGE_SUCCESS': draft.email = action.payload.profile.email; draft.username = action.payload.profile.username; return draft; case 'MY_PAGE_FAILTURE': draft = initialState.profile; return draft; default: return draft; } }); }; const getMyApplicationListReducer = ( state = initialState.getMyApplicationList, action: any, ): MyPageState['getMyApplicationList'] => { return produce(state, draft => { switch (action.type) { case 'GET_MY_APPLICATION_LIST_REQUEST': draft.status = 'FETCHING'; return draft; case 'GET_MY_APPLICATION_LIST_SUCCESS': draft.list = action.payload.myApplication; draft.status = 'SUCCESS'; return draft; case 'GET_MY_APPLICATION_LIST_FAILTURE': draft.status = 'FAILTURE'; return draft; case 'GET_MY_TEAM_LIST_REQUEST': draft.status = 'FETCHING'; return draft; case 'GET_MY_TEAM_LIST_SUCCESS': draft.list = action.payload.myTeam; draft.status = 'SUCCESS'; return draft; case 'GET_MY_TEAM_LIST_FAILTURE': draft.status = 'FAILTURE'; return draft; default: return draft; } }); }; export default combineReducers({ profile: myPageReducer, getMyApplicationList: getMyApplicationListReducer, }); <file_sep>import fetcher from '../utils/fetcher'; import { getAuthToken } from 'utils/auth'; export const getMyPage = async () => { const token = getAuthToken(); const headers = token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', } : {}; const { data } = await fetcher.get('/account/profile/', { headers: headers, }); return data; }; export const putMyPage = async (params: FormData) => { const token = getAuthToken(); const headers = token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', } : {}; const { data } = await fetcher.put('/account/profile/', params, { headers: headers, }); const status = data.message; return status; }; export const getMyApplicationList = async () => { const token = getAuthToken(); const headers = token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', } : {}; const { data } = await fetcher.get('/account/profile/application/', { headers: headers, }); return data; }; export const getMyteamList = async () => { const token = getAuthToken(); const headers = token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', } : {}; const { data } = await fetcher.get('account/profile/team/', { headers, }); return data; }; <file_sep>import { AnyAction } from 'redux'; import { RootState } from 'store'; declare global { type StoreState = RootState; type EntitySchema = { request: { (...args: any[]): AnyAction<Type>; type: Type; }; success: { (...args: any[]): AnyAction<Type>; type: Type; }; failure: { (...args: any[]): AnyAction<Type>; type: Type; }; api: (...args: any[]) => any; }; } <file_sep>import fetcher from '../utils/fetcher'; import { getAuthToken } from 'utils/auth'; export interface Question { question: string; } export interface TeamParams { title: string; description: string; planner: number; developer: number; designer: number; region: string; active_status?: string; goal: string; image?: string; questions?: Question[]; } export const createTeam = async (payload: FormData) => { const token = getAuthToken(); const headers = token ? { Authorization: `Bearer ${token}`, 'content-type': 'multipart/form-data; boundary=ebf9f03029db4c2799ae16b5428b06bd', } : {}; const { data } = await fetcher.post('/teams/board/', payload, { headers, }); return data; }; export const detailTeam = async (team_id: number) => { const token = getAuthToken(); const headers = token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', } : {}; const { data } = await fetcher.get(`/teams/board/${team_id}/`, { headers, }); return data; }; export const listTeam = async () => { const { data } = await fetcher.get('/teams/board/'); return data; }; export const listQuestion = async (team_id: number) => { const token = getAuthToken(); const headers = token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', } : {}; const { data } = await fetcher.get(`/teams/board/${team_id}/questions/`, { headers, }); return data; }; <file_sep>export {}; declare global { export interface Window { naver: any; } } <file_sep>import styled from 'styled-components'; export const CardImageWrap = styled.span` padding-top: 75%; overflow: hidden; `; export const Img = styled.img` transform: scale(1); top: 0px; left: 0px; width: 100%; height: 100%; object-fit: cover; position: absolute; opacity: 1; `; // &.animation { // img { // transition: transform 0.3s ease 0s, opacity 0.1s linear 0s; // &:hover { // transform: scale(1.1); // } // } // } // } <file_sep>import styled from 'styled-components'; export const DetailTeamWrap = styled.div` padding: 60px 1.375rem 0; flex-direction: column; align-items: center; display: flex; `; export const Container = styled.div` width: 70%; `; export const Title = styled.h1` font-size: 3rem; text-align: center; font-weight: 800; `; export const SubTitle = styled.div` font-size: 1rem; text-align: center; `; export const Hr = styled.hr` width: 100%; margin: 3% 0; border: 1px solid #efefef; `; export const Description = styled.div` margin: 5% 0 10% 0; font-weight: 800; `; export const CreateButton = styled.button` width: 14%; height: 30px; border-radius: 15px; border: 0px solid; font-size: 12px; font-weight: 600; background-color: #3562ff; color: #ffffff; text-align: center; cursor: pointer; display: block; margin-left: auto; `; export const ImageWrap = styled.div` text-align: center; height: 50%; `; export const TeamPeopleWrap = styled.div``; export const TeamPeopleTitle = styled.p` font-size: 1.25rem; font-weight: 600; `; export const TeamPeopleContent = styled.div` display: flex; margin-left: 15px; `; export const TeamPeopleImage = styled.div` width: 48px; height: 48px; background-color: #fff; border-radius: 100%; `; export const TeamPeople = styled.div` margin: 0 15px; `; <file_sep>이 프로젝트는 [Create React App](https://github.com/facebook/create-react-app)을 통해서 구축되었습니다. # 프로그라피 6기 - Fitple ## Fitple 프로젝트 > 프로그라피 6기 Fitple팀의 프론트엔드 프로젝트 리포지토리 입니다. 본 프로젝트는 2개의 리포지토리를 가지고 있습니다. - [프론트엔드 리포지토리](https://github.com/prography/gaegata-frontend) - [백엔드 리포지토리](https://github.com/prography/6th-fitple-backend) ## 실행 ```shell git clone https://github.com/prography/gaegata-frontend.git cd gaegata-frontend yarn yarn start ``` ## 코딩스타일 에어비엔비의 스타일가이드와 Prettier를 사용합니다. **꼭!** ESlint와 Prettier 설정을 해주세요. - [ESLint & Prettier 설정방법](https://velog.io/@velopert/eslint-and-prettier-in-react) - [에어비엔비 스타일가이드](https://github.com/airbnb/javascript) ## 풀리퀘스트(PR) 가이드 > 자기가 무슨 작업을 했는지 참고할만한 내용을 자세히 적어주세요. > 또한 이전 코드와 비교하면서 오타나 필요 없는 코드가 있는지 꼼꼼히 확인해주세요. ##### 체크리스트 ✅ - 푸쉬 전에는 항상 **ESlint** 체크하기 - **console.log**는 항상 제거 - 내가 보기 어려운 코드는 남도 어려움. **주석 꼼꼼히 달기** - 문제를 해결했으면 **해결 방안과 원인**도 같이 적어주기 <file_sep>import Home from 'pages/Home'; import CreateTeam from 'pages/CreateTeam/index'; import DetailTeam from 'pages/DetailTeam/index'; import MyPage from 'pages/MyPage/index'; import Feedback from 'pages/Feedback'; export const routes = [ { path: '/', page: Home, exact: true, }, { path: '/team/create', page: CreateTeam, exact: true, }, { path: '/team/detail/:team_id', page: DetailTeam, exact: true, }, { path: '/mypage', page: MyPage, exact: true, }, { path: '/mypage/:menu(application|made)', page: MyPage, exact: true, }, { path: '/mypage/application/:sortby', page: MyPage, exact: true, }, { path: '/mypage/own', page: MyPage, exact: true, }, { path: '/feedback', page: Feedback, exact: true, }, ]; <file_sep>import styled from 'styled-components'; export const FooterContainer = styled.footer` padding: 30px 0; border-top: 1px solid #e8e8e8; background-color: #f9f9f9; color: #999; `; export const Container = styled.div` max-width: 1200px; width: 90%; margin: 0 auto; `; export const FooterContent = styled.div``; export const PersonalInformationArea = styled.ul` display: flex; margin: 0; padding: 0; li { a { margin-right: 20px; color: #999; transition: color 0.2s; &:hover { color: $main-color-blue; } } } `; export const FooterDescription = styled.div` margin-top: 20px; font-size: 0.75rem; span { font-size: 0.825rem; &.dd { &:before { content: '|'; display: inline; padding: 0 5px; color: #999; } } } } `; <file_sep>import { User } from './user'; export interface IComment { team: number; id?: number; user?: User; parent?: number; comment: string; created_at?: string; is_deleted?: boolean; reply?: IComment[]; } <file_sep>import { all, fork } from 'redux-saga/effects'; import authSaga from './auth'; import teamSaga from './team'; import applyTeamSage from './apply'; import myPageSaga from './mypage'; import commentSaga from './comment'; import userProfileFuck from './userprofile'; function* rootSaga() { yield all([ fork(authSaga), fork(teamSaga), fork(applyTeamSage), fork(myPageSaga), fork(commentSaga), fork(userProfileFuck), ]); } export default rootSaga; <file_sep>export interface IApply { job: string; answer1: IAnswer; answer2: IAnswer; answer3: IAnswer; } export interface IAnswer { question: number; answer: string; } export interface Applicants { id: number; applicant: { id: number; username: string; image: string; }; join_status: string; job: string; created_at: string; } <file_sep>import styled from 'styled-components'; export const ApplyWrap = styled.div` display: flex; flex-direction: column; min-height: 450px; `; export const ApplyTitle = styled.p` font-size: 2rem; margin: 4% 0; font-weight: 800; margin-bottom: 10px; `; export const FieldWrap = styled.div` display: flex; margin-top: 5%; `; export const NumberInputWrap = styled.div` width: 80%; `; export const NumberInput = styled.input` padding-right: 15px; padding-left: 15px; border-radius: 5px; border: 1px solid #e1e2e3; font-size: 15px; color: #333; `; export const ApplyButton = styled.button` width: 100%; height: 60px; border-radius: 5px 5px; border: 0px solid; font-size: 14px; font-weight: 600; text-align: center; cursor: pointer; background-color: #393c42; color: #fff; `; export const Hr = styled.hr` width: 20%; display: inline-block; margin: 33px 10px; `; export const ItemWrap = styled.div` margin: 5% 0; `; export const TextArea = styled.textarea` display: block; width: 100%; height: 150px; padding: 15px; border-radius: 5px; border: 1px solid #e1e2e3; font-size: 15px; color: #333; background-color: #f7f8fb; border: 0px solid; margin: 10px 0; `; <file_sep>import styled from 'styled-components'; export const CreateButton = styled.button` width: 14%; height: 30px; border-radius: 15px; border: 0px solid; font-size: 12px; font-weight: 600; background-color: #3562ff; color: #ffffff; text-align: center; cursor: pointer; display: block; `; export const TextArea = styled.textarea` border-radius: 10px; display: block; width: 100%; height: 150px; padding: 15px; border-radius: 5px; border: 1px solid #f7f8fb; font-size: 15px; color: #333; background-color: #f7f8fb; width: 70%; margin: 10px 0; `; <file_sep>import styled from 'styled-components'; export const RegisterWrap = styled.div` display: flex; flex-direction: column; justify-content: center; min-height: 450px; `; export const RegisterTitle = styled.p` font-size: 2rem; margin: 4% 0; font-weight: 800; margin-bottom: 10px; `; export const RegisterContent = styled.p` padding-top: 1%; font-size: 0.88rem; color: #777777; font-weight: 800; padding-bottom: 1%; `; <file_sep>import fetcher from 'utils/fetcher'; export interface LoginParams { email: string; password: string; } export const postLogin = async (payload: LoginParams) => { const { data } = await fetcher.post('account/user/login/', payload); return data; }; export interface EmailCheckParams { email: string; } export const emailCheck = async (payload: EmailCheckParams) => { const { data } = await fetcher.post('account/user/check/', payload); return data; }; export interface RegisterParams { email: string; username: string; password: string; } export const postRigster = async (payload: RegisterParams) => { const { data } = await fetcher.post('account/user/create/', payload); return data; }; export const getUser = async (token?: string) => { const headers = token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', } : {}; const { data } = await fetcher.get('account/profile/', { headers, }); return data; }; <file_sep>import { all, fork, call, take } from 'redux-saga/effects'; import { fetchEntity } from '../utils/saga'; import { GET_COMMENTS, GetComments, getCommentsEntity, } from '../store/comment/action'; const fetchGetComments = fetchEntity(getCommentsEntity); function* watchGetComments() { while (true) { const { params }: GetComments = yield take(GET_COMMENTS); yield call(fetchGetComments, params); } } export default function* root() { yield all([fork(watchGetComments)]); } <file_sep>import { createEntity } from '../../utils/redux'; import * as teamApi from '../../api/team'; export const CREAT_TEAM = 'CREAT_TEAM'; export const DETAIL_TEAM = 'DETAIL_TEAM'; export const LIST_TEAM = 'LIST_TEAM'; export const LIST_QUESTION = 'LIST_QUESTION'; export const createTeamEntity = createEntity(CREAT_TEAM, teamApi.createTeam); export const createTeam = (params: FormData) => ({ type: CREAT_TEAM, params, }); export const detailTeamEntity = createEntity(DETAIL_TEAM, teamApi.detailTeam); export const detailTeam = (params: number) => ({ type: DETAIL_TEAM, params, }); export const listTeamEntity = createEntity(LIST_TEAM, teamApi.listTeam); export const listTeam = (params: string) => ({ type: LIST_TEAM, params, }); export const listQuestionEntity = createEntity( LIST_QUESTION, teamApi.listQuestion, ); export const listQuestion = (params: number) => ({ type: LIST_QUESTION, params, }); export type CreateTeam = ReturnType<typeof createTeam>; export type DetailTeam = ReturnType<typeof detailTeam>; export type ListTeam = ReturnType<typeof listTeam>; export type ListQuestion = ReturnType<typeof listQuestion>; <file_sep>import { createEntity } from 'utils/redux'; import * as profileApi from 'api/profile'; export const USER_PROFILE_FUCK = 'USER_PROFILE_FUCK'; export const userProfileFuckEntity = createEntity( USER_PROFILE_FUCK, profileApi.getUserProfile, ); export const userProfileFuck = (user_id: number) => ({ type: USER_PROFILE_FUCK, user_id, }); export type UserProfileFuck = ReturnType<typeof userProfileFuck>; <file_sep>import { all, fork, call, take } from 'redux-saga/effects'; import { fetchEntity } from '../utils/saga'; import { UserProfileFuck, USER_PROFILE_FUCK, userProfileFuckEntity, } from '../store/profile/action'; const fetchUserProfile = fetchEntity(userProfileFuckEntity); function* watchUserProfileFuck() { while (true) { const { user_id }: UserProfileFuck = yield take(USER_PROFILE_FUCK); yield call(fetchUserProfile, user_id); } } export default function* root() { yield all([fork(watchUserProfileFuck)]); } <file_sep>import { createEntity } from 'utils/redux'; import * as myPageApi from 'api/myPage'; export const MY_PAGE = 'MY_PAGE'; export const GET_MY_APPLICATION_LIST = 'GET_MY_APPLICATION_LIST'; export const GET_MY_TEAM_LIST = 'GET_MY_TEAM_LIST'; export const myPageEntity = createEntity(MY_PAGE, myPageApi.getMyPage); export const myPage = () => ({ type: MY_PAGE, }); export const getMyApplicationListEntity = createEntity( GET_MY_APPLICATION_LIST, myPageApi.getMyApplicationList, ); export const getMyApplicationList = () => ({ type: GET_MY_APPLICATION_LIST, }); export const getMyTeamListEntity = createEntity( GET_MY_TEAM_LIST, myPageApi.getMyteamList, ); export const getMyTeamList = () => ({ type: GET_MY_TEAM_LIST, }); export type MyPage = ReturnType<typeof myPage>; export type GetMyApplicationList = ReturnType<typeof getMyApplicationList>; export type GetMyTeamList = ReturnType<typeof getMyTeamList>; <file_sep>import { createEntity } from '../../utils/redux'; import * as applyApi from '../../api/applyTeam'; export const APPLY_TEAM = 'APPLY_TEAM'; export const APPLY_TEAM_1 = 'APPLY_TEAM_1'; export const APPLY_TEAM_2 = 'APPLY_TEAM_2'; export const APPLICANT_LIST = 'APPLICANT_LIST'; export const APPROVE_APPLICANT = 'APPROVE_APPLICANT'; export const REFUSE_APPLICANT = 'REFUSE_APPLICANT'; export const RESET = 'RESET'; export const applyTeamEntity = createEntity(APPLY_TEAM, applyApi.postApplyTeam); export const applyTeam = (params: applyApi.IApplyParams, team_id: number) => ({ type: APPLY_TEAM, params, team_id, }); export const applicantsEntity = createEntity( APPLICANT_LIST, applyApi.getApplicantList, ); export const applicants = (team_id: number) => ({ type: APPLICANT_LIST, team_id, }); export const approveApplicantEntity = createEntity( APPROVE_APPLICANT, applyApi.getApproveApplicant, ); export const approveApplicant = (id: number) => ({ type: APPROVE_APPLICANT, id, }); export const refuseApplicantEntity = createEntity( REFUSE_APPLICANT, applyApi.getRefuseApplicant, ); export const refuseApplicant = (id: number) => ({ type: REFUSE_APPLICANT, id, }); interface IApplyTeam01 { job: string; answer1: { question: number; answer: string }; } export const applyTeam01 = (params: IApplyTeam01) => ({ type: APPLY_TEAM_1, params, }); interface IApplyTeam02 { answer2: { question: number; answer: string }; answer3: { question: number; answer: string }; } export const applyTeam02 = (params: IApplyTeam02) => ({ type: APPLY_TEAM_2, params, }); export const reset = () => ({ type: RESET, }); export type ApplyTeam = ReturnType<typeof applyTeam>; export type Applicants = ReturnType<typeof applicants>; export type ApproveApplicant = ReturnType<typeof approveApplicant>; export type RefuseApplicant = ReturnType<typeof refuseApplicant>; <file_sep>import { all, fork, call, take } from 'redux-saga/effects'; import { fetchEntity } from '../utils/saga'; import { APPLY_TEAM, ApplyTeam, applyTeamEntity, applicantsEntity, APPLICANT_LIST, Applicants, APPROVE_APPLICANT, approveApplicantEntity, RefuseApplicant, refuseApplicantEntity, REFUSE_APPLICANT, ApproveApplicant, } from '../store/apply/action'; const fetchApplyTeam = fetchEntity(applyTeamEntity); const fetchApplicantList = fetchEntity(applicantsEntity); const fetchAproveApplicant = fetchEntity(approveApplicantEntity); const fetchRefuseApplicant = fetchEntity(refuseApplicantEntity); function* watchApplyTeam() { while (true) { const { params, team_id }: ApplyTeam = yield take(APPLY_TEAM); yield call(fetchApplyTeam, params, team_id); } } function* watchApplicantList() { while (true) { const { team_id }: Applicants = yield take(APPLICANT_LIST); yield call(fetchApplicantList, team_id); } } function* watchAproveApplicant() { while (true) { const { id }: ApproveApplicant = yield take(APPROVE_APPLICANT); yield call(fetchAproveApplicant, id); } } function* watchRefuseApplicant() { while (true) { const { id }: RefuseApplicant = yield take(REFUSE_APPLICANT); yield call(fetchRefuseApplicant, id); } } export default function* root() { yield all([ fork(watchApplyTeam), fork(watchApplicantList), fork(watchAproveApplicant), fork(watchRefuseApplicant), ]); } <file_sep>import fetcher from '../utils/fetcher'; import { getAuthToken } from 'utils/auth'; import { IAnswer } from 'models/apply'; export interface IApplyParams { team: { job: string; }; answers: IAnswer[]; } export const postApplyTeam = async (payload: IApplyParams, team_id: number) => { const token = getAuthToken(); const headers = token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', } : {}; const { data } = await fetcher.post( `teams/board/${team_id}/applications/`, payload, { headers, }, ); return data; }; export const getApplicantList = async (team_id: number) => { const token = getAuthToken(); const headers = token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', } : {}; const { data } = await fetcher.get(`teams/board/${team_id}/applications/`, { headers: headers, }); return data; }; export interface ApproveApplicantParams { id: number; } export const getApproveApplicant = async (id: ApproveApplicantParams) => { const token = getAuthToken(); const headers = token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', } : {}; const { data } = await fetcher.get(`applications/${id}/approve/`, { headers: headers, }); return data; }; export const getRefuseApplicant = async (id: ApproveApplicantParams) => { const token = getAuthToken(); const headers = token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', } : {}; const { data } = await fetcher.get(`applications/${id}/refuse/`, { headers: headers, }); return data; }; <file_sep>import { combineReducers } from 'redux'; import AuthReducer, { AuthState } from './auth'; import TeamReducer, { TeamState } from './team'; import ApplyReducer, { ApplyTeamState } from './apply'; import MyPageReudecer, { MyPageState } from './mypage'; import CommentReudecer, { CommentState } from './comment'; import UserProfileReducer, { UserProfileState } from './profile'; export type RootState = { auth: AuthState; team: TeamState; applyTeam: ApplyTeamState; myPage: MyPageState; comment: CommentState; userProfile: UserProfileState; }; export default combineReducers({ auth: AuthReducer, team: TeamReducer, applyTeam: ApplyReducer, myPage: MyPageReudecer, comment: CommentReudecer, userProfile: UserProfileReducer, }); <file_sep>import { produce } from 'immer'; import { combineReducers } from 'redux'; import { IApply } from 'models/apply'; import { IQuestion } from 'models/question'; export type ApplyTeamState = { applyTeam: IApply & { progress: string; status: string; }; applicants: { applyList: { team_questions: IQuestion[]; team: number; applications: []; message: string; }; status: string; }; aproveApplicant: { status: string; }; }; const initialState: ApplyTeamState = { applyTeam: { job: '', answer1: { question: -1, answer: '' }, answer2: { question: -1, answer: '' }, answer3: { question: -1, answer: '' }, progress: 'INIT', status: 'INIT', }, applicants: { applyList: { team_questions: [], team: 0, applications: [], message: '', }, status: '', }, aproveApplicant: { status: 'INIT', }, }; const applyTeamReducer = ( state = initialState.applyTeam, action: any, ): ApplyTeamState['applyTeam'] => { return produce(state, draft => { switch (action.type) { case 'APPLY_TEAM_REQUEST': draft.status = 'FETCHING'; return draft; case 'APPLY_TEAM_SUCCESS': draft.status = 'SUCCESS'; return draft; case 'APPLY_TEAM_FAILURE': draft.status = 'FAILTURE'; return draft; case 'APPLY_TEAM_1': draft.job = action.params.job; draft.answer1 = action.params.answer1; draft.progress = '2'; return draft; case 'APPLY_TEAM_2': draft.answer2 = action.params.answer2; draft.answer3 = action.params.answer3; draft.progress = '3'; return draft; case 'RESET': draft = initialState.applyTeam; default: return draft; } }); }; const applicantsReducer = ( state = initialState.applicants, action: any, ): ApplyTeamState['applicants'] => { return produce(state, draft => { switch (action.type) { case 'APPLICANT_LIST_REQUEST': draft.status = 'FETCHING'; return draft; case 'APPLICANT_LIST_SUCCESS': draft.applyList = { ...action.payload, }; draft.status = 'SUCCESS'; return draft; case 'APPLICANT_LIST_FAILURE': draft.status = 'FAILTURE'; return draft; default: return draft; } }); }; const applyApplicantReducer = ( state = initialState.aproveApplicant, action: any, ): ApplyTeamState['aproveApplicant'] => { return produce(state, draft => { switch (action.type) { case 'APPROVE_APPLICANT_REQUEST': draft.status = 'FETCHING'; return draft; case 'APPROVE_APPLICANT_SUCCESS': draft.status = 'SUCCESS'; return draft; case 'APPROVE_APPLICANT_FAILURE': draft.status = 'FAILTURE'; case 'REFUSE_APPLICANT_REQUEST': draft.status = 'FETCHING'; return draft; case 'REFUSE_APPLICANT_SUCCESS': draft.status = 'SUCCESS'; return draft; case 'REFUSE_APPLICANT_FAILURE': draft.status = 'FAILTURE'; return draft; default: return draft; } }); }; export default combineReducers({ applyTeam: applyTeamReducer, applicants: applicantsReducer, aproveApplicant: applyApplicantReducer, }); <file_sep>import { all, fork, call, take } from 'redux-saga/effects'; import { fetchEntity } from '../utils/saga'; import { createTeamEntity, CreateTeam, CREAT_TEAM, DetailTeam, DETAIL_TEAM, detailTeamEntity, ListTeam, LIST_TEAM, listTeamEntity, listQuestionEntity, LIST_QUESTION, ListQuestion, } from '../store/team/action'; const fetchCreateTeam = fetchEntity(createTeamEntity); const fetchDetailTeam = fetchEntity(detailTeamEntity); const fetchListTeam = fetchEntity(listTeamEntity); const fetchListQuestion = fetchEntity(listQuestionEntity); function* watchCreateTeam() { while (true) { const { params }: CreateTeam = yield take(CREAT_TEAM); yield call(fetchCreateTeam, params); } } function* watchDetailTeam() { while (true) { const { params }: DetailTeam = yield take(DETAIL_TEAM); yield call(fetchDetailTeam, params); } } function* watchListTeam() { while (true) { const { params }: ListTeam = yield take(LIST_TEAM); yield call(fetchListTeam, params); } } function* watchListQuestion() { while (true) { const { params }: ListQuestion = yield take(LIST_QUESTION); yield call(fetchListQuestion, params); } } export default function* root() { yield all([ fork(watchCreateTeam), fork(watchDetailTeam), fork(watchListTeam), fork(watchListQuestion), ]); } <file_sep>export type User = { id: number; email?: string; livingArea?: string; phone?: string; username: string; image?: string; introduce?: string; }; <file_sep>import { produce } from 'immer'; import { combineReducers } from 'redux'; import { Team } from 'models/team'; import { IQuestion } from 'models/question'; import { User } from 'models/user'; export type TeamState = { team: Team & { status: string; application: boolean; leader: User; authorCheck: boolean; member: User[]; }; teamList: { list: { count: number; next: null; previous: null; results: []; }; status: string; }; questionList: { list: IQuestion[]; status: string; }; }; const initialState: TeamState = { team: { team_id: -1, id: -1, title: '', author: '', description: '', planner: 0, developer: 0, designer: 0, region: '', status: '', goal: '', image: '', created_at: '', application: false, authorCheck: false, job: '', join_status: '', leader: { id: -1, image: '', username: '', }, member: [], }, teamList: { list: { count: 0, next: null, previous: null, results: [], }, status: '', }, questionList: { list: [], status: 'INIT', }, }; const teamReducer = ( state = initialState.team, action: any, ): TeamState['team'] => { return produce(state, draft => { switch (action.type) { case 'CREAT_TEAM_REQUEST': draft.status = 'FETCHING'; return draft; case 'CREAT_TEAM_SUCCESS': draft.id = action.payload.board.id; draft.status = 'CREATE_SUCCESS'; return draft; case 'CREAT_TEAM_FAILURE': draft.status = 'CREATE_FAILTURE'; return draft; case 'DETAIL_TEAM_REQUEST': draft.status = 'FETCHING'; return draft; case 'DETAIL_TEAM_SUCCESS': draft = { ...action.payload.board, }; draft.application = action.payload.application; draft.leader = action.payload.leader; draft.member = action.payload.member; draft.status = 'DETAIL_SUCCESS'; return draft; case 'DETAIL_TEAM_FAILURE': draft.status = 'DETAIL_FAILTURE'; return draft; default: return draft; } }); }; const teamListReducer = ( state = initialState.teamList, action: any, ): TeamState['teamList'] => { return produce(state, draft => { switch (action.type) { case 'LIST_TEAM_REQUEST': return draft; case 'LIST_TEAM_SUCCESS': draft.list = { ...action.payload, }; draft.status = 'LIST_TEAM_SUCCESS'; return draft; case 'LIST_TEAM_FAILTURE': return draft; default: return draft; } }); }; const questionListReducer = ( state = initialState.questionList, action: any, ): TeamState['questionList'] => { return produce(state, draft => { switch (action.type) { case 'LIST_QUESTION_REQUEST': draft.status = 'FETCHING'; return draft; case 'LIST_QUESTION_SUCCESS': draft.status = 'SUCCESS'; draft.list = { ...action.payload, }; return draft; case 'LIST_QUESTION_FAILTURE': draft.status = 'FAILTURE'; return draft; default: return draft; } }); }; export default combineReducers({ team: teamReducer, teamList: teamListReducer, questionList: questionListReducer, }); <file_sep>import fetcher from '../utils/fetcher'; import { getAuthToken } from '../utils/auth'; export interface ICommentParams { team: number; comment: string; parent?: number; } export const postComment = async (params: ICommentParams) => { const token = getAuthToken(); const headers = token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', } : {}; const { data } = await fetcher.post('/teams/comments/', params, { headers: headers, }); return data; }; export const getComments = async (team: number) => { const { data } = await fetcher.get(`/teams/comment/${team}`); return data; }; <file_sep>import { produce } from 'immer'; import { combineReducers } from 'redux'; import { User } from 'models/user'; export type UserProfileState = { userProfile: User; }; const initialState: UserProfileState = { userProfile: { id: -1, username: '', email: '', phone: '', livingArea: '', }, }; const userProfileReducer = ( state = initialState.userProfile, action: any, ): UserProfileState['userProfile'] => { return produce(state, draft => { switch (action.type) { case 'USER_PROFILE_FUCK_REQUEST': return draft; case 'USER_PROFILE_FUCK_SUCCESS': draft.email = action.payload.email; draft.username = action.payload.username; draft.image = action.payload.image; draft.introduce = action.payload.introduce; draft.phone = action.payload.phone; draft.livingArea = action.payload.livingArea; return draft; case 'USER_PROFILE_FUCK_FAILTURE': draft = initialState.userProfile; return draft; case 'RESET': draft = initialState.userProfile; default: return draft; } }); }; export default combineReducers({ userProfile: userProfileReducer, }); <file_sep>const TOKEN_KEY = 'TOKEN_KEY'; export const getAuthToken = () => { return localStorage.getItem(TOKEN_KEY); }; export const setAuthToken = (token: any) => { if (typeof token === 'string') { localStorage.setItem(TOKEN_KEY, token); } }; export const destroyAuthToken = () => { return localStorage.removeItem(TOKEN_KEY); }; <file_sep>import fetcher from '../utils/fetcher'; export const getUserProfile = async (user_id: string) => { const { data } = await fetcher.get(`/account/user/profile/${user_id}/`); return data; }; <file_sep>// type이 있는 ActionCreator 만들기 export const createAction = <P, Type extends string = string>(type: Type) => { function fn(payload?: P): { type: Type }; function fn(payload: P): { type: Type; payload: P }; function fn(payload: any): any { return { type, payload, }; } fn.type = type; return fn; }; // entity 만들기 - 비동기일 때 사용 export const createEntity = <Params extends any[], Res>( prefix: string, api: APIEndpoint<Params, Res>, ) => ({ request: createAction<Params>(`${prefix}_REQUEST`), success: createAction<Res>(`${prefix}_SUCCESS`), failure: createAction<string>(`${prefix}_FAILURE`), api, }); <file_sep>import styled from 'styled-components'; export const CommentInputWrap = styled.div` padding-bottom: 20px; `; export const CommetTextArea = styled.textarea` overflow: hidden; overflow-wrap: break-word; height: 80px; width: 100%; outline: none; padding: 1rem; border: 1px solid #e9ecef; border-radius: 4px; resize: none; color: #212529; display: block; line-height: 1.5; -webkit-transition: height 0.2s; transition: height 0.2s; outline: 0; `; export const CommetBtnWrap = styled.div` display: flex; flex-direction: column; align-items: flex-end; padding-top: 10px; `; <file_sep>import styled from 'styled-components'; export const HeaderWrap = styled.header` background-color: #fff; box-shadow: 0 1px 2px 0 rgba(40, 50, 60, 0.06); border-bottom: 1px solid #d9dfeb; position: relative; width: 100%; position: absolute; top: 0; left: 0; height: 60px; display: flex !important; align-items: center; z-index: 900; `; export const HeaderContainer = styled.div` justify-content: space-between; width: 90%; margin: 0 auto; display: flex; `; export const NavLogo = styled.div` font-size: 2rem; font-weight: 800; color: #5b5c5f; `; export const NavUser = styled.div` display: flex; align-items: center; `; export const NavUl = styled.ul` display: flex; flex-direction: row; margin: 0; `; export const NavLi = styled.li` cursor: pointer; padding: 10px; font-weight: 800; margintop: 15px; `; <file_sep>import { User } from './user'; export interface Team { id: number; team_id: number; title: string; author: string; description: string; planner?: number; developer?: number; designer?: number; region?: string; status?: string; goal?: string; image: string; created_at: string; job: string; join_status: string; } <file_sep>import fetcher from 'utils/fetcher'; export interface IFeedbackParam { feedback: string; } export const postFeedback = async (params: IFeedbackParam) => { const { data } = await fetcher.post('/feedback/opinion/', params); return data.message; }; <file_sep>import { createStore, Store, applyMiddleware, compose } from 'redux'; import createSagaMiddleware from 'redux-saga'; import State from 'store'; import rootSaga from 'sagas'; //saga 미들웨어 생성 const sagaMiddleware = createSagaMiddleware(); const middleWares = applyMiddleware(sagaMiddleware); // 개발환경일때만 크롬 확장프로그램 추가 const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const configureStore = (): Store => { const store: Store = createStore(State, composeEnhancers(middleWares)); sagaMiddleware.run(rootSaga); return store; }; export default configureStore; <file_sep>import styled from 'styled-components'; export const PageLoadingOverlay = styled.div` text-align: center; width: 100vw; height: 100vh; display: flex; align-items: center; justify-content: center; `; export const CreateBanner = styled.div` width: 100%; border-radius: 10px; padding: 30px; background: #f5f5f5; border: 1px solid #efefef; margin-bottom: 60px; display: flex; flex-direction: row; justify-content: space-between; h2 { font-size: 1.25rem; margin: 0; font-family: Noto Sans Medium; color: #5f76f3; } p { margin: 0; font-family: Noto Sans Light; } .btn-wrap { display: flex; align-items: center; .apply-btn { &:hover { color: #fff; } } } `; <file_sep>import { createEntity } from '../../utils/redux'; import * as commentApi from '../../api/comment'; export const GET_COMMENTS = 'GET_COMMENTS'; export const getCommentsEntity = createEntity( GET_COMMENTS, commentApi.getComments, ); export const getComments = (params: number) => ({ type: GET_COMMENTS, params, }); export type GetComments = ReturnType<typeof getComments>; <file_sep>import styled from 'styled-components'; export const CommentNickname = styled.span` font-size: 0.7rem; `; export const CommentContent = styled.p` padding-right: 8px; font-size: 12px; line-height: 18px; `; <file_sep>import styled from 'styled-components'; interface InputPropsType { error?: String; } export const ProfileWrap = styled.div``; export const ProfileImageBox = styled.div` display: flex; flex-direction: column; align-items: center; text-align: center; `; export const ProfileImage = styled.div` border-radius: 50%; width: 200px; height: 200px; border: 1px solid #efefef; overflow: hidden; margin-bottom: 20px; `; export const Image = styled.img` width: 198px; `; export const H3 = styled.h3` font-size: 1.5rem; `; export const Span = styled.span` font-size: 0.8rem; color: #aaa; `; export const P = styled.p` font-size: 0.8rem; `; export const Input = styled.input<InputPropsType>` width: 100%; height: 40px; padding-right: 15px; padding-left: 15px; border-radius: 5px; border: 1px solid #f7f8fb; font-size: 15px; color: #333; background-color: #f7f8fb; margin: 10px 0; border-color: ${(props: InputPropsType) => (props.error ? 'red' : '')}; `; export const SelectArea = styled.select` display: block; width: 25%; height: 40px; padding-right: 15px; padding-left: 15px; border-radius: 5px; border: 1px solid #f7f8fb; font-size: 15px; color: #333; background-color: #f7f8fb; margin: 10px 0; `; export const Button = styled.button` width: 60px; height: 30px; border-radius: 15px; border: 0px solid; font-size: 12px; font-weight: 600; background-color: #3562ff; color: #ffffff; text-align: center; cursor: pointer; display: block; margin-left: auto; margin-top: 5%; margin-bottom: 5%; `; export const TextArea = styled.textarea<InputPropsType>` display: block; width: 100%; height: 150px; padding: 15px; border-radius: 5px; border: 1px solid #f7f8fb; font-size: 15px; color: #333; background-color: #f7f8fb; margin: 10px 0; border-color: ${(props: InputPropsType) => (props.error ? 'red' : '')}; `; <file_sep>import styled from 'styled-components'; interface ButtonPropsType { color: string; backgroundColor: string; } interface InputPropsType { error?: String; } export const ItemWrap = styled.div` padding-bottom: 12px; color: #767676; display: block; justify-content: center; `; export const LoginButton = styled.button<ButtonPropsType>` justify-content: center; align-items: center; width: 50%; height: 60px; border-radius: 40px 40px; border: 0px solid; font-size: 14px; font-weight: 600; color: ${({ color }: ButtonPropsType) => color}; background-color: ${({ backgroundColor }: ButtonPropsType) => backgroundColor}; text-align: center; cursor: pointer; `; export const LoginInput = styled.input<InputPropsType>` height: 60px; width: 50%; padding-right: 15px; padding-left: 15px; border-radius: 40px 40px; border: 1px solid #e1e2e3; font-size: 15px; color: #333; border-color: ${(props: InputPropsType) => (props.error ? 'red' : '')}; `; <file_sep>import styled from 'styled-components'; export const ProfileWrap = styled.div` padding: 25px 0; `; export const ProfileImageBox = styled.div` display: flex; flex-direction: column; align-items: center; text-align: center; `; export const ProfileImage = styled.div` border-radius: 50%; width: 200px; height: 200px; border: 1px solid #efefef; overflow: hidden; margin-bottom: 20px; `; export const Image = styled.img` width: 198px; `; export const H3 = styled.h3` font-size: 1.5rem; `; export const Span = styled.span` font-size: 0.8rem; color: #aaa; `; export const P = styled.p` font-size: 0.8rem; `; export const Button = styled.button` width: 60px; height: 30px; border-radius: 15px; border: 0px solid; font-size: 12px; font-weight: 600; background-color: #3562ff; color: #ffffff; text-align: center; cursor: pointer; display: block; margin-left: auto; margin-top: 5%; margin-bottom: 5%; `;
354cdac459e7faf125142aa5675ce5555628e7a4
[ "Markdown", "TypeScript" ]
59
TypeScript
prography/gaegata-frontend
6d049efc6f2b3f6a915b717eb827c873bf5b9e5e
c2bf8d2dcb3ff46e79dab269ac2a2fade7f403dd
refs/heads/master
<file_sep>const Discord = require("discord.js"); const Client = new Discord.Client(); const fs = require("fs"); const config = require("./config.json") const token = config.token; Client.commands = new Discord.Collection(); Client.aliases = new Discord.Collection(); Client.commands = new Discord.Collection(); Client.aliases = new Discord.Collection(); fs.readdir("./commands/ticket/", (err, files) => { if(err) console.error((err)); let jsfile = files.filter(f => f.split(".").pop() === "js"); if(jsfile.length <= 0) return; jsfile.forEach((f, i) => { delete require.cache[require.resolve(`./commands/ticket/${f}`)] let props = require(`./commands/ticket/${f}`) console.log(`${f} loaded!`); Client.commands.set(props.help.name, props); props.aliases.forEach(alias => { Client.aliases.set(alias, props.help.name); }); }); }); fs.readdir("./commands/admin/", (err, files) => { if(err) console.error((err)); let jsfile = files.filter(f => f.split(".").pop() === "js"); if(jsfile.length <= 0) return; jsfile.forEach((f, i) => { delete require.cache[require.resolve(`./commands/admin/${f}`)] let props = require(`./commands/admin/${f}`) console.log(`${f} loaded!`); Client.commands.set(props.help.name, props); props.aliases.forEach(alias => { Client.aliases.set(alias, props.help.name); }); }); }); fs.readdir("./events/", (async function (err, files) { let jsfile = files.filter(f => f.split(".").pop() === "js"); jsfile.forEach(file => { const eventName = file.split(".")[0]; const event = new(require(`./events/${file}`))(Client); Client.on(eventName, (...args) => event.run(...args)); const mod = require.cache[require.resolve(`./events/${file}`)]; delete require.cache[require.resolve(`./events/${file}`)]; const index = mod.parent.children.indexOf(mod); if (index !== -1) mod.parent.children.splice(index, 1); }); })); Client.on("disconnect", () => console.log("Client is disconnecting.")) .on("error", e => console.log(e)); Client.login(token);
1feb506870becbd7d90c91dcf7d0ab0d764403b1
[ "JavaScript" ]
1
JavaScript
Spi0nGaviria/Docks
9164678d0c7da32b19c235d67214558a726e1e36
cf60c422445f092751ecda43012184f631369e70
refs/heads/master
<repo_name>nabil2305/Python-Search-Engine<file_sep>/Database/main.py import mysql.connector class Database: mydb = mysql.connector.connect( host="localhost", user="nabil", password="<PASSWORD>", database="mydatabase" ) mycursor = mydb.cursor() #mycursor.execute("CREATE TABLE loc23(name VARCHAR(255),location VARCHAR(255))") def insert(self, mylist1, file_name): print("filename") print(file_name) # mycursor = Database.mydb.cursor() # mycursor.execute("CREATE TABLE loc4 (location VARCHAR(255))") sql = "INSERT INTO loc23 (name,location) VALUES (%s,%s)" for val in mylist1: val1 = [(file_name),(val)] val2=tuple(val1) Database.mycursor.execute(sql, val2) Database.mydb.commit() print( "records are inserted.") def query(self,file_name): symbol=file_name Database.mycursor.execute("SELECT location FROM loc23 WHERE name LIKE %s", (symbol,)) myresult = Database.mycursor.fetchall() query_length=len(myresult) if(query_length>0): for x in myresult: print("Query from database") print(x) return query_length <file_sep>/main.py from Drives.main import Drives from Searching.main import Searching from Database.main import Database def main(): search_object=Searching() print('enter file to be searched') file_input=input(); # ans1=search_object.find_file_in_all_drives(file_input) # dbs=Database() # dbs.insert(ans1,file_input) #print(ans1) dbs=Database() database_search_result=dbs.query(file_input) if(database_search_result<=0): #ans1=search_object.find_file_in_all_drives(file_input) ans2=search_object.create_thread(file_input) dbs=Database() dbs.insert(ans2,file_input) drive_obj=Drives() available_Drives=drive_obj.get_drives() print('total drives in the system') for i in available_Drives: print(i) if __name__ == '__main__': main() <file_sep>/Drives/main.py import win32api class Drives: def __init__(self): self.drives = [] def get_drives(self): for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]: self.drives.append(drive) return self.drives <file_sep>/Searching/main.py import os import re from threading import Thread import win32api from Drives.main import Drives from Database.main import Database class Searching: global data data = [] def __init__(self): pass def find_file_in_all_drives(self, file_name): rex = re.compile(file_name) drive_obj = Drives() drives = drive_obj.get_drives() for i in drives: self.find_file(i, rex) return data def find_file(self, root_folder, rex): for root, dirs, files in os.walk(root_folder): for f in files: result = rex.search(f) if result: print("data from searching") print(os.path.join(root, f)) data.append(os.path.join(root, f)) break def create_thread(self,file_name): threads_list=[] drive_obj=Drives() drives=drive_obj.get_drives() for each in range(len(drives)): process=Thread(target=self.find_file_in_all_drives,args=(file_name,)) process.start() threads_list.append(process) for t in threads_list: t.join() return data;
bfaa6b25a620451bfaa873638db1823b49181c60
[ "Python" ]
4
Python
nabil2305/Python-Search-Engine
7f76089ca626a5a20c27163f66c5211b28d599d0
5e79e1008da4f1128ea3bdf18268e07b5ade0f47
refs/heads/master
<repo_name>DrZhouKarl/MASS<file_sep>/pcdet/models/detectors/pointpillar.py from .detector3d_template import Detector3DTemplate from .unet.unet import UNet, SimplifiedUNet from .segmentation_head import FCNMaskHead import sys from .erfnet import Net import os import torch.nn.functional as F import torch.nn as nn import torch from ...ops.roiaware_pool3d import roiaware_pool3d_utils from PIL import Image import numpy as np class FocalLoss(nn.Module): """ copy from: https://github.com/Hsuxu/Loss_ToolBox-PyTorch/blob/master/FocalLoss/FocalLoss.py This is a implementation of Focal Loss with smooth label cross entropy supported which is proposed in 'Focal Loss for Dense Object Detection. (https://arxiv.org/abs/1708.02002)' Focal_Loss= -1*alpha*(1-pt)*log(pt) :param num_class: :param alpha: (tensor) 3D or 4D the scalar factor for this criterion :param gamma: (float,double) gamma > 0 reduces the relative loss for well-classified examples (p>0.5) putting more focus on hard misclassified example :param smooth: (float,double) smooth value when cross entropy :param balance_index: (int) balance class index, should be specific when alpha is float :param size_average: (bool, optional) By default, the losses are averaged over each loss element in the batch. """ def __init__(self, apply_nonlin=None, alpha=None, gamma=2, balance_index=0, smooth=1e-5, size_average=True): super(FocalLoss, self).__init__() self.apply_nonlin = apply_nonlin self.alpha = alpha self.gamma = gamma self.balance_index = balance_index self.smooth = smooth self.size_average = size_average if self.smooth is not None: if self.smooth < 0 or self.smooth > 1.0: raise ValueError('smooth value should be in [0,1]') def forward(self, logit, target): if self.apply_nonlin is not None: logit = self.apply_nonlin(logit) num_class = logit.shape[1] if logit.dim() > 2: # N,C,d1,d2 -> N,C,m (m=d1*d2*...) logit = logit.view(logit.size()[0], logit.size()[1], logit.size()[3]) logit = logit.permute(0, 2, 1).contiguous() logit = logit.view(-1, logit.size(-1)) target = torch.unsqueeze(target, 1) target = target.view(-1, 1) # print(logit.shape, target.shape) # alpha = self.alpha if alpha is None: alpha = torch.ones(num_class, 1) elif isinstance(alpha, (list, np.ndarray)): assert len(alpha) == num_class alpha = torch.FloatTensor(alpha).view(num_class, 1) alpha = alpha / alpha.sum() elif isinstance(alpha, float): alpha = torch.ones(num_class, 1) alpha = alpha * (1 - self.alpha) alpha[self.balance_index] = self.alpha else: raise TypeError('Not support alpha type') if alpha.device != logit.device: alpha = alpha.to(logit.device) idx = target.cpu().long() one_hot_key = torch.FloatTensor(target.size()[0], num_class).zero_() one_hot_key = one_hot_key.scatter_(1, idx, 1) if one_hot_key.device != logit.device: one_hot_key = one_hot_key.to(logit.device) if self.smooth: one_hot_key = torch.clamp( one_hot_key, self.smooth / (num_class - 1), 1.0 - self.smooth) pt = (one_hot_key * logit).sum(1) + self.smooth logpt = pt.log() gamma = self.gamma alpha = alpha[idx] alpha = torch.squeeze(alpha) loss = -1 * alpha * torch.pow((1 - pt), gamma) * logpt if self.size_average: loss = loss.mean() else: loss = loss.sum() return loss def one_hot(labels, num_classes): ''' Converts an integer label torch.autograd.Variable to a one-hot Variable. Parameters ---------- labels : torch.autograd.Variable of torch.cuda.LongTensor N x 1 x H x W, where N is batch size. Each value is an integer representing correct classification. Returns ------- target : torch.autograd.Variable of torch.cuda.FloatTensor N x C x H x W, where C is class number. One-hot encoded. ''' one_hot = torch.cuda.FloatTensor(labels.size()[0], num_classes, labels.size()[2], labels.size()[3]).zero_() target = one_hot.scatter_(1, labels.data, 1) return target def one_hot_1d(data, num_classes): n_values = num_classes n_values = torch.eye(n_values)[data] return n_values class PointPillar(Detector3DTemplate): def __init__(self, model_cfg, num_class, dataset): super().__init__(model_cfg=model_cfg, num_class=num_class, dataset=dataset) self.module_list = self.build_networks() # self.segmentation_head = UNet(64, 12) # for attentional fusion # self.segmentation_head = SimplifiedUNet(64, 12) # for concat fusion self.segmentation_head = SimplifiedUNet(128, 12) self.focal_loss = FocalLoss() def forward(self, batch_dict): module_index = 0 for cur_module in self.module_list[:2]: module_index += 1 batch_dict = cur_module(batch_dict) if module_index == 2: # points_mean = batch_dict["points_coor"] dict_seg = [] dict_cls_num = [] label_b = batch_dict["labels_seg"] # batch, c, h, w = label_b.size() # targets_crr = label_b.view(batch, c, h, w) # torch.cat(dict_seg,dim=0).view(batch,c,h,w) targets_crr = label_b spatial_features = batch_dict["spatial_features"] pred = self.segmentation_head(spatial_features) batch_dict['prediction'] = pred # label = torch.argmax(pred[0].unsqueeze(0),dim=1).flatten().cpu().numpy().astype(np.float32).tobytes() # f=open("/mrtstorage/users/kpeng/labe.bin",'wb') # f.write(label) # f.close() # sys.exit() # targets_crr = targets_crr.contiguous().view(batch, c, h, w) """ code for geomertic consistency """ if self.training: # targets_crr = targets_crr.contiguous().view(batch, c, h, w) nozero_mask = targets_crr != 0 targets_crr = torch.clamp(targets_crr[nozero_mask], 1, 12) # ori_target = targets_crr targets_crr = one_hot_1d((targets_crr - 1).long(), 12).unsqueeze(0).permute(0, 2, 1).cuda() pred = pred.permute(0, 2, 3, 1).unsqueeze(1)[nozero_mask].squeeze().unsqueeze(0).permute(0, 2, 1) object_list = [0, 2, 3] # for obj in object_list: # if obj == 1: # mask_obj = ori_target == obj # else: # mask_obj = mask_obj | (targets_crr == obj) weight = torch.ones_like(targets_crr) # print(weight.size()) # sys.exit() # mask_person = targets_crr == 1 # weight[mask_obj]==5 # weight[mask_person]==8 # for dense gt TODO weight[:, 0, :] = 2 # weight 5 for other dynamic object weight[:, [1, 2, 3], :] = 7.5 # weight8 for pedestrain # for sparse # weight[:, 0, :] = 2 # weight 5 for vehicle # weight[:, [1, 2, 3], :] = 8 # weight8 for person, two wheel and rider loss_seg = F.binary_cross_entropy_with_logits(pred, targets_crr, reduction='mean', weight=weight) ret_dict = { 'loss': loss_seg } disp_dict = {} tb_dict = {} return ret_dict, tb_dict, disp_dict else: return batch_dict # pred_dicts, recall_dicts = self.post_processing(batch_dict) # return pred_dicts, recall_dicts def get_training_loss(self): disp_dict = {} loss_rpn, tb_dict = self.dense_head.get_loss() tb_dict = { 'loss_rpn': loss_rpn.item(), **tb_dict } loss = loss_rpn return loss, tb_dict, disp_dict <file_sep>/voxelize/dense.cpp // pybind libraries #include <pybind11/pybind11.h> #include <pybind11/eigen.h> #include <pybind11/stl.h> // C/C++ includes #include <cmath> #include <cfloat> #include <vector> #include <chrono> #include <math.h> // #include <omp.h> namespace py = pybind11; namespace Eigen { typedef Matrix<bool, Dynamic, 1> VectorXb; typedef Matrix<signed char,Dynamic,1> VectorXsc; }; Eigen::VectorXf _compute_dense_gt(const Eigen::MatrixXf & original_points, const Eigen::VectorXf & pc_range, const Eigen::VectorXf & voxel_size, const int class_number) { // py::gil_scoped_acquire acquire; // const double & pxmin = pc_range[0]; const double & pymin = pc_range[1]; const double & pzmin = pc_range[2]; const double & pxmax = pc_range[3]; const double & pymax = pc_range[4]; const double & pzmax = pc_range[5]; // const int vxsize = 1000; //(pxmax - pxmin) / voxel_size[0] +1; const int vysize = 500; //(pymax - pymin) / voxel_size[1] +1; const int vzsize = (pzmax - pzmin) / voxel_size[2]; //const Eigen::Vector3i grid_size(vxsize, vysize, vzsize); //std::cout<<"1234_testtest"<<std::endl; // const int G1 = vxsize; const int G2 = vysize * G1; //result in y*x format //const int G3 = vzsize * GO2; const int G3 = 13 * G2;//result format class_number*y*x // //Eigen::RowVector3f offset3d(pxmin, pymin, pzmin); //Eigen::RowVector4f offset4d(pxmin, pymin, pzmin, 0.0f); // //std::cout<<G3<<std::endl; Eigen::VectorXf dense_gt = Eigen::VectorXf::Constant(G3, 0.0); //std::cout<<dense_gt.cols()<<std::endl; // go through all sampled points and put them into different bins based on the timestamps //std::vector<std::vector<int>> original_indices (T, std::vector<int>()); for (int i=0; i< original_points.rows(); ++i) { const double pt_x = original_points(i,0) - pxmin; const double pt_y = original_points(i,1) - pymin; const double pt_z = original_points(i,2) - pzmin; if ((pt_x < 0)||(pt_x >= (pxmax-pxmin-0.1))||(pt_y < 0)||(pt_y >= (pymax-pymin-0.1))||(pt_z < 0) || (pt_z >= (pzmax-pzmin-0.1))) { continue; } //const double pt_z = original_points(i,2); const int pt_class = original_points(i,4); const int index_x = ceil(pt_x/voxel_size[0]); const int index_y = ceil(pt_y/voxel_size[1]); //const double index_z = pt_z/voxel_size[2]; const int vector_index = (int)pt_class * G2 + index_y * G1 + index_x; //std::cout<<vector_index<<std::endl; if ((vector_index < 0)||(vector_index) > dense_gt.rows()){ std::cout<<index_x<<std::endl; std::cout<<index_y<<std::endl; std::cout<<pt_class<<std::endl; std::cout<<vector_index<<std::endl; //goto k; } dense_gt[vector_index]++; } k:; return dense_gt; } PYBIND11_MODULE(dense, m) { m.doc() = "LiDAR voxelization"; m.def("compute_dense_gt", &_compute_dense_gt, py::arg("original_points"), py::arg("pc_range"), py::arg("voxel_size"), py::arg("class_number") ); } <file_sep>/pcdet/datasets/augmentor/augmentor_utils.py import numpy as np import cv2 from ...utils import common_utils def get_rotation_scale_matrix2d(center, angle, scale): """ :param center: [x, y] :param angle: angle in radians, >0: clockwise :param scale: >1 enlarge :return: """ alpha = scale * np.cos(-angle) beta = scale * np.sin(-angle) return np.array([[alpha, beta, center[0] - beta * center[1]], [-beta, alpha, beta * center[0] + (1 - alpha) * center[1]]]) def global_rotation_voxel_feat(voxel_feat, theta, scale=1.0): ny, nx, c = voxel_feat.shape # H W C # rot_mat = get_rotation_scale_matrix2d((int(nx / 2), int(ny / 2)), theta, scale) rot_mat = cv2.getRotationMatrix2D((int(nx / 2), int(ny / 2)), -theta * 180 / np.pi, scale) voxel_feat = cv2.warpAffine(voxel_feat, rot_mat, (nx, ny), flags=cv2.INTER_NEAREST) # H W C return voxel_feat.reshape(ny, nx, -1) def global_scale_voxel_feat(voxel_feat, scale, theta=0.0): ny, nx, c = voxel_feat.shape # H W C # rot_mat = get_rotation_scale_matrix2d((int(nx / 2), int(ny / 2)), theta, scale) rot_mat = cv2.getRotationMatrix2D((int(nx / 2), int(ny / 2)), -theta * 180 / np.pi, scale) voxel_feat = cv2.warpAffine(voxel_feat, rot_mat, (nx, ny), flags=cv2.INTER_NEAREST) # H W C return voxel_feat.reshape(ny, nx, -1) def random_flip_along_x(gt_seg, points, observations): """ Args: gt_seg: 500, 1000, 1 points: (M, 3 + C) Returns: """ enable = np.random.choice([False, True], replace=False, p=[0.5, 0.5]) if enable: points[:, 1] = -points[:, 1] gt_seg = np.flipud(gt_seg) if observations is not None: observations = np.flipud(observations) return gt_seg, points, observations def random_flip_along_y(gt_seg, points, observations): """ Args: gt_seg: 500, 1000, 1 points: (M, 3 + C) Returns: """ enable = np.random.choice([False, True], replace=False, p=[0.5, 0.5]) if enable: points[:, 0] = -points[:, 0] gt_seg = np.fliplr(gt_seg) if observations is not None: observations = np.fliplr(observations) return gt_seg, points, observations def global_rotation(gt_seg, points, observations, rot_range): """ Args: gt_boxes: (N, 7 + C), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C), rot_range: [min, max] Returns: """ noise_rotation = np.random.uniform(rot_range[0], rot_range[1]) points = common_utils.rotate_points_along_z(points[np.newaxis, :, :], np.array([noise_rotation]))[0] gt_seg = global_rotation_voxel_feat(gt_seg, noise_rotation) if observations is not None: observations = global_rotation_voxel_feat(observations, noise_rotation) return gt_seg, points, observations def global_scaling(gt_seg, points, observatjions, scale_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading] points: (M, 3 + C), scale_range: [min, max] Returns: """ if scale_range[1] - scale_range[0] < 1e-3: return gt_seg, points, observatjions noise_scale = np.random.uniform(scale_range[0], scale_range[1]) points[:, :3] *= noise_scale gt_seg = global_scale_voxel_feat(gt_seg, noise_scale) if observatjions is not None: observatjions = global_scale_voxel_feat(observatjions, noise_scale) return gt_seg, points, observatjions def global_translate_voxel_feat(voxel_feat, dw, dh): ny, nx, c = voxel_feat.shape # H W C mat = np.array([[1, 0, dw], [0, 1, dh]], dtype=np.float32) voxel_feat = cv2.warpAffine(voxel_feat, mat, (nx, ny), flags=cv2.INTER_NEAREST) # H W C return voxel_feat.reshape(ny, nx, -1) def global_translate(gt_seg, points, observations, noise_translate_std): """ Apply global translation to gt_boxes and points. """ if not isinstance(noise_translate_std, (list, tuple, np.ndarray)): noise_translate_std = np.array([noise_translate_std, noise_translate_std, noise_translate_std]) std_x, std_y, std_z = noise_translate_std noise_translate = np.array([np.random.normal(0, std_x, 1), np.random.normal(0, std_y, 1), np.random.normal(0, std_z, 1)]).T # 1 3 # clip to 3*std noise_translate = np.clip(noise_translate, [-3.0*std_x, -3.0*std_y, -3.0*std_z], [3.0*std_x, 3.0*std_y, 3.0*std_z]) points[:, :3] += noise_translate dw = noise_translate[0, 0] // 0.1 dh = noise_translate[0, 1] // 0.1 gt_seg = global_translate_voxel_feat(gt_seg, dw, dh) if observations is not None: observations = global_translate_voxel_feat(observations, dw, dh) return gt_seg, points, observations <file_sep>/mapping/mapping.cpp // pybind libraries #include <pybind11/pybind11.h> #include <pybind11/eigen.h> #include <pybind11/stl.h> // C/C++ includes #include <cmath> #include <cfloat> #include <vector> #include <chrono> // #include <omp.h> namespace py = pybind11; namespace Eigen { typedef Matrix<bool, Dynamic, 1> VectorXb; typedef Matrix<signed char,Dynamic,1> VectorXsc; }; /* * @brief returns all the voxels that are traversed by a ray going from start to end * @param start : continous world position where the ray starts * @param end : continous world position where the ray end * @return vector of voxel ids hit by the ray in temporal order * * <NAME>, <NAME>. A Fast Voxel Traversal Algorithm for Ray Tracing. Eurographics '87 * * Code adapted from: https://github.com/francisengelmann/fast_voxel_traversal * * Warning: * This is not production-level code. */ inline bool _voxel_traversal(std::vector<Eigen::Vector3i> & visited_voxels, const Eigen::Vector3d & ray_start, const Eigen::Vector3d & ray_end, const Eigen::Vector3i & grid_size, const double voxel_size) { // Compute normalized ray direction. Eigen::Vector3d ray = ray_end-ray_start; // ray.normalize(); // This id of the first/current voxel hit by the ray. // Using floor (round down) is actually very important, // the implicit int-casting will round up for negative numbers. Eigen::Vector3i current_voxel(floor(ray_start[0]/voxel_size), floor(ray_start[1]/voxel_size), floor(ray_start[2]/(voxel_size))); // create aliases for indices of the current voxel int &vx = current_voxel[0], &vy = current_voxel[1], &vz = current_voxel[2]; // create maximum indices for each dimension (set the boundaries) const int vxsize = grid_size[0], vysize = grid_size[1], vzsize = grid_size[2]; // The id of the last voxel hit by the ray. // TODO: what happens if the end point is on a border? Eigen::Vector3i last_voxel(floor(ray_end[0]/voxel_size), floor(ray_end[1]/voxel_size), floor(ray_end[2]/(voxel_size))); // In which direction the voxel ids are incremented. int stepX = (ray[0] >= 0) ? 1:-1; // correct int stepY = (ray[1] >= 0) ? 1:-1; // correct int stepZ = (ray[2] >= 0) ? 1:-1; // correct // Distance along the ray to the next voxel border from the current position (tMaxX, tMaxY, tMaxZ). double next_voxel_boundary_x = (vx+stepX)*voxel_size; // correct double next_voxel_boundary_y = (vy+stepY)*voxel_size; // correct double next_voxel_boundary_z = (vz+stepZ)*(voxel_size); // correct // tMaxX, tMaxY, tMaxZ -- distance until next intersection with voxel-border // the value of t at which the ray crosses the first vertical voxel boundary double tMaxX = (ray[0]!=0) ? (next_voxel_boundary_x - ray_start[0])/ray[0] : DBL_MAX; // double tMaxY = (ray[1]!=0) ? (next_voxel_boundary_y - ray_start[1])/ray[1] : DBL_MAX; // double tMaxZ = (ray[2]!=0) ? (next_voxel_boundary_z - ray_start[2])/ray[2] : DBL_MAX; // // tDeltaX, tDeltaY, tDeltaZ -- // how far along the ray we must move for the horizontal component to equal the width of a voxel // the direction in which we traverse the grid // can only be FLT_MAX if we never go in that direction double tDeltaX = (ray[0]!=0) ? voxel_size/ray[0]*stepX : DBL_MAX; double tDeltaY = (ray[1]!=0) ? voxel_size/ray[1]*stepY : DBL_MAX; double tDeltaZ = (ray[2]!=0) ? (voxel_size)/ray[2]*stepZ : DBL_MAX; // Note: I am not sure why there is a need to do this, but I am keeping it for now // possibly explained by: https://github.com/francisengelmann/fast_voxel_traversal/issues/6 Eigen::Vector3i diff(0,0,0); bool neg_ray=false; if (vx!=last_voxel[0] && ray[0]<0) { diff[0]--; neg_ray=true; } if (vy!=last_voxel[1] && ray[1]<0) { diff[1]--; neg_ray=true; } if (vz!=last_voxel[2] && ray[2]<0) { diff[2]--; neg_ray=true; } visited_voxels.push_back(current_voxel); if (neg_ray) { current_voxel+=diff; visited_voxels.push_back(current_voxel); } // ray casting loop bool truncated = false; while (current_voxel != last_voxel) { if (tMaxX < tMaxY) { if (tMaxX < tMaxZ) { vx += stepX; truncated = (vx < 0 || vx >= vxsize); tMaxX += tDeltaX; } else { vz += stepZ; truncated = (vz < 0 || vz >= vzsize); tMaxZ += tDeltaZ; } } else { if (tMaxY < tMaxZ) { vy += stepY; truncated = (vy < 0 || vy >= vysize); tMaxY += tDeltaY; } else { vz += stepZ; truncated = (vz < 0 || vz >= vzsize); tMaxZ += tDeltaZ; } } if (truncated) break; visited_voxels.push_back(current_voxel); } return truncated; } std::tuple<Eigen::VectorXsc, Eigen::VectorXb, Eigen::VectorXb> _compute_visibility_and_masks( const Eigen::MatrixXf & original_points, const Eigen::MatrixXf & sampled_points, const Eigen::MatrixXf & sensor_origins, const Eigen::VectorXf & time_stamps, const Eigen::VectorXf & pc_range, const double voxel_size, const bool culling_sampled, const bool culling_original) { // py::gil_scoped_acquire acquire; // const double & pxmin = pc_range[0]; const double & pymin = pc_range[1]; const double & pzmin = pc_range[2]; const double & pxmax = pc_range[3]; const double & pymax = pc_range[4]; const double & pzmax = pc_range[5]; // const int vxsize = (pxmax - pxmin) / voxel_size; const int vysize = (pymax - pymin) / voxel_size; const int vzsize = (pzmax - pzmin) / (voxel_size); const Eigen::Vector3i grid_size(vxsize, vysize, vzsize); // const int T = time_stamps.size() - 1; const int G1 = vxsize; const int G2 = vysize * G1; const int G3 = vzsize * G2; const int G4 = T * G3; // Eigen::RowVector3f offset3d(pxmin, pymin, pzmin); Eigen::RowVector4f offset4d(pxmin, pymin, pzmin, 0.0f); // const signed char OCCUPIED = 1; const signed char UNKNOWN = 0; const signed char FREE = -1; Eigen::VectorXsc visibility = Eigen::VectorXsc::Constant(G4, UNKNOWN); // Eigen::VectorXb original_visible_point_mask = Eigen::VectorXb::Zero(original_points.rows()); Eigen::VectorXb sampled_visible_point_mask = Eigen::VectorXb::Zero(sampled_points.rows()); // go through all sampled points and put them into different bins based on the timestamps std::vector<std::vector<int>> original_indices (T, std::vector<int>()); for (int i = 0, last_t = -1; i < original_points.rows(); ++ i) { const double pt = original_points(i,3); if (last_t >= 0 && time_stamps[last_t] <= pt && pt < time_stamps[last_t+1]) { original_indices[last_t].push_back(i); } else { for (int t = 0; t < T; ++ t) { if (time_stamps[t] <= pt && pt < time_stamps[t+1]) { original_indices[t].push_back(i); last_t = t; break; } } } } // go through all sampled points and put them into different bins based on the timestamps std::vector<std::vector<int>> sampled_indices (T, std::vector<int>()); for (int i = 0, last_t = -1; i < sampled_points.rows(); ++ i) { const double pt = sampled_points(i,3); if (last_t >= 0 && time_stamps[last_t] <= pt && pt < time_stamps[last_t+1]) { sampled_indices[last_t].push_back(i); } else { for (int t = 0; t < T; ++ t) { if (time_stamps[t] <= pt && pt < time_stamps[t+1]) { sampled_indices[t].push_back(i); last_t = t; break; } } } } // sometimes we happen to sample objects with a shorter history // when this happens, we replicate lidar points from the closest timestamp to make up the missing sweeps // we do not explicitly replicate the points, we replicate the indices to the big point matrix // this is a poor man's trick as opposed to building a dense point cloud model for every object // t = 0 is the current time stamp for (int t = 0, last_t = -1; t < T; ++ t) { if (sampled_indices[t].size() > 0) { last_t = t; } else if (last_t >= 0) { sampled_indices[t] = sampled_indices[last_t]; } } // #pragma omp parallel for for (int t = 0; t < T; ++ t) { // set up update variable and sensor origin Eigen::VectorXf update = Eigen::VectorXf::Zero(G3); Eigen::Vector3d origin = (sensor_origins.row(t) - offset3d).cast<double>(); // first, we compute a voxel mask for sampled points std::vector<bool> sampled_occupied_voxel_mask(G3, false); for (const int & i : sampled_indices[t]) { const int vx = floor((sampled_points(i,0) - pxmin) / voxel_size); const int vy = floor((sampled_points(i,1) - pymin) / voxel_size); const int vz = floor((sampled_points(i,2) - pzmin) / (voxel_size)); if (0 <= vz && vz < vzsize && 0 <= vy && vy < vysize && 0 <= vx && vx < vxsize) { const int vidx = vz * G2 + vy * G1 + vx; sampled_occupied_voxel_mask[vidx] = true; } } // cast original rays and stop at voxels occupied by sampled points for (const int & i : original_indices[t]) { Eigen::Vector3d point = (original_points.row(i) - offset4d).head(3).cast<double>(); std::vector<Eigen::Vector3i> visited_voxels; bool truncated = _voxel_traversal(visited_voxels, origin, point, grid_size, voxel_size); const int M = visited_voxels.size(); for (int j = 0; j < M; ++ j) { const int &vx = visited_voxels[j][0], &vy = visited_voxels[j][1], &vz = visited_voxels[j][2]; const int vidx = vz * G2 + vy * G1 + vx; const int midx = t * G3 + vidx; if (sampled_occupied_voxel_mask[vidx]) { if (culling_original) { visibility[midx] = OCCUPIED; break; } else { visibility[midx] = FREE; } } else if (visibility[midx] == OCCUPIED) { continue; } else { visibility[midx] = (j==M-1 && !truncated) ? OCCUPIED : FREE ; } } } // second, we compute a voxel mask for original points std::vector<bool> original_occupied_voxel_mask(G3, false); for (const int & i : original_indices[t]) { const int vx = floor((original_points(i,0) - pxmin) / voxel_size); const int vy = floor((original_points(i,1) - pymin) / voxel_size); const int vz = floor((original_points(i,2) - pzmin) / (voxel_size)); if (0 <= vz && vz < vzsize && 0 <= vy && vy < vysize && 0 <= vx && vx < vxsize) { const int vidx = vz * G2 + vy * G1 + vx; original_occupied_voxel_mask[vidx] = true; } } // cast sampled rays and mark voxels occupied by original points for (const int & i : sampled_indices[t]) { Eigen::Vector3d point = (sampled_points.row(i) - offset4d).head(3).cast<double>(); std::vector<Eigen::Vector3i> visited_voxels; bool truncated = _voxel_traversal(visited_voxels, origin, point, grid_size, voxel_size); const int M = visited_voxels.size(); for (int j = 0; j < M; ++ j) { const int &vx = visited_voxels[j][0], &vy = visited_voxels[j][1], &vz = visited_voxels[j][2]; const int vidx = vz * G2 + vy * G1 + vx; const int midx = t * G3 + vidx; if (original_occupied_voxel_mask[vidx]) { if (culling_sampled) { visibility[midx] = OCCUPIED; break; } else { visibility[midx] = FREE; } } else if (visibility[midx] == OCCUPIED) { continue; } else { visibility[midx] = (j==M-1 && !truncated) ? OCCUPIED : FREE ; } } } // go through the final visibility update and compute a binary mask for original points for (const int & i : original_indices[t]) { const int vx = floor((original_points(i,0) - pxmin) / voxel_size); const int vy = floor((original_points(i,1) - pymin) / voxel_size); const int vz = floor((original_points(i,2) - pzmin) / (voxel_size)); if (0 <= vz && vz < vzsize && 0 <= vy && vy < vysize && 0 <= vx && vx < vxsize) { const int midx = t * G3 + vz * G2 + vy * G1 + vx; original_visible_point_mask[i] = (visibility[midx] == OCCUPIED); } } // go through the final visibility update and compute a binary mask for sampled points for (const int & i : sampled_indices[t]) { const int vx = floor((sampled_points(i,0) - pxmin) / voxel_size); const int vy = floor((sampled_points(i,1) - pymin) / voxel_size); const int vz = floor((sampled_points(i,2) - pzmin) / (voxel_size)); if (0 <= vz && vz < vzsize && 0 <= vy && vy < vysize && 0 <= vx && vx < vxsize) { const int midx = t * G3 + vz * G2 + vy * G1 + vx; sampled_visible_point_mask[i] = (visibility[midx] == OCCUPIED); } } } return std::make_tuple(visibility, original_visible_point_mask, sampled_visible_point_mask); } Eigen::VectorXsc _compute_visibility(const Eigen::MatrixXf & original_points, const Eigen::MatrixXf & sensor_origins, const Eigen::VectorXf & time_stamps, const Eigen::VectorXf & pc_range, const double voxel_size) { // py::gil_scoped_acquire acquire; // const double & pxmin = pc_range[0]; const double & pymin = pc_range[1]; const double & pzmin = pc_range[2]; const double & pxmax = pc_range[3]; const double & pymax = pc_range[4]; const double & pzmax = pc_range[5]; // const int vxsize = (pxmax - pxmin) / voxel_size; const int vysize = (pymax - pymin) / voxel_size; const int vzsize = (pzmax - pzmin) / (voxel_size); const Eigen::Vector3i grid_size(vxsize, vysize, vzsize); // const int T = time_stamps.size() - 1; const int G1 = vxsize; const int G2 = vysize * G1; const int G3 = vzsize * G2; const int G4 = T * G3; // Eigen::RowVector3f offset3d(pxmin, pymin, pzmin); Eigen::RowVector4f offset4d(pxmin, pymin, pzmin, 0.0f); // const signed char OCCUPIED = 1; const signed char UNKNOWN = 0; const signed char FREE = -1; Eigen::VectorXsc visibility = Eigen::VectorXsc::Constant(G4, UNKNOWN); // go through all sampled points and put them into different bins based on the timestamps std::vector<std::vector<int>> original_indices (T, std::vector<int>()); for (int i = 0, last_t = -1; i < original_points.rows(); ++ i) { const double pt = original_points(i,3); if (last_t >= 0 && time_stamps[last_t] <= pt && pt < time_stamps[last_t+1]) { original_indices[last_t].push_back(i); } else { for (int t = 0; t < T; ++ t) { if (time_stamps[t] <= pt && pt < time_stamps[t+1]) { original_indices[t].push_back(i); last_t = t; break; } } } } // #pragma omp parallel for for (int t = 0; t < T; ++ t) { // COMPUTE VISIBILITY Eigen::VectorXf update = Eigen::VectorXf::Zero(G3); Eigen::Vector3d origin = (sensor_origins.row(t) - offset3d).cast<double>(); for (const int & i : original_indices[t]) { Eigen::Vector3d point = (original_points.row(i) - offset4d).head(3).cast<double>(); std::vector<Eigen::Vector3i> visited_voxels; bool truncated = _voxel_traversal(visited_voxels, origin, point, grid_size, voxel_size); const int M = visited_voxels.size(); for (int j = 0; j < M; ++ j) { const int &vx = visited_voxels[j][0], &vy = visited_voxels[j][1], &vz = visited_voxels[j][2]; const int vidx = vz * G2 + vy * G1 + vx; const int midx = t * G3 + vidx; if (visibility[midx] == OCCUPIED) { continue; } else { visibility[midx] = (j==M-1 && !truncated) ? OCCUPIED : FREE ; } } } } return visibility; } std::tuple<Eigen::VectorXf, Eigen::VectorXb, Eigen::VectorXb> _compute_logodds_and_masks( const Eigen::MatrixXf & original_points, const Eigen::MatrixXf & sampled_points, const Eigen::MatrixXf & sensor_origins, const Eigen::VectorXf & time_stamps, const Eigen::VectorXf & pc_range, const double voxel_size, const double lo_occupied, const double lo_free, const bool culling_original, const bool culling_sampled) { // py::gil_scoped_acquire acquire; // const double & pxmin = pc_range[0]; const double & pymin = pc_range[1]; const double & pzmin = pc_range[2]; const double & pxmax = pc_range[3]; const double & pymax = pc_range[4]; const double & pzmax = pc_range[5]; // const int vxsize = (pxmax - pxmin) / voxel_size; const int vysize = (pymax - pymin) / voxel_size; const int vzsize = (pzmax - pzmin) / (voxel_size); const Eigen::Vector3i grid_size(vxsize, vysize, vzsize); // const int T = time_stamps.size() - 1; const int G1 = vxsize; const int G2 = vysize * G1; const int G3 = vzsize * G2; // Eigen::RowVector3f offset3d(pxmin, pymin, pzmin); Eigen::RowVector4f offset4d(pxmin, pymin, pzmin, 0.0f); // Eigen::VectorXf logodds = Eigen::VectorXf::Zero(G3); // Eigen::VectorXb original_visible_point_mask = Eigen::VectorXb::Zero(original_points.rows()); Eigen::VectorXb sampled_visible_point_mask = Eigen::VectorXb::Zero(sampled_points.rows()); // go through all sampled points and put them into different bins based on the timestamps std::vector<std::vector<int>> original_indices (T, std::vector<int>()); for (int i = 0, last_t = -1; i < original_points.rows(); ++ i) { const double pt = original_points(i,3); if (last_t >= 0 && time_stamps[last_t] <= pt && pt < time_stamps[last_t+1]) { original_indices[last_t].push_back(i); } else { for (int t = 0; t < T; ++ t) { if (time_stamps[t] <= pt && pt < time_stamps[t+1]) { original_indices[t].push_back(i); last_t = t; break; } } } } // go through all sampled points and put them into different bins based on the timestamps std::vector<std::vector<int>> sampled_indices (T, std::vector<int>()); for (int i = 0, last_t = -1; i < sampled_points.rows(); ++ i) { const double pt = sampled_points(i,3); if (last_t >= 0 && time_stamps[last_t] <= pt && pt < time_stamps[last_t+1]) { sampled_indices[last_t].push_back(i); } else { for (int t = 0; t < T; ++ t) { if (time_stamps[t] <= pt && pt < time_stamps[t+1]) { sampled_indices[t].push_back(i); last_t = t; break; } } } } // sometimes we happen to sample objects with a shorter history // when this happens, we replicate lidar points from the closest timestamp to make up the missing sweeps // we do not explicitly replicate the points, we replicate the indices to the big point matrix // this is a poor man's trick as opposed to building a dense point cloud model for every object // t = 0 is the current time stamp for (int t = 0, last_t = -1; t < T; ++ t) { if (sampled_indices[t].size() > 0) { last_t = t; } else if (last_t >= 0) { sampled_indices[t] = sampled_indices[last_t]; } } // #pragma omp parallel for num_threads(3) for (int t = 0; t < T; ++ t) { // set up update variable and sensor origin Eigen::VectorXf update = Eigen::VectorXf::Zero(G3); Eigen::Vector3d origin = (sensor_origins.row(t) - offset3d).cast<double>(); // first, we compute a voxel mask for sampled points std::vector<bool> sampled_occupied_voxel_mask(G3, false); for (const int & i : sampled_indices[t]) { const int vx = floor((sampled_points(i,0) - pxmin) / voxel_size); const int vy = floor((sampled_points(i,1) - pymin) / voxel_size); const int vz = floor((sampled_points(i,2) - pzmin) / (voxel_size)); if (0 <= vz && vz < vzsize && 0 <= vy && vy < vysize && 0 <= vx && vx < vxsize) { const int vidx = vz * G2 + vy * G1 + vx; sampled_occupied_voxel_mask[vidx] = true; } } // cast original rays and stop at voxels occupied by sampled points for (const int & i : original_indices[t]) { Eigen::Vector3d point = (original_points.row(i) - offset4d).head(3).cast<double>(); std::vector<Eigen::Vector3i> visited_voxels; bool truncated = _voxel_traversal(visited_voxels, origin, point, grid_size, voxel_size); const int M = visited_voxels.size(); for (int j = 0; j < M; ++ j) { const int &vx = visited_voxels[j][0], &vy = visited_voxels[j][1], &vz = visited_voxels[j][2]; const int vidx = vz * G2 + vy * G1 + vx; if (sampled_occupied_voxel_mask[vidx]) { if (culling_original) { update[vidx] = lo_occupied; break; } else { update[vidx] = lo_free; } } else if (update[vidx] > 0) { continue; } else { update[vidx] = (j==M-1 && !truncated) ? lo_occupied : lo_free; } } } // second, we compute a voxel mask for original points std::vector<bool> original_occupied_voxel_mask(G3, false); for (const int & i : original_indices[t]) { const int vx = floor((original_points(i,0) - pxmin) / voxel_size); const int vy = floor((original_points(i,1) - pymin) / voxel_size); const int vz = floor((original_points(i,2) - pzmin) / (voxel_size)); if (0 <= vz && vz < vzsize && 0 <= vy && vy < vysize && 0 <= vx && vx < vxsize) { const int vidx = vz * G2 + vy * G1 + vx; original_occupied_voxel_mask[vidx] = true; } } // cast sampled rays and mark voxels occupied by original points for (const int & i : sampled_indices[t]) { Eigen::Vector3d point = (sampled_points.row(i) - offset4d).head(3).cast<double>(); std::vector<Eigen::Vector3i> visited_voxels; bool truncated = _voxel_traversal(visited_voxels, origin, point, grid_size, voxel_size); const int M = visited_voxels.size(); for (int j = 0; j < M; ++ j) { const int &vx = visited_voxels[j][0], &vy = visited_voxels[j][1], &vz = visited_voxels[j][2]; const int vidx = vz * G2 + vy * G1 + vx; if (original_occupied_voxel_mask[vidx]) { if (culling_sampled) { update[vidx] = lo_occupied; break; } else { update[vidx] = lo_free; } } else if (update[vidx] > 0) { continue; } else { update[vidx] = (j==M-1 && !truncated) ? lo_occupied : lo_free; } } } // go through the final logodds update and compute a binary mask for original points for (const int & i : original_indices[t]) { const int vx = floor((original_points(i,0) - pxmin) / voxel_size); const int vy = floor((original_points(i,1) - pymin) / voxel_size); const int vz = floor((original_points(i,2) - pzmin) / (voxel_size)); if (0 <= vz && vz < vzsize && 0 <= vy && vy < vysize && 0 <= vx && vx < vxsize) { const int vidx = vz * G2 + vy * G1 + vx; original_visible_point_mask[i] = (update[vidx] > 0); } } // go through the final logodds update and compute a binary mask for sampled points for (const int & i : sampled_indices[t]) { const int vx = floor((sampled_points(i,0) - pxmin) / voxel_size); const int vy = floor((sampled_points(i,1) - pymin) / voxel_size); const int vz = floor((sampled_points(i,2) - pzmin) / (voxel_size)); if (0 <= vz && vz < vzsize && 0 <= vy && vy < vysize && 0 <= vx && vx < vxsize) { const int vidx = vz * G2 + vy * G1 + vx; sampled_visible_point_mask[i] = (update[vidx] > 0); } } // update logodds // #pragma omp critical logodds += update; } return std::make_tuple(logodds, original_visible_point_mask, sampled_visible_point_mask); } Eigen::VectorXf _compute_logodds(const Eigen::MatrixXf & original_points, const Eigen::MatrixXf & sensor_origins, const Eigen::VectorXf & time_stamps, const Eigen::VectorXf & pc_range, const double voxel_size, const double lo_occupied, const double lo_free) { // py::gil_scoped_acquire acquire; // const double & pxmin = pc_range[0]; const double & pymin = pc_range[1]; const double & pzmin = pc_range[2]; const double & pxmax = pc_range[3]; const double & pymax = pc_range[4]; const double & pzmax = pc_range[5]; // const int vxsize = (pxmax - pxmin) / voxel_size; const int vysize = (pymax - pymin) / voxel_size; const int vzsize = (pzmax - pzmin) / (voxel_size); const Eigen::Vector3i grid_size(vxsize, vysize, vzsize); // const int T = time_stamps.size() - 1; const int G1 = vxsize; const int G2 = vysize * G1; const int G3 = vzsize * G2; // Eigen::RowVector3f offset3d(pxmin, pymin, pzmin); Eigen::RowVector4f offset4d(pxmin, pymin, pzmin, 0.0f); // Eigen::VectorXf logodds = Eigen::VectorXf::Zero(G3); // go through all sampled points and put them into different bins based on the timestamps std::vector<std::vector<int>> original_indices (T, std::vector<int>()); for (int i = 0, last_t = -1; i < original_points.rows(); ++ i) { const double pt = original_points(i,3); if (last_t >= 0 && time_stamps[last_t] <= pt && pt < time_stamps[last_t+1]) { original_indices[last_t].push_back(i); } else { for (int t = 0; t < T; ++ t) { if (time_stamps[t] <= pt && pt < time_stamps[t+1]) { original_indices[t].push_back(i); last_t = t; break; } } } } // #pragma omp parallel for num_threads(3) for (int t = 0; t < T; ++ t) { // COMPUTE VISIBILITY Eigen::VectorXf update = Eigen::VectorXf::Zero(G3); Eigen::Vector3d origin = (sensor_origins.row(t) - offset3d).cast<double>(); for (const int & i : original_indices[t]) { Eigen::Vector3d point = (original_points.row(i) - offset4d).head(3).cast<double>(); std::vector<Eigen::Vector3i> visited_voxels; bool truncated = _voxel_traversal(visited_voxels, origin, point, grid_size, voxel_size); const int M = visited_voxels.size(); for (int j = 0; j < M; ++ j) { const int &vx = visited_voxels[j][0], &vy = visited_voxels[j][1], &vz = visited_voxels[j][2]; const int vidx = vz * G2 + vy * G1 + vx; if (update[vidx] > 0) { // if the voxel has been marked as occupied, move on continue; } else if (j == M-1 && !truncated) { // if it is the last voxel of an untrunc ray, mark it as occupied update[vidx] = lo_occupied; } else { // otherwise it must be a free voxel update[vidx] = lo_free; } } } // #pragma omp critical logodds += update; } return logodds; } PYBIND11_MODULE(mapping, m) { m.doc() = "LiDAR voxel-based ray tracing"; m.def("compute_visibility_and_masks", &_compute_visibility_and_masks, py::arg("original_points"), py::arg("sampled_points"), py::arg("sensor_origins"), py::arg("time_stamps"), py::arg("pc_range"), py::arg("voxel_size"), py::arg("culling_original")=true, py::arg("culling_sampled")=false ); m.def("compute_visibility", &_compute_visibility, py::arg("original_points"), py::arg("sensor_origins"), py::arg("time_stamps"), py::arg("pc_range"), py::arg("voxel_size") ); m.def("compute_logodds_and_masks", &_compute_logodds_and_masks, py::arg("original_points"), py::arg("sampled_points"), py::arg("sensor_origins"), py::arg("time_stamps"), py::arg("pc_range"), py::arg("voxel_size"), py::arg("lo_occupied")=std::log(0.7/(1-0.7)), py::arg("lo_free")=std::log(0.4/(1-0.4)), py::arg("culling_original")=true, py::arg("culling_sampled")=false ); m.def("compute_logodds", &_compute_logodds, py::arg("original_points"), py::arg("sensor_origins"), py::arg("time_stamps"), py::arg("pc_range"), py::arg("voxel_size"), py::arg("lo_occupied")=std::log(0.7/(1-0.7)), py::arg("lo_free")=std::log(0.4/(1-0.4)) ); } <file_sep>/voxelize/CMakeLists.txt cmake_minimum_required(VERSION 3.10.0) project(dense) set (CMAKE_CXX_STANDARD 14) set(CMAKE_BUILD_TYPE Release) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/..) set(CMAKE_CXX_FLAGS "-Wall -Wextra") set(CMAKE_CXX_FLAGS_RELEASE "-O3") find_package(Eigen3) include_directories(${EIGEN3_INCLUDE_DIRS}) # add_subdirectory(pybind11) find_package(pybind11) pybind11_add_module(dense dense.cpp) # find_package(OpenMP) # target_link_libraries(mapping PRIVATE OpenMP::OpenMP_CXX) <file_sep>/tools/eval_utils/eval_utils.py import pickle import time import math import numpy as np import torch import tqdm # import Path from pathlib import Path from pcdet.models import load_data_to_gpu from pcdet.utils import common_utils import sys import time import os import cv2 from PIL import Image color_map={ "0" : [255, 255, 255], "1": [0, 0, 255], "11": [255, 120, 60], "3": [245, 230, 100], "4": [200, 40, 50], "5": [255, 0, 255], "8": [255, 200, 20], "10": [0, 175, 0], "6": [75, 0, 75], "7": [75, 0, 175], "2": [30, 30, 255], "12": [150, 240, 80], "9": [135,60,0] } def id_to_rgb(pred_id): shape = list(pred_id.shape)[:2] shape.append(3) rgb = np.zeros(shape, dtype=np.uint8) + 255 for i in range(0, 12): mask = pred_id[:, :, 0] == i # print(mask.shape) if mask.sum() == 0: continue rgb[mask] = np.array(color_map[str(i + 1)]) return rgb.astype(np.uint8) def get_iou(pred, gt, number, intersect, union, index, logger, result_dir, time_stamp, n_classes=12): total_miou = 0.0 class_name = ["vehicle", "person", "two-wheel", "rider", "road", "sidewalk", "otherground", "building", "object", "vegetation", "trunk", "terrain"] iou_list_sum = torch.zeros([n_classes]) for i in range(len(pred)): pred_tmp = pred[i] gt_tmp = gt[i] for j in range(n_classes): match = (pred_tmp == j).int() + (gt_tmp == j).int() it = torch.sum(match == 2).item() un = torch.sum(match > 0).item() intersect[j] += it union[j] += un # iou = [] # class_list = [] # if (number % 50) | (number == index) == 0: # file = open(result_dir / ("eval_" + time_stamp + ".txt"), 'a') # for k in range(len(intersect)): # if union[k] != 0: # class_list.append(class_name[k]) # iou.append(intersect[k] / union[k]) # else: # continue # miou = ((sum(iou)) / (len(iou))) # iou = torch.Tensor(iou) # file.write("******************eval_%f******************\n" % number) # print("*******************eval_result**********************:\n") # for j, class_index in enumerate(class_list): # logger.info('iou_%s: %f' % (class_index, iou[j])) # file.write('iou_%s: %f' % (class_index, iou[j]) + '\n') # logger.info('miou: %f' % (miou)) # file.write('miou: %f' % (miou) + '\n') # file.write("****************************************************\n") # print("****************************************************") # # file.write("******************eval_%f******************"%number) # # file.write() # file.close() return intersect, union def statistics_info(cfg, ret_dict, metric, disp_dict): for cur_thresh in cfg.MODEL.POST_PROCESSING.RECALL_THRESH_LIST: metric['recall_roi_%s' % str(cur_thresh)] += ret_dict.get('roi_%s' % str(cur_thresh), 0) metric['recall_rcnn_%s' % str(cur_thresh)] += ret_dict.get('rcnn_%s' % str(cur_thresh), 0) metric['gt_num'] += ret_dict.get('gt', 0) min_thresh = cfg.MODEL.POST_PROCESSING.RECALL_THRESH_LIST[0] disp_dict['recall_%s' % str(min_thresh)] = \ '(%d, %d) / %d' % ( metric['recall_roi_%s' % str(min_thresh)], metric['recall_rcnn_%s' % str(min_thresh)], metric['gt_num']) def eval_one_epoch(cfg, model, dataloader, epoch_id, logger, dist_test=False, save_to_file=False, result_dir=None): result_dir.mkdir(parents=True, exist_ok=True) t = time.localtime() timestamp = time.strftime('%b-%d-%Y_%H%M', t) final_output_dir = result_dir / 'final_result' / 'data' if save_to_file: final_output_dir.mkdir(parents=True, exist_ok=True) logger.info('*************** EPOCH %s EVALUATION *****************' % epoch_id) if dist_test: num_gpus = torch.cuda.device_count() local_rank = cfg.LOCAL_RANK % num_gpus model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[local_rank], broadcast_buffers=False ) model.eval() start_time = time.time() n_val = len(dataloader) with tqdm.tqdm(total=n_val, desc='Val', unit='batch', leave=False) as pbar: intersection = torch.zeros(12) union = torch.zeros(12) for i, batch_dict in enumerate(dataloader): load_data_to_gpu(batch_dict) with torch.no_grad(): pred_dict = model(batch_dict) torch.set_printoptions(profile="full") batch_size, c, h, w = pred_dict["prediction"].size() dense_gt = pred_dict["labels_seg"] # 0 to 12 observation = pred_dict["observations"] # no_obser_mask = observation <= 0 # nonzero_mask = dense_gt.view(batch_size, 1, h, w) != 0 # mask = torch.zeros_like(observation) # b, 1,500,1000 # mask[nonzero_mask] = 1 # mask[no_obser_mask] = 0 # anti_mask = ~(mask.bool()) # dense_gt[anti_mask] = 0 pred = pred_dict["prediction"][:, :12, :, :] pred = torch.argmax(pred, dim=1, keepdim=True) # 2 1 500 1000 no_obser_mask = observation <= 0 pred[no_obser_mask] = -1 # save pred as img prediction_save_path = result_dir / "eval_segmentation/" prediction_save_path.mkdir(parents=True, exist_ok=True) # for batch_index in range(batch_size): # img_path = prediction_save_path / ('%08d.png' % int(pred_dict['frame_id'][0][batch_index])) # cls_id = pred[batch_index].cpu().numpy().astype(np.uint8) # cls_id = np.transpose(cls_id, (1, 2, 0)) # rgb = id_to_rgb(cls_id) # rgb = Image.fromarray(rgb) # rgb.save(str(img_path)) no_gt_mask = dense_gt.view(batch_size, 1, h, w) == 0 pred[no_gt_mask] = -1 dense_gt[no_obser_mask] = 0 dense_gt = dense_gt - 1 # from -1 to 11 prediction_save_path = result_dir / "eval_segmentation/" prediction_save_path.mkdir(parents=True, exist_ok=True) # for batch_index in range(batch_size): # image_save_path = prediction_save_path / (str(i * batch_size + batch_index) + ".bin") # label = pred[batch_index].flatten().cpu().numpy().astype(np.float32).tobytes() # f = open(image_save_path, 'wb+') # f.write(label) # f.close() # pred = pred.permute(0,2,3,1) # pred[anti_mask] = -1 # intersection = torch.zeros(12) # union = torch.zeros(12) # pred = pred.permute(0,2,3,1) intersection, union = get_iou(pred, dense_gt, i + 1, intersection, union, n_val * batch_size, logger, result_dir, timestamp) pbar.update() class_list = [] iou = [] ret_dict = {} class_name = ["vehicle", "person", "two-wheel", "rider", "road", "sidewalk", "otherground", "building", "object", "vegetation", "trunk", "terrain"] file = open(result_dir / ("eval_%s.txt" % epoch_id), 'a') for k in range(len(intersection)): if union[k] != 0: class_list.append(class_name[k]) iou.append(intersection[k] / union[k]) else: continue miou = ((sum(iou)) / (len(iou))) iou = torch.Tensor(iou) file.write("******************eval_whole_dataset******************\n") print("*******************eval_result whole dataset**********************:\n") for j, class_index in enumerate(class_list): logger.info('iou_%s: %f' % (class_index, iou[j])) file.write('iou_%s: %f' % (class_index, iou[j]) + '\n') ret_dict['iou_%s' % class_index] = iou[j] logger.info('miou: %f' % (miou)) file.write('miou: %f' % (miou) + '\n') ret_dict['miou']= miou file.write("****************************************************\n") print("****************************************************") file.close() logger.info('****************Evaluation done.*****************') return ret_dict if __name__ == '__main__': pass <file_sep>/label_processing_tools/lidarseg_annotools.py import sys import glob import os import json import numpy as np import torch filepath="/cvhci/data/nuScenes/data/lidarseg/v1.0-trainval" savepath="/home/kpeng/pc14/nu_lidar_seg/processed_anno_new/" """ 'car:5', 1 'truck:5', 2 'construction_vehicle:5',5 'bus:5', 3,4 'trailer:5', 9 'barrier:5',21 'motorcycle:5', 6 'bicycle:5',7 'pedestrian:5',12,13,14,18 'traffic_cone:5',20 flat """ def eachFile(filepath): pathDir = os.listdir(filepath) if not os.path.exists(savepath): os.mkdir(savepath) dic = {} for file_name in pathDir: file_path = os.path.join('%s/%s' % (filepath, file_name)) save_file_path = os.path.join('%s/%s' % (savepath, file_name)) semantic_labels = torch.from_numpy(np.fromfile(file_path, dtype=np.uint8,count=-1)) #print(torch.max(semantic_labels)) points_number = len(semantic_labels) new_label = torch.zeros([points_number], dtype=semantic_labels.dtype, device=semantic_labels.device) """ mask_car = semantic_labels == 1 mask_truck = semantic_labels == 2 mask_c_vehicle = semantic_labels == 5 mask_bus = (semantic_labels == 3) | (semantic_labels == 4) mask_trailer = semantic_labels == 9 mask_barrier = semantic_labels == 21 mask_motorcycle = semantic_labels == 6 mask_bicycle = semantic_labels == 7 mask_pedestrian = (semantic_labels == 12) | (semantic_labels == 13) | (semantic_labels == 14) | (semantic_labels == 18) mask_traffic_cone = semantic_labels == 20 mask_driveable_area = semantic_labels == 24 mask_sidewalk = semantic_labels == 25 mask_terrain = semantic_labels ==26 mask_others = semantic_labels == 27 mask_static_others = (semantic_labels == 30)| (semantic_labels == 8) mask_vegetation = semantic_labels == 29 mask_manmade = semantic_labels==28 """ """ mask_barrier = semantic_labels == 21 mask_bicycle= semantic_labels == 7 mask_bus = (semantic_labels == 3)|(semantic_labels == 4) mask_car = semantic_labels == 1 mask_c_v = semantic_labels == 5 mask_motocycle = semantic_labels == 6 mask_ped = (semantic_labels == 12) | (semantic_labels == 13) | (semantic_labels == 14) | (semantic_labels==18) mask_cone = semantic_labels == 20 mask_trailer = semantic_labels == 9 mask_truck = semantic_labels == 2 mask_drive = semantic_labels == 24 mask_other_flat = semantic_labels == 27 mask_sidewalk = semantic_labels == 25 mask_terrain = semantic_labels == 26 mask_manmade = semantic_labels == 28 mask_vegetation = semantic_labels == 17 """ mask_barrier = semantic_labels == 9 mask_bicycle= semantic_labels == 14 mask_bus = (semantic_labels == 15)|(semantic_labels == 16) mask_car = semantic_labels == 17 mask_c_v = semantic_labels == 18 mask_motocycle = semantic_labels == 21 mask_ped = (semantic_labels == 2) | (semantic_labels == 3) | (semantic_labels == 4) | (semantic_labels==5) | (semantic_labels==6) | (semantic_labels==7)|(semantic_labels==8) mask_cone = semantic_labels == 12 mask_trailer = semantic_labels == 22 mask_truck = semantic_labels == 23 mask_drive = semantic_labels == 24 mask_other_flat = semantic_labels == 25 mask_sidewalk = semantic_labels == 26 mask_terrain = semantic_labels == 27 mask_manmade = semantic_labels == 28 mask_vegetation = semantic_labels == 30 new_label[mask_barrier] = 1 new_label[mask_bicycle] = 2 new_label[mask_bus] = 3 new_label[mask_car] = 4 new_label[mask_c_v] = 5 new_label[mask_motocycle] = 6 new_label[mask_ped] = 7 new_label[mask_cone] = 8 new_label[mask_trailer] = 9 new_label[mask_truck] =10 new_label[mask_drive] = 11 new_label[mask_other_flat] = 12 new_label[mask_sidewalk] = 13 new_label[mask_terrain] = 14 new_label[mask_manmade] = 15 new_label[mask_vegetation] = 16 """ new_label[mask_car] = 1 new_label[mask_truck] = 2 new_label[mask_c_vehicle] = 3 new_label[mask_bus] = 4 new_label[mask_trailer] = 5 new_label[mask_barrier] = 6 content= new_label.numpy() #.tobytes() #print(np.max(content)) #sys.exit() """ #print(torch.sum(mask_vegetation.float())) #sys.exit() #filepath='123.bin' binfile = open(save_file_path, 'wb+') #追加写入 binfile.write(content) #binfile.close() if __name__ == "__main__": eachFile(filepath) <file_sep>/pcdet/models/backbones_3d/vfe/pillar_vfe.py import torch from ....ops.roiaware_pool3d import roiaware_pool3d_utils import torch.nn as nn import torch.nn.functional as F from .vfe_template import VFETemplate import sys from torch_geometric.nn import FeaStConv from knn_cuda import KNN from torch_cluster import fps class PFNLayer(nn.Module): def __init__(self, in_channels, out_channels, use_norm=True, last_layer=False): super().__init__() self.last_vfe = last_layer self.use_norm = use_norm if not self.last_vfe: out_channels = out_channels // 2 if self.use_norm: self.linear = nn.Linear(in_channels, out_channels, bias=False) self.norm = nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.01) else: self.linear = nn.Linear(in_channels, out_channels, bias=True) self.part = 50000 def forward(self, inputs): if inputs.shape[0] > self.part: # nn.Linear performs randomly when batch size is too large num_parts = inputs.shape[0] // self.part part_linear_out = [self.linear(inputs[num_part*self.part:(num_part+1)*self.part]) for num_part in range(num_parts+1)] x = torch.cat(part_linear_out, dim=0) else: x = self.linear(inputs) torch.backends.cudnn.enabled = False x = self.norm(x.permute(0, 2, 1)).permute(0, 2, 1) if self.use_norm else x torch.backends.cudnn.enabled = True x = F.relu(x) x_max = torch.max(x, dim=1, keepdim=True)[0] if self.last_vfe: return x_max else: x_repeat = x_max.repeat(1, inputs.shape[1], 1) x_concatenated = torch.cat([x, x_repeat], dim=2) return x_concatenated class Graph_attention(nn.Module): def __init__(self, in_channels, hidden_channels): super(Graph_attention, self).__init__() #self.Linear1 = nn.Sequential(nn.Linear(2*in_channels, hidden_channels),nn.ReLU()) self.feast1=FeaStConv(in_channels, in_channels) self.feast1_2=FeaStConv(in_channels, hidden_channels) self.relu=nn.ReLU() #self.Linear2 = nn.Sequential(nn.Linear(2*hidden_channels,in_channels),nn.ReLU()) self.feast2=FeaStConv(hidden_channels,in_channels) self.feast2_2=FeaStConv(in_channels, in_channels) self.fc1 = nn.Linear(2*in_channels, in_channels) self.sigmoid = nn.Softmax(dim=0) #self.PillarScatter(denseshape, num_input_features=9) self.batch_size=2 def forward(self,x): b,p,c = x.size() #print(x.size()) #xyz_x = x[:,:,:3] #x = self.PillarScatter(x,coors,self.batch_size) #features = x[batch,:,:,:] #print(x.size()) #y = (x[:, :, :].sum(dim=1, keepdim=True) / num_voxels.type_as(x).view(-1,1,1)) y = torch.max(x, dim=1, keepdim=True)[0].view(b,c) voxel_number = y.size()[0] #row = torch.arange(0,b).unsqueeze(-1).repeat(1,b).view(1,b*b) batch = torch.zeros(b).long().cuda() col = fps(y, batch, ratio=0.02, random_start=True).cuda() fps_p = len(col) row = torch.arange(0,b).unsqueeze(-1).repeat(1,fps_p).view(1,b*fps_p).long().cuda() col = col.repeat(b,1).view(1,b*fps_p) edge_index = torch.cat([row,col], dim=0) #print(edge_index.size()) #k=30 #knn = KNN(k=30, transpose_mode=True).cuda() #dist, col = knn(xyz[:,:,:3], xyz[:,:,:3]) # 1, 6000, 20 """ row = torch.arange(start=0, end=voxel_number).unsqueeze(-1).repeat(1,k).resize(voxel_number*k).long().cuda() col = col.view(-1) mask = 1 - torch.isinf(dist).view(-1).int() row, col = row.view(-1)[mask.long()], col.view(-1)[mask.long()] edge_index = torch.cat([row.unsqueeze(0), col.unsqueeze(0)], dim=0)""" #print(y.size(), edge_index.size()) #y=y.squeeze() ##y = torch.cat([xyz,y], dim=-1) out= self.relu(self.feast1(y,edge_index)) #out = out #print(out.size()) ##out = torch.cat([xyz, out],dim=-1) out = self.relu(self.feast1_2(out,edge_index)) ##out = torch.cat([xyz, out], dim=-1) out = self.relu(self.feast2(out, edge_index)) ##out = torch.cat([xyz, out], dim=-1) attention=self.sigmoid(self.feast2_2(out,edge_index)) #print(attention.size()) #attention = torch.stack(attention) out = x*attention.unsqueeze(1) #print(out.size()) out=torch.cat([out,x], dim=-1) #print(out.size()) out=self.fc1(out) return out def PCA(X, k=2): X_mean = torch.mean(X, 0) X = X - X_mean.expand_as(X) # SVD U,S,V = torch.svd(torch.t(X)) return torch.mm(X,U[:,:k]) class lstm_attention(nn.Module): def __init__(self, input_dim, hidden_dim): super(lstm_attention,self).__init__() self.lstm = nn.LSTM(input_dim,hidden_dim,1,batch_first=True,bidirectional=True) self.reduce = nn.Linear(4*input_dim,input_dim) #self.relu = nn.ReLU() self.softmax = nn.Sigmoid() def forward(self,features, points_mean): p,_,c = features.size() X_1D = PCA(points_mean.squeeze(), 1) #print(points_mean.size()) #X_1D = lpp.fit_transform(points_mean.squeeze()) #X_1D = torch.from_numpy(gpumap.GPUMAP(n_neighbors=5, n_components=1).fit_transform(points_mean.squeeze().cpu().numpy())).cuda() #r,phi,theta = cart2sph(points_mean) #_,indices = torch.sort(torch.square(r.squeeze())*torch.square(phi.squeeze())) #print(X_1D.size()) _,indices = torch.sort(X_1D.squeeze()) indices = indices.squeeze() features = features[indices,:,:].squeeze() #print(features.size()) feature_max = torch.max(features, dim=1, keepdim=True)[0] feature_mean = torch.mean(features,dim=1,keepdim=True) #center_max = torch.mean(feature_max, dim=0, keepdim=True).repeat(p,1,1) #center_mean = torch.mean(feature_mean,dim=0,keepdim=True).repeat(p,1,1) #distance_max = torch.sqrt(torch.sum(torch.square(torch.abs(feature_max - center_max)),dim=-1,keepdim=True)).squeeze() #distance_mean = torch.sqrt(torch.sum(torch.square(torch.abs(feature_mean - center_mean)),dim=-1,keepdim=True)).squeeze() #p,1,1 #_, indices_max = torch.sort(distance_max,0,descending=False) #_, indices_mean = torch.sort(distance_mean,0,descending=False) #sorted_max = feature_max[indices_max,:,:] #sorted_mean = feature_mean[indices_mean,:,:] out_max = self.lstm(feature_max)[0] out_mean = self.lstm(feature_mean)[0] #canvas_max = torch.zeros([p,1,2*c], dtype=feature_max.dtype,device=feature_max.device) #canvas_mean = torch.zeros([p,1,2*c], dtype=feature_mean.dtype,device=feature_mean.device) #canvas_max[indices_max,:,:] = out_max #canvas_mean[indices_mean,:,:] = out_mean final = self.softmax(self.reduce(torch.cat([out_max,out_mean], dim=-1))) canvas = torch.zeros([p,1,c],dtype=out_max.dtype,device=out_max.device) canvas[indices,:,:]=final return canvas class pointsmean_attention(nn.Module): def __init__(self, c_num, p_num): super(pointsmean_attention, self).__init__() self.fc1=nn.Sequential( nn.Linear(c_num+3, 1), nn.ReLU(inplace=True) ) self.fc2 = nn.Sequential( nn.Linear(20, 1), nn.ReLU(inplace=True) ) self.sigmoid = nn.Sigmoid() def forward(self, voxel_center, feature): voxel_center_repeat = voxel_center.repeat(1, feature.shape[1],1) voxel_feat_concat = torch.cat([feature,voxel_center_repeat], dim=-1) feat_2 = self.fc1(voxel_feat_concat) feat_2 = feat_2.permute(0,2,1).contiguous() voxel_feat_concat = self.fc2(feat_2) voxel_attention_weight = self.sigmoid(voxel_feat_concat) return voxel_attention_weight class PillarVFE(VFETemplate): def __init__(self, model_cfg, num_point_features, voxel_size, point_cloud_range): super().__init__(model_cfg=model_cfg) num_point_features=4 self.use_norm = self.model_cfg.USE_NORM self.with_distance = self.model_cfg.WITH_DISTANCE self.use_absolute_xyz = self.model_cfg.USE_ABSLOTE_XYZ num_point_features += 6 if self.use_absolute_xyz else 3 if self.with_distance: num_point_features += 1 self.num_filters = self.model_cfg.NUM_FILTERS assert len(self.num_filters) > 0 num_filters = [num_point_features] + list(self.num_filters) pfn_layers = [] for i in range(len(num_filters) - 1): in_filters = num_filters[i] out_filters = num_filters[i + 1] pfn_layers.append( PFNLayer(in_filters, out_filters, self.use_norm, last_layer=(i >= len(num_filters) - 2)) ) self.pfn_layers = nn.ModuleList(pfn_layers) self.relu = nn.ReLU() self.lstm_attention = lstm_attention(num_point_features, num_point_features) self.graph_attention=Graph_attention(num_point_features, 4) #self.graph_attention_2=Graph_attention(num_input_features,4) self.pointsmean_attention = pointsmean_attention(num_point_features, 100) #self.pointsmean_attention_2 = pointsmean_attention(num_input_features, 100) #self.feastconv = FeaStConv(20, num_input_features-1, 3, True, 1) self.FC1=nn.Sequential( nn.Linear(2*num_point_features, num_point_features), nn.ReLU(inplace=True), ) self.FC2=nn.Sequential( nn.Linear(num_point_features,num_point_features), nn.ReLU(inplace=True), ) self.voxel_x = voxel_size[0] self.voxel_y = voxel_size[1] self.voxel_z = voxel_size[2] self.x_offset = self.voxel_x / 2 + point_cloud_range[0] self.y_offset = self.voxel_y / 2 + point_cloud_range[1] self.z_offset = self.voxel_z / 2 + point_cloud_range[2] def get_output_feature_dim(self): return self.num_filters[-1] def get_paddings_indicator(self, actual_num, max_num, axis=0): actual_num = torch.unsqueeze(actual_num, axis + 1) max_num_shape = [1] * len(actual_num.shape) max_num_shape[axis + 1] = -1 max_num = torch.arange(max_num, dtype=torch.int, device=actual_num.device).view(max_num_shape) paddings_indicator = actual_num.int() > max_num return paddings_indicator def forward(self, batch_dict, **kwargs): #print(batch_dict.keys()) #gt_boxes = batch_dict["gt_boxes"] #print(batch_dict["gt_names"].size()) voxel_features, voxel_num_points, coords = batch_dict['voxels'], batch_dict['voxel_num_points'], batch_dict['voxel_coords'] #print(voxel_features.size()) coords = batch_dict['voxel_coords'] batch_size = coords[:, 0].max().int().item() + 1 # dense_gt = batch_dict['dense_gt'].permute(0,2,3,1).reshape(batch_size*500*1000,13) # 2, 20, 500, 1000 #print(dense_gt[:1,:]) #sys.exit() # weight_5_class = [1,2,3,4] # weight_0_class = [0] # weight_1_class = [5,6,7,8,9,10,11,12] # dense_gt[:,weight_5_class]= dense_gt[:,weight_5_class]*5 # dense_gt[:,weight_0_class]=dense_gt[:,weight_0_class]*0 # dense_gt[:,weight_1_class]=dense_gt[:,weight_1_class]*1 # for i in range(12): # dense_gt[:,i]+=0.12-0.01*i # #print(debse_gt) # dense_gt = torch.argmax(dense_gt,dim=-1) #print(dense_gt[:100]) #print(dense_gt) #sys.exit() #coor = batch_dict['dense_pillar_coords'] """ merge sem gt """ #mask_zero = voxel_features[:,:,-2] == 0 #seg_gt = voxel_features[:,:,5] #seg_get[mask_zero] == dense[:,:,-2][mask_zero] """ end """ #print(batch_dict.keys()) #sys.exit() # v,p,c = voxel_features.size() """ for i in range(gt_boxes.size()[0]): points = voxel_features.resize(v*p,c) box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu( points[:, 0:3].unsqueeze(dim=0).float().cuda(), gt_boxes[:, 0:7].unsqueeze(dim=0).float().cuda() ).long().squeeze(dim=0) torch.set_printoptions(profile="full") print(torch.max(box_idxs_of_pts)) print(gt_boxes.size()) """ voxel_features= voxel_features[:,:,:4] """ encode for segmentation gt for each pillar """ """ zero_mask = dense_gt == 0 length = dense_gt[zero_mask].size()[0] dense_gt_min = torch.min(dense_gt, dim=1,keepdim=True)[0] noise = torch.linspace(-20,-length-20-1,length) dense_gt[zero_mask] = noise.cuda() dense_gt_after = torch.mode(dense_gt.squeeze(),dim=-1,keepdim=True)[0] torch.set_printoptions(profile="full") dense_gt_max = torch.max(dense_gt.squeeze(),dim=-1,keepdim=True)[0] mask_max = dense_gt_max <0 dense_gt_max[mask_max]=0 mask = dense_gt_after < dense_gt_min dense_gt_after[mask] = dense_gt_max[mask] """ # batch_dict["pillar_dense_gt"] = dense_gt """ encode end for segmentation gt for each pillar """ """ encode for dense segmentation gt for each pillar """ """ zero_mask = seg_gt == 0 length = seg_gt[zero_mask].size()[0] seg_gt_min = torch.min(seg_gt, dim=1,keepdim=True)[0] noise = torch.linspace(-20,-length-20-1,length) seg_gt[zero_mask] = noise.cuda() seg_gt_after = torch.mode(seg_gt.squeeze(),dim=-1,keepdim=True)[0] torch.set_printoptions(profile="full") seg_gt_max = torch.max(seg_gt.squeeze(),dim=-1,keepdim=True)[0] mask_max = seg_gt_max <0 seg_gt_max[mask_max]=0 mask = seg_gt_after < seg_gt_min seg_gt_after[mask] = seg_gt_max[mask] batch_dict["pillar_seg_gt"] = seg_gt_after """ #print(seg_gt_after) #sys.exit() """ encode end for segmentation gt for each pillar """ points_mean = voxel_features[:, :, :3].sum(dim=1, keepdim=True) / voxel_num_points.type_as(voxel_features).view(-1, 1, 1) f_cluster = voxel_features[:, :, :3] - points_mean f_center = torch.zeros_like(voxel_features[:,: , :3]) center = torch.zeros_like(voxel_features[:,1,:3]).view(voxel_features.size()[0],1,3) #coor = torch.zeros([3,512,512], dtype=f_center.dtype, device=f_center.device) #x = torch.linspace(0,512,512) #*self.voxel_x + self.x_offset #z = torch.linspace(0,1,1) #y = torch.linspace(0,512,512) #grid_x,grid_y,grid_z = torch.meshgrid(x,y,z) #coor = torch.cat([(grid_x*self.voxel_x + self.x_offset).unsqueeze(-1), (grid_y*self.voxel_y + self.y_offset).unsqueeze(-1), (grid_z*self.voxel_z + self.z_offset).unsqueeze(-1)], dim=-1) #coor = coor.view(512*512,3) center[:,:,0] = (coords[:, 3].to(voxel_features.dtype).unsqueeze(1) * self.voxel_x + self.x_offset) center[:,:,1] = (coords[:, 2].to(voxel_features.dtype).unsqueeze(1) * self.voxel_y + self.y_offset) center[:,:,2] = (coords[:, 1].to(voxel_features.dtype).unsqueeze(1) * self.voxel_z + self.z_offset) f_center[:, :, 0] = voxel_features[:, :, 0] - (coords[:, 3].to(voxel_features.dtype).unsqueeze(1) * self.voxel_x + self.x_offset) f_center[:, :, 1] = voxel_features[:, :, 1] - (coords[:, 2].to(voxel_features.dtype).unsqueeze(1) * self.voxel_y + self.y_offset) f_center[:, :, 2] = voxel_features[:, :, 2] - (coords[:, 1].to(voxel_features.dtype).unsqueeze(1) * self.voxel_z + self.z_offset) if self.use_absolute_xyz: features = [voxel_features, f_cluster, f_center] else: features = [voxel_features[..., 3:], f_cluster, f_center] # batch_dict["points_mean"]=center # batch_dict["points_coor"]=coor if self.with_distance: points_dist = torch.norm(voxel_features[:, :, :3], 2, 2, keepdim=True) features.append(points_dist) features = torch.cat(features, dim=-1) voxel_count = features.shape[1] mask = self.get_paddings_indicator(voxel_num_points, voxel_count, axis=0) mask = torch.unsqueeze(mask, -1).type_as(voxel_features) features *= mask batch_spatial_features={} container = torch.zeros_like(features) for index in range(batch_size): batch_mask = coords[:, 0] ==index batch_features = features[batch_mask, :] #batch_spatial_features.append(spatial_feature) batch_points_mean = points_mean[batch_mask,:] lstm_attention = self.lstm_attention(batch_features,batch_points_mean) batch_features = lstm_attention*batch_features features_ori = batch_features batch_features = self.graph_attention(batch_features) voxel_attention1 = self.pointsmean_attention(batch_points_mean, batch_features) batch_features = voxel_attention1 * batch_features out1 = torch.cat([batch_features, features_ori],dim=-1) #print(out1.size()) #point_gcn_feature = self.gcn(inputPC=features).cuda() out1 = self.FC1(out1) #features = self.graph_attention(features, num_voxels) #features = self.graph_attention_2(out1) #voxel_attention2 = self.pointsmean_attention_2(points_mean, features) #features = voxel_attention2 * features #out2 = out1 + features out1 = self.FC2(out1) container[batch_mask,:] = out1 # Forward pass through PFNLayers #final_result.append(features) #len1,len2 = final_result[0].size()[0], final_result[1].size()[0] #features = torch.cat([final_result[0], final_result[1]],dim=0) """ dense gt """ features = container for pfn in self.pfn_layers: features = pfn(features) features = features.squeeze() batch_dict['pillar_features'] = features return batch_dict <file_sep>/pcdet/datasets/visi.py from collections import defaultdict from pathlib import Path import os import pickle import torch import numpy as np # import torch.utils.data as torch_data # from data_loader_odo import data_loader # from ..utils import common_utils # from .augmentor.data_augmentor import DataAugmentor # from .processor.data_processor import DataProcessor # from .processor.point_feature_encoder import PointFeatureEncoder import sys from mapping import mapping # from voxelize import dense from pathlib import Path def label_generator(): file_name = "/home/ki/input/kitti/semantickitti/dataset/sample.pkl" # save_path = Path("/home/ki/input/kitti/semantickitti/dataset/pillarseg/visibility") save_path = Path("/home/ki/hdd0/input/kitti/semantickitti/pillarseg/visibility") save_path.mkdir(parents=True, exist_ok=True) open_file = open(file_name, "rb") files_seq = pickle.load(open_file) open_file.close() # locate = "/home/kpeng/pc14/kitti_odo/training/09/000577.bin" # index = files_seq.index(locate) for point_path in files_seq: # dense_path = '/home/kpeng/training/' +str(point_path).split('/')[-2] +'/'+ str(point_path).split('/')[-1] points = np.fromfile(str(point_path), dtype=np.float32, count=-1).reshape([-1, 4])[:, :4] pc_range = np.array([-50.0, -25.0, -2.5, 50.0, 25.0, 1.5], dtype=np.float32) # voxel_size = np.array([0.1, 0.1, 8], dtype=np.float32) # dense_gt[:,-1] = np.clip(dense_gt[:,-1],0,12) indices = np.cumsum([0] + [points.shape[0]]).astype(int) origins = np.array([[0, 0, 0]], dtype=np.float32) num_points = points.shape[0] num_original = num_points # time_stamps = np.array([-1000,0],dtype=np.float32) time_stamps = np.zeros([num_points], dtype=np.float32) time_stamps = points[ indices[:-1], -1] # counting on the fact we do not miss points from any intermediate time_stamps time_stamps = (time_stamps[:-1] + time_stamps[1:]) / 2 time_stamps = [-1000.0] + time_stamps.tolist() + [1000.0] # add boundaries time_stamps = np.array(time_stamps) indices = np.array([0], dtype=np.float32) visi = mapping.compute_logodds(points, origins, time_stamps, pc_range, 0.1).reshape(1, 40, 500, 1000) # print((visi!=0).sum()) # sys.exit() visi = torch.from_numpy(visi).reshape(1 * 40 * 500 * 1000, 1) # 2, 20, 500, 1000 # print(dense_gt[:1,:]) # sys.exit() # weight_5_class = [1,2,3,4] # weight_0_class = [0] # weight_1_class = [5,6,7,8,9,10,11,12] # dense_gt[:,weight_5_class]= dense_gt[:,weight_5_class]*5 # dense_gt[:,weight_0_class]=dense_gt[:,weight_0_class]*0 # dense_gt[:,weight_1_class]=dense_gt[:,weight_1_class]*1 # for i in range(12): # dense_gt[:,i]+=0.12-0.01*i # #print(debse_gt) visi = visi.flatten().numpy().astype(np.float32).tobytes() f_path = save_path / (str(point_path).split('/')[-3] + '/' + str(point_path).split('/')[-1]) f_path.parent.mkdir(parents=True, exist_ok=True) print(f_path) f = open(str(f_path), 'wb') f.write(visi) f.close() if __name__ == '__main__': label_generator() <file_sep>/pcdet/datasets/augmentor/test_DA.py import numpy as np import time from collections import defaultdict import cv2 from skimage import io from PIL import Image def show_feat(feat): img = (20 * feat).astype(np.uint8) feat_toshow = Image.fromarray(img) feat_toshow.show() def get_rotation_scale_matrix2d(center, angle, scale): """ :param center: [x, y] :param angle: angle in radians, >0: clockwise :param scale: >1 enlarge :return: """ alpha = scale * np.cos(-angle) # minus only for this application beta = scale * np.sin(-angle) return np.array([[alpha, beta, (1 - alpha) * center[0] - beta * center[1]], [-beta, alpha, beta * center[0] + (1 - alpha) * center[1]]]) def global_rotation_voxel_feat(voxel_feat, theta, scale=1.0): ny, nx, c = voxel_feat.shape # H W C # rot_mat = get_rotation_scale_matrix2d((int(nx / 2), int(ny / 2)), theta, scale) rot_mat = cv2.getRotationMatrix2D((int(nx / 2), int(ny / 2)), -theta * 180 / np.pi, scale) voxel_feat = cv2.warpAffine(voxel_feat, rot_mat, (nx, ny), flags=cv2.INTER_NEAREST) # H W C return voxel_feat.reshape(ny, nx, 1) def global_scale_voxel_feat(voxel_feat, scale, theta=0.0): ny, nx, c = voxel_feat.shape # H W C # rot_mat1 = get_rotation_scale_matrix2d((nx//2, ny//2), theta, scale) rot_mat = cv2.getRotationMatrix2D((int(nx / 2), int(ny / 2)), -theta * 180 / np.pi, scale) voxel_feat = cv2.warpAffine(voxel_feat, rot_mat, (nx, ny), flags=cv2.INTER_NEAREST) # H W C return voxel_feat.reshape(ny, nx, 1) def global_translate_voxel_feat(voxel_feat, dw, dh): ny, nx, c = voxel_feat.shape # H W C mat = np.array([[1, 0, dw], [0, 1, dh]], dtype=np.float32) voxel_feat = cv2.warpAffine(voxel_feat, mat, (nx, ny), flags=cv2.INTER_NEAREST) # H W C return voxel_feat.reshape(ny, nx, 1) gt_file = '~/000031.png' gt = np.array(io.imread(gt_file), dtype=np.float32) print(gt.shape) show_feat(gt) gt = np.expand_dims(gt, -1) print(gt.shape) gt_x = np.flipud(gt) # show_feat(gt_x.squeeze(-1)) gt_y = np.fliplr(gt) # show_feat(gt_y.squeeze()) gt_scale = global_scale_voxel_feat(gt, 1.2) # show_feat(gt_scale.squeeze(-1)) gt_rot = global_rotation_voxel_feat(gt, 0.2) # show_feat(gt_rot.squeeze(-1)) gt_trans = global_translate_voxel_feat(gt, 100, -50) show_feat(gt_trans.squeeze(-1)) <file_sep>/mapping/CMakeLists.txt cmake_minimum_required(VERSION 3.13.3) project(mapping) set (CMAKE_CXX_STANDARD 14) set(CMAKE_BUILD_TYPE Release) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/..) set(CMAKE_CXX_FLAGS "-Wall -Wextra") set(CMAKE_CXX_FLAGS_RELEASE "-O3") find_package(Eigen3) include_directories(${EIGEN3_INCLUDE_DIRS}) # add_subdirectory(pybind11) find_package(pybind11) pybind11_add_module(mapping mapping.cpp) # find_package(OpenMP) # target_link_libraries(mapping PRIVATE OpenMP::OpenMP_CXX) <file_sep>/pcdet/models/backbones_2d/map_to_bev/pointpillar_scatter.py import torch import numpy as np import torch.nn as nn import sys def one_hot(labels, num_classes): ''' Converts an integer label torch.autograd.Variable to a one-hot Variable. Parameters ---------- labels : torch.autograd.Variable of torch.cuda.LongTensor N x 1 x H x W, where N is batch size. Each value is an integer representing correct classification. Returns ------- target : torch.autograd.Variable of torch.cuda.FloatTensor N x C x H x W, where C is class number. One-hot encoded. ''' one_hot = torch.cuda.FloatTensor(labels.size(0), num_classes, labels.size(2), labels.size(3)).zero_() target = one_hot.scatter_(1, labels.data, 1) return target class PointPillarScatter(nn.Module): def __init__(self, model_cfg, grid_size, **kwargs): super().__init__() self.model_cfg = model_cfg self.num_bev_features = self.model_cfg.NUM_BEV_FEATURES self.nx, self.ny, self.nz = grid_size # self.nx = 1001 self.conv_obser = nn.Sequential( nn.Conv2d(1, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64, eps=1e-3, momentum=0.01), nn.ReLU() ) # self.w_pillar = nn.Sequential( # nn.Conv2d(64, 1, kernel_size=3, padding=1, bias=False), # nn.BatchNorm2d(1, eps=1e-3, momentum=0.01), # ) # self.w_obser = nn.Sequential( # nn.Conv2d(64, 1, kernel_size=3, padding=1, bias=False), # nn.BatchNorm2d(1, eps=1e-3, momentum=0.01), # ) assert self.nz == 1 # self.num = 0 def forward(self, batch_dict, **kwargs): pillar_features, coords = batch_dict['pillar_features'], batch_dict['voxel_coords'] # print(coords.shape) # pillar_seg = batch_dict["pillar_seg_gt"] batch_size = coords[:, 0].max().int().item() + 1 # dense_seg = batch_dict["labels_seg"].resize(batch_size,1,500,1000) # dense_coor = batch_dict["dense_pillar_coords"] # print(pillar_features.dtype) # sys.exit() # visibility = batch_dict['vis'].to(torch.float32).contiguous().permute(0, 3, 1, # 2).contiguous() # 2, 40, 512, 512 batch_spatial_features = [] # batch_size = coords[:, 0].max().int().item() + 1 for batch_idx in range(batch_size): spatial_feature = torch.zeros( 64, self.nz * self.nx * self.ny, dtype=pillar_features.dtype, device=pillar_features.device) batch_mask = coords[:, 0] == batch_idx this_coords = coords[batch_mask, :] indices = this_coords[:, 1] + this_coords[:, 2] * self.nx + this_coords[:, 3] indices = indices.type(torch.long) pillars = pillar_features[batch_mask, :] pillars = pillars.t() spatial_feature[:, indices] = pillars batch_spatial_features.append(spatial_feature) """ dense gt """ ''' batch_spatial_dense = [] batch_size = dense_coor[:, 0].max().int().item() + 1 for batch_idx in range(batch_size): spatial_dense = torch.zeros( 1, self.nz * self.nx * self.ny, dtype=pillar_features.dtype, device=pillar_features.device) batch_mask = dense_coor[:, 0] == batch_idx this_coords = dense_coor[batch_mask, :] indices = this_coords[:, 1] + this_coords[:, 2] * self.nx + this_coords[:, 3] indices = indices.type(torch.long) gts = dense_seg[batch_mask, :] gts = gts.t() spatial_dense[:, indices] = gts #print(indices.size()) #print(spatial_dense) batch_spatial_dense.append(spatial_dense) ''' """ end """ # torch.autograd.set_detect_anomaly(True) batch_spatial_features = torch.stack(batch_spatial_features, 0) # batch_spatial_dense = torch.stack(batch_spatial_dense, 0).contiguous().view(batch_size, 1, self.ny,self.nx) # print(batch_spatial_dense.size()) # sys.exit() """ merge """ # batch_spatial_features = batch_spatial_features.contiguous().view(batch_size, (self.num_bev_features+3) * self.nz, self.ny, self.nx) # batch_seg_labels = batch_spatial_features[:,-4,:,:].unsqueeze(1) # zero_mask = batch_seg_labels == 0 # batch_seg_labels = dense_seg # print(batch_spatial_dense[zero_mask]) # sys.exit() """ end """ batch_spatial_features = batch_spatial_features.view(batch_size, self.num_bev_features * self.nz, self.ny, self.nx) observations = batch_dict['observations'].contiguous().view(batch_size, 1, self.ny, self.nx) observations = self.conv_obser(observations) # Attentional fusion module # weight_pillar = self.w_pillar(batch_spatial_features) # weight_obser = self.w_obser(observations) # weight = torch.softmax(torch.cat([weight_pillar, weight_obser], dim=1), dim=1) # batch_spatial_features = batch_spatial_features * weight[:, 0:1, :, :] + observations * weight[:, 1:, :, :] # concat fusion module batch_spatial_features = torch.cat([batch_spatial_features, observations], dim=1) batch_dict['spatial_features'] = batch_spatial_features.contiguous() """ # np.save('pillar' + str(self.num), batch_spatial_features[:, 0:2, :, :].cpu().detach().numpy()) # batch_seg_labels = batch_spatial_features[:,-4,:,:].unsqueeze(1) # batch_dict['labels_seg'] = batch_seg_labels # line = torch.zeros([2,1,512,16]).cuda() # for i in range(16): # line[:,:,:,-1]=i # batch_seg_labels = torch.cat([batch_seg_labels, line], dim=-1) # onehot_labels = one_hot(batch_seg_labels.to(torch.int64),16) # onehot_labels = onehot_labels[:,:,:,:512] # batch_pointsmean = batch_spatial_features[:,64:,:,:] # batch_dict['pointsmean'] = batch_pointsmean # torch.autograd.set_detect_anomaly(True) # batch_spatial_features = batch_spatial_features[:, :self.num_bev_features, :, :] # re_f = self.zp(batch_spatial_features) re_f = self.conv_pillar(batch_spatial_features) # visibility = self.zp(visibility) visibility = self.relu(self.conv_visi(visibility.permute(0, 1, 3, 2))) re_v = self.relu(self.conv_visi_2(visibility)) # re_v = visibility # re_f = batch_spatial_features # print(re_v.dtype) # print(re_f.dtype) # sys.exit() attention = self.softmax(torch.cat([re_v, re_f], dim=1)) att1 = attention[:, 0, :, :] att2 = attention[:, 1, :, :] re_v = att1.unsqueeze(1).repeat(1, 64, 1, 1).contiguous() * re_v re_f = att2.unsqueeze(1).repeat(1, 64, 1, 1).contiguous() * re_f batch_spatial_features = re_v + re_f batch_dict['spatial_features'] = batch_spatial_features # batch_dict['one_hot']=onehot_labels # print('vis' in batch_dict.keys()) """ # debug data augmentation # file_name = str(self.num) # self.num += 1 # gt_seg_tosave = batch_dict['labels_seg'].cpu().numpy() # np.save('gt_seg' + file_name, gt_seg_tosave) # # obser = batch_dict['observations'].cpu().numpy() # np.save('obser' + file_name, obser) # # print('saving: ', self.num) return batch_dict <file_sep>/pcdet/version.py __version__ = "0.3.0+be0ddc4" <file_sep>/label_processing_tools/ego.py #%matplotlib inline from nuscenes import NuScenes import os import numpy as np import torch import json import sys import glob import logging from scipy.spatial.transform import Rotation as R from pyquaternion import Quaternion logging.basicConfig(level=logging.DEBUG) file_path = "/mrtstorage/users/kpeng/nu_lidar_seg/concat_lidar_flat_divided_new/" save_path = "/mrtstorage/users/kpeng/nu_lidar_seg/concat_lidar_flat_divided/new_2/" def seg_concat(): nusc = NuScenes(version='v1.0-trainval', dataroot='/mrtstorage/users/kpeng/nuscene_pcdet/data/nuscenes/v1.0-trainval/', verbose=True) #print(len(nusc.scene)) scene_list = {} #time_list = {} scene_token = {} scene_ego = {} count = 0 for scene in nusc.scene: prev_token = scene["first_sample_token"] last_token = scene["last_sample_token"] prev_sample_token = nusc.get('sample',prev_token)['data']['LIDAR_TOP'] #print(prev) prev_filename = nusc.get('sample_data', prev_sample_token)['filename'] scene_list[str(count)]=[] #scene_list[str(count)].append(prev_filename) scene_token[str(count)]=[] #scene_token[str(count)].append(prev_sample_token) scene_ego[str(count)]=[] #time_list[str(count)]=[] #print(scene_list) #sys.exit() if prev_filename.split('/')[0] == 'samples': scene_list[str(count)].append(prev_filename) scene_token[str(count)].append(prev_sample_token) #print("") scene_ego_token = nusc.get('sample_data', prev_sample_token)['ego_pose_token'] scene_ego[str(count)].append(nusc.get('ego_pose', scene_ego_token)) count_n = 0 while True: next_token = nusc.get('sample_data', prev_sample_token)['next'] if next_token == "": break next_filename = nusc.get('sample_data', next_token)['filename'] next_ego_token = nusc.get('sample_data', next_token)['ego_pose_token'] if next_filename.split('/')[0] == 'samples': scene_ego[str(count)].append(nusc.get('ego_pose', next_ego_token)) scene_list[str(count)].append(next_filename) scene_token[str(count)].append(next_token) count_n += 1 prev_sample_token = next_token if count_n == scene["nbr_samples"]-1: break count +=1 return scene_list, scene_token, scene_ego,nusc,count def transform_matrix(translation: np.ndarray = np.array([0, 0, 0]), rotation: Quaternion = Quaternion([1, 0, 0, 0]), inverse: bool = False) -> np.ndarray: """ Convert pose to transformation matrix. :param translation: <np.float32: 3>. Translation in x, y, z. :param rotation: Rotation in quaternions (w ri rj rk). :param inverse: Whether to compute inverse transform matrix. :return: <np.float32: 4, 4>. Transformation matrix. """ tm = np.eye(4) if inverse: rot_inv = rotation.rotation_matrix.T trans = np.transpose(-np.array(translation)) tm[:3, :3] = rot_inv tm[:3, 3] = rot_inv.dot(trans) """ print(trans) print("ddddddddddd") print(tm[:3,3]) print("dddddddddd") """ else: tm[:3, :3] = rotation.rotation_matrix tm[:3, 3] = np.transpose(np.array(translation)) """ print("d") print(translation) print("d")""" return tm def pc_ego_list(scene_list_1,scene_token_1,scene_ego_1,nusc, count): #print(scene_token) #scene_ego = {} #print(count) for scene_idx in range(len(scene_list_1.keys())): key = str(scene_idx) scene_file_list = scene_list_1[key] scene_token_list = scene_token_1[key] scene_ego_list = scene_ego_1[key] num_samples = len(scene_token_list) #print(scene_file_list) #print(num_samples) #scene_ego[str(sene_idx)] = {} for idx in range(len(scene_token_list)): #print(idx) scene_token = scene_token_list[idx] key_frame_sample = nusc.get('sample_data', scene_token)['filename'] key_frame = nusc.get('sample_data', scene_token) calibrated_sensor_token = key_frame['calibrated_sensor_token'] key_rotation = nusc.get('calibrated_sensor', calibrated_sensor_token)['rotation'] key_trans = nusc.get('calibrated_sensor', calibrated_sensor_token)['translation'] k_r_e = transform_matrix(key_trans, Quaternion(key_rotation),True) key_pc = np.fromfile(file_path+key_frame_sample, dtype=np.float32, count=-1).reshape(-1,6) scene_ego_idx = scene_ego_list[idx] #scene_ego_token = scene_ego_idx["ego_pose_token"] scene_ego_trans = np.array(scene_ego_idx["translation"]) scene_ego_rot = np.array(scene_ego_idx["rotation"]).tolist() scene_ego_timestamp = scene_ego_idx["timestamp"] threshold = 2 * np.max(np.linalg.norm(key_pc[:,:3])) #print(threshold) transform_matrix_k= transform_matrix(scene_ego_trans, Quaternion(scene_ego_rot),True) #t_k = scene_ego_trans #r_k = (R.from_quat(scene_ego_rot)).as_matrix() final_pc = key_pc for id in range(num_samples): scene_token_re = scene_token_list[id] scene_re_idx = scene_ego_list[id] translation_re = np.array(scene_re_idx["translation"]) rot_re = np.array(scene_re_idx["rotation"]).tolist() r_sensor_token = nusc.get('sample_data', scene_token)['calibrated_sensor_token'] rot_to_ego = nusc.get('calibrated_sensor', r_sensor_token)['rotation'] trans_to_ego = nusc.get('calibrated_sensor', r_sensor_token)['translation'] r_r_e = transform_matrix(trans_to_ego, Quaternion(rot_to_ego)) transform_matrix_r= transform_matrix(translation_re, Quaternion(rot_re)) #t_r = translation_re #r_r = np.array(r_r) #r_r = (R.from_quat(rot_re)).as_matrix() distance = np.linalg.norm(scene_ego_trans - translation_re) if distance <= threshold: #print(1) #print(distance) #anno_seg_re = torch.from_numpy(np.float32(np.fromfile("/mrtstorage/users/kpeng/nu_lidar_seg/processed_with_flat_divided/"+scene_token_re+"_$ sample_re = nusc.get('sample_data', scene_token_re)['filename'] #print(sample_re) re_pc = np.fromfile(file_path+sample_re, dtype=np.float32, count=-1).reshape(-1,6) anno_seg_re = re_pc[:,-1] mask_flat =(anno_seg_re ==1)|(anno_seg_re==8)| (anno_seg_re == 11) | (anno_seg_re == 12) | (anno_seg_re == 13) | (anno_seg_re == 14) | (anno_$ #sample_re = nusc.get('sample_data', scene_token_re)['filename'] #re_pc = np.fromfile(file_path+sample_re, dtype=np.float32, count=-1).reshape(-1,6) re_pc_flat = re_pc[mask_flat] # point_num, [x,y,z,r,t,seg_anno] #print(re_pc_flat.shape) p_n = re_pc_flat.shape[0] homo = np.concatenate((re_pc_flat[:,:3],np.ones((p_n,1))),axis=-1) #re_pc_flat[:,:3] = (r_k@((r_r@re_pc_flat[:,:3].T).T+t_r - t_k).T).T #re_pc_flat[:,:3] = (r_k@((r_r@re_pc_flat[:,:3].T).T - t_r + t_k).T).T re_pc_flat[:,:3] = (((k_r_e@(transform_matrix_k @ (transform_matrix_r @ (r_r_e@ homo.T))))).T)[:,:3] #print(r_k) #print(r_r) #print(r_r) #test_point = np.ones((3,1)) #print(np.sum(r_k@r_r@re_pc_flat[:,:3].T-re_pc_flat[:,:3].T)) #print("ddddddddddddddddddddddd") #print(t_k) #print(t_r) #print(r_k @ (r_r @ t_r)) #print(t_k) #print("-----------------------") #sys.exit() #re_pc_flat[:,:2] = (np.transpose(np.linalg.inv(r_k) @ r_r @ np.transpose(re_pc_flat[:,:3], (1,0)), (1,0)) + np.linalg.inv(r_k) @ r_r @ t_r -$ #re_pc_flat[:,:2] = (np.transpose(np.linalg.inv(r_k)@r_r@np.transpose(re_pc_flat[:,:3],(1,0)),(1,0))+np.linalg.inv(r_k) @ (-t_k+t_r))[:,:2] #print(re_pc_flat.shape) #print("+++++") #print(final_pc.shape) final_pc = np.concatenate((final_pc,re_pc_flat),axis=0) #sys.exit() binfile = open(save_path+key_frame_sample, 'wb+') binfile.write(final_pc.flatten().tobytes()) binfile.close() print(save_path+key_frame_sample) sys.exit() if __name__ == "__main__": a,b,c,d,e =seg_concat() <file_sep>/README.md # MASS: Multi-Attentional Semantic Segmentation of LiDAR Data for Dense Top-View Understanding <img src="docs/MASS.png" align="right" width="50%"> We are aiming at recovering dense top-view semantic segmentation based on sparse LiDAR signal input. Our code is built based on OpenPCDet repo https://github.com/open-mmlab/OpenPCDet.git. # OpenPCDet `OpenPCDet` is a clear, simple, self-contained open source project for LiDAR-based 3D object detection. It is also the official code release of [`[PointRCNN]`](https://arxiv.org/abs/1812.04244), [`[Part-A^2 net]`](https://arxiv.org/abs/1907.03670) and [`[PV-RCNN]`](https://arxiv.org/abs/1912.13192). ## Introduction ## Label Densification Nuscenes tools: The tools for generating dense top-view label through multi-scene aggregating and top-view projection is in label processing tools. The lidaeseg_annotools.py maps nuScenes classes to desired class index in MASS. Then lidar_seg_label_cating.py will concate the semantic segmentation label for each LiDAR point. ego.py is leveraged for multi-frame lidar densification using the ego pose given by nuScenes. gt_img.py gives the color map and visualize the prediction/label. ## Visibility Map Generation Code is in voxelize folder, please run cmake first to build it and use dense.cpp to generate the visibility map. Thanks to https://github.com/peiyunh/wysiwyg.git. ## Branches Master branch is currently set up for SemanticKITTI dataset. Config file can be found in tools/cfgs/nuscenes_models/cbgs_pp_multihead.yaml, please follow the guidance of OpenPCDet to run the code. Code for nuScenes dataset can be found in branch nuscenes_pillarseg. For SemanticKitti dataset, if you have get accessed to Kitti-odo and SemanticKitti dataset, please forward the access email from KITTI to <EMAIL>, the download link for the dense and sparse top-view semantic segmentation label will be given. The label is stored in binary file wuth data type float32 and should be reshaped as (500,1000) to match our code. semantic_kitti_pillarseg is for SemanticKitti dataset while using the same config file as tools/cfgs/nuscenes_models/cbgs_pp_multihead.yaml to run. ## Installation Please refer to [INSTALL.md](docs/INSTALL.md) for the installation of `OpenPCDet`. ## Getting Started Please refer to [GETTING_STARTED.md](docs/GETTING_STARTED.md) to learn more usage about this project. ## License `MASS` is released under the [Apache 2.0 license](LICENSE). ## Acknowledgement `MASS` is an open source project for dense top-view semantic segmentation based on LiDAR input. We would thanks https://github.com/open-mmlab/OpenPCDet.git for the great baseline. ## Citation If you find this project useful in your research, please consider cite: ``` @article{peng2021mass, title={MASS: Multi-Attentional Semantic Segmentation of LiDAR Data for Dense Top-View Understanding}, author={<NAME> <NAME>, Alina and Zhang, Jiaming and <NAME> and Heidenreich, Philipp and Stiller, Christoph and Stiefelhagen, Rainer}, journal={arXiv preprint arXiv:2107.00346}, year={2021} } ``` ## Contribution Welcome to be a member of the OpenPCDet development team by contributing to this repo, and feel free to contact us for any potential contributions. <file_sep>/label_processing_tools/gt_img.py from collections import defaultdict from pathlib import Path from PIL import Image import os import pickle import torch import numpy as np import matplotlib.pyplot as plt #import torch.utils.data as torch_data #from data_loader_odo import data_loader #from ..utils import common_utils #from .augmentor.data_augmentor import DataAugmentor #from .processor.data_processor import DataProcessor #from .processor.point_feature_encoder import PointFeatureEncoder import sys #from mapping import mapping #from voxelize.voxelize import dense color_map_1={ "0" : [255, 255, 255], "1": [245, 150, 100], "4": [250, 80, 100], "16": [255, 0, 0], "7": [180, 30, 80], "3": [255, 0, 0], "9": [30, 30, 255], "8": [200, 40, 255], "2": [90, 30, 150], "11": [255, 0, 255], "12": [75, 0, 75], "14": [255, 150, 255], "15": [0, 255, 0], "5": [0, 60, 135], "13": [0, 255, 0], "10" :[0, 0, 255], "6": [255, 255, 50], "17": [80, 240, 150], "18": [150,240,255], "19": [0,255,255] } color_map ={ "0": [255, 255, 255], "1": [112, 128, 144], "2": [220, 20, 60], "3": [255, 127, 80], "4": [255, 158, 0], "5": [233, 150, 70], "6": [255, 61, 99], "7": [0, 0, 230], "8": [47, 79, 79], "9": [255, 140, 0], "10": [255, 99, 71], "11": [0, 207, 191], "12": [175, 0, 75], "13": [75, 0, 75], "14": [112, 180, 60], "15": [222, 184, 135], "16": [0, 175, 0] } def recursive_glob(rootdir=".", suffix=""): return [ os.path.join(looproot, filename) for looproot, _, filenames in os.walk(rootdir) for filename in filenames if filename.endswith(suffix) ] def colorized_image_generator(): #file_name = "/home/kpeng/pc14/sample_test.pkl" save_path = "/home/kpeng/pc14/nuscenes/colorized_gt/" #open_file = open(file_name, "rb") file_path = "/home/kpeng/pc14/nuscenes/label_image_dense/LIDAR_TOP/" files_seq = recursive_glob(rootdir=file_path, suffix=".png") #files_seq = pickle.load(open_file) #open_file.close() #print(files_seq) #sys.exit() #locate = "/home/kpeng/pc14/kitti_odo/training/08/0000168.bin" #index = files_seq.index(locate) for point_path in files_seq: #dense_path = '/home/kpeng/pc14/nuscenes/label_image_dense/LIDAR_TOP/n015-2018-09-25-13-17-43+0800__LIDAR_TOP__1537852966648600.png' pointcloud = np.array(Image.open(point_path)).reshape(512,512,1) #np.fromfile(str(dense_path), dtype=np.float32, count=-1).reshape([512,512,1]) print(np.sum(pointcloud==4)) picture = np.zeros([512,512,3]) #print(np.max(pointcloud)) for i in range(0,17): mask = pointcloud[:,:,-1] == i #print(mask.shape) if mask.sum() == 0: continue picture[mask]=np.array(color_map[str(i)])/255 #plt.figure() #picture=np.transpose() img_path = save_path +str(point_path).split('/')[-2] +'/'+ str(point_path).split('/')[-1].split('.')[0]+'.png' print(img_path) plt.imsave(img_path,picture) #sys.exit() def label_generator(): #file_name = "/home/kpeng/pc14/sample_test.pkl" save_path = "/mrtstorage/users/kpeng/nu_lidar_seg/label_image_dense/" #open_file = open(file_name, "rb") file_path = "/mrtstorage/users/kpeng/nu_lidar_seg/concat_lidar_flat_divided/new_2/samples/LIDAR_TOP/" #files_seq = pickle.load(open_file) files_seq = recursive_glob(rootdir=file_path, suffix=".bin") #open_file.close() #locate = "/home/kpeng/pc14/kitti_odo/training/10/000362.bin" #index = files_seq.index(locate) for point_path in files_seq: dense_path = point_path dense_gt = np.fromfile(str(dense_path), dtype=np.float32, count=-1).reshape([-1, 6])[:, :6] #print(np.max(dense_gt[:,-1])) pc_range = np.array([-51.2, -51.2, -5.0, 51.2, 51.2, 3.0],dtype=np.float32) voxel_size = np.array([0.2,0.2,8],dtype=np.float32) dense_gt[:,-1] = np.clip(dense_gt[:,-1],0,17) dense_gt = dense.compute_dense_gt(dense_gt, pc_range,voxel_size,17).reshape(1,17,512,512) dense_gt = torch.from_numpy(dense_gt).permute(0,2,3,1).reshape(1*512*512,17) # 2, 20, 500, 1000 #print(torch.sum(torch.max(dense_gt[:,-1]))) #sys.exit() weight_5_class = [2,3,4,5,6,7,10] weight_0_class = [0] weight_1_class = [1,8,9,11,12,13,14,15,16] dense_gt[:,weight_5_class]= dense_gt[:,weight_5_class]*5 dense_gt[:,weight_0_class]=dense_gt[:,weight_0_class]*0 dense_gt[:,weight_1_class]=dense_gt[:,weight_1_class]*1 for i in range(17): dense_gt[:,i]+=0.16-0.01*i #print(debse_gt) #print(torch.sum(torch.max(dense_gt[:,16]))) dense_gt = torch.argmax(dense_gt,dim=-1).view(512,512).numpy() #print(np.max(dense_gt)) #sys.exit() #print(save_path+str(point_path).split('/')[-2] +'/'+ str(point_path).split('/')[-1]) save=save_path+str(point_path).split('/')[-2] +'/'+ str(point_path).split('/')[-1].split('.')[0]+'.png' #sys.exit() dense_gt=np.clip(dense_gt,0,255).astype(np.uint8) im = Image.fromarray(dense_gt) print(save) im.save(save) #f.write(dense_gt) #f.close() if __name__ == '__main__': #label_generator() colorized_image_generator() <file_sep>/pcdet/datasets/augmentor/vis_pillars_feat.py import numpy as np from PIL import Image import torch def show_feat(feat): img = (20 * feat).astype(np.uint8) feat_toshow = Image.fromarray(img) feat_toshow.show() file_name = '0.npy' gt_file = '../../../tools/gt_seg' + file_name pillar_file = '../../../tools/pillar' + file_name obser_file = '../../../tools/obser' + file_name voxel_feat = np.load(gt_file) print('Seg gt Shape: ', voxel_feat.shape) print('Seg max: ', voxel_feat.max()) show_feat(voxel_feat[0, 0, :, :]) pillar_feat = np.load(pillar_file) pillar_feat = np.clip(pillar_feat, 0, 1) print('Pillar Shape: ', pillar_feat.shape) pillar_slice_feat = pillar_feat[0, 1, :, :] show_feat(pillar_slice_feat*12) obser_feat = np.load(obser_file)*255 print('obser max: ', obser_feat.max()) show_feat(obser_feat[0, 0, :, :]*12) <file_sep>/pcdet/datasets/dataset.py from collections import defaultdict from pathlib import Path import os import pickle import numpy as np import torch.utils.data as torch_data # from data_loader_odo import data_loader from ..utils import common_utils from .augmentor.data_augmentor import DataAugmentor from .processor.data_processor import DataProcessor from .processor.point_feature_encoder import PointFeatureEncoder import sys from pathlib import Path from skimage import io import time def recursive_glob(rootdir=".", suffix=""): return [ os.path.join(looproot, filename) for looproot, _, filenames in os.walk(rootdir) for filename in filenames if filename.endswith(suffix) ] class DatasetTemplate(torch_data.Dataset): def __init__(self, dataset_cfg=None, class_names=None, training=True, root_path=None, logger=None): super().__init__() self.dataset_cfg = dataset_cfg self.training = training self.class_names = class_names self.logger = logger self.root_path = root_path if root_path is not None else Path(self.dataset_cfg.DATA_PATH) self.logger = logger if self.dataset_cfg is None or class_names is None: return self.point_cloud_range = np.array(self.dataset_cfg.POINT_CLOUD_RANGE, dtype=np.float32) self.point_feature_encoder = PointFeatureEncoder( self.dataset_cfg.POINT_FEATURE_ENCODING, point_cloud_range=self.point_cloud_range ) self.data_augmentor = DataAugmentor( self.root_path, self.dataset_cfg.DATA_AUGMENTOR, self.class_names, logger=self.logger ) if self.training else None self.data_processor = DataProcessor( self.dataset_cfg.DATA_PROCESSOR, point_cloud_range=self.point_cloud_range, training=self.training ) self.grid_size = self.data_processor.grid_size self.voxel_size = self.data_processor.voxel_size self.total_epochs = 0 self._merge_all_iters_to_one_epoch = False self.root = Path("/home/kpeng/pc14/") self.gt_dense_bin_root = self.root / 'kitti_odo/training' self.gt_dense_img_root = self.root / 'dense_label' self.gt_obser_img_root = self.root / 'occupancy' self.gt_sparse_img_root= self.root / 'sparse_label' if training == True: self.split = "train" sequence = ["00", "01", "02", "03", "04", "05", "06", "07", "09", "10"] file_name = "/home/kpeng/pc14/sample_test.pkl" else: self.split = "test" sequence = ["08"] file_name = "/home/kpeng/pc14/sample.pkl" self.files_seq = [] # comment it out when generate sample file # for idx, scene in enumerate(sequence): # self.files_seq.extend(recursive_glob(str(self.root) + '/sequences/' + scene + '/', suffix=".bin")) # print(self.files_seq) # open_file = open(file_name, "wb") # pickle.dump(self.files_seq, open_file) # open_file.close() # sys.exit() # end open_file = open(file_name, "rb") self.files_seq = pickle.load(open_file) open_file.close() # print(len(self.files_seq) @property def mode(self): return 'train' if self.training else 'test' def __getstate__(self): d = dict(self.__dict__) del d['logger'] return d def __setstate__(self, d): self.__dict__.update(d) @staticmethod def generate_prediction_dicts(batch_dict, pred_dicts, class_names, output_path=None): """ To support a custom dataset, implement this function to receive the predicted results from the model, and then transform the unified normative coordinate to your required coordinate, and optionally save them to disk. Args: batch_dict: dict of original data from the dataloader pred_dicts: dict of predicted results from the model pred_boxes: (N, 7), Tensor pred_scores: (N), Tensor pred_labels: (N), Tensor class_names: output_path: if it is not None, save the results to this path Returns: """ def merge_all_iters_to_one_epoch(self, merge=True, epochs=None): if merge: self._merge_all_iters_to_one_epoch = True self.total_epochs = epochs else: self._merge_all_iters_to_one_epoch = False def get_dense_gt_bin(self, seq, index): f_file = self.gt_dense_bin_root / seq / ('%s.bin' % index) assert f_file.exists() return np.fromfile(str(f_file), dtype=np.float32, count=-1).reshape(500, 1000, 1) def get_dense_gt_img(self, seq, index): f_file = self.gt_dense_img_root / seq / ('%s.png' % index) assert f_file.exists() return np.array(io.imread(f_file), dtype=np.float32).reshape(500, 1000, 1) def get_grid_dense_gt_img(self, seq, index): f_file = self.gt_obser_img_root / seq / ('%015d.png' % int(index)) assert f_file.exists() return np.array(io.imread(f_file), dtype=np.float32).reshape(500, 1000, 1) def get_sparse_gt_img(self, seq, index): f_file = self.gt_sparse_img_root / seq / ('%06d.png' % int(index)) #print(f_file) assert f_file.exists() return np.array(io.imread(f_file), dtype=np.float32).reshape(500, 1000, 1) def get_obser_img(self, seq, index): f_file = self.gt_obser_img_root / seq / ('%06d.png' % int(index)) assert f_file.exists() return np.array(io.imread(f_file), dtype=np.float32).reshape(500, 1000, 1) def __len__(self): return len(self.files_seq) def __getitem__(self, index): """ To support a custom dataset, implement this function to load the raw data (and labels), then transform them to the unified normative coordinate and call the function self.prepare_data() to process the data and send them to the model. Args: index: Returns: """ #t1=time.clock() data_dict = {} point_path = self.files_seq[index].rstrip() #if not point_path.exists(): # print(str(point_path)) # print(point_path) point_path = "/home/kpeng/pc14/kitti_odo/training/"+point_path.split('/')[-2]+"/velodyne/"+point_path.split('/')[-1] points = np.fromfile(str(point_path), dtype=np.float32, count=-1).reshape([-1, 4]) mask = common_utils.mask_points_by_range(points, self.point_cloud_range) points = points[mask] points = np.concatenate([points, np.zeros([points.shape[0], 1])], axis=-1) data_dict["points"] = points seq = str(point_path).split('/')[-3] idx = Path(point_path).stem data_dict['frame_id'] = seq+idx # TODO dense gt # seg_gt = self.get_dense_gt_bin(seq, idx) seg_gt = self.get_dense_gt_img(seq, idx) # get grid dense gt # seg_gt = self.get_grid_dense_gt_img(seq, idx)[:500, :1000, :] # remapping from franks if to pengs # seg_gt = seg_gt + 1 # bkgd_mask = seg_gt == 31 # seg_gt[bkgd_mask] = 0 # sparse gt # seg_gt = self.get_sparse_gt_img(seq, idx)[:500, :1000, :] # remapping from franks if to pengs # seg_gt = seg_gt + 1 # bkgd_mask = seg_gt == 31 # seg_gt[bkgd_mask] = 0 data_dict['labels_seg'] = seg_gt # load observations obser = self.get_obser_img(seq, idx)[:500, :1000, :] # print(obser.shape) data_dict['observations'] = obser data_dict = self.prepare_data(data_dict) seg_gt = np.transpose(data_dict['labels_seg'], (2, 0, 1)) # 1, 500, 1000 data_dict['labels_seg'] = seg_gt obser = np.transpose(data_dict['observations'], (2, 0, 1)) data_dict['observations'] = obser / 255 # normalization data_dict.pop('points', None) #print(t1-time.clock()) #sys.exit() return data_dict def prepare_data(self, data_dict): """ Args: data_dict: points: (N, 3 + C_in) gt_boxes: optional, (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] gt_names: optional, (N), string ... Returns: data_dict: frame_id: string points: (N, 3 + C_in) gt_boxes: optional, (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] gt_names: optional, (N), string use_lead_xyz: bool voxels: optional (num_voxels, max_points_per_voxel, 3 + C) voxel_coords: optional (num_voxels, 3) voxel_num_points: optional (num_voxels) ... """ if self.training: data_dict = self.data_augmentor.forward(data_dict=data_dict) # debug data augmentation # gt_seg = data_dict['labels_gt'] # data_dict = self.point_feature_encoder.forward(data_dict) data_dict = self.data_processor.forward( data_dict=data_dict ) if self.training and len(data_dict['voxel_coords']) == 0: new_index = np.random.randint(self.__len__()) print('Error frame id: ', data_dict['frame_id']) return self.__getitem__(new_index) return data_dict @staticmethod def collate_batch(batch_list, _unused=False): data_dict = defaultdict(list) # print("test") # sys.exit() for cur_sample in batch_list: for key, val in cur_sample.items(): data_dict[key].append(val) batch_size = len(batch_list) ret = {} # data_dict.pop('points_sp', None) data_dict.pop('indices', None) data_dict.pop('origins', None) # print(data_dict.keys()) # sys.exit() ret['frame_id'] = [] for key, val in data_dict.items(): # print('collate: ', key) try: if key in ['voxels', 'voxel_num_points']: ret[key] = np.concatenate(val, axis=0) elif key in ['points', 'voxel_coords', 'dense_point']: coors = [] for i, coor in enumerate(val): coor_pad = np.pad(coor, ((0, 0), (1, 0)), mode='constant', constant_values=i) coors.append(coor_pad) ret[key] = np.concatenate(coors, axis=0) elif key in ['gt_boxes']: max_gt = max([len(x) for x in val]) batch_gt_boxes3d = np.zeros((batch_size, max_gt, val[0].shape[-1]), dtype=np.float32) for k in range(batch_size): batch_gt_boxes3d[k, :val[k].__len__(), :] = val[k] ret[key] = batch_gt_boxes3d elif key == 'frame_id': ret[key].append(data_dict['frame_id']) else: ret[key] = np.stack(val, axis=0) except: print('Error in collate_batch: key=%s' % key) raise TypeError # print('vis' in ret.keys()) ret['batch_size'] = batch_size return ret <file_sep>/pcdet/datasets/gt_image_label.py from collections import defaultdict from pathlib import Path import os import pickle import torch import numpy as np # import torch.utils.data as torch_data # from data_loader_odo import data_loader # from ..utils import common_utils # from .augmentor.data_augmentor import DataAugmentor # from .processor.data_processor import DataProcessor # from .processor.point_feature_encoder import PointFeatureEncoder import sys # from mapping import mapping from voxelize import dense import cv2 from pathlib import Path def label_generator(): file_name = "/home/ki/input/kitti/semantickitti/dataset/val_sample.pkl" save_path = "/home/ki/input/kitti/semantickitti/dataset/pillarseg/gt_dense_bin/" img_save_path = "/home/ki/input/kitti/semantickitti/dataset/pillarseg/gt_dense_image/" open_file = open(file_name, "rb") files_seq = pickle.load(open_file) open_file.close() for point_path in files_seq: dense_path = '/home/ki/hdd0/input/kitti/semantickitti/dense/' +str(point_path).split('/')[-3] +'/'+ str(point_path).split('/')[-1] dense_gt = np.fromfile(str(dense_path), dtype=np.float32, count=-1).reshape([-1, 5])[:, :5] pc_range = np.array([-50.0, -25.0, -3.0, 50.0, 25.0, 1.0], dtype=np.float32) voxel_size = np.array([0.1, 0.1, 4], dtype=np.float32) dense_gt[:, -1] = np.clip(dense_gt[:, -1], 0, 12) dense_gt = dense.compute_dense_gt(dense_gt, pc_range, voxel_size, 13).reshape(1, 13, 500, 1000) dense_gt = torch.from_numpy(dense_gt).permute(0, 2, 3, 1).reshape(1 * 500 * 1000, 13) # 2, 20, 500, 1000 weight_5_class = [1, 2, 3, 4] weight_0_class = [0] weight_1_class = [5, 6, 7, 8, 9, 10, 11, 12] dense_gt[:, weight_5_class] = dense_gt[:, weight_5_class] * 5 dense_gt[:, weight_0_class] = dense_gt[:, weight_0_class] * 0 dense_gt[:, weight_1_class] = dense_gt[:, weight_1_class] * 1 for i in range(12): dense_gt[:, i] += 0.12 - 0.01 * i # print(debse_gt) dense_gt = torch.argmax(dense_gt, dim=-1).view(500 * 1000, 1).numpy() dense_gt_bin = dense_gt.astype(np.float32).tobytes() print(save_path + str(point_path).split('/')[-3] + '/' + str(point_path).split('/')[-1]) bin_file = Path(save_path + str(point_path).split('/')[-3] + '/' + str(point_path).split('/')[-1]) bin_file.parent.mkdir(parents=True, exist_ok=True) f = open(str(bin_file), 'wb') f.write(dense_gt_bin) f.close() img_path = Path(img_save_path + str(point_path).split('/')[-3] + '/' + str(point_path).split('/')[-1].split('.')[0] + '.png') img_path.parent.mkdir(parents=True, exist_ok=True) cv2.imwrite(str(img_path), dense_gt.reshape(500, 1000, 1).astype(np.uint8)) if __name__ == '__main__': label_generator()<file_sep>/pcdet/datasets/data_loader_odo.py import os import torch import numpy as np import scipy.misc as m import functools import operator from torch.utils import data import sys def recursive_glob(rootdir=".", suffix=""): return [ os.path.join(looproot,filename) for looproot,_, filenames in os.walk(rootdir) for filename in filenames if filename.endswith(suffix) ] class data_loader(data.Dataset): def __init__( self, root, split="train", is_transform=False, version="kitti-odo", test_mode=False, ): self.root = "/home/ki/input/kitti/semantickitti/dataset/sequences/" self.split = split self.data_dict = {} self.files_seq = [] #for index in sequence_num: #self.files_seq.extend(recursive_glob(rootdir=self.root, suffix=".bin")) #print(self.files_seq) #self.files = functools.reduce(operator.iconcat, self.files_seq, []) if split == "train": sequence = ["00","01","02","03","04","05","06","07","09","10"] else: sequence = ["08"] #file_list = [] for idx, scene in enumerate(sequence): self.files_seq.extend(recursive_glob(self.root+scene+'/', suffix=".bin")) print(len(self.files_seq)) def __len__(self): """__len__""" return len(self.files_seq) def __getitem__(self, index): """__getitem__ :param index: """ point_path = self.files_seq[index].rstrip() points = np.fromfile(str(point_path), dtype=np.float32, count=-1).reshape([-1, 4])[:, :4] dense_path = '/home/ki/hdd0/input/kitti/semantickitti/dense/' +str(point_path).split('/')[-2] +'/'+ str(point_path).split('/')[-1] dense_gt = np.fromfile(str(dense_path), dtype=np.float32, count=-1).reshape([-1, 5])[:, :5] self.data_dict["dense_gt"]=dense_gt self.data_dict["points"] = points return self.data_dict if __name__ == "__main__": import matplotlib.pyplot as plt #augmentations = Compose([Scale(2048), RandomRotate(10), RandomHorizontallyFlip(0.5)]) local_path = "/home/kunyu/pc14/kitti_odo/training/" dst = data_loader(local_path) bs = 1 trainloader = data.DataLoader(dst, batch_size=1, num_workers=0) for i, data_samples in enumerate(trainloader): pcs = data_samples #import pdb #pdb.set_trace() print(pcs['dense_gt'].shape) sys.exit()
afd81b8b2b6c054c2d280278cb580a3a22dcf393
[ "Markdown", "Python", "CMake", "C++" ]
20
Python
DrZhouKarl/MASS
739beb376b3fb16d8d2eba0f119448a1fddf9544
ba1950289f3a2af79ee242207d73dea97e066af1
refs/heads/master
<repo_name>giladmadmon/image_ex3<file_sep>/ImageService.Communication/Model/Event/DataReceivedEventArgs.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ImageService.Communication.Model.Event { public class DataReceivedEventArgs : EventArgs { public string Data { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="DataReceivedEventArgs"/> class. /// </summary> /// <param name="data">The data.</param> public DataReceivedEventArgs(string data) { this.Data = data; } } } <file_sep>/ImageService/ImageService/Server/ServerCommunication.cs using ImageService.Communication; using ImageService.Communication.Interfaces; using ImageService.Communication.Model.Event; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ImageService.ImageService.Server { public class ServerCommunication { private const string IP = "127.0.0.1"; private const int PORT = 8003; private IClientCommunicationChannel m_server; private static ServerCommunication m_serverCommunication; public event EventHandler<DataReceivedEventArgs> OnDataReceived { add { m_server.OnDataRecieved += value; } remove { m_server.OnDataRecieved -= value; } } /// <summary> /// Gets the instance. /// </summary> /// <value> /// The instance. /// </value> public static ServerCommunication Instance { get { if(m_serverCommunication == null) { m_serverCommunication = new ServerCommunication(); } return m_serverCommunication; } } /// <summary> /// Prevents a default instance of the <see cref="ServerCommunication"/> class from being created. /// </summary> private ServerCommunication() { m_server = new TcpServerChannel(IP, PORT); m_server.Start(); } /// <summary> /// Sends the specified data. /// </summary> /// <param name="data">The data.</param> public void Send(string data) { m_server.Send(data); } } } <file_sep>/ImageService.Communication/Singleton/ClientCommunication.cs using ImageService.Communication; using ImageService.Communication.Interfaces; using ImageService.Communication.Model; using ImageService.Communication.Model.Event; using ImageService.Infrastructure.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace ImageService.Communication.Singleton{ public class ClientCommunication { private static string IP = "127.0.0.1"; private static int PORT = 8003; private static ClientCommunication m_ClientCommunication = null; private IClientCommunicationChannel m_client; /// <summary> /// Gets the instance. /// </summary> /// <value> /// The instance. /// </value> public static ClientCommunication Instance { get { if(m_ClientCommunication == null || !m_ClientCommunication.Connected) { m_ClientCommunication = new ClientCommunication(); } return m_ClientCommunication; } } /// <summary> /// Gets a value indicating whether this <see cref="ClientCommunication"/> is connected. /// </summary> /// <value> /// <c>true</c> if connected; otherwise, <c>false</c>. /// </value> public bool Connected { get { return m_client.Connected; } } /// <summary> /// Occurs when the client receives data. /// </summary> public event EventHandler<DataReceivedEventArgs> OnDataRecieved { add { m_client.OnDataRecieved += value; } remove { m_client.OnDataRecieved -= value; } } /// <summary> /// Prevents a default instance of the <see cref="ClientCommunication"/> class from being created. /// </summary> private ClientCommunication() { m_client = new TcpClientChannel(IP, PORT); m_client.Start(); } /// <summary> /// Sends the specified command message. /// </summary> /// <param name="cmdMsg">The command message.</param> /// <returns></returns> public int Send(CommandMessage cmdMsg) { return m_client.Send(cmdMsg.ToJSON()); } /// <summary> /// Closes this instance. /// </summary> public void Close() { Send(new CommandMessage(CommandEnum.CloseClientCommand, new string[] { })); m_client.Close(); m_client = null; } } }
e112bb512dc10617caac202d788cbfb8abf303ba
[ "C#" ]
3
C#
giladmadmon/image_ex3
3774b0122da78a425b24da8505c102562e9fc8a4
db4d4d8b579c3ab74cd34f79f0697382d08b2419
refs/heads/master
<repo_name>ArtObr/indy-scp<file_sep>/scp/main.py from scp.indy_constants import CONTRACT_LEDGER_ID from scp.request_handlers.contract_batch_hanlder import ContractBatchHandler from scp.request_handlers.contract_request_handler import ContractRequestHandler from scp.vm.base import VM from state.pruning_state import PruningState from storage.helper import initKeyValueStorage from plenum.common.ledger import Ledger from ledger.compact_merkle_tree import CompactMerkleTree from plenum.common.constants import KeyValueStorageType def integrate_plugin_in_node(node): update_config(node) init_storages(node) init_virtual_machine(node) register_req_handlers(node) register_batch_handlers(node) return node def update_config(node): config = node.config config.contractTransactionsFile = 'contract_transactions' config.contractStateStorage = KeyValueStorageType.Rocksdb config.contractStateDbName = 'contract_state' def init_storages(node): # Token ledger and state init if CONTRACT_LEDGER_ID not in node.ledger_ids: node.ledger_ids.append(CONTRACT_LEDGER_ID) token_state = init_contract_state(node) token_ledger = init_contract_ledger(node) node.db_manager.register_new_database(CONTRACT_LEDGER_ID, token_ledger, token_state) init_token_database(node) def init_virtual_machine(node): node.virtual_machine = VM() def init_contract_ledger(node): return Ledger(CompactMerkleTree(hashStore=node.getHashStore('contract')), dataDir=node.dataLocation, fileName=node.config.contractTransactionsFile, ensureDurability=node.config.EnsureLedgerDurability) def init_contract_state(node): return PruningState( initKeyValueStorage( node.config.contractStateStorage, node.dataLocation, node.config.contractStateDbName, db_config=node.config.db_state_config) ) def init_token_database(node): node.ledgerManager.addLedger(CONTRACT_LEDGER_ID, node.db_manager.get_ledger(CONTRACT_LEDGER_ID), postTxnAddedToLedgerClbk=node.postTxnFromCatchupAddedToLedger) node.on_new_ledger_added(CONTRACT_LEDGER_ID) def register_req_handlers(node): node.write_manager.register_req_handler(ContractRequestHandler(node.db_manager, node.write_req_validator, node.virtual_machine)) def register_batch_handlers(node): node.write_manager.register_batch_handler(ContractBatchHandler(node.db_manager), add_to_begin=True) node.write_manager.register_batch_handler(node.write_manager.node_reg_handler, ledger_id=CONTRACT_LEDGER_ID) node.write_manager.register_batch_handler(node.write_manager.primary_reg_handler, ledger_id=CONTRACT_LEDGER_ID) node.write_manager.register_batch_handler(node.write_manager.audit_b_handler, ledger_id=CONTRACT_LEDGER_ID) <file_sep>/tests/test_pool_get_set_contract.py import json import pytest from eth_utils import encode_hex from plenum.test.helper import sdk_get_and_check_replies from indy_common.constants import ENDORSER_STRING from plenum.common.exceptions import RequestRejectedException from plenum.test.pool_transactions.helper import sdk_add_new_nym, sdk_sign_and_send_prepared_request from scp.indy_constants import CONTRACT_INVOKE from tests.test_get_set_contract import contract_code def send_contract_txn(looper, creators_wallet, sdk_pool_handle, code, contract_dest): wh, _ = creators_wallet request = json.dumps({ 'identifier': creators_wallet[1], 'reqId': 999999999, 'protocolVersion': 2, 'operation': { 'type': CONTRACT_INVOKE, 'contract_code': encode_hex(code), 'contract_dest': contract_dest, } }) request_couple = sdk_sign_and_send_prepared_request(looper, creators_wallet, sdk_pool_handle, request) reply = sdk_get_and_check_replies(looper, [request_couple]) return reply def testStewardCreatesAEndorser(helpers, looper, sdk_pool_handle, sdk_wallet_steward): sdk_add_new_nym(looper, sdk_pool_handle, sdk_wallet_steward, role=ENDORSER_STRING) send_contract_txn(looper, sdk_wallet_steward, sdk_pool_handle, contract_code, '') <file_sep>/scp/precompiles/blake2.py import blake2b from eth_utils import ( ValidationError, ) from scp._utils.blake2.coders import extract_blake2b_parameters from scp.exceptions import ( VMError, ) from scp.abc import ( ComputationAPI, ) GAS_COST_PER_ROUND = 1 def blake2b_fcompress(computation: ComputationAPI) -> ComputationAPI: try: parameters = extract_blake2b_parameters(computation.msg.data_as_bytes) except ValidationError as exc: raise VMError(f"Blake2b input parameter validation failure: {exc}") from exc num_rounds = parameters[0] gas_cost = GAS_COST_PER_ROUND * num_rounds computation.consume_gas(gas_cost, reason=f"Blake2b Compress Precompile w/ {num_rounds} rounds") computation.output = blake2b.compress(*parameters) return computation <file_sep>/scp/abc.py from abc import ( ABC, abstractmethod ) from typing import ( Any, Callable, ClassVar, ContextManager, Dict, Iterable, Iterator, MutableMapping, Optional, Sequence, Tuple, Type, TypeVar, Union, NamedTuple) from uuid import UUID import rlp from eth_bloom import BloomFilter from eth_typing import ( Address, BlockNumber, Hash32, ) from eth_utils import ExtendedDebugLogger from eth_keys.datatypes import PrivateKey from scp.constants import ( BLANK_ROOT_HASH, ) from scp.exceptions import VMError from scp.typing import ( BytesOrView, JournalDBCheckpoint, AccountState, HeaderParams, VMConfiguration, ) T = TypeVar('T') class MiningHeaderAPI(rlp.Serializable, ABC): """ A class to define a block header without ``mix_hash`` and ``nonce`` which can act as a temporary representation during mining before the block header is sealed. """ parent_hash: Hash32 uncles_hash: Hash32 coinbase: Address state_root: Hash32 transaction_root: Hash32 receipt_root: Hash32 bloom: int difficulty: int block_number: BlockNumber gas_limit: int gas_used: int timestamp: int extra_data: bytes class BlockHeaderAPI(MiningHeaderAPI): """ A class derived from :class:`~eth.abc.MiningHeaderAPI` to define a block header after it is sealed. """ mix_hash: Hash32 nonce: bytes class LogAPI(rlp.Serializable, ABC): """ A class to define a written log. """ address: Address topics: Sequence[int] data: bytes @property @abstractmethod def bloomables(self) -> Tuple[bytes, ...]: ... class ReceiptAPI(rlp.Serializable, ABC): """ A class to define a receipt to capture the outcome of a transaction. """ state_root: bytes gas_used: int bloom: int logs: Sequence[LogAPI] @property @abstractmethod def bloom_filter(self) -> BloomFilter: ... class BaseTransactionAPI(ABC): """ A class to define all common methods of a transaction. """ @abstractmethod def validate(self) -> None: """ Hook called during instantiation to ensure that all transaction parameters pass validation rules. """ ... @property @abstractmethod def intrinsic_gas(self) -> int: """ Convenience property for the return value of `get_intrinsic_gas` """ ... @abstractmethod def get_intrinsic_gas(self) -> int: """ Return the intrinsic gas for the transaction which is defined as the amount of gas that is needed before any code runs. """ ... @abstractmethod def gas_used_by(self, computation: 'ComputationAPI') -> int: """ Return the gas used by the given computation. In Frontier, for example, this is sum of the intrinsic cost and the gas used during computation. """ ... # @abstractmethod # def copy(self: T, **overrides: Any) -> T: # """ # Return a copy of the transaction. # """ # ... class TransactionFieldsAPI(ABC): """ A class to define all common transaction fields. """ nonce: int gas_price: int gas: int to: Address value: int data: bytes v: int r: int s: int @property @abstractmethod def hash(self) -> bytes: ... class UnsignedTransactionAPI(rlp.Serializable, BaseTransactionAPI): """ A class representing a transaction before it is signed. """ nonce: int gas_price: int gas: int to: Address value: int data: bytes # # API that must be implemented by all Transaction subclasses. # @abstractmethod def as_signed_transaction(self, private_key: PrivateKey) -> 'SignedTransactionAPI': """ Return a version of this transaction which has been signed using the provided `private_key` """ ... class SignedTransactionAPI(rlp.Serializable, BaseTransactionAPI, TransactionFieldsAPI): """ A class representing a transaction that was signed with a private key. """ @classmethod @abstractmethod def from_base_transaction(cls, transaction: 'SignedTransactionAPI') -> 'SignedTransactionAPI': """ Create a signed transaction from a base transaction. """ ... @property @abstractmethod def sender(self) -> Address: """ Convenience and performance property for the return value of `get_sender` """ ... # +-------------------------------------------------------------+ # | API that must be implemented by all Transaction subclasses. | # +-------------------------------------------------------------+ # # Validation # @abstractmethod def validate(self) -> None: """ Hook called during instantiation to ensure that all transaction parameters pass validation rules. """ ... # # Signature and Sender # @property @abstractmethod def is_signature_valid(self) -> bool: """ Return ``True`` if the signature is valid, otherwise ``False``. """ ... @abstractmethod def check_signature_validity(self) -> None: """ Check if the signature is valid. Raise a ``ValidationError`` if the signature is invalid. """ ... @abstractmethod def get_sender(self) -> Address: """ Get the 20-byte address which sent this transaction. This can be a slow operation. ``transaction.sender`` is always preferred. """ ... # # Conversion to and creation of unsigned transactions. # @abstractmethod def get_message_for_signing(self) -> bytes: """ Return the bytestring that should be signed in order to create a signed transactions """ ... @classmethod @abstractmethod def create_unsigned_transaction(cls, *, nonce: int, gas_price: int, gas: int, to: Address, value: int, data: bytes) -> UnsignedTransactionAPI: """ Create an unsigned transaction. """ ... class BlockAPI(rlp.Serializable, ABC): """ A class to define a block. """ transaction_class: Type[SignedTransactionAPI] = None @classmethod @abstractmethod def get_transaction_class(cls) -> Type[SignedTransactionAPI]: """ Return the transaction class that is valid for the block. """ ... @classmethod @abstractmethod def from_header(cls, header: BlockHeaderAPI, chaindb: 'ChainDatabaseAPI') -> 'BlockAPI': """ Instantiate a block from the given ``header`` and the ``chaindb``. """ ... @property @abstractmethod def hash(self) -> Hash32: """ Return the hash of the block. """ ... @property @abstractmethod def number(self) -> BlockNumber: """ Return the number of the block. """ ... @property @abstractmethod def is_genesis(self) -> bool: """ Return ``True`` if this block represents the genesis block of the chain, otherwise ``False``. """ ... class BlockImportResult(NamedTuple): imported_block: BlockAPI new_canonical_blocks: Tuple[BlockAPI, ...] old_canonical_blocks: Tuple[BlockAPI, ...] class SchemaAPI(ABC): """ A class representing a database schema that maps values to lookup keys. """ @staticmethod @abstractmethod def make_canonical_head_hash_lookup_key() -> bytes: """ Return the lookup key to retrieve the canonical head from the database. """ ... @staticmethod @abstractmethod def make_block_number_to_hash_lookup_key(block_number: BlockNumber) -> bytes: """ Return the lookup key to retrieve a block hash from a block number. """ ... @staticmethod @abstractmethod def make_block_hash_to_score_lookup_key(block_hash: Hash32) -> bytes: """ Return the lookup key to retrieve the score from a block hash. """ ... @staticmethod @abstractmethod def make_transaction_hash_to_block_lookup_key(transaction_hash: Hash32) -> bytes: """ Return the lookup key to retrieve a transaction key from a transaction hash. """ ... class DatabaseAPI(MutableMapping[bytes, bytes], ABC): """ A class representing a database. """ @abstractmethod def set(self, key: bytes, value: bytes) -> None: """ Assign the ``value`` to the ``key``. """ ... @abstractmethod def exists(self, key: bytes) -> bool: """ Return ``True`` if the ``key`` exists in the database, otherwise ``False``. """ ... @abstractmethod def delete(self, key: bytes) -> None: """ Delete the given ``key`` from the database. """ ... class AtomicWriteBatchAPI(DatabaseAPI): """ The readable/writeable object returned by an atomic database when we start building a batch of writes to commit. Reads to this database will observe writes written during batching, but the writes will not actually persist until this object is committed. """ pass class AtomicDatabaseAPI(DatabaseAPI): """ Like ``BatchDB``, but immediately write out changes if they are not in an ``atomic_batch()`` context. """ @abstractmethod def atomic_batch(self) -> ContextManager[AtomicWriteBatchAPI]: """ Return a :class:`~typing.ContextManager` to write an atomic batch to the database. """ ... class HeaderDatabaseAPI(ABC): """ A class representing a database for block headers. """ db: AtomicDatabaseAPI @abstractmethod def __init__(self, db: AtomicDatabaseAPI) -> None: """ Instantiate the database from an :class:`~eth.abc.AtomicDatabaseAPI`. """ ... # # Canonical Chain API # @abstractmethod def get_canonical_block_hash(self, block_number: BlockNumber) -> Hash32: """ Return the block hash for the canonical block at the given number. Raise ``BlockNotFound`` if there's no block header with the given number in the canonical chain. """ ... @abstractmethod def get_canonical_block_header_by_number(self, block_number: BlockNumber) -> BlockHeaderAPI: """ Return the block header with the given number in the canonical chain. Raise ``HeaderNotFound`` if there's no block header with the given number in the canonical chain. """ ... @abstractmethod def get_canonical_head(self) -> BlockHeaderAPI: """ Return the current block header at the head of the chain. """ ... # # Header API # @abstractmethod def get_block_header_by_hash(self, block_hash: Hash32) -> BlockHeaderAPI: """ Return the block header for the given ``block_hash``. Raise ``HeaderNotFound`` if no header with the given ``block_hash`` exists in the database. """ ... @abstractmethod def get_score(self, block_hash: Hash32) -> int: """ Return the score for the given ``block_hash``. """ ... @abstractmethod def header_exists(self, block_hash: Hash32) -> bool: """ Return ``True`` if the ``block_hash`` exists in the database, otherwise ``False``. """ ... @abstractmethod def persist_checkpoint_header(self, header: BlockHeaderAPI, score: int) -> None: """ Persist a checkpoint header with a trusted score. Persisting the checkpoint header automatically sets it as the new canonical head. """ ... @abstractmethod def persist_header(self, header: BlockHeaderAPI ) -> Tuple[Tuple[BlockHeaderAPI, ...], Tuple[BlockHeaderAPI, ...]]: """ Persist the ``header`` in the database. Return two iterable of headers, the first containing the new canonical header, the second containing the old canonical headers """ ... @abstractmethod def persist_header_chain(self, headers: Sequence[BlockHeaderAPI], genesis_parent_hash: Hash32 = None, ) -> Tuple[Tuple[BlockHeaderAPI, ...], Tuple[BlockHeaderAPI, ...]]: """ Persist a chain of headers in the database. Return two iterable of headers, the first containing the new canonical headers, the second containing the old canonical headers :param genesis_parent_hash: *optional* parent hash of the block that is treated as genesis. Providing a ``genesis_parent_hash`` allows storage of headers that aren't (yet) connected back to the true genesis header. """ ... class GasMeterAPI(ABC): """ A class to define a gas meter. """ gas_refunded: int gas_remaining: int # # Write API # @abstractmethod def consume_gas(self, amount: int, reason: str) -> None: """ Consume ``amount`` of gas for a defined ``reason``. """ ... @abstractmethod def return_gas(self, amount: int) -> None: """ Return ``amount`` of gas. """ ... @abstractmethod def refund_gas(self, amount: int) -> None: """ Refund ``amount`` of gas. """ ... class MessageAPI(ABC): """ A message for VM computation. """ code: bytes _code_address: Address create_address: Address data: BytesOrView depth: int gas: int is_static: bool sender: Address should_transfer_value: bool _storage_address: Address to: Address value: int __slots__ = [ 'code', '_code_address', 'create_address', 'data', 'depth', 'gas', 'is_static', 'sender', 'should_transfer_value', '_storage_address' 'to', 'value', ] @property @abstractmethod def code_address(self) -> Address: ... @property @abstractmethod def storage_address(self) -> Address: ... @property @abstractmethod def is_create(self) -> bool: ... @property @abstractmethod def data_as_bytes(self) -> bytes: ... class OpcodeAPI(ABC): """ A class representing an opcode. """ mnemonic: str @abstractmethod def __call__(self, computation: 'ComputationAPI') -> None: """ Execute the logic of the opcode. """ ... @classmethod @abstractmethod def as_opcode(cls: Type[T], logic_fn: Callable[['ComputationAPI'], None], mnemonic: str, gas_cost: int) -> Type[T]: """ Class factory method for turning vanilla functions into Opcode classes. """ ... @abstractmethod def __copy__(self) -> 'OpcodeAPI': """ Return a copy of the opcode. """ ... @abstractmethod def __deepcopy__(self, memo: Any) -> 'OpcodeAPI': """ Return a deep copy of the opcode. """ ... class ChainContextAPI(ABC): """ Immutable chain context information that remains constant over the VM execution. """ @abstractmethod def __init__(self, chain_id: Optional[int]) -> None: """ Initialize the chain context with the given ``chain_id``. """ ... @property @abstractmethod def chain_id(self) -> int: """ Return the chain id of the chain context. """ ... class MemoryAPI(ABC): """ A class representing the memory of the :class:`~eth.abc.VirtualMachineAPI`. """ @abstractmethod def extend(self, start_position: int, size: int) -> None: """ Extend the memory from the given ``start_position`` to the provided ``size``. """ ... @abstractmethod def __len__(self) -> int: """ Return the length of the memory. """ ... @abstractmethod def write(self, start_position: int, size: int, value: bytes) -> None: """ Write `value` into memory. """ ... @abstractmethod def read(self, start_position: int, size: int) -> memoryview: """ Return a view into the memory """ ... @abstractmethod def read_bytes(self, start_position: int, size: int) -> bytes: """ Read a value from memory and return a fresh bytes instance """ ... class StackAPI(ABC): """ A class representing the stack of the :class:`~eth.abc.VirtualMachineAPI`. """ @abstractmethod def push_int(self, value: int) -> None: """ Push an integer item onto the stack. """ ... @abstractmethod def push_bytes(self, value: bytes) -> None: """ Push a bytes item onto the stack. """ ... @abstractmethod def pop1_bytes(self) -> bytes: """ Pop and return a bytes element from the stack. Raise `eth.exceptions.InsufficientStack` if the stack was empty. """ ... @abstractmethod def pop1_int(self) -> int: """ Pop and return an integer from the stack. Raise `eth.exceptions.InsufficientStack` if the stack was empty. """ ... @abstractmethod def pop1_any(self) -> Union[int, bytes]: """ Pop and return an element from the stack. The type of each element will be int or bytes, depending on whether it was pushed with push_bytes or push_int. Raise `eth.exceptions.InsufficientStack` if the stack was empty. """ ... @abstractmethod def pop_any(self, num_items: int) -> Tuple[Union[int, bytes], ...]: """ Pop and return a tuple of items of length ``num_items`` from the stack. The type of each element will be int or bytes, depending on whether it was pushed with stack_push_bytes or stack_push_int. Raise `eth.exceptions.InsufficientStack` if there are not enough items on the stack. Items are ordered with the top of the stack as the first item in the tuple. """ ... @abstractmethod def pop_ints(self, num_items: int) -> Tuple[int, ...]: """ Pop and return a tuple of integers of length ``num_items`` from the stack. Raise `eth.exceptions.InsufficientStack` if there are not enough items on the stack. Items are ordered with the top of the stack as the first item in the tuple. """ ... @abstractmethod def pop_bytes(self, num_items: int) -> Tuple[bytes, ...]: """ Pop and return a tuple of bytes of length ``num_items`` from the stack. Raise `eth.exceptions.InsufficientStack` if there are not enough items on the stack. Items are ordered with the top of the stack as the first item in the tuple. """ ... @abstractmethod def swap(self, position: int) -> None: """ Perform a SWAP operation on the stack. """ ... @abstractmethod def dup(self, position: int) -> None: """ Perform a DUP operation on the stack. """ ... class CodeStreamAPI(ABC): """ A class representing a stream of EVM code. """ program_counter: int @abstractmethod def read(self, size: int) -> bytes: """ Read and return the code from the current position of the cursor up to ``size``. """ ... @abstractmethod def __len__(self) -> int: """ Return the length of the code stream. """ ... @abstractmethod def __getitem__(self, index: int) -> int: """ Return the ordinal value of the byte at the given ``index``. """ ... @abstractmethod def __iter__(self) -> Iterator[int]: """ Iterate over all ordinal values of the bytes of the code stream. """ ... @abstractmethod def peek(self) -> int: """ Return the ordinal value of the byte at the current program counter. """ ... @abstractmethod def seek(self, program_counter: int) -> ContextManager['CodeStreamAPI']: """ Return a :class:`~typing.ContextManager` with the program counter set to ``program_counter``. """ ... @abstractmethod def is_valid_opcode(self, position: int) -> bool: """ Return ``True`` if a valid opcode exists at ``position``. """ ... class StackManipulationAPI(ABC): @abstractmethod def stack_pop_ints(self, num_items: int) -> Tuple[int, ...]: """ Pop the last ``num_items`` from the stack, returning a tuple of their ordinal values. """ ... @abstractmethod def stack_pop_bytes(self, num_items: int) -> Tuple[bytes, ...]: """ Pop the last ``num_items`` from the stack, returning a tuple of bytes. """ ... @abstractmethod def stack_pop_any(self, num_items: int) -> Tuple[Union[int, bytes], ...]: """ Pop the last ``num_items`` from the stack, returning a tuple with potentially mixed values of bytes or ordinal values of bytes. """ ... @abstractmethod def stack_pop1_int(self) -> int: """ Pop one item from the stack and return the ordinal value of the represented bytes. """ ... @abstractmethod def stack_pop1_bytes(self) -> bytes: """ Pop one item from the stack and return the value as ``bytes``. """ ... @abstractmethod def stack_pop1_any(self) -> Union[int, bytes]: """ Pop one item from the stack and return the value either as byte or the ordinal value of a byte. """ ... @abstractmethod def stack_push_int(self, value: int) -> None: """ Push ``value`` on the stack which must be a 256 bit integer. """ ... @abstractmethod def stack_push_bytes(self, value: bytes) -> None: """ Push ``value`` on the stack which must be a 32 byte string. """ ... class ComputationAPI(ContextManager['ComputationAPI'], StackManipulationAPI): """ The base class for all execution computations. """ msg: MessageAPI logger: ExtendedDebugLogger code: CodeStreamAPI opcodes: Dict[int, OpcodeAPI] = None state: 'StateAPI' return_data: bytes @abstractmethod def __init__(self, state: 'StateAPI', message: MessageAPI) -> None: """ Instantiate the computation. """ ... # # Convenience # @property @abstractmethod def is_origin_computation(self) -> bool: """ Return ``True`` if this computation is the outermost computation at ``depth == 0``. """ ... # # Error handling # @property @abstractmethod def is_success(self) -> bool: """ Return ``True`` if the computation did not result in an error. """ ... @property @abstractmethod def is_error(self) -> bool: """ Return ``True`` if the computation resulted in an error. """ ... @property @abstractmethod def error(self) -> VMError: """ Return the :class:`~eth.exceptions.VMError` of the computation. Raise ``AttributeError`` if no error exists. """ ... @error.setter def error(self, value: VMError) -> None: """ Set an :class:`~eth.exceptions.VMError` for the computation. """ # See: https://github.com/python/mypy/issues/4165 # Since we can't also decorate this with abstract method we want to be # sure that the setter doesn't actually get used as a noop. raise NotImplementedError @abstractmethod def raise_if_error(self) -> None: """ If there was an error during computation, raise it as an exception immediately. :raise VMError: """ ... @property @abstractmethod def should_burn_gas(self) -> bool: """ Return ``True`` if the remaining gas should be burned. """ ... @property @abstractmethod def should_return_gas(self) -> bool: """ Return ``True`` if the remaining gas should be returned. """ ... @property @abstractmethod def should_erase_return_data(self) -> bool: """ Return ``True`` if the return data should be zerod out due to an error. """ ... # # Memory Management # @abstractmethod def extend_memory(self, start_position: int, size: int) -> None: """ Extend the size of the memory to be at minimum ``start_position + size`` bytes in length. Raise `eth.exceptions.OutOfGas` if there is not enough gas to pay for extending the memory. """ ... @abstractmethod def memory_write(self, start_position: int, size: int, value: bytes) -> None: """ Write ``value`` to memory at ``start_position``. Require that ``len(value) == size``. """ ... @abstractmethod def memory_read(self, start_position: int, size: int) -> memoryview: """ Read and return a view of ``size`` bytes from memory starting at ``start_position``. """ ... @abstractmethod def memory_read_bytes(self, start_position: int, size: int) -> bytes: """ Read and return ``size`` bytes from memory starting at ``start_position``. """ ... # # Gas Consumption # @abstractmethod def consume_gas(self, amount: int, reason: str) -> None: """ Consume ``amount`` of gas from the remaining gas. Raise `eth.exceptions.OutOfGas` if there is not enough gas remaining. """ ... @abstractmethod def return_gas(self, amount: int) -> None: """ Return ``amount`` of gas to the available gas pool. """ ... @abstractmethod def refund_gas(self, amount: int) -> None: """ Add ``amount`` of gas to the pool of gas marked to be refunded. """ ... @abstractmethod def get_gas_refund(self) -> int: """ Return the number of refunded gas. """ ... @abstractmethod def get_gas_used(self) -> int: """ Return the number of used gas. """ ... @abstractmethod def get_gas_remaining(self) -> int: """ Return the number of remaining gas. """ ... # # Stack management # @abstractmethod def stack_swap(self, position: int) -> None: """ Swap the item on the top of the stack with the item at ``position``. """ ... @abstractmethod def stack_dup(self, position: int) -> None: """ Duplicate the stack item at ``position`` and pushes it onto the stack. """ ... # # Computation result # @property @abstractmethod def output(self) -> bytes: """ Get the return value of the computation. """ ... @output.setter def output(self, value: bytes) -> None: """ Set the return value of the computation. """ # See: https://github.com/python/mypy/issues/4165 # Since we can't also decorate this with abstract method we want to be # sure that the setter doesn't actually get used as a noop. raise NotImplementedError # # Runtime operations # @abstractmethod def prepare_child_message(self, gas: int, to: Address, value: int, data: BytesOrView, code: bytes, **kwargs: Any) -> MessageAPI: """ Helper method for creating a child computation. """ ... @abstractmethod def apply_child_computation(self, child_msg: MessageAPI) -> 'ComputationAPI': """ Apply the vm message ``child_msg`` as a child computation. """ ... @abstractmethod def generate_child_computation(self, child_msg: MessageAPI) -> 'ComputationAPI': """ Generate a child computation from the given ``child_msg``. """ ... @abstractmethod def add_child_computation(self, child_computation: 'ComputationAPI') -> None: """ Add the given ``child_computation``. """ ... # # Account management # @abstractmethod def register_account_for_deletion(self, beneficiary: Address) -> None: """ Register the address of ``beneficiary`` for deletion. """ ... @abstractmethod def get_accounts_for_deletion(self) -> Tuple[Tuple[Address, Address], ...]: """ Return a tuple of addresses that are registered for deletion. """ ... # # EVM logging # @abstractmethod def add_log_entry(self, account: Address, topics: Tuple[int, ...], data: bytes) -> None: """ Add a log entry. """ ... @abstractmethod def get_raw_log_entries(self) -> Tuple[Tuple[int, bytes, Tuple[int, ...], bytes], ...]: """ Return a tuple of raw log entries. """ ... @abstractmethod def get_log_entries(self) -> Tuple[Tuple[bytes, Tuple[int, ...], bytes], ...]: """ Return the log entries for this computation and its children. They are sorted in the same order they were emitted during the transaction processing, and include the sequential counter as the first element of the tuple representing every entry. """ ... # # State Transition # @abstractmethod def apply_message(self) -> 'ComputationAPI': """ Execution of a VM message. """ ... @abstractmethod def apply_create_message(self) -> 'ComputationAPI': """ Execution of a VM message to create a new contract. """ ... @classmethod @abstractmethod def apply_computation(cls, state: 'StateAPI', message: MessageAPI) -> 'ComputationAPI': """ Perform the computation that would be triggered by the VM message. """ ... # # Opcode API # @property @abstractmethod def precompiles(self) -> Dict[Address, Callable[['ComputationAPI'], None]]: """ Return a dictionary where the keys are the addresses of precompiles and the values are the precompile functions. """ ... @abstractmethod def get_opcode_fn(self, opcode: int) -> OpcodeAPI: """ Return the function for the given ``opcode``. """ ... class TransactionExecutorAPI(ABC): """ A class providing APIs to execute transactions on VM state. """ @abstractmethod def __init__(self, vm_state: 'StateAPI') -> None: """ Initialize the executor from the given ``vm_state``. """ ... @abstractmethod def __call__(self, transaction: SignedTransactionAPI) -> 'ComputationAPI': """ Execute the ``transaction`` and return a :class:`eth.abc.ComputationAPI`. """ ... @abstractmethod def validate_transaction(self, transaction: SignedTransactionAPI) -> None: """ Validate the given ``transaction``. Raise a ``ValidationError`` if the transaction is invalid. """ ... @abstractmethod def build_evm_message(self, transaction: SignedTransactionAPI) -> MessageAPI: """ Build and return a :class:`~eth.abc.MessageAPI` from the given ``transaction``. """ ... @abstractmethod def build_computation(self, message: MessageAPI, transaction: SignedTransactionAPI) -> 'ComputationAPI': """ Apply the ``message`` to the VM and use the given ``transaction`` to retrieve the context from. """ ... @abstractmethod def finalize_computation(self, transaction: SignedTransactionAPI, computation: 'ComputationAPI') -> 'ComputationAPI': """ Finalize the ``transaction``. """ ... class ConfigurableAPI(ABC): """ A class providing inline subclassing. """ @classmethod @abstractmethod def configure(cls: Type[T], __name__: str = None, **overrides: Any) -> Type[T]: ... class StateAPI(ConfigurableAPI): """ The base class that encapsulates all of the various moving parts related to the state of the VM during execution. Each :class:`~eth.abc.VirtualMachineAPI` must be configured with a subclass of the :class:`~eth.abc.StateAPI`. .. note:: Each :class:`~eth.abc.StateAPI` class must be configured with: - ``computation_class``: The :class:`~eth.abc.ComputationAPI` class for vm execution. - ``transaction_context_class``: The :class:`~eth.abc.TransactionContextAPI` class for vm execution. """ # # Set from __init__ # computation_class: Type[ComputationAPI] transaction_executor_class: Type[TransactionExecutorAPI] = None @abstractmethod def __init__( self, db: AtomicDatabaseAPI) -> None: """ Initialize the state. """ ... # # Block Object Properties (in opcodes) # @property @abstractmethod def coinbase(self) -> Address: """ Return the current ``coinbase`` from the current :attr:`~execution_context` """ ... @property @abstractmethod def timestamp(self) -> int: """ Return the current ``timestamp`` from the current :attr:`~execution_context` """ ... @property @abstractmethod def block_number(self) -> BlockNumber: """ Return the current ``block_number`` from the current :attr:`~execution_context` """ ... @property @abstractmethod def difficulty(self) -> int: """ Return the current ``difficulty`` from the current :attr:`~execution_context` """ ... @property @abstractmethod def gas_limit(self) -> int: """ Return the current ``gas_limit`` from the current :attr:`~transaction_context` """ ... @abstractmethod def get_storage(self, address: Address, slot: int, from_journal: bool = True) -> int: """ Return the storage at ``slot`` for ``address``. """ ... @abstractmethod def set_storage(self, address: Address, slot: int, value: int) -> None: """ Write ``value`` to the given ``slot`` at ``address``. """ ... @abstractmethod def delete_storage(self, address: Address) -> None: """ Delete the storage at ``address`` """ ... @abstractmethod def delete_account(self, address: Address) -> None: """ Delete the account at the given ``address``. """ ... @abstractmethod def get_balance(self, address: Address) -> int: """ Return the balance for the account at ``address``. """ ... @abstractmethod def set_balance(self, address: Address, balance: int) -> None: """ Set ``balance`` to the balance at ``address``. """ ... @abstractmethod def delta_balance(self, address: Address, delta: int) -> None: """ Apply ``delta`` to the balance at ``address``. """ ... @abstractmethod def get_nonce(self, address: Address) -> int: """ Return the nonce at ``address``. """ ... @abstractmethod def set_nonce(self, address: Address, nonce: int) -> None: """ Set ``nonce`` as the new nonce at ``address``. """ ... @abstractmethod def increment_nonce(self, address: Address) -> None: """ Increment the nonce at ``address``. """ ... @abstractmethod def get_code(self, address: Address) -> bytes: """ Return the code at ``address``. """ ... @abstractmethod def set_code(self, address: Address, code: bytes) -> None: """ Set ``code`` as the new code at ``address``. """ ... @abstractmethod def get_code_hash(self, address: Address) -> Hash32: """ Return the hash of the code at ``address``. """ ... @abstractmethod def delete_code(self, address: Address) -> None: """ Delete the code at ``address``. """ ... @abstractmethod def has_code_or_nonce(self, address: Address) -> bool: """ Return ``True`` if either a nonce or code exists at the given ``address``. """ ... @abstractmethod def account_exists(self, address: Address) -> bool: """ Return ``True`` if an account exists at ``address``. """ ... @abstractmethod def touch_account(self, address: Address) -> None: """ Touch the account at the given ``address``. """ ... @abstractmethod def account_is_empty(self, address: Address) -> bool: """ Return ``True`` if the account at ``address`` is empty, otherwise ``False``. """ ... # # Access self._chaindb # @abstractmethod def snapshot(self) -> Tuple[Hash32, UUID]: """ Perform a full snapshot of the current state. Snapshots are a combination of the :attr:`~state_root` at the time of the snapshot and the checkpoint from the journaled DB. """ ... @abstractmethod def revert(self, snapshot: Tuple[Hash32, UUID]) -> None: """ Revert the VM to the state at the snapshot """ ... @abstractmethod def commit(self, snapshot: Tuple[Hash32, UUID]) -> None: """ Commit the journal to the point where the snapshot was taken. This merges in any changes that were recorded since the snapshot. """ ... @abstractmethod def lock_changes(self) -> None: """ Locks in all changes to state, typically just as a transaction starts. This is used, for example, to look up the storage value from the start of the transaction, when calculating gas costs in EIP-2200: net gas metering. """ ... @abstractmethod def persist(self) -> None: """ Persist the current state to the database. """ ... # # Access self.prev_hashes (Read-only) # @abstractmethod def get_ancestor_hash(self, block_number: BlockNumber) -> Hash32: """ Return the hash for the ancestor block with number ``block_number``. Return the empty bytestring ``b''`` if the block number is outside of the range of available block numbers (typically the last 255 blocks). """ ... # # Computation # @abstractmethod def get_computation(self, message: MessageAPI) -> ComputationAPI: """ Return a computation instance for the given `message` and `transaction_context` """ ... # # Execution # @abstractmethod def apply_transaction(self, transaction: SignedTransactionAPI) -> ComputationAPI: """ Apply transaction to the vm state :param transaction: the transaction to apply :return: the computation """ ... @abstractmethod def get_transaction_executor(self) -> TransactionExecutorAPI: """ Return the transaction executor. """ ... @abstractmethod def validate_transaction(self, transaction: SignedTransactionAPI) -> None: """ Validate the given ``transaction``. """ ... class VirtualMachineAPI(ConfigurableAPI): """ The :class:`~eth.abc.VirtualMachineAPI` class represents the Chain rules for a specific protocol definition such as the Frontier or Homestead network. .. note:: Each :class:`~eth.abc.VirtualMachineAPI` class must be configured with: - ``block_class``: The :class:`~eth.abc.BlockAPI` class for blocks in this VM ruleset. - ``_state_class``: The :class:`~eth.abc.StateAPI` class used by this VM for execution. """ fork: str # noqa: E701 # flake8 bug that's fixed in 3.6.0+ extra_data_max_bytes: ClassVar[int] @abstractmethod def __init__(self) -> None: """ Initialize the virtual machine. """ ... @property @abstractmethod def state(self) -> StateAPI: """ Return the current state. """ ... @abstractmethod def build_state(self, db: AtomicDatabaseAPI, header: BlockHeaderAPI, chain_context: ChainContextAPI, previous_hashes: Iterable[Hash32] = (), ) -> StateAPI: """ You probably want `VM().state` instead of this. Occasionally, you want to build custom state against a particular header and DB, even if you don't have the VM initialized. This is a convenience method to do that. """ ... # # Execution # @abstractmethod def apply_transaction(self, transaction: SignedTransactionAPI ) -> ComputationAPI: """ Apply the transaction to the current block. This is a wrapper around :func:`~eth.vm.state.State.apply_transaction` with some extra orchestration logic. :param header: header of the block before application :param transaction: to apply """ ... @abstractmethod def execute_bytecode(self, origin: Address, gas_price: int, gas: int, to: Address, sender: Address, value: int, data: bytes, code: bytes, code_address: Address = None) -> ComputationAPI: """ Execute raw bytecode in the context of the current state of the virtual machine. """ ... @abstractmethod def apply_all_transactions( self, transactions: Sequence[SignedTransactionAPI], base_header: BlockHeaderAPI ) -> Tuple[BlockHeaderAPI, Tuple[ReceiptAPI, ...], Tuple[ComputationAPI, ...]]: """ Determine the results of applying all transactions to the base header. This does *not* update the current block or header of the VM. :param transactions: an iterable of all transactions to apply :param base_header: the starting header to apply transactions to :return: the final header, the receipts of each transaction, and the computations """ ... <file_sep>/tests/test_get_set_contract.py from pathlib import Path from typing import NamedTuple from eth_utils import ( decode_hex, encode_hex ) from scp.abc import AtomicDatabaseAPI from scp.db.atomic import AtomicDB from scp.db.backends.level import LevelDB from scp.db.chain import ChainDB from scp.tools.factories.transaction import ( new_transaction ) from scp.vm.base import VM from scp.vm.opcode_values import CALLDATALOADFUNCTION, EQ, PUSH1, JUMPI, JUMPDEST, RETURN, SSTORE, PUSH32, PUSH4, SLOAD, \ MSTORE from scp.vm.state import VMState contract_OOP_code = \ ''' contract GetSetContract { string value = "Initial "; function getValue() returns(string) { return value; } function setValue(string value) public { value = value; } } ''' contract_code = bytes([ CALLDATALOADFUNCTION, PUSH1, # jump to constructor 0x0, EQ, PUSH1, 0x1C, # dest of constuctor JUMPI, CALLDATALOADFUNCTION, PUSH4, # jump to getValue() *'2096'.encode(), EQ, PUSH1, 0x42, # dest of getValue JUMPI, CALLDATALOADFUNCTION, PUSH4, # jump to setValue(string) *'93a0'.encode(), EQ, PUSH1, 0x41, # dest of setValue(string) JUMPI, RETURN, JUMPDEST, # 26 constuctor code PUSH32, *'Hello World'.encode().rjust(32, b'\x00'), PUSH1, 0x0, SSTORE, RETURN, JUMPDEST, # 66 getValue code PUSH1, 0x0, SLOAD, PUSH1, 0x0, MSTORE, PUSH1, 0x20, PUSH1, 0x0, RETURN ]) call_get_value_code = bytes([*'2096'.encode()]) def create_test_txn(data, sender, to): Txn = NamedTuple('txn', (('data', bytes), ('sender', bytes), ('to', bytes))) return Txn(data, sender, to) def test_apply_transaction(): vm = VM() recipient = b'' amount = 0 from_ = b'' tx = create_test_txn(contract_code, from_, recipient) computation = vm.apply_transaction(tx) recipient = b'+\xea/ _\n\x1b6t\xc8\xd1\xd7\xae\xe6\xb1q"\xa2\xf7:' tx = create_test_txn(call_get_value_code, from_, recipient) computation = vm.apply_transaction(tx) assert computation.output.decode('utf-8').lstrip('\0') == 'Hello World' <file_sep>/scp/vm/state.py import contextlib from typing import ( Iterator, Tuple, Type, ) from uuid import UUID from eth_typing import ( Address, BlockNumber, Hash32, ) from eth_utils import ( ExtendedDebugLogger, get_extended_debug_logger, encode_hex, ) from eth_utils.toolz import nth from scp._utils.address import generate_contract_address from scp._utils.datatypes import ( Configurable, ) from scp.abc import ( AtomicDatabaseAPI, ComputationAPI, MessageAPI, SignedTransactionAPI, StateAPI, TransactionExecutorAPI, ) from scp.constants import ( MAX_PREV_HEADER_DEPTH, CREATE_CONTRACT_ADDRESS, ) from scp.exceptions import ContractCreationCollision from scp.vm.computation import BaseComputation from scp.vm.message import Message from scp.vm.transaction import HomesteadUnsignedTransaction class VMTransactionExecutor(TransactionExecutorAPI): def __init__(self, vm_state: StateAPI) -> None: self.vm_state = vm_state def __call__(self, transaction: SignedTransactionAPI) -> ComputationAPI: self.validate_transaction(transaction) message = self.build_evm_message(transaction) computation = self.build_computation(message, transaction) finalized_computation = self.finalize_computation(transaction, computation) return finalized_computation def validate_transaction(self, transaction: SignedTransactionAPI) -> None: # Validate the transaction # transaction.validate() self.vm_state.validate_transaction(transaction) def build_evm_message(self, transaction: SignedTransactionAPI) -> MessageAPI: # Increment Nonce # self.vm_state.increment_nonce(transaction.sender) if transaction.to == CREATE_CONTRACT_ADDRESS: contract_address = generate_contract_address( transaction.sender, # self.vm_state.get_nonce(transaction.sender) - 1, 1 ) data = b'' code = transaction.data self.vm_state.set_code(contract_address, transaction.data) else: contract_address = None data = transaction.data code = self.vm_state.get_code(transaction.to) message = Message( gas=1, to=transaction.to, sender=transaction.sender, value=0, data=data, code=code, create_address=contract_address, ) return message def build_computation(self, message: MessageAPI, transaction: SignedTransactionAPI) -> ComputationAPI: if message.is_create: is_collision = self.vm_state.has_code_or_nonce( message.storage_address ) if is_collision: # The address of the newly created contract has *somehow* collided # with an existing contract address. computation = self.vm_state.get_computation(message) computation.error = ContractCreationCollision( f"Address collision while creating contract: " f"{encode_hex(message.storage_address)}" ) self.vm_state.logger.debug2( "Address collision while creating contract: %s", encode_hex(message.storage_address), ) else: computation = self.vm_state.get_computation( message ).apply_create_message() else: computation = self.vm_state.get_computation( message).apply_message() return computation def finalize_computation(self, transaction: SignedTransactionAPI, computation: ComputationAPI) -> ComputationAPI: return computation class VMState(Configurable, StateAPI): # # Set from __init__ # __slots__ = ['_db', 'execution_context', '_account_db'] computation_class: Type[ComputationAPI] = BaseComputation transaction_executor_class: Type[TransactionExecutorAPI] = VMTransactionExecutor def __init__(self) -> None: self._account_db = { } self._account_storage = { b'+\xea/ _\n\x1b6t\xc8\xd1\xd7\xae\xe6\xb1q"\xa2\xf7:': { } } def apply_transaction(self, transaction: SignedTransactionAPI) -> ComputationAPI: executor = self.get_transaction_executor() return executor(transaction) def validate_transaction(self, transaction: SignedTransactionAPI) -> None: pass # # Logging # @property def logger(self) -> ExtendedDebugLogger: return get_extended_debug_logger(f'eth.vm.state.{self.__class__.__name__}') # # Block Object Properties (in opcodes) # @property def coinbase(self) -> Address: return self.execution_context.coinbase @property def timestamp(self) -> int: return self.execution_context.timestamp @property def block_number(self) -> BlockNumber: return self.execution_context.block_number @property def difficulty(self) -> int: return self.execution_context.difficulty @property def gas_limit(self) -> int: return self.execution_context.gas_limit # # Access to account db # @property def state_root(self) -> Hash32: return self._account_db.state_root def make_state_root(self) -> Hash32: return self._account_db.make_state_root() def get_storage(self, address: Address, slot: int, from_journal: bool = True) -> int: storage = self._account_storage.get(address) return storage.get(slot) def set_storage(self, address: Address, slot: int, value: int) -> None: storage = self._account_storage.get(address) storage[slot] = value def delete_storage(self, address: Address) -> None: self._account_db.delete_storage(address) def delete_account(self, address: Address) -> None: self._account_db.delete_account(address) def get_balance(self, address: Address) -> int: return self._account_db.get_balance(address) def set_balance(self, address: Address, balance: int) -> None: self._account_db.set_balance(address, balance) def delta_balance(self, address: Address, delta: int) -> None: self.set_balance(address, self.get_balance(address) + delta) def get_nonce(self, address: Address) -> int: return self._account_db.get_nonce(address) def set_nonce(self, address: Address, nonce: int) -> None: self._account_db.set_nonce(address, nonce) def increment_nonce(self, address: Address) -> None: self._account_db.increment_nonce(address) def get_code(self, address: Address) -> bytes: return self._account_db.get(address) def set_code(self, address: Address, code: bytes) -> None: self._account_db[address] = code def get_code_hash(self, address: Address) -> Hash32: return self._account_db.get_code_hash(address) def delete_code(self, address: Address) -> None: self._account_db.delete_code(address) def has_code_or_nonce(self, address: Address) -> bool: # return self._account_db.account_has_code_or_nonce(address) return False def account_exists(self, address: Address) -> bool: return self._account_db.account_exists(address) def touch_account(self, address: Address) -> None: self._account_db.touch_account(address) def account_is_empty(self, address: Address) -> bool: return self._account_db.account_is_empty(address) # # Access self._chaindb # def snapshot(self) -> Tuple[Hash32, UUID]: return self.state_root, self._account_db.record() def revert(self, snapshot: Tuple[Hash32, UUID]) -> None: state_root, account_snapshot = snapshot # first revert the database state root. self._account_db.state_root = state_root # now roll the underlying database back self._account_db.discard(account_snapshot) def commit(self, snapshot: Tuple[Hash32, UUID]) -> None: _, account_snapshot = snapshot self._account_db.commit(account_snapshot) def lock_changes(self) -> None: self._account_db.lock_changes() def persist(self) -> None: self._account_db.persist() # # Access self.prev_hashes (Read-only) # def get_ancestor_hash(self, block_number: int) -> Hash32: ancestor_depth = self.block_number - block_number - 1 is_ancestor_depth_out_of_range = ( ancestor_depth >= MAX_PREV_HEADER_DEPTH or ancestor_depth < 0 or block_number < 0 ) if is_ancestor_depth_out_of_range: return Hash32(b'') try: return nth(ancestor_depth, self.execution_context.prev_hashes) except StopIteration: # Ancestor with specified depth not present return Hash32(b'') # # Computation # def get_computation(self, message: MessageAPI) -> ComputationAPI: if self.computation_class is None: raise AttributeError("No `computation_class` has been set for this State") else: computation = self.computation_class(self, message) return computation # # Execution # def get_transaction_executor(self) -> TransactionExecutorAPI: return self.transaction_executor_class(self) @classmethod def create_unsigned_transaction(cls, *, nonce: int, gas_price: int, gas: int, to: Address, value: int, data: bytes) -> 'HomesteadUnsignedTransaction': return HomesteadUnsignedTransaction(nonce, gas_price, gas, to, value, data) <file_sep>/scp/vm/spoof.py from typing import Any, Union from scp._utils.spoof import SpoofAttributes from scp.abc import SignedTransactionAPI, UnsignedTransactionAPI class SpoofTransaction(SpoofAttributes): def __init__(self, transaction: Union[SignedTransactionAPI, UnsignedTransactionAPI], **overrides: Any) -> None: super().__init__(transaction, **overrides) <file_sep>/scp/indy_constants.py from scp.indy_transaction import ContractTransactions CONTRACT_LEDGER_ID = 2005 CONTRACT_INVOKE = ContractTransactions.CONTRACT_INVOKE.value<file_sep>/scp/vm/base.py import logging from typing import ( Any, ClassVar, Iterable, Sequence, Tuple, Type, ) from eth_typing import ( Address, Hash32, ) from eth_utils import ( ValidationError, ) from scp._utils.datatypes import ( Configurable, ) from scp.abc import ( AtomicDatabaseAPI, BlockHeaderAPI, ChainContextAPI, ComputationAPI, ReceiptAPI, SignedTransactionAPI, StateAPI, UnsignedTransactionAPI, VirtualMachineAPI, ) from scp.vm.interrupt import ( EVMMissingData, ) from scp.vm.message import ( Message, ) from scp.vm.state import VMState class VM(Configurable, VirtualMachineAPI): extra_data_max_bytes: ClassVar[int] = 32 fork: str = None # noqa: E701 # flake8 bug that's fixed in 3.6.0+ _state_class: Type[StateAPI] = VMState _state = None _block = None cls_logger = logging.getLogger('eth.vm.base.VM') def __init__(self) -> None: pass @property def state(self) -> StateAPI: if self._state is None: self._state = self.build_state() return self._state @classmethod def build_state(self) -> StateAPI: return self._state_class() # # Execution # def apply_transaction(self, transaction) -> ComputationAPI: computation = self.state.apply_transaction(transaction) return computation def execute_bytecode(self, origin: Address, gas_price: int, gas: int, to: Address, sender: Address, value: int, data: bytes, code: bytes, code_address: Address = None, ) -> ComputationAPI: if origin is None: origin = sender # Construct a message message = Message( gas=gas, to=to, sender=sender, value=value, data=data, code=code, code_address=code_address, ) # Construction a tx context transaction_context = self.state.get_transaction_context_class()( gas_price=gas_price, origin=origin, ) # Execute it in the VM return self.state.get_computation(message, transaction_context).apply_computation( self.state, message, transaction_context, ) def apply_all_transactions( self, transactions: Sequence[SignedTransactionAPI], base_header: BlockHeaderAPI ) -> Tuple[BlockHeaderAPI, Tuple[ReceiptAPI, ...], Tuple[ComputationAPI, ...]]: if base_header.block_number != self.get_header().block_number: raise ValidationError( f"This VM instance must only work on block #{self.get_header().block_number}, " f"but the target header has block #{base_header.block_number}" ) receipts = [] computations = [] previous_header = base_header result_header = base_header for transaction in transactions: try: snapshot = self.state.snapshot() receipt, computation = self.apply_transaction( previous_header, transaction, ) except EVMMissingData as exc: self.state.revert(snapshot) raise result_header = self.add_receipt_to_header(previous_header, receipt) previous_header = result_header receipts.append(receipt) computations.append(computation) receipts_tuple = tuple(receipts) computations_tuple = tuple(computations) return result_header, receipts_tuple, computations_tuple # # Transactions # def create_transaction(self, *args: Any, **kwargs: Any) -> SignedTransactionAPI: return self.get_transaction_class()(*args, **kwargs) @classmethod def create_unsigned_transaction(cls, *, nonce: int, gas_price: int, gas: int, to: Address, value: int, data: bytes) -> UnsignedTransactionAPI: return cls.get_transaction_class().create_unsigned_transaction( nonce=nonce, gas_price=gas_price, gas=gas, to=to, value=value, data=data ) <file_sep>/scp/request_handlers/contract_request_handler.py from typing import NamedTuple from eth_utils import decode_hex from indy_node.server.request_handlers.action_req_handlers.utils import generate_action_result from plenum.common.txn_util import get_request_data from indy_common.authorize.auth_actions import AuthActionAdd from indy_common.authorize.auth_request_validator import WriteRequestValidator from plenum.server.database_manager import DatabaseManager from plenum.server.request_handlers.handler_interfaces.action_request_handler import ActionRequestHandler from plenum.common.request import Request from scp.indy_constants import CONTRACT_LEDGER_ID, CONTRACT_INVOKE from scp.vm.base import VM class ContractRequestHandler(ActionRequestHandler): def __init__(self, database_manager: DatabaseManager, write_req_validator: WriteRequestValidator, virtual_machine: VM ): super().__init__(database_manager, CONTRACT_INVOKE, CONTRACT_LEDGER_ID) self.write_req_validator = write_req_validator self.virtual_machine = virtual_machine def static_validation(self, request: Request): pass def dynamic_validation(self, request: Request): self._validate_request_type(request) self.write_req_validator.validate(request, [AuthActionAdd(txn_type=CONTRACT_INVOKE, field='*', value='*')]) def process_action(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) Txn = NamedTuple('txn', (('data', bytes), ('sender', bytes), ('to', bytes))) txn = Txn(decode_hex(operation['contract_code']), identifier, operation['contract_dest']) computation = self.virtual_machine.apply_transaction(txn) result = generate_action_result(request) # result[DATA] = self.info_tool.info return result <file_sep>/tests/test_vm.py from pathlib import Path import pytest from eth_utils import ( decode_hex, ValidationError, ) from scp import constants from scp.abc import AtomicDatabaseAPI, ConsensusContextAPI from scp.db.backends.level import LevelDB from scp.db.chain import ChainDB from scp.tools.factories.transaction import ( new_transaction ) from scp.vm.chain_context import ChainContext from scp.vm.forks import HomesteadVM class ConsensusContext(ConsensusContextAPI): def __init__(self, db: AtomicDatabaseAPI): self.db = db def test_apply_transaction(): db = LevelDB(Path('/home/alice/dev/level_db')) vm = HomesteadVM(None, ChainDB(db), ChainContext(None), ConsensusContext(db)) recipient = b'1' * 20 amount = 0 from_ = '' # tx = new_transaction(vm, from_, recipient, amount, b'', data=decode_hex('6d4c')) tx = new_transaction(vm, from_, recipient, amount, b'', data=b'ce6d4') receipt, computation = vm.apply_transaction(vm.get_header(), tx) a = 10 <file_sep>/scp/request_handlers/contract_batch_hanlder.py from plenum.server.batch_handlers.batch_request_handler import BatchRequestHandler from plenum.server.database_manager import DatabaseManager from scp.indy_constants import CONTRACT_LEDGER_ID class ContractBatchHandler(BatchRequestHandler): def __init__(self, database_manager: DatabaseManager): super().__init__(database_manager, CONTRACT_LEDGER_ID) def post_batch_applied(self, three_pc_batch, prev_handler_result=None): pass def post_batch_rejected(self, ledger_id, prev_handler_result=None): pass <file_sep>/tests/conftest.py import json from plenum.client.wallet import Wallet from plenum.common.constants import STEWARD, TARGET_NYM, TRUSTEE_STRING, VERKEY from plenum.common.txn_util import get_seq_no from sovtoken.util import \ update_token_wallet_with_result from sovtoken.constants import RESULT from sovtoken.test.wallet import TokenWallet from plenum.test.conftest import get_data_for_role, get_payload_data from sovtoken.test.helper import send_get_utxo, send_xfer from sovtoken.test.helpers import form_helpers, libloader from indy_common.test.conftest import tconf as _tconf from indy_node.test.conftest import * from indy.did import create_and_store_my_did from indy.ledger import build_nym_request, sign_and_submit_request from scp.main import integrate_plugin_in_node total_mint = 100 seller_gets = 40 # def build_wallets_from_data(name_seeds, looper, pool_name): def build_wallets_from_data(name_seeds): wallets = [] for name, seed in name_seeds: # wallet_handle = looper.loop.run_until_complete( # _gen_wallet_handler(pool_name, name)) # looper.loop.run_until_complete( # create_and_store_my_did(wallet_handle, # json.dumps({'seed': seed}))) # wallets.append(wallet_handle) w = Wallet(name) w.addIdentifier(seed=seed.encode()) wallets.append(w) return wallets @pytest.fixture(scope="module") def tconf(_tconf): oldMax3PCBatchSize = _tconf.Max3PCBatchSize oldMax3PCBatchWait = _tconf.Max3PCBatchWait _tconf.Max3PCBatchSize = 1000 _tconf.Max3PCBatchWait = 1 yield _tconf _tconf.Max3PCBatchSize = oldMax3PCBatchSize _tconf.Max3PCBatchWait = oldMax3PCBatchWait @pytest.fixture(scope="module") def SF_token_wallet(): return TokenWallet('SF_MASTER') @pytest.fixture(scope="module") def SF_address(SF_token_wallet): seed = 'sf000000000000000000000000000000'.encode() SF_token_wallet.add_new_address(seed=seed) return next(iter(SF_token_wallet.addresses.keys())) @pytest.fixture(scope="module") def seller_token_wallet(): return TokenWallet('SELLER') @pytest.fixture(scope="module") def seller_address(seller_token_wallet): # Token selling/buying platform's address seed = 'se000000000000000000000000000000'.encode() seller_token_wallet.add_new_address(seed=seed) return next(iter(seller_token_wallet.addresses.keys())) @pytest.fixture(scope="module") def trustee_wallets(trustee_data, looper, sdk_pool_data): return build_wallets_from_data(trustee_data) @pytest.fixture(scope="module") def steward_wallets(poolTxnData): steward_data = get_data_for_role(poolTxnData, STEWARD) return build_wallets_from_data(steward_data) @pytest.fixture(scope="module") def sdk_trustees(looper, sdk_wallet_handle, trustee_data): trustees = [] for _, trustee_seed in trustee_data: did_future = create_and_store_my_did(sdk_wallet_handle, json.dumps({"seed": trustee_seed})) did, _ = looper.loop.run_until_complete(did_future) trustees.append(did) return trustees @pytest.fixture(scope="module") def sdk_wallet_trustee(sdk_wallet_handle, sdk_trustees): return sdk_wallet_handle, sdk_trustees[0] @pytest.fixture(scope="module") def sdk_stewards(looper, sdk_wallet_handle, poolTxnData): stewards = [] pool_txn_stewards_data = get_data_for_role(poolTxnData, STEWARD) for _, steward_seed in pool_txn_stewards_data: did_future = create_and_store_my_did(sdk_wallet_handle, json.dumps({"seed": steward_seed})) did, _ = looper.loop.run_until_complete(did_future) stewards.append(did) return stewards @pytest.fixture(scope="module") def sdk_wallet_steward(sdk_wallet_handle, sdk_stewards): return sdk_wallet_handle, sdk_stewards[0] @pytest.fixture(scope="module") def nodeSetWithIntegratedContractPlugin(do_post_node_creation, tconf, nodeSet): return nodeSet @pytest.fixture(scope='module') def helpers( nodeSetWithIntegratedContractPlugin, looper, sdk_pool_handle, trustee_wallets, steward_wallets, sdk_wallet_client, sdk_wallet_handle, sdk_trustees, sdk_stewards ): return form_helpers( nodeSetWithIntegratedContractPlugin, looper, sdk_pool_handle, trustee_wallets, steward_wallets, sdk_wallet_client, (sdk_wallet_handle, sdk_stewards[0]), sdk_wallet_handle, sdk_trustees, sdk_stewards ) @pytest.fixture(scope="module") def do_post_node_creation(): # Integrate plugin into each node. def _post_node_creation(node): integrate_plugin_in_node(node) return _post_node_creation <file_sep>/README.md # indy-scp indy-scp - indy smart contract plugin *Work in progress* Integrating Ethereum virtual machine into Hyperledger Indy. Details of VM implementation was taken from https://github.com/ethereum/py-evm <file_sep>/.flake8 [flake8] ignore = N801, N802, N803, N806, N813, C901, E501, F401 exclude = # common places .git,__pycache__,docs/source/conf.py,old,build,dist,.eggs max-complexity = 10 <file_sep>/scp/vm/transaction.py from eth_keys.datatypes import PrivateKey from eth_typing import Address from eth_utils import ValidationError from rlp.sedes import big_endian_int, binary from scp._utils.transactions import create_transaction_signature, validate_transaction_signature, \ extract_transaction_sender from scp.abc import UnsignedTransactionAPI, SignedTransactionAPI from scp.constants import CREATE_CONTRACT_ADDRESS from scp.rlp.sedes import address from scp.rlp.transactions import BaseTransactionMethods, BASE_TRANSACTION_FIELDS, BaseTransactionFields from scp.tools import rlp from scp.validation import validate_uint256, validate_is_integer, validate_canonical_address, validate_is_bytes, \ validate_lt_secpk1n, validate_gte, validate_lte, validate_lt_secpk1n2 class BaseUnsignedTransaction(BaseTransactionMethods, UnsignedTransactionAPI): fields = [ ('nonce', big_endian_int), ('gas_price', big_endian_int), ('gas', big_endian_int), ('to', address), ('value', big_endian_int), ('data', binary), ] class BaseTransaction(BaseTransactionFields, BaseTransactionMethods, SignedTransactionAPI): # noqa: E501 # this is duplicated to make the rlp library happy, otherwise it complains # about no fields being defined but inheriting from multiple `Serializable` # bases. fields = BASE_TRANSACTION_FIELDS @classmethod def from_base_transaction(cls, transaction): return rlp.decode(rlp.encode(transaction), sedes=cls) def sender(self) -> Address: return self.get_sender() # +-------------------------------------------------------------+ # | API that must be implemented by all Transaction subclasses. | # +-------------------------------------------------------------+ # # Validation # def validate(self) -> None: if self.gas < self.intrinsic_gas: raise ValidationError("Insufficient gas") self.check_signature_validity() # # Signature and Sender # @property def is_signature_valid(self) -> bool: try: self.check_signature_validity() except ValidationError: return False else: return True class FrontierTransaction(BaseTransaction): @property def v_min(self) -> int: return 27 @property def v_max(self) -> int: return 28 def validate(self) -> None: validate_uint256(self.nonce, title="Transaction.nonce") validate_uint256(self.gas_price, title="Transaction.gas_price") validate_uint256(self.gas, title="Transaction.gas") if self.to != CREATE_CONTRACT_ADDRESS: validate_canonical_address(self.to, title="Transaction.to") validate_uint256(self.value, title="Transaction.value") validate_is_bytes(self.data, title="Transaction.data") validate_uint256(self.v, title="Transaction.v") validate_uint256(self.r, title="Transaction.r") validate_uint256(self.s, title="Transaction.s") validate_lt_secpk1n(self.r, title="Transaction.r") validate_gte(self.r, minimum=1, title="Transaction.r") validate_lt_secpk1n(self.s, title="Transaction.s") validate_gte(self.s, minimum=1, title="Transaction.s") validate_gte(self.v, minimum=self.v_min, title="Transaction.v") validate_lte(self.v, maximum=self.v_max, title="Transaction.v") super().validate() def check_signature_validity(self) -> None: validate_transaction_signature(self) def get_sender(self) -> Address: return extract_transaction_sender(self) # def get_intrinsic_gas(self) -> int: # return frontier_get_intrinsic_gas(self) def get_message_for_signing(self) -> bytes: return rlp.encode(FrontierUnsignedTransaction( nonce=self.nonce, gas_price=self.gas_price, gas=self.gas, to=self.to, value=self.value, data=self.data, )) @classmethod def create_unsigned_transaction(cls, *, nonce: int, gas_price: int, gas: int, to: Address, value: int, data: bytes) -> 'FrontierUnsignedTransaction': return FrontierUnsignedTransaction(nonce, gas_price, gas, to, value, data) class FrontierUnsignedTransaction(BaseUnsignedTransaction): def validate(self) -> None: validate_uint256(self.nonce, title="Transaction.nonce") validate_is_integer(self.gas_price, title="Transaction.gas_price") validate_uint256(self.gas, title="Transaction.gas") if self.to != CREATE_CONTRACT_ADDRESS: validate_canonical_address(self.to, title="Transaction.to") validate_uint256(self.value, title="Transaction.value") validate_is_bytes(self.data, title="Transaction.data") super().validate() def as_signed_transaction(self, private_key: PrivateKey): v, r, s = create_transaction_signature(self, private_key) return FrontierTransaction( nonce=self.nonce, gas_price=self.gas_price, gas=self.gas, to=self.to, value=self.value, data=self.data, v=v, r=r, s=s, ) # def get_intrinsic_gas(self) -> int: # return frontier_get_intrinsic_gas(self) class HomesteadTransaction(FrontierTransaction): def validate(self) -> None: super().validate() validate_lt_secpk1n2(self.s, title="Transaction.s") # def get_intrinsic_gas(self) -> int: # return homestead_get_intrinsic_gas(self) def get_message_for_signing(self) -> bytes: return rlp.encode(HomesteadUnsignedTransaction( nonce=self.nonce, gas_price=self.gas_price, gas=self.gas, to=self.to, value=self.value, data=self.data, )) @classmethod def create_unsigned_transaction(cls, *, nonce: int, gas_price: int, gas: int, to: Address, value: int, data: bytes) -> 'HomesteadUnsignedTransaction': return HomesteadUnsignedTransaction(nonce, gas_price, gas, to, value, data) class HomesteadUnsignedTransaction(FrontierUnsignedTransaction): def as_signed_transaction(self, private_key: PrivateKey) -> HomesteadTransaction: v, r, s = create_transaction_signature(self, private_key) return HomesteadTransaction( nonce=self.nonce, gas_price=self.gas_price, gas=self.gas, to=self.to, value=self.value, data=self.data, v=v, r=r, s=s, ) def get_intrinsic_gas(self) -> int: pass <file_sep>/scp/vm/logic/block.py from scp.abc import ComputationAPI def blockhash(computation: ComputationAPI) -> None: block_number = computation.stack_pop1_int() block_hash = computation.state.get_ancestor_hash(block_number) computation.stack_push_bytes(block_hash) def coinbase(computation: ComputationAPI) -> None: computation.stack_push_bytes(computation.state.coinbase) def timestamp(computation: ComputationAPI) -> None: computation.stack_push_int(computation.state.timestamp) def number(computation: ComputationAPI) -> None: computation.stack_push_int(computation.state.block_number) def difficulty(computation: ComputationAPI) -> None: computation.stack_push_int(computation.state.difficulty) def gaslimit(computation: ComputationAPI) -> None: computation.stack_push_int(computation.state.gas_limit) <file_sep>/scp/vm/logic/sha3.py from eth_hash.auto import keccak from scp import constants from scp._utils.numeric import ( ceil32, ) from scp.abc import ComputationAPI def sha3(computation: ComputationAPI) -> None: start_position, size = computation.stack_pop_ints(2) computation.extend_memory(start_position, size) sha3_bytes = computation.memory_read_bytes(start_position, size) word_count = ceil32(len(sha3_bytes)) // 32 gas_cost = constants.GAS_SHA3WORD * word_count computation.consume_gas(gas_cost, reason="SHA3: word gas cost") result = keccak(sha3_bytes) computation.stack_push_bytes(result)
c0e1419573a906e512f66ef74168b6c3d1e66398
[ "Markdown", "Python", "INI" ]
18
Python
ArtObr/indy-scp
831eb68e36ea8bd4a2d60d62a1a46f1e71df54c5
1545967cd6a67c379d82193ad2a7dd7e0e41905a
refs/heads/master
<repo_name>walid-chekkouri/QuickSort-and-MergeSort-in-Cpp<file_sep>/QuickSort.cpp #include <string> #include <iostream> using namespace std; void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } int partition(int arr[], int l, int h) { int pivot = arr[l]; int i = l, j =h; do { do { i++; } while (arr[i] <= pivot); do { j--; } while (arr[j] > pivot); if (i < j)swap(&arr[i], &arr[j]); } while (i<j); swap(&arr[l], &arr[j]); return j; } void quickSort(int arr[], int l, int h) { if (l < h) { int j = partition(arr, l, h); quickSort(arr, l, j); quickSort(arr, j+1, h); } } void display(int arr[], const int N) { for (int i = 0; i < N; i++) { cout << arr[i] << endl; } } int main() { int arr[] = {90,13,7,12,16,9,24,5,10,1}; const int N = 10; quickSort(arr, 0, N); display(arr, N); system("pause"); return 0; }<file_sep>/MergeSort.cpp #include <string> #include <iostream> using namespace std; void merge(int arr[], int l, int mid, int h) { int i=l, j=mid+1, k=l; int arr2[100]; while (i <= mid && j <= h) { if (arr[i] < arr[j]) arr2[k++] = arr[i++]; else arr2[k++] = arr[j++]; } for (; i <= mid; i++) arr2[k++] = arr[i]; for (; j <= h; j++) arr2[k++] = arr[j]; for (int i = l; i <= h; i++) arr[i] = arr2[i]; } void mergeSort(int arr[], int l, int r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h //int m = l + (r - l) / 2; int m =( l + r ) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } } void display(int arr[], const int N) { for (int i = 0; i < N; i++) { cout << arr[i] << endl; } } int main() { int arr[] = {10,9,8,7,6,5,4,3,2,1}; const int N = 10; mergeSort(arr, 0, N-1); display(arr, N); system("pause"); return 0; }
94000a8c5f03ea3f5a998d9ddeba2aad4bddbdca
[ "C++" ]
2
C++
walid-chekkouri/QuickSort-and-MergeSort-in-Cpp
a4556e3ad6f3b6ca4dff7b8e44ac70c9bcd38ddb
48dde0aca0f1ecdfd1ab2667b15b1e6cb28215c2
refs/heads/master
<file_sep>import React, {useState} from 'react'; import GridProductos from './components/GridProductos'; const ListaProductos = () => { const [searchValue, setSearchValue] = useState(''); return ( <GridProductos searchValue={searchValue} setSearchValue={setSearchValue}></GridProductos> ) } export default ListaProductos;<file_sep>import React from 'react'; const CrearProducto = () => { return(<div>Crear producto</div>) }; export default CrearProducto;<file_sep>const INITIAL_STATE = { productosNotf: 0, facturasNotf: 0, userNotf: 0 } const reducer = (state = INITIAL_STATE, action) => { switch (action.type) { case 'get_productos_notf': return { ...state, productosNotf: action.payload }; case 'get_factura_notf': return { ...state, facturasNotf: action.payload }; case 'get_user_notf': return { ...state, userNotf: action.payload }; default: return state; } } export default reducer;<file_sep>import React, { useState } from 'react'; import Paper from '@material-ui/core/Paper'; import { SearchState, IntegratedFiltering, } from '@devexpress/dx-react-grid'; import { Grid, Table, Toolbar, SearchPanel, TableHeaderRow, } from '@devexpress/dx-react-grid-material-ui'; const GridProductos = ({ searchValue, setSearchValue }) => { const [columns] = useState([ { name: 'nombre', title: 'Nombre' }, { name: 'descripcion', title: 'Description' }, { name: 'precio_unitario', title: 'Precio/U' }, { name: 'disponible', title: 'Disponible' }, { name: 'opciones', title: 'Opciones' } ]); const [data, setData] = useState([ { nombre: 'Balón', descripcion: 'Balón de futbol', precio_unitario: 5000, disponible: 2 }, { nombre: 'Mesa', descripcion: 'Mesa de billar', precio_unitario: 20000, disponible: 3 }, { nombre: 'Abrigo', descripcion: 'Abrigo de invierno', precio_unitario: 20000, disponible: 1 } ]); return ( <Paper> <Grid rows={data} columns={columns} > <SearchState value={searchValue} onValueChange={setSearchValue} /> <IntegratedFiltering /> <Table /> <TableHeaderRow /> <Toolbar /> <SearchPanel /> </Grid> </Paper> ) }; export default GridProductos;<file_sep>import React, { useState } from 'react'; import Paper from '@material-ui/core/Paper'; import { SearchState, IntegratedFiltering, } from '@devexpress/dx-react-grid'; import { Grid, Table, Toolbar, SearchPanel, TableHeaderRow, } from '@devexpress/dx-react-grid-material-ui'; const GridProductos = ({ searchValue, setSearchValue }) => { const [columns] = useState([ { name: 'vendedor', title: 'Vendedor' }, { name: 'cliente', title: 'Cliente' }, { name: 'codigo', title: 'Código' }, { name: 'estado', title: 'Estado' }, { name: 'fechaRegistro', title: 'Fecha de Registro' }, { name: 'fechaCompra', title: 'Fecha de Compra' }, { name: 'totalProductos', title: 'Total Productos Comprados' }, { name: 'valorTotalIVA', title: 'Valor Total IVA' }, { name: 'valorTotal', title: 'Valor Total' }, { name: 'opciones', title: 'Opciones' } ]); const opciones = ( [<button>Anular</button>, <button>MostrarPDF</button>]) const [data, setData] = useState([ { vendedor: '<NAME>', cliente: '<NAME>', codigo: '36B', estado: 'HABILITADA', fechaRegistro: '16/01/2020', fechaCompra: '16/01/2020', totalProductos: 30, valorTotalIVA: 300, valorTotal: 400, opciones: opciones }, { vendedor: '<NAME>', descripcion: '<NAME>', codigo: '37B', estado: 'ANULADA', fechaRegistro: '02/10/2020', fechaCompra: '16/01/2020', totalProductos: 30, valorTotalIVA: 300, valorTotal: 300, opciones: opciones }, { vendedor: '<NAME>', descripcion: '<NAME>', codigo: '36A', estado: 'HABILITADA', fechaRegistro: '24/12/2020', fechaCompra: '24/12/2020', totalProductos: 30, valorTotalIVA: 300, valorTotal: 800, opciones: opciones } ]); return ( <Paper> <Grid rows={data} columns={columns} > <SearchState value={searchValue} onValueChange={setSearchValue} /> <IntegratedFiltering /> <Table /> <TableHeaderRow /> <Toolbar /> <SearchPanel /> </Grid> </Paper> ) }; export default GridProductos;
e6f372128a562e4af348393ecbe29731fafbc64c
[ "JavaScript" ]
5
JavaScript
juancsr/facturacion-front-end
8bff2b692d0a5c6cdb57255381041230017b5097
61729afe63d1da0b867c27ab3079a844468af851
refs/heads/master
<repo_name>BayBenj/rhyme-scorer<file_sep>/tables/VowelTables.java package tables; import java.io.Serializable; import java.util.List; public class VowelTables implements Serializable { public HeightTable heightTable; public FrontnessTable frontnessTable; public RoundnessTable roundnessTable; public TensionTable tensionTable; public StressTable stressTable; public VowelTables(HeightTable heightTable, FrontnessTable frontnessTable, RoundnessTable roundnessTable, TensionTable tensionTable, StressTable stressTable) { this.heightTable = heightTable; this.frontnessTable = frontnessTable; this.roundnessTable = roundnessTable; this.tensionTable = tensionTable; this.stressTable = stressTable; } public static void printLogLikelihoods(VowelTables randoms, VowelTables rhymes) { System.out.println("\n\nLog-Likelihoods"); System.out.println("\nHeight"); HeightTable.printLogLikelihood(randoms.heightTable, rhymes.heightTable); System.out.println("\nFrontness"); FrontnessTable.printLogLikelihood(randoms.frontnessTable, rhymes.frontnessTable); System.out.println("\nRoundess"); RoundnessTable.printLogLikelihood(randoms.roundnessTable, rhymes.roundnessTable); System.out.println("\nTension"); TensionTable.printLogLikelihood(randoms.tensionTable, rhymes.tensionTable); System.out.println("\nStress"); StressTable.printLogLikelihood(randoms.stressTable, rhymes.stressTable); } public static VowelTables getLogLikelihoodTables(VowelTables randoms, VowelTables rhymes) { //height HeightTable ll_heightTable = new HeightTable(); for (int i = 0; i < randoms.heightTable.get_i_size(); i++) { List<Double> list = ll_heightTable.get(i); for (int j = 0; j < randoms.heightTable.get_j_size(); j++) { if (i <= j) list.set(j, ProbabilityTable.computeLogLikelihood((int)randoms.heightTable.cell(i,j), randoms.heightTable.total(),(int)rhymes.heightTable.cell(i,j),rhymes.heightTable.total())); } } //frontness FrontnessTable ll_frontnessTable = new FrontnessTable(); for (int i = 0; i < randoms.frontnessTable.get_i_size(); i++) { List<Double> list = ll_frontnessTable.get(i); for (int j = 0; j < randoms.frontnessTable.get_j_size(); j++) { if (i <= j) list.set(j, ProbabilityTable.computeLogLikelihood((int)randoms.frontnessTable.cell(i,j), randoms.frontnessTable.total(),(int)rhymes.frontnessTable.cell(i,j),rhymes.frontnessTable.total())); } } //roundness RoundnessTable ll_roundnessTable = new RoundnessTable(); for (int i = 0; i < randoms.roundnessTable.get_i_size(); i++) { List<Double> list = ll_roundnessTable.get(i); for (int j = 0; j < randoms.roundnessTable.get_j_size(); j++) { if (i <= j) list.set(j, ProbabilityTable.computeLogLikelihood((int)randoms.roundnessTable.cell(i,j), randoms.roundnessTable.total(),(int)rhymes.roundnessTable.cell(i,j),rhymes.roundnessTable.total())); } } //tension TensionTable ll_tensionTable = new TensionTable(); for (int i = 0; i < randoms.tensionTable.get_i_size(); i++) { List<Double> list = ll_tensionTable.get(i); for (int j = 0; j < randoms.tensionTable.get_j_size(); j++) { if (i <= j) list.set(j, ProbabilityTable.computeLogLikelihood((int)randoms.tensionTable.cell(i,j), randoms.tensionTable.total(),(int)rhymes.tensionTable.cell(i,j),rhymes.tensionTable.total())); } } //stress StressTable ll_stressTable = new StressTable(); for (int i = 0; i < randoms.stressTable.get_i_size(); i++) { List<Double> list = ll_stressTable.get(i); for (int j = 0; j < randoms.stressTable.get_j_size(); j++) { if (i <= j) list.set(j, ProbabilityTable.computeLogLikelihood((int)randoms.stressTable.cell(i,j), randoms.stressTable.total(),(int)rhymes.stressTable.cell(i,j),rhymes.stressTable.total())); } } return new VowelTables(ll_heightTable, ll_frontnessTable, ll_roundnessTable, ll_tensionTable, ll_stressTable); } public void LL_table_printLL() { System.out.println("\nHeight:"); heightTable.printLL(); System.out.println("\nFrontness:"); frontnessTable.printLL(); System.out.println("\nRoundness:"); roundnessTable.printLL(); System.out.println("\nTension:"); tensionTable.printLL(); System.out.println("\nStress:"); stressTable.printLL(); } public void printProbabilities() { System.out.println("\n\nProbabilities"); System.out.println("\nHeight"); heightTable.printProbability(); System.out.println("\nFrontness"); frontnessTable.printProbability(); System.out.println("\nRoundness"); roundnessTable.printProbability(); System.out.println("\nTension"); tensionTable.printProbability(); System.out.println("\nStress:"); stressTable.printProbability(); } public void printCounts() { System.out.println("\nHeight:"); this.heightTable.print(); System.out.println("\nFrontness:"); this.frontnessTable.print(); System.out.println("\nRoundness:"); this.roundnessTable.print(); System.out.println("\nTension:"); this.tensionTable.print(); System.out.println("\nStress:"); this.stressTable.print(); } public void foldTables() { this.heightTable.foldDiagonally(); this.frontnessTable.foldDiagonally(); this.roundnessTable.foldDiagonally(); this.tensionTable.foldDiagonally(); this.stressTable.foldDiagonally(); } } <file_sep>/ben_alignment/ConsonantAligner.java package ben_alignment; import tables.*; import phonetics.ConsonantPhoneme; import phonetics.ConsonantPronunciation; import java.util.ArrayList; import java.util.List; public abstract class ConsonantAligner { public static Alignment align2ConsonantSequences(List<ConsonantPhoneme> c1, List<ConsonantPhoneme> c2, MultiConsonantTables ll_tables, double m_w, double p_w, double v_w) { Double[][] alignmentTable = new Double[c1.size() + 1][c2.size() + 1]; BackPointer[][] backPointers = new BackPointer[c1.size() + 1][c2.size() + 1]; for (int i = 0; i < c1.size() + 1; i++) { for (int j = 0; j < c2.size() + 1; j++) { if (i == 0 && j == 0) { alignmentTable[i][j] = 0.0; backPointers[i][j] = null; continue; } if (i == 0 || j == 0) { ConsonantPhoneme ph; if (i == 0) ph = c2.get(0); else ph = c1.get(0); int m = ll_tables.mannerTable.getCoord(ph.phonemeEnum.getManner()); int p = ll_tables.placeTable.getCoord(ph.phonemeEnum.getPlace()); int v = ll_tables.voicingTable.getCoord(ph.phonemeEnum.isVoiced()); if (i == 0) { alignmentTable[i][j] = weightedSum(ll_tables, m_w, p_w, v_w, Gap.BEG, m, p, v) + alignmentTable[i][j - 1]; backPointers[i][j] = BackPointer.LEFT; continue; } if (j == 0) { alignmentTable[i][j] = weightedSum(ll_tables, m_w, p_w, v_w, Gap.BEG, m, p, v) + alignmentTable[i - 1][j]; backPointers[i][j] = BackPointer.UP; continue; } } ConsonantPhoneme ph1 = c1.get(i - 1); ConsonantPhoneme ph2 = c2.get(j - 1); int m1 = ll_tables.mannerTable.getCoord(ph1.phonemeEnum.getManner()); int p1 = ll_tables.placeTable.getCoord(ph1.phonemeEnum.getPlace()); int v1 = ll_tables.voicingTable.getCoord(ph1.phonemeEnum.isVoiced()); int m2 = ll_tables.mannerTable.getCoord(ph2.phonemeEnum.getManner()); int p2 = ll_tables.placeTable.getCoord(ph2.phonemeEnum.getPlace()); int v2 = ll_tables.voicingTable.getCoord(ph2.phonemeEnum.isVoiced()); double diag = weightedSum(ll_tables,m_w,p_w,v_w,m1,m2,p1,p2,v1,v2) + alignmentTable[i - 1][j - 1]; double left = weightedSum(ll_tables,m_w,p_w,v_w,(i == c1.size() - 1 ? Gap.END : Gap.MID),m1,p1,v1) + alignmentTable[i][j - 1]; double up = weightedSum(ll_tables,m_w,p_w,v_w,(j == c2.size() - 1 ? Gap.END : Gap.MID),m1,p1,v1) + alignmentTable[i - 1][j]; if (diag >= left) { if (diag >= up) { alignmentTable[i][j] = diag; backPointers[i][j] = BackPointer.DIAG; } else { alignmentTable[i][j] = alignmentTable[i - 1][j] + up; backPointers[i][j] = BackPointer.UP; } } else { if (left >= up) { alignmentTable[i][j] = alignmentTable[i][j - 1] + left; backPointers[i][j] = BackPointer.LEFT; } else { alignmentTable[i][j] = alignmentTable[i - 1][j] + up; backPointers[i][j] = BackPointer.UP; } } } } // printAlignmentTable(c1,c2,alignmentTable); // printAlignmentTable(c1,c2,backPointers); // System.out.print("\n"); return backtrack(backPointers, c1, c2, alignmentTable, ll_tables, m_w, p_w, v_w); } private static void printAlignmentTable(List<ConsonantPhoneme> c1, List<ConsonantPhoneme> c2, Object[][] table) { for (int i = 0; i < table[0].length; i++) { if (i == 0) System.out.print("\t$\t"); else System.out.print(c2.get(i - 1) + "\t"); } System.out.print("\n"); for (int i = 0; i < table.length; i++) { if (i == 0) System.out.print("$\t"); else System.out.print(c1.get(i - 1) + "\t"); for (int j = 0; j < table[i].length; j++) { if (table[i][j] instanceof Double) { System.out.print(Math.floor(((Double) table[i][j]) * 1000) / 1000 + "\t"); } else { if (table[i][j] == BackPointer.LEFT) { System.out.print("<-\t"); } else if (table[i][j] == BackPointer.UP) { System.out.print("^\t"); } else { System.out.print("DIA\t"); } } } System.out.print("\n"); } } private static Alignment backtrack(BackPointer[][] backPointers, List<ConsonantPhoneme> c1, List<ConsonantPhoneme> c2, Double[][] alignmentTable, MultiConsonantTables scoringMatrices, double m_w, double p_w, double v_w) { double totalNormalizedScores = 0.0; ConsonantPronunciation r1 = new ConsonantPronunciation(); ConsonantPronunciation r2 = new ConsonantPronunciation(); int i = c1.size(); int j = c2.size(); int steps = 0; while (i > 0 || j > 0) { BackPointer dir = backPointers[i][j]; double actualScore = 0.0; //backtrack, build alignment backwards switch (dir) { case DIAG: double loggedVal = alignmentTable[i][j] - alignmentTable[i - 1][j - 1]; actualScore = deLog(loggedVal); r1.add(0, c1.get(i - 1)); r2.add(0, c2.get(j - 1)); i--; j--; break; case UP: loggedVal = alignmentTable[i][j] - alignmentTable[i - 1][j]; actualScore = deLog(loggedVal); r1.add(0, c1.get(i - 1)); r2.add(0, null); i--; break; case LEFT: loggedVal = alignmentTable[i][j] - alignmentTable[i][j - 1]; actualScore = deLog(loggedVal); r1.add(0, null); r2.add(0, c2.get(j - 1)); j--; break; default: break; } double normalizedPairScore; if (r1.get(0) == null || r2.get(0) == null) { if (r1.get(0) == null) { normalizedPairScore = actualScore / optimalPhonemeScore(r2.get(0), scoringMatrices, m_w, p_w, v_w); } else { normalizedPairScore = actualScore / optimalPhonemeScore(r1.get(0), scoringMatrices, m_w, p_w, v_w); } } else { normalizedPairScore = ((actualScore / optimalPhonemeScore(r1.get(0), scoringMatrices, m_w, p_w, v_w)) + (actualScore / optimalPhonemeScore(r2.get(0), scoringMatrices, m_w, p_w, v_w))) / 2.0; } totalNormalizedScores += normalizedPairScore; steps++; } final double score = alignmentTable[c1.size()][c2.size()] / ((double)steps); final double normalizedScore = totalNormalizedScores / ((double)steps); final Alignment result = new Alignment(r1, r2, steps, score, normalizedScore, alignmentTable, backPointers); return result; } public static Alignment greedilyAlign2ConsonantSequences(List<ConsonantPhoneme> c1, List<ConsonantPhoneme> c2, MonoConsonantTables monoLLTables) { if (c1.isEmpty() && c2.isEmpty()) { return new Alignment(new ArrayList<>(), new ArrayList<>(), -1, -1,-1, null, null); } //add gaps else if (c1.isEmpty() && !c2.isEmpty()) { List<ConsonantPhoneme> l1 = new ArrayList<>(); List<ConsonantPhoneme> l2 = new ArrayList<>(); for (ConsonantPhoneme c : c2) { l1.add(null); l2.add(c); } return new Alignment(l1,l2, c2.size(), -1,-1, null, null); } else if (!c1.isEmpty() && c2.isEmpty()) { List<ConsonantPhoneme> l1 = new ArrayList<>(); List<ConsonantPhoneme> l2 = new ArrayList<>(); for (ConsonantPhoneme c : c1) { l1.add(c); l2.add(null); } return new Alignment(l1,l2,c1.size(),-1,-1, null, null); } //find highest-scoring match double highestScore = Double.NEGATIVE_INFINITY; int high_i = -1; int high_j = -1; for (int i = 0; i < c1.size(); i++) { for (int j = 0; j < c2.size(); j++) { int m1 = monoLLTables.mannerTable.getCoord(c1.get(i).getManner()); int p1 = monoLLTables.placeTable.getCoord(c1.get(i).getPlace()); int v1 = monoLLTables.voicingTable.getCoord(c1.get(i).isVoiced()); int m2 = monoLLTables.mannerTable.getCoord(c2.get(j).getManner()); int p2 = monoLLTables.placeTable.getCoord(c2.get(j).getPlace()); int v2 = monoLLTables.voicingTable.getCoord(c2.get(j).isVoiced()); double matchValue = monoLLTables.mannerTable.cell(m1,m2) + monoLLTables.placeTable.cell(p1,p2) + monoLLTables.voicingTable.cell(v1,v2); if (matchValue > highestScore) { highestScore = matchValue; high_i = i; high_j = j; } } } List<ConsonantPhoneme> l1 = new ArrayList<>(); List<ConsonantPhoneme> l2 = new ArrayList<>(); l1.add(c1.get(high_i)); l2.add(c2.get(high_j)); Alignment currAlignment = new Alignment(l1,l2, l1.size(), -1,-1, null, null); //recurse left if (high_i > 0 || high_j > 0) { List<ConsonantPhoneme> left1 = new ArrayList<>(); List<ConsonantPhoneme> left2 = new ArrayList<>(); if (high_i != 0) { left1.addAll(c1.subList(0, high_i)); } if (high_j != 0) { left2.addAll(c2.subList(0, high_j)); } Alignment leftAlignment = greedilyAlign2ConsonantSequences(left1, left2, monoLLTables); currAlignment.c1.addAll(0, leftAlignment.c1); currAlignment.c2.addAll(0, leftAlignment.c2); } //recurse right if (high_i < c1.size() - 1 || high_j < c2.size() - 1) { List<ConsonantPhoneme> right1 = new ArrayList<>(); List<ConsonantPhoneme> right2 = new ArrayList<>(); if (high_i != c1.size() - 1) { right1.addAll(c1.subList(high_i + 1, c1.size())); } if (high_j != c2.size() - 1) { right2.addAll(c2.subList(high_j + 1, c2.size())); } Alignment rightAlignment = greedilyAlign2ConsonantSequences(right1, right2, monoLLTables); currAlignment.c1.addAll(rightAlignment.c1); currAlignment.c2.addAll(rightAlignment.c2); } return currAlignment; } private static double weightedSum(MultiConsonantTables tables, double mannerWeight, double placeWeight, double voicingWeight, int m1, int m2, int p1, int p2, int v1, int v2) { final double scoreSum = (tables.mannerTable.cell(m1,m2) * mannerWeight) + (tables.placeTable.cell(p1,p2) * placeWeight) + (tables.voicingTable.cell(v1,v2) * voicingWeight); final double weightSum = mannerWeight + placeWeight + voicingWeight; final double result = scoreSum / weightSum; return result; } private static double weightedSum(MultiConsonantTables tables, double mannerWeight, double placeWeight, double voicingWeight, Gap g, int m, int p, int v) { final int m2 = tables.mannerTable.getGapCoord(g); final int p2 = tables.placeTable.getGapCoord(g); final int v2 = tables.voicingTable.getGapCoord(g); final double scoreSum = (tables.mannerTable.cell(m,m2) * mannerWeight) + (tables.placeTable.cell(p,p2) * placeWeight) + (tables.voicingTable.cell(v,v2) * voicingWeight); final double weightSum = mannerWeight + placeWeight + voicingWeight; final double result = scoreSum / weightSum; return result; } private static double optimalPhonemeScore(ConsonantPhoneme cp, MultiConsonantTables tables, double mannerWeight, double placeWeight, double voicingWeight) { final int m = tables.mannerTable.getCoord(cp.phonemeEnum.getManner()); final int p = tables.placeTable.getCoord(cp.phonemeEnum.getPlace()); final int v = tables.voicingTable.getCoord(cp.phonemeEnum.isVoiced()); final double result = weightedSum(tables, mannerWeight, placeWeight, voicingWeight, m,m, p,p, v,v); final double de_logged = deLog(result); return de_logged; } private static double deLog(double d) { return Math.pow(Math.E, d); } } /* NORMALIZE GLOBAL ALIGNMENT SCORES!!! Take out of log space = base^n For every aligned pair(ph1, ph2): pairScore = (actual(ph1, ph2) / optimal ph1) + (actual(ph1, ph2) / optimal ph2) / 2 actual = diff between current cell and pointed to cell optimal = taken from table of phonemes against themselves Then take the mean of all pairs */ /* Normalize vowel stuff Re-code bad code Ensure entire score is normalized Switch to marginal probabilities for denominator of LL score, use RZ data instead of CMU iterator Search thru serialized data, if all equal coda lengths, scrape again Inspect RZ api for new endpoints */ <file_sep>/tables/MonoConsonantTables.java package tables; import java.util.List; public class MonoConsonantTables { public MonoMannerTable mannerTable; public MonoPlaceTable placeTable; public MonoVoicingTable voicingTable; public MonoConsonantTables(MonoMannerTable mannerTable, MonoPlaceTable placeTable, MonoVoicingTable voicingTable) { this.mannerTable = mannerTable; this.placeTable = placeTable; this.voicingTable = voicingTable; } public static void printLogLikelihoods(MonoConsonantTables randoms, MonoConsonantTables rhymes) { System.out.println("\n\nLog-Likelihoods"); System.out.println("\nManner of articulation"); MannerTable.printLogLikelihood(randoms.mannerTable, rhymes.mannerTable); System.out.println("\nPlace of articulation"); PlaceTable.printLogLikelihood(randoms.placeTable, rhymes.placeTable); System.out.println("\nVoicing"); VoicingTable.printLogLikelihood(randoms.voicingTable, rhymes.voicingTable); } public static MonoConsonantTables getLogLikelihoodTables(MonoConsonantTables randoms, MonoConsonantTables rhymes) { //manner MonoMannerTable ll_mannerTable = new MonoMannerTable(); for (int i = 0; i < randoms.mannerTable.get_i_size(); i++) { List<Double> list = ll_mannerTable.get(i); for (int j = 0; j < randoms.mannerTable.get_j_size(); j++) { if (i <= j) list.set(j, ProbabilityTable.computeLogLikelihood((int)randoms.mannerTable.cell(i,j), randoms.mannerTable.total(),(int)rhymes.mannerTable.cell(i,j),rhymes.mannerTable.total())); } } //place MonoPlaceTable ll_placeTable = new MonoPlaceTable(); for (int i = 0; i < randoms.placeTable.get_i_size(); i++) { List<Double> list = ll_placeTable.get(i); for (int j = 0; j < randoms.placeTable.get_j_size(); j++) { if (i <= j) list.set(j, ProbabilityTable.computeLogLikelihood((int)randoms.placeTable.cell(i,j), randoms.placeTable.total(),(int)rhymes.placeTable.cell(i,j),rhymes.placeTable.total())); } } //voicing MonoVoicingTable ll_voicingTable = new MonoVoicingTable(); for (int i = 0; i < randoms.voicingTable.get_i_size(); i++) { List<Double> list = ll_voicingTable.get(i); for (int j = 0; j < randoms.voicingTable.get_j_size(); j++) { if (i <= j) list.set(j, ProbabilityTable.computeLogLikelihood((int)randoms.voicingTable.cell(i,j), randoms.voicingTable.total(),(int)rhymes.voicingTable.cell(i,j),rhymes.voicingTable.total())); } } return new MonoConsonantTables(ll_mannerTable, ll_placeTable, ll_voicingTable); } public void LL_table_printLL() { System.out.println("\nManner of articulation:"); this.mannerTable.printLL(); System.out.println("\nPlace of articulation:"); this.placeTable.printLL(); System.out.println("\nVoicing:"); this.voicingTable.printLL(); } public void printProbabilities() { System.out.println("\n\nProbabilities"); System.out.println("\nManner of articulation"); mannerTable.printProbability(); System.out.println("\nPlace of articulation"); placeTable.printProbability(); System.out.println("\nVoicing"); voicingTable.printProbability(); } public void printCounts() { System.out.println("\nManner of articulation:"); this.mannerTable.print(); System.out.println("\nPlace of articulation:"); this.placeTable.print(); System.out.println("\nVoicing:"); this.voicingTable.print(); } public void foldTables() { this.mannerTable.foldDiagonally(); this.placeTable.foldDiagonally(); this.voicingTable.foldDiagonally(); } } <file_sep>/genetic/GeneticMain.java package genetic; import data.DataContainer; import data.ScoreDataset; import data.SimpleDataset; import main.Main; import phonetics.syllabic.LL_Rhymer; import tables.MultiTables; import java.io.IOException; import java.util.*; public class GeneticMain { public final static Random r = new Random(); private final static int topIndividualN = 20; private final static int offspringN = 100; private final static int maxGenerations = 1000; public final static double fitnessThreshold = 0.5; private final static int rzCorpusSize = 10000; public static double temp = 100.00; private final static double coolingRate = 0.1; public static SimpleDataset data; public static ScoreDataset score_data; public static void main(String[] args) { long startTime = System.nanoTime(); try { Main.main(null); } catch (IOException e) { e.printStackTrace(); } //set scoring tables MultiTables tables = Main.finalTables; Individual.tables = tables; // data = DataContainer.rhymeZoneAdvanced; score_data = DataContainer.rhymeZoneScoredAdvanced; Map<String, Double> values = LL_Rhymer.get100Weights(); TreeSet<Individual> topIndividuals = new TreeSet<>(); for (int i = 0; i < topIndividualN; i++) { Individual temp = new Individual(values); temp.mutate(); // temp.calculateBinaryFitness(); temp.classifyByScore(); topIndividuals.add(temp); } double bestFitnessYet = 101; double bestOfGeneration = 101; double generationalTop10Average; Individual bestIndividualYet; int generation = 0; // while (bestOfGeneration > 0.0 && generation < maxGenerations) { while (generation < maxGenerations) { generation++; System.out.println("Generation " + generation + "..."); //top individuals mate List<Individual> allIndividualsOfNewGeneration = mateTopIndividuals(topIndividuals); List<Individual> pool = new ArrayList<>(allIndividualsOfNewGeneration); //OPTIONAL -- mix parents and new generation pool.addAll(topIndividuals); //find top topIndividualN individuals of new generation topIndividuals = findTopIndividuals(pool); generationalTop10Average = generationalAverage(topIndividuals); //update highestFitness bestOfGeneration = topIndividuals.first().getMean_sq_error();//last for binary F-score //update absolutes if (bestOfGeneration < bestFitnessYet) { bestFitnessYet = bestOfGeneration; bestIndividualYet = topIndividuals.first(); System.out.println("\tNew best individual for " + rzCorpusSize + ": " + bestIndividualYet.getMean_sq_error()); Map<String,Double> map = bestIndividualYet.getValues(); System.out.println("\t\tfrontness: " + map.get("frontness")); System.out.println("\t\theight: " + map.get("height")); System.out.println("\t\troundness: " + map.get("roundness")); System.out.println("\t\ttension: " + map.get("tension")); System.out.println("\t\tstress: " + map.get("stress") + "\n"); System.out.println("\t\tmanner: " + map.get("manner")); System.out.println("\t\tplace: " + map.get("place")); System.out.println("\t\tvoicing: " + map.get("voicing") + "\n"); System.out.println("\t\tonset: " + map.get("onset")); System.out.println("\t\tnucleus: " + map.get("nucleus")); System.out.println("\t\tcoda: " + map.get("coda") + "\n"); } System.out.println("\tTemp: " + temp); System.out.println("\tAvrg fitness for Gen" + generation + ": " + generationalTop10Average); System.out.println("\tBest fitness for Gen" + generation + ": " + bestOfGeneration); System.out.println("\tBest fitness of all: " + bestFitnessYet); //cool mutation rate if (temp > 1.0) temp -= coolingRate; } System.out.println("\tBest individual of final generation: " + topIndividuals.first().getMean_sq_error()); Map<String,Double> map = topIndividuals.first().getValues(); System.out.println("\t\tfrontness: " + map.get("frontness")); System.out.println("\t\theight: " + map.get("height") + "\n"); System.out.println("\t\troundness: " + map.get("roundness") + "\n"); System.out.println("\t\ttension: " + map.get("tension") + "\n"); System.out.println("\t\tstress: " + map.get("stress") + "\n"); System.out.println("\t\tmanner: " + map.get("manner")); System.out.println("\t\tplace: " + map.get("place")); System.out.println("\t\tvoicing: " + map.get("voicing") + "\n"); System.out.println("\t\tonset: " + map.get("onset")); System.out.println("\t\tnucleus: " + map.get("nucleus")); System.out.println("\t\tcoda: " + map.get("coda") + "\n"); long endTime = System.nanoTime(); long totalTime = endTime - startTime; if (totalTime / 1000000000 > 59) { int minutes = (int) (totalTime / 1000000000 / 60); int seconds = (int) (totalTime / 1000000000); System.out.println("TIME: " + minutes + " minutes " + seconds + " seconds"); } else System.out.println(("TIME: " + (totalTime / 1000000000) % 60 + " seconds")); } public static List<Individual> mateTopIndividuals(Collection<Individual> topIndividuals) { //TODO optimize so only lists come in? or they stay as treesets for sorting? List<Individual> result = new ArrayList<>(); for (int i = 0; i < offspringN; i++) { int n1 = r.nextInt(topIndividuals.size()); int n2 = n1; while (n2 == n1) { n2 = r.nextInt(topIndividuals.size()); } Individual mater1 = null; int j = 0; for (Individual individual : topIndividuals) { if (j == n1) { mater1 = individual; break; } j++; } Individual mater2 = null; j = 0; for (Individual individual : topIndividuals) { if (j == n2) { mater2 = individual; break; } j++; } Individual child = mater1.crossover(mater2); child.mutate(); // child.calculateBinaryFitness(); child.classifyByScore(); result.add(child); } return result; } public static TreeSet<Individual> findTopIndividuals(Collection<Individual> allIndividuals) { TreeSet<Individual> calculatedIndividuals = new TreeSet<>(); //sort by fitness, return the top topIndividualN for (Individual ind : allIndividuals) { if (ind.getMean_sq_error() == 101) // ind.calculateBinaryFitness(); ind.classifyByScore(); calculatedIndividuals.add(ind); } TreeSet<Individual> result = new TreeSet<>(); try { for (int i = 0; i < topIndividualN; i++) { if (!calculatedIndividuals.isEmpty()) { result.add(calculatedIndividuals.first()); calculatedIndividuals.remove(calculatedIndividuals.first()); } else break; } } catch (NoSuchElementException e) { e.printStackTrace(); } return result; } public static double generationalAverage(Collection<Individual> inds) { double total = 0; for (Individual ind : inds) { total += ind.getMean_sq_error(); } return total / inds.size(); } } <file_sep>/tables/PlaceTable.java package tables; import phonetics.PlaceOfArticulation; public abstract class PlaceTable extends ProbabilityTable { public PlaceTable() { super(); } public void fillCell(PlaceOfArticulation p1, PlaceOfArticulation p2) { int x = getCoord(p1); int y = getCoord(p2); Double cell = this.get(x).get(y); if (cell == null || cell <= 0) this.get(x).set(y, 1.0); else this.get(x).set(y, cell + 1.0); } public void fillGapCell(Gap g, PlaceOfArticulation m) { int x = getCoord(m); int y = getGapCoord(g); Double cell = this.get(x).get(y); if (cell == null || cell <= 0) this.get(x).set(y, 1.0); else this.get(x).set(y, cell + 1.0); } public int getSize() { return 7; } public int getCoord(PlaceOfArticulation p) { switch (p) { case BILABIAL: return bilabial(); case LABIODENTAL: return labiodental(); case INTERDENTAL: return interdental(); case ALVEOLAR: return alveolar(); case PALATAL: return palatal(); case VELAR: return velar(); case GLOTTAL: return glottal(); } return -1; } public String lineName(int i) { if (i >= getSize()) { return gapName(i - getSize()); } switch (i) { case 0: return "bil"; case 1: return "lab"; case 2: return "int"; case 3: return "alv"; case 4: return "pal"; case 5: return "vel"; case 6: return "glo"; } return null; } public static void printLogLikelihood(PlaceTable randomMatches, PlaceTable rhymeMatches) { System.out.print("\t"); for (int i = 0; i < randomMatches.get_j_size(); i++) { System.out.print(randomMatches.lineName(i) + "\t"); } System.out.print("\n"); for (int i = 0; i < randomMatches.get_i_size(); i++) { System.out.print(randomMatches.lineName(i) + "\t"); for (int j = 0; j < randomMatches.get_j_size(); j++) { if (i > j) System.out.print("-\t"); else System.out.print(Math.floor((computeLogLikelihood((int)(double)randomMatches.get(i).get(j),randomMatches.total(),(int)(double)rhymeMatches.get(i).get(j),rhymeMatches.total())) * 1000) / 1000 + "\t"); } System.out.print("\n"); } } public int bilabial() { return 0; } public int labiodental() { return 1; } public int interdental() { return 2; } public int alveolar() { return 3; } public int palatal() { return 4; } public int velar() { return 5; } public int glottal() { return 6; } } /* BILABIAL, LABIODENTAL, INTERDENTAL, ALVEOLAR, PALATAL, VELAR, GLOTTAL */ <file_sep>/tables/MonoVoicingTable.java package tables; public class MonoVoicingTable extends VoicingTable { @Override public int get_i_size() { return getSize(); } @Override public int get_j_size() { return getSize(); } } <file_sep>/tables/ProbabilityTable.java package tables; import java.io.Serializable; import java.util.ArrayList; public abstract class ProbabilityTable extends ArrayList<ArrayList<Double>> implements Serializable { public ProbabilityTable() { super(); for (int i = 0; i < this.get_i_size(); i++) { this.add(i, new ArrayList<>()); for (int j = 0; j < this.get_j_size(); j++) { this.get(i).add(j, 0.0); } } } public void foldDiagonally() { for (int i = 1; i < this.get_i_size(); i++) { for (int j = 0; j < this.get_j_size(); j++) { if (i > j) { this.get(j).set(i, this.get(j).get(i) + this.get(i).get(j)); this.get(i).set(j, 0.0); } } } } public void print() { System.out.print("\t"); for (int i = 0; i < this.get_j_size(); i++) { System.out.print(this.lineName(i) + "\t"); } System.out.print("\n"); for (int i = 0; i < this.get_i_size(); i++) { System.out.print(this.lineName(i) + "\t"); for (int j = 0; j < this.get_j_size(); j++) { if (i > j) System.out.print("-\t"); else System.out.print(((int)(double)(this.get(i).get(j)))+ "\t"); } System.out.print("\n"); } } public void printLL() { System.out.print("\t"); for (int i = 0; i < this.get_j_size(); i++) { System.out.print(this.lineName(i) + "\t"); } System.out.print("\n"); for (int i = 0; i < this.get_i_size(); i++) { System.out.print(this.lineName(i) + "\t"); for (int j = 0; j < this.get_j_size(); j++) { if (i > j) System.out.print("-\t"); else System.out.print(Math.floor((this.get(i).get(j)) * 1000) / 1000 + "\t"); } System.out.print("\n"); } } public void printProbability() { System.out.print("\t"); for (int i = 0; i < this.get_j_size(); i++) { System.out.print(this.lineName(i) + "\t"); } System.out.print("\n"); for (int i = 0; i < this.get_i_size(); i++) { System.out.print(this.lineName(i) + "\t"); for (int j = 0; j < this.get_j_size(); j++) { if (i > j) System.out.print("-\t"); else System.out.print(Math.floor(this.get(i).get(j) / this.total() * 1000) / 1000 + "\t"); } System.out.print("\n"); } } public static double computeLogLikelihood(int randomMatches, int randomTotal, int rhymeMatches, int rhymeTotal) { if (randomMatches == 0 || rhymeMatches == 0) return 0; // double result = ((double)rhymeMatches/(double)rhymeTotal) / ((double)randomMatches/(double)randomTotal); double result = Math.log(((double)rhymeMatches/(double)rhymeTotal) / ((double)randomMatches/(double)randomTotal)); return result; } public int total() { int result = 0; for (int i = 0; i < this.get_i_size(); i++) { for (int j = 0; j < this.get_j_size(); j++) { result += this.get(i).get(j); } } return result; } public double cell(int i, int j) { if (i > j) return this.get(j).get(i); return this.get(i).get(j); } public int getGapCoord(Gap g) { switch (g) { case BEG: return getSize() + 0; case MID: return getSize() + 1; case END: return getSize() + 2; } return -1; } public String gapName(int i) { switch (i) { case 0: return "G1"; case 1: return "G2"; case 2: return "G3"; } return null; } public abstract int get_i_size(); public abstract int get_j_size(); public abstract int getSize(); public abstract String lineName(int i); } <file_sep>/tables/FrontnessTable.java package tables; import phonetics.Frontness; import java.io.Serializable; public class FrontnessTable extends ProbabilityTable implements Serializable { public FrontnessTable() { super(); } public int getSize() { return 3; } @Override public int get_i_size() { return getSize(); } @Override public int get_j_size() { return getSize(); } public void fillCell(Frontness f1, Frontness f2) { int x = getCoord(f1); int y = getCoord(f2); Double cell = this.get(x).get(y); if (cell == null || cell <= 0) this.get(x).set(y, 1.0); else this.get(x).set(y, cell + 1.0); } public int getCoord(Frontness f) { switch (f) { case FRONT: return front(); case CENTRAL: return central(); case BACK: return back(); } return -1; } public String lineName(int i) { switch (i) { case 0: return "fro"; case 1: return "cen"; case 2: return "bac"; } return null; } public static void printLogLikelihood(FrontnessTable randomMatches, FrontnessTable rhymeMatches) { System.out.print("\t"); for (int i = 0; i < randomMatches.getSize(); i++) { System.out.print(randomMatches.lineName(i) + "\t"); } System.out.print("\n"); for (int i = 0; i < randomMatches.getSize(); i++) { System.out.print(randomMatches.lineName(i) + "\t"); for (int j = 0; j < randomMatches.getSize(); j++) { if (i > j) System.out.print("-\t"); // else System.out.print((computeLogLikelihood((int)(double)randomMatches.get(i).get(j),randomMatches.total(),(int)(double)rhymeMatches.get(i).get(j),rhymeMatches.total())) + "\t"); else System.out.print(Math.floor((computeLogLikelihood((int)(double)randomMatches.get(i).get(j),randomMatches.total(),(int)(double)rhymeMatches.get(i).get(j),rhymeMatches.total()))* 1000) / 1000 + "\t"); } System.out.print("\n"); } } public int front() { return 0; } public int central() { return 1; } public int back() { return 2; } } <file_sep>/ben_alignment/BackPointer.java package ben_alignment; public enum BackPointer { UP, LEFT, DIAG } <file_sep>/tables/RoundnessTable.java package tables; import phonetics.Roundness; import java.io.Serializable; public class RoundnessTable extends ProbabilityTable implements Serializable { public RoundnessTable() { super(); } public int getSize() { return 2; } @Override public int get_i_size() { return getSize(); } @Override public int get_j_size() { return getSize(); } public void fillCell(Roundness r1, Roundness r2) { int x = getCoord(r1); int y = getCoord(r2); Double cell = this.get(x).get(y); if (cell == null || cell <= 0) this.get(x).set(y, 1.0); else this.get(x).set(y, cell + 1.0); } public int getCoord(Roundness r) { switch (r) { case ROUND: return round(); case NOT_ROUND: return not_round(); } return -1; } public String lineName(int i) { switch (i) { case 0: return "rou"; case 1: return "not"; } return null; } public static void printLogLikelihood(RoundnessTable randomMatches, RoundnessTable rhymeMatches) { System.out.print("\t"); for (int i = 0; i < randomMatches.getSize(); i++) { System.out.print(randomMatches.lineName(i) + "\t"); } System.out.print("\n"); for (int i = 0; i < randomMatches.getSize(); i++) { System.out.print(randomMatches.lineName(i) + "\t"); for (int j = 0; j < randomMatches.getSize(); j++) { if (i > j) System.out.print("-\t"); // else System.out.print((computeLogLikelihood((int)(double)randomMatches.get(i).get(j),randomMatches.total(),(int)(double)rhymeMatches.get(i).get(j),rhymeMatches.total())) + "\t"); else System.out.print(Math.floor((computeLogLikelihood((int)(double)randomMatches.get(i).get(j),randomMatches.total(),(int)(double)rhymeMatches.get(i).get(j),rhymeMatches.total()))* 1000) / 1000 + "\t"); } System.out.print("\n"); } } public int round() { return 0; } public int not_round() { return 1; } } <file_sep>/tables/VoicingTable.java package tables; import java.io.Serializable; public abstract class VoicingTable extends ProbabilityTable implements Serializable { public int getSize() { return 2; } public void fillCell(boolean v1, boolean v2) { int x = getCoord(v1); int y = getCoord(v2); Double cell = this.get(x).get(y); if (cell == null || cell <= 0) this.get(x).set(y, 1.0); else this.get(x).set(y, cell + 1.0); } public void fillGapCell(Gap g, boolean b) { int x = getCoord(b); int y = getGapCoord(g); Double cell = this.get(x).get(y); if (cell == null || cell <= 0) this.get(x).set(y, 1.0); else this.get(x).set(y, cell + 1.0); } public int getCoord(boolean b) { if (b) return 0; return 1; } public String lineName(int i) { if (i >= getSize()) { return gapName(i - getSize()); } switch (i) { case 0: return "v"; case 1: return "no"; } return null; } public static void printLogLikelihood(VoicingTable randomMatches, VoicingTable rhymeMatches) { System.out.print("\t"); for (int i = 0; i < randomMatches.get_j_size(); i++) { System.out.print(randomMatches.lineName(i) + "\t"); } System.out.print("\n"); for (int i = 0; i < randomMatches.get_i_size(); i++) { System.out.print(randomMatches.lineName(i) + "\t"); for (int j = 0; j < randomMatches.get_j_size(); j++) { if (i > j) System.out.print("-\t"); // else System.out.print((computeLogLikelihood((int)(double)normalMatches.get(i).get(j),normalMatches.total(),(int)(double)rhymeMatches.get(i).get(j),rhymeMatches.total())) + "\t"); else System.out.print(Math.floor((ProbabilityTable.computeLogLikelihood((int)(double)randomMatches.get(i).get(j),randomMatches.total(),(int)(double)rhymeMatches.get(i).get(j),rhymeMatches.total())) * 1000) / 1000 + "\t"); } System.out.print("\n"); } } } <file_sep>/main/Main.java package main; import java.io.*; import java.util.*; import data.DataContainer; import data.DataLoader; import data.ScoreDataset; import data.SimpleDataset; import phonetics.ConsonantPhoneme; import phonetics.VowelPhoneme; import phonetics.syllabic.LL_Rhymer; import phonetics.syllabic.Syllable; import phonetics.syllabic.SyllableList; import phonetics.syllabic.WordSyllables; import ben_alignment.*; import tables.*; import utils.Pair; public abstract class Main { public static String rootPath; public static MultiTables finalTables; public static void main(String[] args) throws IOException { setupRootPath(); DataContainer.setupDict(); DataContainer.rhymeZoneScoredAdvanced = DataLoader.deserializeScoredRhymes("RZ-adv", DataContainer.size); DataContainer.rhymeZoneScoredAdvanced.clean(); DataContainer.setupRzDict(DataContainer.rhymeZoneScoredAdvanced); finalTables = deserializeTables(); // SimpleDataset randomRzMatches = getRandomRzMatches(); // // //monophonemic // System.out.println("\n\nMONOPHONEMIC (consonants and vowels)"); // MonoTables randoms = findMonoCountsOnly(randomRzMatches); // MonoTables rhymes = findMonoCountsOnly(DataContainer.rhymeZoneScoredAdvanced); // randoms.foldAll(); // rhymes.foldAll(); // // System.out.println("\n\nVOWELS"); //// System.out.println("\n\nNear rhyme counts: " + rhymes.vowelTables.heightTable.total() + " total matches"); //// rhymes.vowelTables.printCounts(); //// System.out.println("\n\nRandom counts: " + randoms.vowelTables.frontnessTable.total() + " total matches"); //// randoms.vowelTables.printCounts(); // VowelTables mono_ll_vowel_tables = VowelTables.getLogLikelihoodTables(randoms.vowelTables, rhymes.vowelTables); // mono_ll_vowel_tables.LL_table_printLL(); // // System.out.println("\n\nCONSONANTS"); //// System.out.println("\n\nNear rhyme counts: " + rhymes.consonantTables.mannerTable.total() + " total matches"); //// rhymes.consonantTables.printCounts(); //// System.out.println("\n\nRandom counts: " + randoms.consonantTables.mannerTable.total() + " total matches"); //// randoms.consonantTables.printCounts(); // MonoConsonantTables mono_ll_consonant_tables = MonoConsonantTables.getLogLikelihoodTables(randoms.consonantTables, rhymes.consonantTables); // mono_ll_consonant_tables.LL_table_printLL(); // // //multiphonemic // System.out.println("\n\nMULTIPHONEMIC (consonants only)"); // MultiTables randoms2 = findAllCounts(randomRzMatches, mono_ll_consonant_tables); // MultiTables rhymes2 = findAllCounts(DataContainer.rhymeZoneScoredAdvanced, mono_ll_consonant_tables); // randoms2.foldAll(); // rhymes2.foldAll(); // // System.out.println("\n\nNear rhyme counts: " + rhymes2.consonantTables.mannerTable.total() + " total matches"); // rhymes2.consonantTables.printCounts(); // System.out.println("\n\nRandom counts: " + randoms2.consonantTables.mannerTable.total() + " total matches"); // randoms2.consonantTables.printCounts(); // MultiConsonantTables multi_ll_tables = MultiConsonantTables.getLogLikelihoodTables(randoms2.consonantTables, rhymes2.consonantTables); // multi_ll_tables.LL_table_printLL(); // // finalTables = new MultiTables(multi_ll_tables, mono_ll_vowel_tables); // serializeTables(finalTables); // LL_Rhymer.test(finalTables); } public static void serializeTables(MultiTables tables) { System.out.print("Serializing tables..."); try { FileOutputStream fileOut = new FileOutputStream(Main.rootPath + "data/tables/ll_tables.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(tables); out.close(); fileOut.close(); System.out.println("Serialized tables saved in data/tables/ll_tables.ser"); } catch(IOException i) { i.printStackTrace(); } } public static MultiTables deserializeTables() { System.out.print("Deserializing tables..."); MultiTables result = null; try { FileInputStream fileIn = new FileInputStream(Main.rootPath + "data/tables/ll_tables.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); result = (MultiTables) in.readObject(); in.close(); fileIn.close(); System.out.println("done!"); } catch(IOException i) { i.printStackTrace(); } catch(ClassNotFoundException c) { System.out.println("class not found"); c.printStackTrace(); } return result; } public static SimpleDataset getRandomRzMatches() { SimpleDataset result = new SimpleDataset(); Iterator<String> iterator = DataContainer.RZdictionary.iterator(); for (String s1 : DataContainer.RZdictionary) { String s2; for (int i = 0; i < 300; i++) { Set<String> set = new HashSet<>(); if (!iterator.hasNext()) { iterator = DataContainer.RZdictionary.iterator(); } s2 = iterator.next(); while (s1.equals(s2) || s2 == null || s2.isEmpty() || s2 == "") { if (!iterator.hasNext()) { iterator = DataContainer.RZdictionary.iterator(); } s2 = iterator.next(); } if (result.get(s1) == null) { set.add(s2); result.put(s1, set); } else { Set<String> oldSet = result.get(s1); oldSet.add(s2); result.put(s1, oldSet); } } } return result; } public static MonoTables findMonoCountsOnly(ScoreDataset dataset) { SimpleDataset result = new SimpleDataset(); for (Map.Entry<String, Set<Pair<String,Integer>>> entry : dataset.entrySet()) { Set<String> set = new HashSet<>(); for (Pair<String,Integer> pair : entry.getValue()) { set.add(pair.getFirst()); } result.put(entry.getKey(), set); } return findMonoCountsOnly(result); } public static MonoTables findMonoCountsOnly(SimpleDataset dataset) { MonoConsonantTables consonantResult = new MonoConsonantTables(new MonoMannerTable(), new MonoPlaceTable(), new MonoVoicingTable()); VowelTables vowelResult = new VowelTables(new HeightTable(), new FrontnessTable(), new RoundnessTable(), new TensionTable(), new StressTable()); for (Map.Entry<String,Set<String>> entry : dataset.entrySet()) { WordSyllables r1 = DataContainer.dictionary.get(entry.getKey()); for (String s : entry.getValue()) { WordSyllables r2 = DataContainer.dictionary.get(s); if (r1 != null && r2 != null && r1.last() != null && r2.last() != null && (r1.last().getCoda() != null || r2.last().getCoda() != null)) { //monophonemic end codas if (r1.last().getCoda() != null && r2.last().getCoda() != null && r1.last().getCoda().size() == 1 && r2.last().getCoda().size() == 1) consonantResult = manageConsonantMatch(consonantResult, r1.last().getCoda().get(0),r2.last().getCoda().get(0)); //end nuclei vowelResult = manageVowelMatches(vowelResult, r1.last().getNucleus(),r2.last().getNucleus()); } //do counts of middle onsets and codas and nuclei if (r1.getRhymeTailFromStress().size() == r2.getRhymeTailFromStress().size() && r1.getRhymeTailFromStress().size() > 1) { SyllableList rt1 = r1.getRhymeTailFromStress(); SyllableList rt2 = r2.getRhymeTailFromStress(); //monophonemic onsets in rhyme tail for (int i = 0; i < rt1.size(); i++) { Syllable syl1 = rt1.get(i); Syllable syl2 = rt2.get(i); if (syl1 == null || !syl1.hasOnset() || syl1.getOnset().size() != 1 || syl2 == null || !syl2.hasOnset() || syl2.getOnset().size() != 1) continue; consonantResult = manageConsonantMatch(consonantResult, syl1.getOnset().get(0),syl2.getOnset().get(0)); } //monophonemic codas in rhyme tail (excluding final syllable) for (int i = 0; i < rt1.size(); i++) { Syllable syl1 = rt1.get(i); Syllable syl2 = rt2.get(i); if (i == rt1.size() - 1 || syl1 == null || !syl1.hasCoda() || syl1.getCoda().size() != 1 || syl2 == null || !syl2.hasCoda() || syl2.getCoda().size() != 1) continue; consonantResult = manageConsonantMatch(consonantResult, syl1.getCoda().get(0),syl2.getCoda().get(0)); } //nuclei in rhyme tail (excluding final syllable) for (int i = 0; i < rt1.size(); i++) { Syllable syl1 = rt1.get(i); Syllable syl2 = rt2.get(i); if (i == rt1.size() - 1 || syl1 == null || !syl1.hasNucleus() || syl2 == null || !syl2.hasNucleus()) continue; vowelResult = manageVowelMatches(vowelResult, syl1.getNucleus(),syl2.getNucleus()); } } } } return new MonoTables(consonantResult, vowelResult); } public static MultiTables findAllCounts(ScoreDataset dataset, MonoConsonantTables monoLLTables) { SimpleDataset result = new SimpleDataset(); for (Map.Entry<String, Set<Pair<String,Integer>>> entry : dataset.entrySet()) { Set<String> set = new HashSet<>(); for (Pair<String,Integer> pair : entry.getValue()) { set.add(pair.getFirst()); } result.put(entry.getKey(), set); } return findAllCounts(result, monoLLTables); } public static MultiTables findAllCounts(SimpleDataset dataset, MonoConsonantTables monoLLTables) { MultiConsonantTables consonantResult = new MultiConsonantTables(new MultiMannerTable(), new MultiPlaceTable(), new MultiVoicingTable()); VowelTables vowelResult = new VowelTables(new HeightTable(), new FrontnessTable(), new RoundnessTable(), new TensionTable(), new StressTable()); for (Map.Entry<String,Set<String>> entry : dataset.entrySet()) { WordSyllables r1 = DataContainer.dictionary.get(entry.getKey()); for (String s : entry.getValue()) { WordSyllables r2 = DataContainer.dictionary.get(s); if (r1 != null && r2 != null && r1.last() != null && r2.last() != null && (r1.last().getCoda() != null || r2.last().getCoda() != null)) { //monophonemic end codas if (r1.last().getCoda() != null && r2.last().getCoda() != null && r1.last().getCoda().size() == 1 && r2.last().getCoda().size() == 1) consonantResult = manageConsonantMatch(consonantResult, r1.last().getCoda().get(0),r2.last().getCoda().get(0)); //end nuclei vowelResult = manageVowelMatches(vowelResult, r1.last().getNucleus(),r2.last().getNucleus()); //multiphonemic end codas if (r1.last().getCoda().size() > 1 || r2.last().getCoda().size() > 1) { Alignment alignment = ConsonantAligner.greedilyAlign2ConsonantSequences(r1.last().getCoda(), r2.last().getCoda(), monoLLTables); consonantResult = manageConsonantMatches(consonantResult, alignment); } } //do counts of middle onsets and codas and nuclei if (r1.getRhymeTailFromStress().size() == r2.getRhymeTailFromStress().size() && r1.getRhymeTailFromStress().size() > 1) { SyllableList rt1 = r1.getRhymeTailFromStress(); SyllableList rt2 = r2.getRhymeTailFromStress(); //monophonemic onsets in rhyme tail for (int i = 0; i < rt1.size(); i++) { Syllable syl1 = rt1.get(i); Syllable syl2 = rt2.get(i); if (syl1 == null || !syl1.hasOnset() || syl1.getOnset().size() != 1 || syl2 == null || !syl2.hasOnset() || syl2.getOnset().size() != 1) continue; consonantResult = manageConsonantMatch(consonantResult, syl1.getOnset().get(0),syl2.getOnset().get(0)); } //monophonemic codas in rhyme tail (excluding final syllable) for (int i = 0; i < rt1.size(); i++) { Syllable syl1 = rt1.get(i); Syllable syl2 = rt2.get(i); if (i == rt1.size() - 1 || syl1 == null || !syl1.hasCoda() || syl1.getCoda().size() != 1 || syl2 == null || !syl2.hasCoda() || syl2.getCoda().size() != 1) continue; consonantResult = manageConsonantMatch(consonantResult, syl1.getCoda().get(0),syl2.getCoda().get(0)); } //nuclei in rhyme tail (excluding final syllable) for (int i = 0; i < rt1.size(); i++) { Syllable syl1 = rt1.get(i); Syllable syl2 = rt2.get(i); if (i == rt1.size() - 1 || syl1 == null || !syl1.hasNucleus() || syl2 == null || !syl2.hasNucleus()) continue; vowelResult = manageVowelMatches(vowelResult, syl1.getNucleus(),syl2.getNucleus()); } //multiphonemic onsets in rhyme tail for (int i = 0; i < rt1.size(); i++) { Syllable syl1 = rt1.get(i); Syllable syl2 = rt2.get(i); if (syl1 == null || !syl1.hasOnset() || syl1.getOnset().size() <= 1 || syl2 == null || !syl2.hasOnset() || syl2.getOnset().size() <= 1) continue; Alignment alignment = ConsonantAligner.greedilyAlign2ConsonantSequences(syl1.getOnset(), syl2.getOnset(), monoLLTables); consonantResult = manageConsonantMatches(consonantResult, alignment); } //multiphonemic codas in rhyme tail (excluding final syllable) for (int i = 0; i < rt1.size(); i++) { Syllable syl1 = rt1.get(i); Syllable syl2 = rt2.get(i); if (i == rt1.size() - 1 || syl1 == null || !syl1.hasCoda() || syl1.getCoda().size() != 1 || syl2 == null || !syl2.hasCoda() || syl2.getCoda().size() != 1) continue; Alignment alignment = ConsonantAligner.greedilyAlign2ConsonantSequences(syl1.getCoda(), syl2.getCoda(), monoLLTables); consonantResult = manageConsonantMatches(consonantResult, alignment); } } } } return new MultiTables(consonantResult, vowelResult); } public static MonoConsonantTables manageConsonantMatch(MonoConsonantTables tables, ConsonantPhoneme r1consonant, ConsonantPhoneme r2consonant) { tables.mannerTable.fillCell(r1consonant.phonemeEnum.getManner(),r2consonant.phonemeEnum.getManner()); tables.placeTable.fillCell(r1consonant.phonemeEnum.getPlace(),r2consonant.phonemeEnum.getPlace()); tables.voicingTable.fillCell(r1consonant.phonemeEnum.isVoiced(),r2consonant.phonemeEnum.isVoiced()); return tables; } public static MultiConsonantTables manageConsonantMatch(MultiConsonantTables tables, ConsonantPhoneme r1consonant, ConsonantPhoneme r2consonant) { tables.mannerTable.fillCell(r1consonant.phonemeEnum.getManner(),r2consonant.phonemeEnum.getManner()); tables.placeTable.fillCell(r1consonant.phonemeEnum.getPlace(),r2consonant.phonemeEnum.getPlace()); tables.voicingTable.fillCell(r1consonant.phonemeEnum.isVoiced(),r2consonant.phonemeEnum.isVoiced()); return tables; } public static MultiConsonantTables manageConsonantMatches(MultiConsonantTables tables, Alignment alignment) { List<ConsonantPhoneme> r1consonants = alignment.c1; List<ConsonantPhoneme> r2consonants = alignment.c2; for (int i = 0; i < r1consonants.size(); i++) { //double null, no gap if (r1consonants.get(i) == null && r2consonants.get(i) == null) continue; //beginning gap else if (i == 0 && (r1consonants.get(i) == null || r2consonants.get(i) == null)) { if (r1consonants.get(i) == null) { tables.mannerTable.fillGapCell(Gap.BEG, r2consonants.get(i).phonemeEnum.getManner()); tables.placeTable.fillGapCell(Gap.BEG, r2consonants.get(i).phonemeEnum.getPlace()); tables.voicingTable.fillGapCell(Gap.BEG, r2consonants.get(i).phonemeEnum.isVoiced()); } else { tables.mannerTable.fillGapCell(Gap.BEG, r1consonants.get(i).phonemeEnum.getManner()); tables.placeTable.fillGapCell(Gap.BEG, r1consonants.get(i).phonemeEnum.getPlace()); tables.voicingTable.fillGapCell(Gap.BEG, r1consonants.get(i).phonemeEnum.isVoiced()); } } //end gap else if (i == r1consonants.size() - 1 && (r1consonants.get(i) == null || r2consonants.get(i) == null)) { if (r1consonants.get(i) == null) { tables.mannerTable.fillGapCell(Gap.END, r2consonants.get(i).phonemeEnum.getManner()); tables.placeTable.fillGapCell(Gap.END, r2consonants.get(i).phonemeEnum.getPlace()); tables.voicingTable.fillGapCell(Gap.END, r2consonants.get(i).phonemeEnum.isVoiced()); } else { tables.mannerTable.fillGapCell(Gap.END, r1consonants.get(i).phonemeEnum.getManner()); tables.placeTable.fillGapCell(Gap.END, r1consonants.get(i).phonemeEnum.getPlace()); tables.voicingTable.fillGapCell(Gap.END, r1consonants.get(i).phonemeEnum.isVoiced()); } } //middle gap else if (r1consonants.get(i) == null || r2consonants.get(i) == null) { if (r1consonants.get(i) == null) { tables.mannerTable.fillGapCell(Gap.MID, r2consonants.get(i).phonemeEnum.getManner()); tables.placeTable.fillGapCell(Gap.MID, r2consonants.get(i).phonemeEnum.getPlace()); tables.voicingTable.fillGapCell(Gap.MID, r2consonants.get(i).phonemeEnum.isVoiced()); } else { tables.mannerTable.fillGapCell(Gap.MID, r1consonants.get(i).phonemeEnum.getManner()); tables.placeTable.fillGapCell(Gap.MID, r1consonants.get(i).phonemeEnum.getPlace()); tables.voicingTable.fillGapCell(Gap.MID, r1consonants.get(i).phonemeEnum.isVoiced()); } } else { tables.mannerTable.fillCell(r1consonants.get(i).phonemeEnum.getManner(), r2consonants.get(i).phonemeEnum.getManner()); tables.placeTable.fillCell(r1consonants.get(i).phonemeEnum.getPlace(), r2consonants.get(i).phonemeEnum.getPlace()); tables.voicingTable.fillCell(r1consonants.get(i).phonemeEnum.isVoiced(), r2consonants.get(i).phonemeEnum.isVoiced()); } } return tables; } public static VowelTables manageVowelMatches(VowelTables tables, VowelPhoneme r1, VowelPhoneme r2) { tables.heightTable.fillCell(r1.phonemeEnum.getHeight(),r2.phonemeEnum.getHeight()); tables.frontnessTable.fillCell(r1.phonemeEnum.getFrontness(),r2.phonemeEnum.getFrontness()); tables.roundnessTable.fillCell(r1.phonemeEnum.getRoundness(),r2.phonemeEnum.getRoundness()); tables.tensionTable.fillCell(r1.phonemeEnum.getTension(),r2.phonemeEnum.getTension()); tables.stressTable.fillCell(r1.stress,r2.stress); return tables; } public static void setupRootPath() { //Set the root path of Lyrist in U final File currentDirFile = new File(""); Main.rootPath = currentDirFile.getAbsolutePath() + "/"; } // public double computeFScoreForRhymingFunction(Dataset dataset, RhymeFunction rhymeFunction) { // // } public double computeFitness(int truePositives, int falsePositives, int falseNegatives) { double precision = computePrecision(truePositives, falsePositives); double recall = computeRecall(truePositives, falseNegatives); double fScore = computeFScore(precision, recall); return fScore; } public static double computeFScore(double precision, double recall) { return 2 * ((precision * recall) / (precision + recall)); } public static double computePrecision(double truePositives, double falsePositives) { return truePositives / (truePositives + falsePositives); } public static double computeRecall(double truePositives, double falseNegatives) { return truePositives / (truePositives + falseNegatives); } } /* Steps 1. Compute log-likelihood tables for monophonemic voicing, manner, and place 2. Greedily align all codas (including multiphonemic) to get aligned phonemes using the scoring matrix computed in step 1. By "greedily align" this means simply to take the best matching phoneme pair based on linguistic features using the scoring matrices from step 1; then take the next best; and so on, ensuring that the order of phonemes is maintained in the pairwise association. This does not require a gap cost to perform this alignment. 3. Using the multiphonemic alignments from step 2, *update the linguistic scoring matrices from step 1 with log-likelihoods from the newly aligned phonemes (including gaps). */ <file_sep>/data/DataLoader.java package data; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import phonetics.Phoneticizer; import main.*; import utils.Pair; import java.io.*; import java.util.*; public abstract class DataLoader { public static ScoreDataset loadScoredDataset(String name, String baseUrl, int sizeLimit) throws IOException, JSONException { ScoreDataset result = new ScoreDataset(); int i = 0; for (String word : Phoneticizer.syllableDict.keySet()) { if (i > sizeLimit) break; word = word.replaceAll("[^\\w]",""); word = word.toLowerCase(); System.out.print(i + " "); List<JSONObject> o = HttpInterface.get(baseUrl + word); if (o == null) continue; Set<Pair<String, Integer>> rhymes = new HashSet<>(); for (JSONObject object : o) { String tempWord = new String(object.getString("word")); Integer tempScore = new Integer(object.getInt("score")); rhymes.add(new Pair(tempWord, tempScore)); } result.put(word,rhymes); if (i == 10000 || i == 5000) { serializeRhymes(name, result, i); System.out.println("SERIALIZED FIRST " + i + " " + name + " RHYMES"); } i++; } return result; } public static SimpleDataset loadDataset(String name, String baseUrl, int sizeLimit) throws IOException, JSONException { SimpleDataset result = new SimpleDataset(); int i = 0; for (String word : Phoneticizer.syllableDict.keySet()) { if (i > sizeLimit) break; word = word.replaceAll("[^\\w]",""); word = word.toLowerCase(); System.out.print(i + " "); List<JSONObject> o = HttpInterface.get(baseUrl + word); if (o == null) continue; Set<String> rhymes = new HashSet<>(); for (JSONObject object : o) { String tempWord = new String(object.getString("word")); rhymes.add(tempWord); } result.put(word,rhymes); if ((i % 100000 == 0 && i != 0) || i == 10000) { serializeRhymes(name, result, i); System.out.println("SERIALIZED FIRST " + i + " " + name + " RHYMES"); } i++; } return result; } public static SimpleDataset deserializeRhymes(String name, int size) { System.out.print("Deserializing " + name + " rhymes..."); SimpleDataset result = null; try { FileInputStream fileIn = new FileInputStream(Main.rootPath + "data/rhyme_data/" + name + "-" + size + ".ser"); ObjectInputStream in = new ObjectInputStream(fileIn); result = (SimpleDataset) in.readObject(); in.close(); fileIn.close(); System.out.println("done!"); } catch(IOException i) { i.printStackTrace(); } catch(ClassNotFoundException c) { System.out.println(name + " rhyme class not found"); c.printStackTrace(); } return result; } public static ScoreDataset deserializeScoredRhymes(String name, int size) { System.out.print("Deserializing " + name + " rhymes..."); ScoreDataset result = null; try { FileInputStream fileIn = new FileInputStream(Main.rootPath + "data/rhyme_data/" + name + "-scored-" + size + ".ser"); ObjectInputStream in = new ObjectInputStream(fileIn); result = (ScoreDataset) in.readObject(); in.close(); fileIn.close(); System.out.println("done!"); } catch(IOException i) { i.printStackTrace(); } catch(ClassNotFoundException c) { System.out.println(name + " rhyme class not found"); c.printStackTrace(); } return result; } private static void serializeRhymes(String name, SimpleDataset rhymes, int size) { System.out.print("Serializing " + name + " rhymes..."); try { FileOutputStream fileOut = new FileOutputStream(Main.rootPath + "data/rhyme_data/" + name + "-" + size + ".ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(rhymes); out.close(); fileOut.close(); System.out.println("Serialized " + name + " rhymes saved in data/rhyme_data/" + name + "-" + size + ".ser"); } catch(IOException i) { i.printStackTrace(); } } private static void serializeRhymes(String name, ScoreDataset rhymes, int size) { System.out.print("Serializing " + name + " rhymes..."); try { FileOutputStream fileOut = new FileOutputStream(Main.rootPath + "data/rhyme_data/" + name + "-scored-" + size + ".ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(rhymes); out.close(); fileOut.close(); System.out.println("Serialized " + name + " rhymes saved in data/rhyme_data/" + name + "-scored-" + size + ".ser"); } catch(IOException i) { i.printStackTrace(); } } public static List<JSONObject> parseJson(String jsonData) throws JSONException { List<JSONObject> result = new ArrayList<>(); final JSONArray array; try { array = new JSONArray(jsonData); } catch (JSONException e) { e.printStackTrace(); return null; } final int n = array.length(); for (int i = 0; i < n; ++i) { final JSONObject entry = array.getJSONObject(i); result.add(entry); } return result; } } <file_sep>/tables/Stress.java package tables; public enum Stress { PRI, SEC, NUL } <file_sep>/tables/MultiTables.java package tables; import java.io.Serializable; public class MultiTables implements Serializable { public MultiConsonantTables consonantTables; public VowelTables vowelTables; public MultiTables(MultiConsonantTables consonantTables, VowelTables vowelTables) { this.consonantTables = consonantTables; this.vowelTables = vowelTables; } public void foldAll() { consonantTables.foldTables(); vowelTables.foldTables(); } } <file_sep>/phonetics/syllabic/LL_Rhymer.java package phonetics.syllabic; import ben_alignment.Alignment; import ben_alignment.ConsonantAligner; import data.DataContainer; import genetic.Individual; import main.Main; import phonetics.*; import tables.MultiTables; import tables.ProbabilityTable; import tables.VowelTables; import java.util.*; public class LL_Rhymer { public final MultiTables ll_tables; private final double frontnessWeight; private final double heightWeight; private final double roundnessWeight; private final double tensionWeight; private final double stressWeight; private final double mannerWeight; private final double placeWeight; private final double voicingWeight; private final double onsetWeight; private final double nucleusWeight; private final double codaWeight; public static void main(String[] args) { Main.setupRootPath(); DataContainer.setupDict(); MultiTables tables = Main.deserializeTables(); // tables.consonantTables.LL_table_printLL(); // tables.vowelTables.LL_table_printLL(); // test(tables); String word = "keyboard"; Map<String, Double> rhymes = rhymesByThresholds(.95, 1.0, tables, word); TreeMap<String, Double> map = sortMapByValue(rhymes); System.out.println("RHYMES W/ " + word); for (Map.Entry<String,Double> entry : map.entrySet()) { System.out.println("\t" + entry.getKey() + "\t" + entry.getValue()); } } public LL_Rhymer(MultiTables ll_tables, double frontnessWeight, double heightWeight, double roundnessWeight, double tensionWeight, double stressWeight, double mannerWeight, double placeWeight, double voicingWeight, double onsetWeight, double nucleusWeight, double codaWeight) { this.ll_tables = ll_tables; this.frontnessWeight = frontnessWeight; this.heightWeight = heightWeight; this.roundnessWeight = roundnessWeight; this.tensionWeight = tensionWeight; this.stressWeight = stressWeight; this.mannerWeight = mannerWeight; this.placeWeight = placeWeight; this.voicingWeight = voicingWeight; this.onsetWeight = onsetWeight; this.nucleusWeight = nucleusWeight; this.codaWeight = codaWeight; } public LL_Rhymer(MultiTables ll_tables, Individual indiv) { this.ll_tables = ll_tables; this.frontnessWeight = indiv.getValues().get("frontness"); this.heightWeight = indiv.getValues().get("height"); this.roundnessWeight = indiv.getValues().get("roundness"); this.tensionWeight = indiv.getValues().get("tension"); this.stressWeight = indiv.getValues().get("stress"); this.mannerWeight = indiv.getValues().get("manner"); this.placeWeight = indiv.getValues().get("place"); this.voicingWeight = indiv.getValues().get("voicing"); this.onsetWeight = indiv.getValues().get("onset"); this.nucleusWeight = indiv.getValues().get("nucleus"); this.codaWeight = indiv.getValues().get("coda"); } public static TreeMap<String, Double> sortMapByValue(Map<String, Double> map){ Comparator<String> comparator = new ValueComparator(map); //TreeMap is a map sorted by its keys. //The comparator is used to sort the TreeMap by keys. TreeMap<String, Double> result = new TreeMap<>(comparator); result.putAll(map); return result; } // a comparator that compares Strings static class ValueComparator implements Comparator<String>{ Map<String, Double> map = new HashMap<>(); public ValueComparator(Map<String, Double> map){ this.map.putAll(map); } @Override public int compare(String s1, String s2) { if(map.get(s1) >= map.get(s2)){ return -1; }else{ return 1; } } } public static void test(MultiTables tables) { Set<String> words = new HashSet<>(); words.add("slant"); words.add("lies"); words.add("delight"); words.add("surprise"); words.add("eased"); words.add("kind"); words.add("blind"); // words.add("died"); // words.add("room"); // words.add("air"); // words.add("storm"); // words.add("dry"); // words.add("firm"); // words.add("king"); // words.add("away"); // words.add("be"); // words.add("was"); // words.add("fly"); // words.add("buzz"); // words.add("me"); // words.add("then"); // words.add("see"); int i = 0; for (String s1 : words) { for (String s2 : words) { if (!s1.equals(s2)) { oneTest(i, tables, s1, s2); } i++; } } // oneTest(1, tables, "storm", "away"); // oneTest(2, tables, "buzz", "was"); // oneTest(3, tables, "rock", "blot"); // oneTest(4, tables, "socks", "bricks"); // oneTest(5, tables, "socks", "blot"); // oneTest(5, tables, "bricks", "blot"); } public static void oneTest(int n, MultiTables tables, String s1, String s2) { System.out.println("\n\nTest " + n); List<WordSyllables> w1 = (Phoneticizer.getSyllables(s1)); List<WordSyllables> w2 = (Phoneticizer.getSyllables(s2)); double ga_score = LL_Rhymer.score2WordsByGaOptimizedWeights(tables,w1.get(0),w2.get(0)); // double weightless_score = LL_Rhymer.score2WordsWeightless(tables,w1.get(0),w2.get(0)); // double experimental_score = LL_Rhymer.score2WordsByExperimentalWeights(tables,w1.get(0),w2.get(0)); System.out.println("GA-optimized score for f(" + s1 + ", " + s2 + ") = " + ga_score); // System.out.println("zero weights score for f(" + s1 + ", " + s2 + ") = " + weightless_score); // System.out.println("experimental score for f(" + s1 + ", " + s2 + ") = " + experimental_score); } public static Map<String,Double> rhymesByThresholds(double min, double max, MultiTables tables, String s) { Map<String,Double> result = new HashMap<>(); WordSyllables w = (Phoneticizer.getSyllables(s)).get(0); for (Map.Entry<String, WordSyllables> entry : DataContainer.dictionary.entrySet()) { if (w.getRhymeTailFromStress().size() != entry.getValue().getRhymeTailFromStress().size()) continue; double score = score2WordsByGaOptimizedWeights(tables, w, entry.getValue()); if (score >= min && score <= max) { result.put(entry.getKey(), score); } } return result; } public static Map<String,Double> getGaOptimizedWeights() { Map<String,Double> map = new HashMap<>(); //As of: Sep 17, 2017 at 3:05pm //F score: 0.9600924 map.put("frontness", 652.94814227208); map.put("height", 1685.6992378582047); map.put("roundness", 1790.3363291882497); map.put("tension", 102.15861192785609); map.put("stress", 730.8691224727166); map.put("manner", 1706.8579995167618); map.put("place", 5.778357487807371); map.put("voicing", 1828.879820873744); map.put("onset", 28.677071986019257); map.put("nucleus", 652.879601960592); map.put("coda", 31.2507357193095); return map; // return normalizeWeights(map); } public static Map<String,Double> get100Weights() { Map<String,Double> map = new HashMap<>(); map.put("frontness", 100.0); map.put("height", 100.0); map.put("roundness", 100.0); map.put("tension", 100.0); map.put("stress", 100.0); map.put("manner", 100.0); map.put("place", 100.0); map.put("voicing", 100.0); map.put("onset", 100.0); map.put("nucleus", 100.0); map.put("coda", 100.0); return map; // return normalizeWeights(map); } public static Map<String,Double> getExperimentalWeights() { Map<String,Double> map = new HashMap<>(); map.put("frontness", 47.447956271080265); map.put("height", 151.347951581586); map.put("roundness", 65.45199233466151); map.put("tension", 118.49472506265411); map.put("stress", 300.0); map.put("manner", 80.80378174654354); map.put("place", 53.05358882143532); map.put("voicing", 25.0); map.put("onset", 40.938284197428366); map.put("nucleus", 100.0); map.put("coda", 87.89520831632227); return map; // return normalizeWeights(map); } public static Map<String,Double> getEqualWeights() { Map<String,Double> map = new HashMap<>(); map.put("frontness", 1.0); map.put("height", 1.0); map.put("roundness", 1.0); map.put("tension", 1.0); map.put("stress", 1.0); map.put("manner", 1.0); map.put("place", 1.0); map.put("voicing", 1.0); map.put("onset", 1.0); map.put("nucleus", 1.0); map.put("coda", 1.0); return map; // return normalizeWeights(map); } public static Map<String,Double> normalizeWeights(Map<String,Double> weights) { double max = Double.MIN_VALUE; double min = Double.MAX_VALUE; for (Map.Entry<String,Double> entry : weights.entrySet()) { double d = entry.getValue(); if (d > max) { max = d; } if (d < min) { min = d; } } for (Map.Entry<String,Double> entry : weights.entrySet()) { entry.setValue((entry.getValue() - min) / (max - min)); } return weights; } public static double score2SyllablesByExperimentalWeights(MultiTables tables, Syllable s1, Syllable s2) { Map<String,Double> map = getExperimentalWeights(); Individual indiv = new Individual(map); LL_Rhymer temp = new LL_Rhymer(tables, indiv); return temp.score2Syllables(s1,s2); } public static double score2SyllablesByGaOptimizedWeights(MultiTables tables, Syllable s1, Syllable s2) { Map<String,Double> map = getGaOptimizedWeights(); Individual indiv = new Individual(map); LL_Rhymer temp = new LL_Rhymer(tables, indiv); return temp.score2Syllables(s1,s2); } public static double score2SyllablesWeightless(MultiTables tables, Syllable s1, Syllable s2) { Map<String,Double> map = getEqualWeights(); Individual indiv = new Individual(map); LL_Rhymer temp = new LL_Rhymer(tables, indiv); return temp.score2Syllables(s1,s2); } public static Double score2WordsByGaOptimizedWeights(MultiTables tables, WordSyllables word1, WordSyllables word2) { if (word1 == null || word2 == null || word1.getRhymeTailFromStress() == null || word2.getRhymeTailFromStress() == null || word1.getRhymeTailFromStress().isEmpty() || word2.getRhymeTailFromStress().isEmpty()) return null; else if (word1.getRhymeTailFromStress().size() != word2.getRhymeTailFromStress().size()) { System.out.println("ERROR: rhyme tails of of unequal length"); return null; } else { SyllableList stressTail1 = word1.getRhymeTailFromStress(); SyllableList stressTail2 = word2.getRhymeTailFromStress(); double total = 0.0; for (int i = 0; i < stressTail1.size(); i++) { Syllable s1 = stressTail1.get(i); Syllable s2 = stressTail2.get(i); double syllablesScore; if (s1.equals(s2)) syllablesScore = 1.0; else syllablesScore = score2SyllablesByGaOptimizedWeights(tables, s1, s2); // System.out.println("syllablesScore " + i + ": " + syllablesScore); total += syllablesScore; } return new Double(total / (double)stressTail1.size()); } } public static Double score2WordsByExperimentalWeights(MultiTables tables, WordSyllables word1, WordSyllables word2) { if (word1 == null || word2 == null || word1.getRhymeTailFromStress() == null || word2.getRhymeTailFromStress() == null || word1.getRhymeTailFromStress().isEmpty() || word2.getRhymeTailFromStress().isEmpty()) return null; else if (word1.getRhymeTailFromStress().size() != word2.getRhymeTailFromStress().size()) { System.out.println("ERROR: rhyme tails of of unequal length"); return null; } else { SyllableList stressTail1 = word1.getRhymeTailFromStress(); SyllableList stressTail2 = word2.getRhymeTailFromStress(); double total = 0.0; for (int i = 0; i < stressTail1.size(); i++) { Syllable s1 = stressTail1.get(i); Syllable s2 = stressTail2.get(i); double syllablesScore; if (s1.equals(s2)) syllablesScore = 1.0; else syllablesScore = score2SyllablesByExperimentalWeights(tables, s1, s2); total += syllablesScore; } return new Double(total / (double)stressTail1.size()); } } public static Double score2WordsWeightless(MultiTables tables, WordSyllables word1, WordSyllables word2) { if (word1 == null || word2 == null || word1.getRhymeTailFromStress() == null || word2.getRhymeTailFromStress() == null || word1.getRhymeTailFromStress().isEmpty() || word2.getRhymeTailFromStress().isEmpty()) return null; else if (word1.getRhymeTailFromStress().size() != word2.getRhymeTailFromStress().size()) { System.out.println("ERROR: rhyme tails of of unequal length"); return null; } else { SyllableList stressTail1 = word1.getRhymeTailFromStress(); SyllableList stressTail2 = word2.getRhymeTailFromStress(); double total = 0.0; for (int i = 0; i < stressTail1.size(); i++) { Syllable s1 = stressTail1.get(i); Syllable s2 = stressTail2.get(i); double syllablesScore; if (s1.equals(s2)) syllablesScore = 1.0; else syllablesScore = score2SyllablesWeightless(tables, s1, s2); total += syllablesScore; } return new Double(total / (double)stressTail1.size()); } } public Double score2Words(WordSyllables word1, WordSyllables word2) { if (word1 == null || word2 == null || word1.getRhymeTailFromStress() == null || word2.getRhymeTailFromStress() == null || word1.getRhymeTailFromStress().isEmpty() || word2.getRhymeTailFromStress().isEmpty()) return null; else if (word1.getRhymeTailFromStress().size() != word2.getRhymeTailFromStress().size()) { System.out.println("ERROR: rhyme tails of of unequal length"); return null; } else { SyllableList stressTail1 = word1.getRhymeTailFromStress(); SyllableList stressTail2 = word2.getRhymeTailFromStress(); double total = 0.0; for (int i = 0; i < stressTail1.size(); i++) { Syllable s1 = stressTail1.get(i); Syllable s2 = stressTail2.get(i); double syllablesScore; if (s1.equals(s2)) syllablesScore = 1.0; else syllablesScore = score2Syllables(s1, s2); total += syllablesScore; } return new Double(total / (double)stressTail1.size()); } } public double score2Syllables(Syllable syl1, Syllable syl2) { if (syl1 == null && syl2 == null) return 1.0; if (syl1 == null || syl2 == null) return 0.0; if (syl1.equals(syl2)) return 1.0; double onsetWeight2 = onsetWeight; double codaWeight2 = codaWeight; //nuclei final VowelPhoneme n1 = syl1.getNucleus(); final VowelPhoneme n2 = syl2.getNucleus(); final double nucleus = score2Vowels(n1, n2) * nucleusWeight; //onsets List<ConsonantPhoneme> o1 = syl1.getOnset(); List<ConsonantPhoneme> o2 = syl2.getOnset(); double onset; if ((o1 == null && o2 == null) || (o1.isEmpty() && o2.isEmpty())) { onset = 0; onsetWeight2 = 0; } else if (o1.equals(o2)) { onset = 1.0; } else { Alignment onset_align = ConsonantAligner.align2ConsonantSequences(o1, o2, ll_tables.consonantTables, mannerWeight, placeWeight, voicingWeight); onset = onset_align.normalizedScore * onsetWeight; } //codas final List<ConsonantPhoneme> c1 = syl1.getCoda(); final List<ConsonantPhoneme> c2 = syl2.getCoda(); double coda; if ((c1 == null && c2 == null) || (c1.isEmpty() && c2.isEmpty())) { coda = 0; codaWeight2 = 0; } else if (c1.equals(c2)) { coda = 1.0; } else { final Alignment coda_align = ConsonantAligner.align2ConsonantSequences(c1, c2, ll_tables.consonantTables, mannerWeight, placeWeight, voicingWeight); coda = coda_align.normalizedScore * codaWeight; } // System.out.println("onset: " + onset); // System.out.println("nucleus: " + nucleus); // System.out.println("coda: " + coda); //syllable final double weightSum = onsetWeight2 + nucleusWeight + codaWeight2; final double syllableScore = (nucleus + onset + coda) / weightSum; return syllableScore; } private double score2Vowels(VowelPhoneme ph1, VowelPhoneme ph2) { if (ph1 == null && ph2 == null) return 1.0; if (ph1 == null || ph2 == null) return 0; if (ph1.equals(ph2)) return 1.0; VowelTables tables = ll_tables.vowelTables; final int f1 = tables.frontnessTable.getCoord(ph1.phonemeEnum.getFrontness()); final int h1 = tables.heightTable.getCoord(ph1.phonemeEnum.getHeight()); final int r1 = tables.roundnessTable.getCoord(ph1.phonemeEnum.getRoundness()); final int t1 = tables.tensionTable.getCoord(ph1.phonemeEnum.getTension()); final int s1 = tables.stressTable.getCoord(ph1.stress); final int f2 = tables.frontnessTable.getCoord(ph2.phonemeEnum.getFrontness()); final int h2 = tables.heightTable.getCoord(ph2.phonemeEnum.getHeight()); final int r2 = tables.roundnessTable.getCoord(ph2.phonemeEnum.getRoundness()); final int t2 = tables.tensionTable.getCoord(ph2.phonemeEnum.getTension()); final int s2 = tables.stressTable.getCoord(ph2.stress); final double frontness = this.normalizedScore(tables.frontnessTable, f1,f2); final double height = this.normalizedScore(tables.frontnessTable, h1,h2); final double roundness = this.normalizedScore(tables.frontnessTable, r1,r2); final double tension = this.normalizedScore(tables.frontnessTable, t1,t2); final double stress = this.normalizedScore(tables.frontnessTable, s1,s2); final double scoreSum = (frontness * frontnessWeight) + (height * heightWeight) + (roundness * roundnessWeight) + (tension * tensionWeight) + (stress * stressWeight); final double weightSum = frontnessWeight + heightWeight + roundnessWeight + tensionWeight + stressWeight; final double result = scoreSum / weightSum; // System.out.println("vowel score: " + result); return result; } //TODO: move these to the ProbabiityTable Class public double normalizedScore(ProbabilityTable table, int x, int y) { return (table.cell(x, y) - this.getMin(table)) / (this.getMax(table) - this.getMin(table)); } private double getMax(ProbabilityTable table) { double max = Double.MIN_VALUE; for (int i = 0; i < table.get_i_size(); i++) { for (int j = 0; j < table.get_j_size(); j++) { if (i <= j && table.get(i).get(j) > max) { max = table.get(i).get(j); } } } return max; } private double getMin(ProbabilityTable table) { double min = Double.MAX_VALUE; for (int i = 0; i < table.get_i_size(); i++) { for (int j = 0; j < table.get_j_size(); j++) { if (i <= j && table.get(i).get(j) < min) { min = table.get(i).get(j); } } } return min; } } <file_sep>/phonetics/syllabic/Rhymer.java package phonetics.syllabic; import genetic.Individual; import main.Main; import phonetics.*; import utils.*; import java.util.List; import java.util.Map; public class Rhymer { private final double frontnessWeight = 100; private final double heightWeight; private final double placeOfArticulationWeight = 100; private final double mannerOfArticulationWeight; private final double voicingWeight; private final double onsetWeight; private final double nucleusWeight = 100; private final double codaWeight; private final double stressWeight; public Rhymer(double frontnessWeight, double heightWeight, double placeOfArticulationWeight, double mannerOfArticulationWeight, double voicingWeight, double onsetWeight, double nucleusWeight, double codaWeight, double stressWeight) { // this.frontnessWeight = frontnessWeight; this.heightWeight = heightWeight; // this.placeOfArticulationWeight = placeOfArticulationWeight; this.mannerOfArticulationWeight = mannerOfArticulationWeight; this.voicingWeight = voicingWeight; this.onsetWeight = onsetWeight; // this.nucleusWeight = nucleusWeight; this.codaWeight = codaWeight; this.stressWeight = stressWeight; } public Rhymer(Individual weights) { Map<String,Double> map = weights.getValues(); // this.frontnessWeight = map.get("frontness"); this.heightWeight = map.get("height"); // this.placeOfArticulationWeight = map.get("place_of_articulation"); this.mannerOfArticulationWeight = map.get("manner_of_articulation"); this.voicingWeight = map.get("voicing"); this.onsetWeight = map.get("onset"); // this.nucleusWeight = map.get("nucleus"); this.codaWeight = map.get("coda"); this.stressWeight = map.get("stress"); } public static void main(String[] args) { Main.setupRootPath(); List<WordSyllables> w1 = (Phoneticizer.getSyllables("fate")); List<WordSyllables> w2 = (Phoneticizer.getSyllables("cat")); Rhymer temp = new Rhymer(100,1,4,5,6,7,8,9,10); double score = temp.score2Syllables(w1.get(0).get(0),w2.get(0).get(0)); System.out.println(score); } public static double score2SyllablesByGaOptimizedWeights(Syllable s1, Syllable s2) { Rhymer temp = new Rhymer(100,87.89145327765064,100,93.74256357399545,27.754425336501495,5.519934718254886,100,125.45080735803514,17.24887448289867); return temp.score2Syllables(s1,s2); /* New best individual: 0.9665289798059271 frontness: 100 height: 87.89145327765064 place of articulation: 100 manner of articulation: 93.74256357399545 voicing: 27.754425336501495 onset: 5.519934718254886 nucleus: 100 coda: 125.45080735803514 stress: 17.24887448289867 */ } public Double score2Words(WordSyllables word1, WordSyllables word2) { if (word1 == null || word2 == null || word1.getRhymeTailFromStress() == null || word2.getRhymeTailFromStress() == null || word1.getRhymeTailFromStress().isEmpty() || word2.getRhymeTailFromStress().isEmpty()) return null; else if (word1.getRhymeTailFromStress().size() != word2.getRhymeTailFromStress().size()) return null; else { double total = 0; for (int i = 0; i < word1.getRhymeTailFromStress().size(); i++) { Syllable s1 = word1.get(i); Syllable s2 = word2.get(i); total += score2Syllables(s1, s2); } return new Double(total / (double)word1.getRhymeTailFromStress().size()); } } public double score2Syllables(Syllable s1, Syllable s2) { if (s1 == null || s2 == null) return 0; if (s1.equals(s2)) return 1.0; int n = 3; List<ConsonantPhoneme> o1 = s1.getOnset(); List<ConsonantPhoneme> o2 = s2.getOnset(); double tempOnsetWeight = onsetWeight; double onsetScore; if (Utils.isNullorEmpty(o1) && Utils.isNullorEmpty(o2)) { n--; onsetScore = 0; tempOnsetWeight = 0; } else onsetScore = scoreConsonantPronunciations(o1,o2); VowelPhoneme n1 = s1.getNucleus(); VowelPhoneme n2 = s2.getNucleus(); double tempNucleusWeight = nucleusWeight; double nucleusScore; if (n1 == null && n2 == null) { n--; nucleusScore = 0; tempNucleusWeight = 0; } else nucleusScore = score2Vowels(n1,n2); List<ConsonantPhoneme> c1 = s1.getCoda(); List<ConsonantPhoneme> c2 = s2.getCoda(); double tempCodaWeight = codaWeight; double codaScore; if (Utils.isNullorEmpty(c1) && Utils.isNullorEmpty(c2)) { // n--; codaScore = 1.0; // tempCodaWeight = 0; } else codaScore = scoreConsonantPronunciations(c1,c2); double total = (tempOnsetWeight + tempNucleusWeight + tempCodaWeight) / n; double onsetMult = tempOnsetWeight / total; double nucleusMult = tempNucleusWeight / total; double codaMult = tempCodaWeight / total; double syllableAlignmentScore = ((onsetMult * onsetScore) + (nucleusMult * nucleusScore) + (codaMult * codaScore)) / n; //stress constraint int stress1 = s1.getStress(); int stress2 = s2.getStress(); if (stress1 == 1) stress1 = 2; else if (stress1 == 2) stress1 = 1; if (stress2 == 1) stress2 = 2; else if (stress2 == 2) stress2 = 1; int stressDiff = Math.abs(stress1 - stress2); if (stressDiff > 0) syllableAlignmentScore /= (stressDiff * (stressWeight / 100) + 1); return syllableAlignmentScore; } private double scoreConsonantPronunciations(List<ConsonantPhoneme> o1, List<ConsonantPhoneme> o2) { if (Utils.isNullorEmpty(o1) && Utils.isNullorEmpty(o2)) return 1.0; if (Utils.isNullorEmpty(o1) || Utils.isNullorEmpty(o2)) return 0.5; if (o1.equals(o2)) return 1.0; //chooses the highest-scoring pair to keep TODO upgrade this eventually double highestScore = 0; for (ConsonantPhoneme cp1 : o1) { for (ConsonantPhoneme cp2 : o2) { double temp = score2Consonants(cp1,cp2); if (temp > highestScore) { highestScore = temp; } } } return highestScore; // double alignmentScore = 0; // List<ConsonantPhoneme> shortest = o1; // List<ConsonantPhoneme> longest = o2; // if (o1.size() > o2.size()) { // shortest = o2; // longest = o1; // } // for (int cp = shortest.size() - 1; cp >= 0; cp--) { // ConsonantPhoneme cp1 = o1.get(cp); // ConsonantPhoneme cp2 = o2.get(cp); // alignmentScore += score2Consonants(cp1, cp2); // } // int n = longest.size(); // double average = alignmentScore / n; // return average; } private double score2Vowels(VowelPhoneme n1, VowelPhoneme n2) { if (n1.getPhonemeEnum() == n2.getPhonemeEnum()) return 1.0; if (n1 == null || n2 == null) return 0; double[] coord1 = PhonemeEnum.getCoord(n1.phonemeEnum); double[] coord2 = PhonemeEnum.getCoord(n2.phonemeEnum); if (coord1 == null || coord2 == null) return 0; double frontnessDiff = Math.abs(coord1[0] - coord2[0]) * frontnessWeight; double hightDiff = Math.abs(coord1[1] - coord2[1]) * heightWeight; double frontScore = Math.pow(frontnessDiff, 2); double heightScore = Math.pow(hightDiff, 2); double euclidianDistance = Math.sqrt(frontScore + heightScore); double normalizingConstant = Math.sqrt(Math.pow(10 * frontnessWeight,2) + Math.pow(10 * heightWeight,2));//TODO does this normalizing constant work? double normalizedDistance = euclidianDistance / normalizingConstant; double vowelMatchScore = 1.0 - normalizedDistance; return vowelMatchScore; } private double score2Consonants(ConsonantPhoneme ph1, ConsonantPhoneme ph2) { if (ph1 == null || ph2 == null) return 0; if (ph1.getPhonemeEnum() == ph2.getPhonemeEnum()) return 1.0; MannerOfArticulation m1 = PhonemeEnum.getManner(ph1.phonemeEnum); MannerOfArticulation m2 = PhonemeEnum.getManner(ph2.phonemeEnum); PlaceOfArticulation p1 = PhonemeEnum.getPlace(ph1.phonemeEnum); PlaceOfArticulation p2 = PhonemeEnum.getPlace(ph2.phonemeEnum); boolean v1 = ph1.isVoiced(); boolean v2 = ph2.isVoiced(); double maxScore = voicingWeight + mannerOfArticulationWeight + placeOfArticulationWeight; double score = 0; if (v1 == v2) score += voicingWeight; if (m1 == m2) score += mannerOfArticulationWeight; if (p1 == p2) score += placeOfArticulationWeight; double result = score / maxScore; return result; } public void align2Codas(ConsonantPronunciation c1, ConsonantPronunciation c2) { Double[][] table = new Double[c1.size()][c2.size()]; for (int i = 0; i < c1.size(); i++) { for (int j = 0; j < c2.size(); j++) { } } } } <file_sep>/utils/Utils.java package utils; import java.io.*; import java.util.*; import java.util.Map.Entry; public class Utils { private static Scanner scanner = new Scanner(System.in); public static void promptEnterKey(String string) { System.out.print(string); scanner.nextLine(); } /* * Credit to http://javatechniques.com/blog/faster-deep-copies-of-java-objects/ */ public static Object deepCopy(Object orig) { Object obj = null; try { // Write the object out to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(orig); out.flush(); out.close(); // Make an input stream from the byte array and read // a copy of the object back in. ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(bos.toByteArray())); obj = in.readObject(); } catch(IOException e) { e.printStackTrace(); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } return obj; } public static <T> String join(List<T> line, String delimiter) { StringBuilder str = new StringBuilder(); boolean first = true; for (T object : line) { if(!first) str.append(delimiter); else first = false; str.append(object); } return str.toString(); } public static String getPositionString(int i) { String posStr = "the "; if (i == -1) { posStr += "LAST"; } else if (i == 0) { posStr += "FIRST"; } else if (i == 1) { posStr += "SECOND"; } else if (i == 2) { posStr += "THIRD"; } else { posStr += (i+1) + "TH"; } return posStr + " position"; } public static <T extends Comparable<T>> Map<T, List<Integer>> sortByListSize(Map<T, List<Integer>> map, final boolean order) { List<Entry<T, List<Integer>>> list = new LinkedList<Entry<T, List<Integer>>>(map.entrySet()); // Sorting the list based on values Collections.sort(list, new Comparator<Entry<T, List<Integer>>>() { public int compare(Entry<T, List<Integer>> o1, Entry<T, List<Integer>> o2) { if (order) { return o1.getValue().size() - o2.getValue().size(); } else { return o2.getValue().size() - o1.getValue().size(); } } }); // Maintaining insertion order with the help of LinkedList Map<T, List<Integer>> sortedMap = new LinkedHashMap<T, List<Integer>>(); for (Entry<T, List<Integer>> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } public static <T> void incrementValueForKey(Map<T, Double> map, T key) { incrementValueForKey(map, key, 1.0); } public static <T> void incrementValueForKey(Map<T, Double> map, T key, Double incrementAmount) { Double count = map.get(key); map.put(key, count == null ? incrementAmount : count + incrementAmount); } public static <S, T> void incrementValueForKeys(Map<S, Map<T, Double>> map2d, S key1, T key2) { incrementValueForKeys(map2d, key1, key2, 1.0); } public static <S, T> void incrementValueForKeys(Map<S, Map<T, Double>> map2d, S key1, T key2, Double incrementAmount) { Map<T,Double> map1d = map2d.get(key1); if (map1d == null) { // never even seen prevState map1d = new HashMap<T,Double>(); map1d.put(key2, incrementAmount); map2d.put(key1, map1d); } else { // seen prev state Double count = map1d.get(key2); map1d.put(key2, count == null ? 1 : count + incrementAmount); } } public static <S extends Comparable<S>, T> T valueForKeyBeforeOrEqualTo(S currPos, SortedMap<S, T> tokens) { T currToken = null; for (S pos : tokens.keySet()) { if (pos.compareTo(currPos) > 0) { return currToken; } currToken = tokens.get(pos); } return currToken; } public static <S extends Comparable<S>, T> T valueForKeyBeforeOrEqualTo(Integer outerKey, S innerKey, SortedMap<Integer, SortedMap<S, T>> tokens) { T returnVal = null; if (tokens.containsKey(outerKey)) { returnVal = valueForKeyBeforeOrEqualTo(innerKey, tokens.get(outerKey)); } if (returnVal != null) return returnVal; outerKey--; while (!tokens.containsKey(outerKey) && outerKey >= 0) { outerKey--; } SortedMap<S, T> innerMap = tokens.get(outerKey); if (innerMap == null) { return null; } else { return innerMap.get(innerMap.lastKey()); } } public static void normalizeByFirstDimension(Map<Integer, Map<Integer, Double>> transitions) { for (Map<Integer, Double> row : transitions.values()) { //compute sum double sum = 0.0; for (Double colVal : row.values()) { sum += colVal; } //normalize for (Entry<Integer, Double> entry : row.entrySet()) { row.put(entry.getKey(), entry.getValue()/sum); } } } public static void normalizeByMaxVal(double[][] matrix) { double max = 0.0; for (double[] row : matrix) { for (double colVal : row) { if (colVal > max) { max = colVal; } } } if (max == 0) return; //normalize for (double[] row : matrix) { for (int i = 0; i < row.length; i ++) { row[i] /= max; } } } public static boolean isNullorEmpty(Collection c) { if (c == null || c.isEmpty()) return true; return false; } }
0e876ace9e8070714d8ae915ab63560f36576d03
[ "Java" ]
18
Java
BayBenj/rhyme-scorer
e22f5d27e9bd3307d0e1704b6f6e9fb5c70071a7
c9ff3c84e5e5a68d8c95b1c1d161804e9c426f03
refs/heads/master
<repo_name>special946/shoppinglist<file_sep>/ShoppingListWear/src/main/java/org/openintents/shopping/wear/ShoppingItemView.java package org.openintents.shopping.wear; import android.content.Context; import android.support.wearable.view.WearableListView; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import org.openintents.shopping.R; public class ShoppingItemView extends FrameLayout implements WearableListView.OnCenterProximityListener { final TextView title; final TextView tags; private final float mDefaultTextSize; private final float mSelectedTextSize; public ShoppingItemView(Context context, float defaultTextSize, float selectedTextSize) { super(context); View.inflate(context, R.layout.item_shopping, this); title = (TextView) findViewById(R.id.title); tags = (TextView) findViewById(R.id.tags); mDefaultTextSize = defaultTextSize; mSelectedTextSize = selectedTextSize; } @Override public void onCenterPosition(boolean b) { title.animate().scaleX(1f).scaleY(1f).alpha(1); tags.animate().scaleX(1f).scaleY(1f).alpha(1); } @Override public void onNonCenterPosition(boolean b) { title.animate().scaleX(0.8f).scaleY(0.8f).alpha(0.6f); tags.animate().scaleX(0.8f).scaleY(0.8f).alpha(0.6f); } }
eda16db5aed01459cdbb9fe88a5515e94e5be107
[ "Java" ]
1
Java
special946/shoppinglist
5ecdc142376fd92276a85c984fc18bd6c4bb9fa1
cc99835d11da986a9bba2aa39c75e266274cecf4
refs/heads/main
<file_sep># MyProgram TeleskuJavaLearning
4db0252143c9537c941e257a1aedc073bfcaf8fb
[ "Markdown" ]
1
Markdown
PrateekUpadhya/MyProgram
11de9694c208475659aad13952c0e401b112824b
2a19ca704a9614f3251f6064238800bfffc5fc0a
refs/heads/main
<file_sep>import React from "react"; import PropTypes from "prop-types"; import Popup from "reactjs-popup"; import "reactjs-popup/dist/index.css"; import Contact from "../Contact"; const PopUp = (props) => { const { popupTitle, popupContent } = props; // console.log(popupTitle, popupContent); /* eslint-disable */ return ( <Popup trigger={<a>{popupTitle}</a>} modal nested> {(close) => { if (popupTitle === "contact us") return ( <div className="modal"> <button className="close" onClick={close}> &times; </button> <div className="header">CONTACT US </div> <div className="content"> <div className="container"> <Contact contactApi={popupContent} /> </div> </div> </div> ); else return ( <div className="modal"> <button className="close" onClick={close}> &times; </button> <div className="header">{popupContent.$.pg_name} </div> <div className="content"> <div className="container"> <div dangerouslySetInnerHTML={{ __html: popupContent._ }} /> </div> </div> </div> ); }} </Popup> ); }; /* eslint-disable */ PopUp.propTypes = { pageTitle: PropTypes.string, popupContent: PropTypes.any, }; export default PopUp; <file_sep>import React, { useRef, useContext, useEffect } from "react"; // import io from "socket.io-client"; import rand_arr_elem from "../../../utils/rand_arr_elem"; // import rand_to_fro from "../../../utils/rand_to_fro"; import { Context } from "../../../data/context"; import gsap from "gsap"; import axios from "axios"; import info from "../../../data/info.json"; import SocketClient from "../../../utils/SocketClient"; import simplePost from "../../../utils/simplePost"; const GamePlay = () => { const winSets = [ ["c1", "c2", "c3"], ["c4", "c5", "c6"], ["c7", "c8", "c9"], ["c1", "c4", "c7"], ["c2", "c5", "c8"], ["c3", "c6", "c9"], ["c1", "c5", "c9"], ["c3", "c5", "c7"], ]; const c1 = useRef(); const c2 = useRef(); const c3 = useRef(); const c4 = useRef(); const c5 = useRef(); const c6 = useRef(); const c7 = useRef(); const c8 = useRef(); const c9 = useRef(); let refsGroup = [c1, c2, c3, c4, c5, c6, c7, c8, c9]; const { name, gameType, gameStep, gameBoard, gamePlay, nextTurnPlay, gameStat, playerType, playerSocket, playerNumber, gameRoom, win, } = useContext(Context); const [nameValue, setNameValue] = name; const [gameTypeValue, setGameTypeValue] = gameType; // eslint-disable-next-line const [gameStepValue, setGameStepValue] = gameStep; const [gameBoardValue, setGameBoardValue] = gameBoard; const [gamePlayValue, setGamePlayValue] = gamePlay; const [nextTurnPlayValue, setNextTurnPlayValue] = nextTurnPlay; const [gameStatValue, setGameStatValue] = gameStat; const [playerTypeValue] = playerType; const [playerSocketValue, setPlayerSocketValue] = playerSocket; const [playerNumberValue, setPlayerNumberValue] = playerNumber; const [gameRoomValue, setGameRoomValue] = gameRoom; const [winValue, setWinValue] = win; /* eslint-disable */ useEffect(() => { if (gameTypeValue !== "live") { setGamePlayValue(!gamePlayValue); if (!gameStatValue) setGameStatValue("Start Game"); checkWin( winSets, gameBoardValue, setGameStatValue, setGamePlayValue, renderWinGrid, playerTypeValue ); } else { if (!playerSocketValue) { setGameStatValue("Connecting..."); setGamePlayValue(false); setGameStatValue("Waiting..."); axios .get(info.getWebSocketClients) .then((response) => { const clients = Object.values(response.data); setPlayerSocketValue( SocketClient( clients, playerType, playerNumber, gamePlay, gameBoard, gameRoom, name, nextTurnPlay, gameStat, win ) ); }) .catch((err) => { setGameStatValue("Something went wrong..."); console.log(err); }); } } gsap.from("#game_stat", { duration: 1, display: "none", opacity: 0, scaleX: 0, scaleY: 0, ease: "power4.in", }); gsap.from("#game_board", { duration: 1, display: "none", opacity: 0, x: -200, y: -200, scaleX: 0, scaleY: 0, ease: "power4.in", }); }, []); useEffect(() => { if (winValue) { checkWin( winSets, gameBoardValue, setGameStatValue, setGamePlayValue, renderWinGrid, playerTypeValue ); } }, [nextTurnPlayValue, playerNumberValue, winValue]); /* eslint-disable */ const clickCell = (e) => { if (!nextTurnPlayValue || !gamePlayValue) return; const cellId = e.target.id.substr(11); if (gameBoardValue[cellId] || !cellId) return; playerTurn(cellId); setNextTurnPlayValue(false); if (gameTypeValue === "live") { liveCheckTurn(); } else { checkTurn(); } }; const liveCheckTurn = () => { const result = checkWin( winSets, gameBoardValue, setGameStatValue, setGamePlayValue, renderWinGrid, playerTypeValue ); // console.log(result); if (result[0]) { setGameStatValue("Opponent Wins"); setWinValue(true); } else if (result[1]) { setGameStatValue("Draw"); setGamePlayValue(false); } simplePost(info.exchangeData, { name: nameValue, board: gameBoardValue, result, to: gameRoomValue, }); }; const endGame = () => { setNameValue(""); setGameTypeValue(""); setGameStepValue("set_name"); setGamePlayValue(false); setGameBoardValue({}); setNextTurnPlayValue(true); setGameStatValue(""); if (gameTypeValue === "live") { playerSocketValue.close(); setPlayerSocketValue(null); setPlayerNumberValue(0); setGameRoomValue(1); setWinValue(false); } }; const playerTurn = (cellId) => { gameBoardValue[cellId] = playerTypeValue; gsap.from(`#game_board-${cellId}`, { duration: 0.3, display: "none", opacity: 0, scaleX: 0, scaleY: 0, ease: "power4.out", }); }; const compTurn = () => { let empty_cells_arr = []; for (let i = 1; i <= 9; i++) { !gameBoardValue["c" + i] && empty_cells_arr.push("c" + i); } const c = rand_arr_elem(empty_cells_arr); gameBoardValue[c] = "o"; gsap.from(`#game_board-${c}`, { duration: 0.3, display: "none", opacity: 0, scaleX: 0, scaleY: 0, ease: "power4.out", }); setNextTurnPlayValue(true); checkWin( winSets, gameBoardValue, setGameStatValue, setGamePlayValue, renderWinGrid, playerTypeValue ); }; const renderWinGrid = (set) => { for (let each of set) { refsGroup.forEach((r) => { if (each === r.current.id.substr(11)) { r.current.className += " win"; } }); } }; const checkTurn = () => { const [win, fin] = checkWin( winSets, gameBoardValue, setGameStatValue, setGamePlayValue, renderWinGrid, playerTypeValue ); // console.log(win); setTimeout(() => { if (!win && !fin) { gameTypeValue !== "live" && nextTurnPlayValue && compTurn(); } }, 500); }; const cellCont = (c) => { return ( <div> {gameBoardValue[c] === "x" && ( <i className="fa fa-times fa-5x player"></i> )} {gameBoardValue[c] === "o" && ( <i className="fa fa-circle-o fa-5x notplayer"></i> )} </div> ); }; return ( <div id="GameMain"> <h1>Play {gameTypeValue}</h1> <div id="game_stat"> <div id="game_stat_msg">{gameStatValue}</div> {gamePlayValue && ( <div id="game_turn_msg"> {nextTurnPlayValue ? "Your turn" : "Opponent turn"} </div> )} </div> <div id="game_board"> <table> <tbody> <tr> <td id="game_board-c1" ref={refsGroup[0]} onClick={clickCell}> {" "} {cellCont("c1")}{" "} </td> <td id="game_board-c2" ref={refsGroup[1]} className="vbrd" onClick={clickCell} > {" "} {cellCont("c2")}{" "} </td> <td id="game_board-c3" ref={refsGroup[2]} onClick={clickCell}> {" "} {cellCont("c3")}{" "} </td> </tr> <tr> <td id="game_board-c4" ref={refsGroup[3]} onClick={clickCell} className="hbrd" > {" "} {cellCont("c4")}{" "} </td> <td id="game_board-c5" ref={refsGroup[4]} onClick={clickCell} className="vbrd hbrd" > {" "} {cellCont("c5")}{" "} </td> <td id="game_board-c6" ref={refsGroup[5]} onClick={clickCell} className="hbrd" > {" "} {cellCont("c6")}{" "} </td> </tr> <tr> <td id="game_board-c7" ref={refsGroup[6]} onClick={clickCell}> {" "} {cellCont("c7")}{" "} </td> <td id="game_board-c8" ref={refsGroup[7]} onClick={clickCell} className="vbrd" > {" "} {cellCont("c8")}{" "} </td> <td id="game_board-c9" ref={refsGroup[8]} onClick={clickCell}> {" "} {cellCont("c9")}{" "} </td> </tr> </tbody> </table> </div> <button type="submit" onClick={endGame} className="button"> <span> End Game <span className="fa fa-caret-right"></span> </span> </button> </div> ); }; export default GamePlay; export const checkWin = ( winSets, gameBoardValue, setGameStatValue, setGamePlayValue, renderWinGrid, playerTypeValue ) => { let set; let win = false; let fin = true; for (let i = 0; !win && i < winSets.length; i++) { set = winSets[i]; if ( gameBoardValue[set[0]] && gameBoardValue[set[0]] === gameBoardValue[set[1]] && gameBoardValue[set[0]] === gameBoardValue[set[2]] ) win = true; } for (let i = 1; i <= 9; i++) !gameBoardValue["c" + i] && (fin = false); if (win) { setGameStatValue( (gameBoardValue[set[0]] === playerTypeValue ? "You" : "Opponent") + " win" ); setGamePlayValue(false); renderWinGrid(set); } else if (fin) { setGameStatValue("Draw"); setGamePlayValue(false); } return [win, fin]; }; <file_sep>import rand_to_fro from "./rand_to_fro"; const rand_arr_elem = function (a) { return a ? a[rand_to_fro(a.length - 1)] : null; }; export default rand_arr_elem; <file_sep>import React from "react"; import { Link } from "react-router-dom"; import PropTypes from "prop-types"; import Logo from "../../../static/image/tic_tac_toe.png"; const Header = (props) => { const { headerContent, mainMenu } = props; const headLogo = headerContent[0].head_l_logo[0].$; const siteTitle = headerContent[0].site_title[0].$; const menu = mainMenu[0].pages[0].p; // console.log(headLogo, siteTitle, menu); return ( <header id="main_header"> <div id="brand"> <div className="container"> <Link to={headLogo.u} className="logo-tl"> <img src={Logo} alt="logo" /> </Link> <Link to={siteTitle.u} className="main-site-name"> {siteTitle.txt} </Link> <nav> <ul> {menu.map(function (p, i) { return ( <li key={i}> <Link to={p.$.u}> <i className={"fa fa-2x " + p.$.ico} aria-hidden="true" ></i> {p.$.name} </Link> </li> ); })} </ul> </nav> </div> </div> </header> ); }; Header.propTypes = { headerContent: PropTypes.any.isRequired, mainMenu: PropTypes.any, }; export default Header; <file_sep>const nodemailer = require("nodemailer"); const info = require("../info.json"); const transporter = nodemailer.createTransport({ service: info.emailService, host: info.emailHost, secure: true, port: info.emailPort, auth: { user: info.emailUser, pass: <PASSWORD>, }, }); const emailSender = (request, response) => { const { name, email, subject, message } = request.body; const mailOptions = { from: `'${name}' <${email}>`, to: info.emailUser, subject: `${subject}`, html: `${message}`, }; transporter.sendMail(mailOptions, (err, info) => { if (err) { console.log(err); response.status(200).json({ status: "error" }); } else { console.log(`Message sent: ${info.response}`); response.status(200).json(info.response); } }); }; module.exports = { emailSender, }; <file_sep>import axios from "axios"; const simplePost = (url, data) => { axios .post(url, { ...data }) .then((result) => { console.log(result.data); }) .catch((err) => { console.log(err); }); }; export default simplePost; <file_sep>import React, { useState, useEffect } from "react"; import XMLData from "./ws_conf.xml"; import axios from "axios"; import xml2js from "xml2js"; export const Context = React.createContext(); const Parser = new xml2js.Parser(); const Provider = (props) => { const [siteContent, setSiteContent] = useState({}); const [name, setName] = useState(""); const [gameStep, setGameStep] = useState("set_name"); const [gameType, setGameType] = useState(""); const [gamePlay, setGamePlay] = useState(false); const [gameBoard, setGameBoard] = useState({}); const [nextTurnPlay, setNextTurnPlay] = useState(true); const [gameStat, setGameStat] = useState(""); const [playerType, setPlayerType] = useState("x"); const [playerSocket, setPlayerSocket] = useState(null); const [playerNumber, setPlayerNumber] = useState(0); const [gameRoom, setGameRoom] = useState("1"); const [win, setWin] = useState(false); useEffect(() => { axios .get(XMLData, { "Content-Type": "application/xml; charset=utf-8", }) .then((response) => { Parser.parseString(response.data, (err, result) => { setSiteContent(result); }); }); }, []); return ( <Context.Provider value={{ siteContent: [siteContent, setSiteContent], name: [name, setName], gameStep: [gameStep, setGameStep], gameType: [gameType, setGameType], gameBoard: [gameBoard, setGameBoard], gamePlay: [gamePlay, setGamePlay], nextTurnPlay: [nextTurnPlay, setNextTurnPlay], gameStat: [gameStat, setGameStat], playerType: [playerType, setPlayerType], playerSocket: [playerSocket, setPlayerSocket], playerNumber: [playerNumber, setPlayerNumber], gameRoom: [gameRoom, setGameRoom], win: [win, setWin], }} > {props.children} </Context.Provider> ); }; export default Provider; export const Consumer = Context.Consumer; <file_sep>import React from "react"; import PropTypes from "prop-types"; import { Link } from "react-router-dom"; const Home = (props) => { const { homeContent } = props; const pgName = homeContent.$.pg_name; const buttons = homeContent.btns; const txt = homeContent.txt[0]; // console.log(pgName, buttons, txt); return ( <div id="Txt_page"> <div id="page-container"> <h1>{pgName}</h1> <div dangerouslySetInnerHTML={{ __html: txt }} /> <div className="btns"> {buttons.map(function (b, i) { return ( <Link to={b.b[0].$.u} key={i}> <button type="submit" className="button"> <span> {b.b[0].$.txt} <span className="fa fa-caret-right"></span> </span> </button> </Link> ); })} </div> </div> </div> ); }; Home.propTypes = { homeContent: PropTypes.any.isRequired, }; export default Home; <file_sep>// import logo from "./logo.svg"; // import "./App.css"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import Provider, { Consumer } from "./data/context"; import Header from "./views/layout/Header"; import Footer from "./views/layout/Footer"; import MainContent from "./views/layout/MainContent"; import Home from "./views/pages/Home"; import Game from "./views/pages/Game"; function App() { return ( <Provider> <Consumer> {(value) => { const { siteContent } = value; const [siteContentValue] = siteContent; const { data } = siteContentValue; // console.log(data); if (data === undefined) { return <div className="App"></div>; } else { return ( <Router> <div className="App"> <Header headerContent={data.header} mainMenu={data.main_menu} ></Header> <Switch> <MainContent> <Route exact path="/TicTacToe" component={() => ( <Home homeContent={data.pgs[0].home[0]} /> )} /> <Route exact path="/ttt" component={Game} /> <Route exact path="/info" component={() => ( <Home homeContent={data.pgs[0].info[0]} /> )} /> </MainContent> </Switch> <Footer footerContent={data.footer} termsAndConditions={data.pgs[0].terms_and_conditions[0]} privacy={data.pgs[0].privacy_policy[0]} contactApi={data.loc[0].SCRIPT__contact_form[0].$.u} ></Footer> </div> </Router> ); } }} </Consumer> </Provider> ); } export default App; <file_sep>import React, { useContext } from "react"; import SetName from "./SetName"; import SetGameType from "./SetGameType"; import GamPlay from "./GamePlay"; import { Context } from "../../../data/context"; const Game = () => { const { name, gameStep } = useContext(Context); const [nameValue] = name; const [gameStepValue] = gameStep; // console.log(gameStepValue, gameBoardValue); return ( <div id="TTT_game"> <div id="page-container"> {gameStepValue === "set_name" && ( <SetName gameStep={gameStep} name={name} /> )} {gameStepValue !== "set_name" && ( <div> <h2>Welcome, {nameValue}</h2> </div> )} {gameStepValue === "set_game_type" && <SetGameType></SetGameType>} {gameStepValue === "start_game" && <GamPlay></GamPlay>} </div> </div> ); }; export default Game; <file_sep>export { default } from "./SocketClient";<file_sep>import React, { useContext } from "react"; import { Context } from "../../../data/context"; const SetName = () => { const { name, gameStep } = useContext(Context); // eslint-disable-next-line const [gameStepValue, setGameStepValue] = gameStep; const [nameValue, setNameValue] = name; const saveName = (e) => { e.preventDefault(); if (nameValue.length > 0) setGameStepValue("set_game_type"); // console.log("save name", gameStepValue, nameValue); }; const onName = (e) => { e.preventDefault(); setNameValue(e.target.value); }; return ( <div id="SetName"> <h1>Set Name</h1> <form onSubmit={saveName}> <div className="input_holder left"> {" "} <label>Name </label> <input type="text" className="input name" placeholder="Name" onChange={onName} required /> </div> <button type="submit" className="button"> <span> SAVE <span className="fa fa-caret-right"></span> </span> </button> </form> </div> ); }; export default SetName; <file_sep>import { w3cwebsocket as W3CWebSocket } from "websocket"; const Socket = ( url, gamePlay, name, gameBoard, nextTurnPlay, gameStat, win ) => { // eslint-disable-next-line const [gamePlayValue, setGamePlayValue] = gamePlay; const [nameValue] = name; // eslint-disable-next-line const [gameBoardValue, setGameBoardValue] = gameBoard; // eslint-disable-next-line const [nextTurnPlayValue, setNextTurnPlayValue] = nextTurnPlay; // eslint-disable-next-line const [gameStatValue, setGameStatValue] = gameStat; // eslint-disable-next-line const [winValue, setWinValue] = win; const socket = new W3CWebSocket(url); socket.onopen = () => { console.log("socket is open"); }; socket.onclose = () => { console.log("socket is closed"); }; socket.onmessage = (message) => { const m = JSON.parse(message.data); console.log("Message from server", m); if (m.name !== nameValue) { setGameBoardValue(m.board); if (!m.result[0] && !m.result[1]) { setGameStatValue("Start Game"); setGamePlayValue(true); setNextTurnPlayValue(nextTurnPlay); } if (m.result[0]) { setGameStatValue("Opponent Wins"); setWinValue(true); } else if (m.result[1]) { setGameStatValue("Draw"); setGamePlayValue(false); } } }; socket.onerror = (error) => { console.log(error); }; return socket; }; export default Socket; <file_sep>import React from "react"; // import { Link } from "react-router-dom"; import PropTypes from "prop-types"; import logo from "../../../static/image/K_logo.png"; import PopUp from "../PopUp"; // import Contact from "../Contact"; const Footer = (props) => { const { footerContent, termsAndConditions, privacy, contactApi } = props; // console.log(termsAndConditions, privacy); const footMsg = footerContent[0].foot_msg[0].$; const items = footerContent[0].items[0].i; const footRLogo = footerContent[0].foot_r_logo[0].$; // console.log(footMsg, items, footRLogo); return ( <footer> <div className="container"> <nav> <ul> {items.map((it, i) => { if (it.$.tp === "ln") { switch (it.$.txt) { case "terms and conditions": return ( <li key={i}> <PopUp popupTitle={it.$.txt} popupContent={termsAndConditions} ></PopUp> </li> ); case "privacy": return ( <li key={i}> <PopUp popupTitle={it.$.txt} popupContent={privacy} ></PopUp> </li> ); case "contact us": return ( <li key={i}> <PopUp popupTitle={it.$.txt} popupContent={contactApi} ></PopUp> </li> ); default: return null; } } else { return <li key={i}>{it.$.txt}</li>; } })} </ul> </nav> <div className="foot_message"> {footMsg.txt} </div> <a className="foot-r-logo" href={footRLogo.u} target={footRLogo.t} rel="noopener noreferrer" > <img alt="footer logo" src={logo} /> </a> </div> </footer> ); }; Footer.propTypes = { footerContent: PropTypes.any.isRequired, }; export default Footer; <file_sep>import React, { useState } from "react"; import validator from "validator"; import PropTypes from "prop-types"; import axios from "axios"; const Contact = (props) => { const { contactApi } = props; const [unsent, setUnsent] = useState(true); const [sending, setSending] = useState(false); const [sent, setSent] = useState(false); const [sentErr, setSentErr] = useState(false); const [nameValid, setNameValid] = useState(true); const [emailValid, setEmailValid] = useState(true); const [subjectValid, setSubjectValid] = useState(true); const [messageValid, setMessageValid] = useState(true); const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [subject, setSubject] = useState(""); const [message, setMessage] = useState(""); const checkForm = () => { const n = name.trim(); const e = email.trim(); const s = subject.trim(); const m = message.trim(); const validName = n.length > 0; const validEmail = validator.isEmail(e); const validSubject = s.length > 0; const validMessage = m.length > 0; setNameValid(validName); setEmailValid(validEmail); setSubjectValid(validSubject); setMessageValid(validMessage); return validName && validEmail && validSubject && validMessage; }; const onNameChange = (e) => { setName(e.target.value); }; const onEmailChange = (e) => { setEmail(e.target.value); }; const onSubjectChange = (e) => { setSubject(e.target.value); }; const onMessageChange = (e) => { setMessage(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); const isValid = checkForm(); if (isValid) { setUnsent(false); setSending(true); axios .post(contactApi, { name, email, subject, message, }) .then( (response) => { // console.log(response); setSending(false); setSent(true); if (response.status !== 200) setSentErr(true); }, (error) => { setSending(false); setSent(true); setSentErr(true); } ); } }; const sendingCopy = ( <div>I am sending your message over the wire.......... please hold.</div> ); const sendingErr = ( <div>There was an error sending your request. Please try again</div> ); const sentCopy = ( <div> <strong> Okay we got your message, we will be touching base shortly. </strong> </div> ); const form = ( <form id="contact_form" onSubmit={handleSubmit} method="POST"> <FieldHolder goodclasses="input_holder left" badclasses="error" isvalid={nameValid.toString()} > <label> Name <span className="required">is a required field</span> </label> <input type="text" className="input name" placeholder="Name" value={name} onChange={onNameChange} required /> </FieldHolder> <FieldHolder goodclasses="input_holder left" badclasses="error" isvalid={emailValid.toString()} > <label> Email <span className="required">is a required field</span> </label> <input type="email" className="input name" placeholder="Your Email" value={email} onChange={onEmailChange} required /> </FieldHolder> <FieldHolder goodclasses="input_holder select_option" badclasses="error" isvalid={subjectValid.toString()} > <label> Subject <span className="required">is a required field</span> </label> <select onChange={onSubjectChange} required> <option value={subject}>Choose one</option> <option>Join / Login</option> <option>An issue with the website</option> <option>Other</option> </select> </FieldHolder> <FieldHolder goodclasses="input_holder clear message" badclasses="error" isvalid={messageValid.toString()} > <label> Message <span className="required">is a required field</span> </label> <textarea className="input textarea" value={message} onChange={onMessageChange} required ></textarea> </FieldHolder> <button type="submit" className="button"> <span> SEND <span className="fa fa-caret-right"></span> </span> </button> <p className="disclaimer"> Any personal information collected in this contact form is so that we can send you the information you have requested. It will not be used for any other reason. </p> </form> ); return ( <> {unsent && form} {sending && sendingCopy} {sent && !sentErr && sentCopy} {sent && sentErr && sendingErr} </> ); }; export default Contact; export const FieldHolder = (props) => { const { isvalid, goodclasses, badclasses } = props; const currentClasses = isvalid ? goodclasses : goodclasses + " " + badclasses; const newProps = Object.assign({}, props, { className: currentClasses }); return <div {...newProps}>{props.children}</div>; }; FieldHolder.propTypes = { children: PropTypes.any, isvalid: PropTypes.string, goodclasses: PropTypes.string.isRequired, badclasses: PropTypes.string.isRequired, }; Contact.propTypes = { contactApi: PropTypes.string.isRequired, };
acf2ee46a88e483048801fddb3940d7b650e48f3
[ "JavaScript" ]
15
JavaScript
WL0416/TicTacToe
6ea77eecfea32c49952ca075bb02ea2afbf8ce33
0d7bd88719e97d9dd5dbedd0fcd9dcda5d1a0011
refs/heads/master
<repo_name>larrylam10/MVCFinalProject<file_sep>/index.php <?php error_reporting(E_ALL ^ E_NOTICE); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Student Registration System</title> <!-- Bootstrap core CSS --> <link href="css/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="css/simple-sidebar.css" rel="stylesheet"> </head> <body> <div class="d-flex" id="wrapper"> <!-- Sidebar --> <div class="bg-light border-right" id="sidebar-wrapper"> <div class="sidebar-heading">Welcome</div> <div class="list-group list-group-flush"> <a href="?request=register" class="list-group-item list-group-item-action bg-light">Register</a> <a href="?request=students-list" class="list-group-item list-group-item-action bg-light">List of Students</a> </div> </div> <!-- Page Content --> <div id="page-content-wrapper"> <div class="container-fluid"> <?php require "db.php"; require "view/registration.php"; require "view/studentlist.php"; require "controller/StudentController.php"; $request = $_REQUEST['request']; if (isset($request)) { $studentController = new StudentController(); switch($request){ case "register": $registrationView = new Registration($studentController); $registrationView->loadRegistrationForm(); break; case "students-list": $studentsListView = new StudentList(); $studentsListView->studentsList(); break; default: echo "url does not exist"; } } ?> </div> </div> <!-- /#page-content-wrapper --> </div> <!-- /#wrapper --> <!-- Bootstrap core JavaScript --> <script src="css/vendor/jquery/jquery.min.js"></script> <script src="css/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> </body> </html><file_sep>/view/studentlist.php <?php class StudentList { private $controller; public function __construct() { $controller = new StudentController(); } public function studentsList() { $controller = new StudentController(); $result = $controller->fetchStudents(); echo "<table class='table table-striped'>"; echo "<thead> <tr><th>Name</th><th>Gender</th><th>Class</th><th>Mobile</th><th>Email</th><th>Address</th></tr> </thead><tbody>"; for($i=0; $i < count($result); $i++) { echo "<tr> <td>".$result[$i]['surname'] ." ". $result[$i]['firstName'] ."</td> <td>". $result[$i]['gender'] ."</td> <td>". $result[$i]['class'] ."</td> <td>". $result[$i]['mobilenumber'] ."</td> <td>". $result[$i]['emailAddress'] ."</td> <td>". $result[$i]['address'] ."</td> </tr>"; } echo "</tbody></table>"; } } ?><file_sep>/controller/StudentController.php <?php Class StudentController extends DB { private $student; public function __construct($student=null) { parent::__construct(); $this->student = $student; } public function registerStudent($student) { $data = [ 'firstName' => $student->firstName, 'surname' => $student->surname, 'gender' => $student->gender, 'class' => $student->class, 'emailAddress' => $student->emailAddress, 'mobilenumber' => $student->mobilenumber, 'address' => $student->address, ]; $sql = "INSERT INTO student (firstName, surname, gender, class, emailAddress, mobilenumber, address) VALUES (:firstName, :surname, :gender, :class, :emailAddress, :mobilenumber, :address)"; $result = $this->insert($sql, $data); if ($result) { $result ="Student registered successfully"; } else { $result ="Failed to register student"; } return $result; } public function fetchStudents() { $sql = "SELECT * FROM student"; $result = $this->select($sql); return $result; } } ?><file_sep>/registration (5).sql -- phpMyAdmin SQL Dump -- version 4.9.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3308 -- Generation Time: Jun 04, 2020 at 02:33 PM -- Server version: 8.0.18 -- PHP Version: 7.3.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `registration` -- -- -------------------------------------------------------- -- -- Table structure for table `student` -- DROP TABLE IF EXISTS `student`; CREATE TABLE IF NOT EXISTS `student` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `firstName` varchar(100) NOT NULL, `surname` varchar(100) NOT NULL, `gender` varchar(6) NOT NULL, `class` varchar(50) NOT NULL, `emailAddress` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, `mobilenumber` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, `address` varchar(100) DEFAULT NULL, PRIMARY KEY (`ID`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; -- -- Dumping data for table `student` -- INSERT INTO `student` (`ID`, `firstName`, `surname`, `gender`, `class`, `emailAddress`, `mobilenumber`, `address`) VALUES (1, 'Larry', 'Mukasa', 'Male', '2', 'Namutebihellen<EMAIL>', '0909090', 'popopo'), (2, 'John', 'Sse', 'Male', '4', '<EMAIL>', '0703404040', '345'), (3, 'John', 'Wasswa', 'Male', '3', '<EMAIL>', '0704898765', '234 Kla'); COMMIT; /*!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 */; <file_sep>/view/registration.php <?php require "model/student.php"; class Registration { private $student; private $studentController; public function __construct($controller, $model=null) { $this->student = $model; $this->studentController = $controller; } public function loadRegistrationForm() { echo " <h1>Enter registration details</h1><br/>&nbsp; <form method='post' action='#'> <input type='text' name='firstName' placeholder='<NAME>' required='required'/><br/>&nbsp;<br/> <input type='text' name='surname' placeholder='Surname' required='required'/><br/>&nbsp;<br/> <input type='text' name='class' placeholder='Class'/><br/>&nbsp;<br/> <select name='gender' required='required'><br/>&nbsp;<br/> <option value='Male' selected='selected'>Male</option> <option value='Female'>Female</option> </select> <input type='email' name='email' placeholder='Email'/><br/>&nbsp;<br/> <input type='text' name='mobilenumber' placeholder='Mobile' required='required'/><br/>&nbsp;<br/> <input type='text' name='address' placeholder='Address'/><br/>&nbsp;<br/> <input type='submit' name='submit-registration' value='Save Data'/> </form> "; if (isset($_REQUEST['submit-registration'])) { $firstName = $_POST['firstName']; $surname = $_POST['surname']; $gender = $_POST['gender']; $class = $_POST['class']; $emailAddress = $_POST['email']; $mobilenumber = $_POST['mobilenumber']; $address = $_POST['address']; // echo $firstName." ".$surname." ".$gender." ".$emailAddress." ".$mobilenumber." ".$address; $student = new Student($firstName, $surname, $gender, $class, $emailAddress, $mobilenumber, $address); $result = $this->studentController->registerStudent($student); echo "<p>$result</p>"; } } } ?><file_sep>/model/student.php <?php class Student { public $ID; public $firstName; public $surname; public $gender; public $class; public $emailAddress; public $mobilenumber; public $address; public function __construct($firstName, $surname, $gender, $class, $emailaddress, $mobilenumber, $address, $id=null) { $this->ID = $id; $this->firstName = $firstName; $this->surname = $surname; $this->gender = $gender; $this->class = $class; $this->emailAddress = $emailaddress; $this->mobilenumber = $mobilenumber; $this->address = $address; } } ?><file_sep>/README.md # MVCFinalProject A sample application that uses the MVC Framework
6fca2db2ef39d0478c02c20c6b1aa6fe8491c716
[ "Markdown", "SQL", "PHP" ]
7
PHP
larrylam10/MVCFinalProject
8980260bd5e319b1f399b2fe33232d52d165e5f0
37b04053a7e0ba6e9a2950fa24a84e26672387a1
refs/heads/master
<repo_name>HaoRanZhuuu/wxtest<file_sep>/MysqlTset/src/com/zhuhaoran/mapper/StudentMapper.java package com.zhuhaoran.mapper; import com.zhuhaoran.po.Student; public interface StudentMapper { public void insertStudent(Student student) throws Exception; } <file_sep>/README.md # wxtest 本项目是参加学校为期一周的暑期夏令营的相关项目 主要了解到的微信开发的基础知识 <file_sep>/MysqlTset/src/com/zhuhaoran/test/getUser.java package com.zhuhaoran.test; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.zhuhaoran.mapper.UserMapper; import com.zhuhaoran.po.User; public class getUser { private SqlSessionFactory sqlSessionFactory; public User getUsers(int id) throws Exception{ //Mybatis // 配置文件 String resources = "sqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resources); // 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); // 数据库会话实例 SqlSession sqlSession = null; // 创建数据库会话实例sqlSession sqlSession = sqlSessionFactory.openSession(); // 查询单个记录,根据用户id查询用户信息 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.findUserById(id); // 输出用户信息 System.out.println(user); return user; } } <file_sep>/MysqlTset/src/com/zhuhaoran/servlet/searchServlet.java package com.zhuhaoran.servlet; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.json.JSONException; import org.json.JSONObject; import com.zhuhaoran.mapper.UserMapper; import com.zhuhaoran.po.User; import com.zhuhaoran.test.getUser; public class searchServlet extends HttpServlet{ private SqlSessionFactory sqlSessionFactory; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain;charset=utf-8"); String id = req.getParameter("id"); int idd = Integer.parseInt(id); //////////////////////////// resp.setCharacterEncoding("utf-8"); PrintWriter out = resp.getWriter(); JSONObject obj = new JSONObject(); try { getUser getUser = new getUser(); User user = getUser.getUsers(idd); obj.put("result", "ok"); obj.put("id", user.getId()); obj.put("name", user.getUsername()); obj.put("password", <PASSWORD>()); obj.put("address", user.getAddress()); obj.put("phone", user.getPhone()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(obj.toString()); out.print(obj.toString()); out.flush(); out.close(); ///////////////////// } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } public static void main(String[] args) { System.out.println("123"); } } <file_sep>/MysqlTset/src/com/zhuhaoran/po/Student.java package com.zhuhaoran.po; import java.util.Date; public class Student { private int id; private String name; private double score; private Date time; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", score=" + score + ", time=" + time + "]"; } } <file_sep>/test.sql /* Navicat MySQL Data Transfer Source Server : db Source Server Version : 50722 Source Host : localhost:3306 Source Database : test Target Server Type : MYSQL Target Server Version : 50722 File Encoding : 65001 Date: 2018-07-17 16:43:58 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `question` -- ---------------------------- DROP TABLE IF EXISTS `question`; CREATE TABLE `question` ( `tid` int(5) NOT NULL AUTO_INCREMENT, `question` varchar(1000) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `opA` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `opB` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `opC` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `opD` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `answer` varchar(2) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`tid`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of question -- ---------------------------- INSERT INTO `question` VALUES ('1', '如果一个方法或变量是\"private\"访问级别,那么它的访问范围是:', '在当前类,或者子类中', '在当前类或者它的父类中', '在当前类,或者它所有的父类中', '在当前类中', 'D'); INSERT INTO `question` VALUES ('2', '以下定义一维数组的语句中,正确的是:()', 'int a [10]', 'int a []=new [10]', 'int a[]\r\nint a []=new int [10]', 'int a []={1,2,3,4,5}', 'D'); INSERT INTO `question` VALUES ('3', '以下哪个不属于JVM堆内存中的区域()?', 'survivor区', '常量池', 'eden区', 'old区', 'B'); INSERT INTO `question` VALUES ('4', '下面有关java实例变量,局部变量,类变量和final变量的说法,错误的是?', '实例变量指的是类中定义的变量,即成员变量,如果没有初始化,会有默认值。', '局部变量指的是在方法中定义的变量,如果没有初始化,会有默认值', '类变量指的是用static修饰的属性', 'final变量指的是用final 修饰的变量', 'B'); INSERT INTO `question` VALUES ('5', '下列不属于算法结构的是()', '输入数据', '处理数据', '存储数据', '输出结果', 'C'); INSERT INTO `question` VALUES ('6', '以下说法错误的是()', '虚拟机中没有泛型,只有普通类和普通方法', '所有泛型类的类型参数在编译时都会被擦除', '创建泛型对象时请指明类型,让编译器尽早的做参数检查', '泛型的类型擦除机制意味着不能在运行时动态获取List<T>中T的实际类型', 'D'); INSERT INTO `question` VALUES ('7', '以下哪项陈述是正确的?', '垃圾回收线程的优先级很高,以保证不再 使用的内存将被及时回收', '垃圾收集允许程序开发者明确指定释放 哪一个对象', '垃圾回收机制保证了JAVA程序不会出现 内存溢出', '以上都不对', 'D'); INSERT INTO `question` VALUES ('8', '下列关于继承的哪项叙述是正确的? ', '在java中类允许多继承', '在java中一个类只能实现一个接口', '在java中一个类不能同时继承一个类和实现一个接口', 'java的单一继承使代码更可靠', 'D'); INSERT INTO `question` VALUES ('9', 'Java 中的集合类包括 ArrayList 、 LinkedList 、 HashMap 等,下列关于集合类描述错误的是?', 'ArrayList和LinkedList均实现了List接口', 'ArrayList访问速度比LinkedList快', '随机添加和删除元素时,ArrayList的表现更加快速', 'HashMap实现Map接口,它允许任何类型的键和值对象,并允许将NULL用作键或值', 'C'); INSERT INTO `question` VALUES ('10', 'Java中用正则表达式截取字符串中第一个出现的英文左括号之前的字符串。比如:北京市(海淀区)(朝阳区)(西城区),截取结果为:北京市。正则表达式为()', '\".*?(?=\\\\()\"', '\".*?(?=\\()\"', '\".*(?=\\\\()\"', '\".*(?=\\()\"', 'A'); -- ---------------------------- -- Table structure for `student` -- ---------------------------- DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `score` double NOT NULL, `time` date NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1; -- ---------------------------- -- Records of student -- ---------------------------- INSERT INTO `student` VALUES ('1', '??Sun Jul 15 16:50:25 CST 2018', '25', '2018-07-15'); INSERT INTO `student` VALUES ('2', 'testSun Jul 15 16:53:17 CST 2018', '0', '2018-07-15'); INSERT INTO `student` VALUES ('3', 'test@Sun Jul 15 16:57:20 CST 2018', '25', '2018-07-15'); INSERT INTO `student` VALUES ('4', 'test@Sun Jul 15 16:57:31 CST 2018', '0', '2018-07-15'); INSERT INTO `student` VALUES ('5', 'test@Sun Jul 15 16:57:41 CST 2018', '25', '2018-07-15'); -- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `phone` varchar(255) DEFAULT NULL, `address` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', '122', '111', '111', '111');
1def98d2f0ff107b15aaab411690fe54903bd1f2
[ "Markdown", "Java", "SQL" ]
6
Java
HaoRanZhuuu/wxtest
1f2983c5513303c75ef44fef9c1c6746fd9bf8c1
e6dcefa67da0c1db0c124a5548d58209665124b3
refs/heads/master
<file_sep>package main; import cisco.java.challenge.GNode; import cisco.java.challenge.Impl.GNodeImpl; import test.cisco.java.challenge.DoWorkGNode; import java.util.*; public class Main { public static void main(String[] args) { GNode gNodeA = new GNodeImpl("A"); GNode gNodeB = new GNodeImpl("B"); GNode gNodeE = new GNodeImpl("E"); GNode gNodeF = new GNodeImpl("F"); GNode gNodeC = new GNodeImpl("C"); GNode gNodeG = new GNodeImpl("G"); GNode gNodeH = new GNodeImpl("H"); GNode gNodeI = new GNodeImpl("I"); GNode gNodeD = new GNodeImpl("D"); // Nodes A -> B -> EF gNodeA.addChild(gNodeB); gNodeB.addChild(gNodeE); gNodeB.addChild(gNodeF); // Nodes A -> C -> GHI gNodeA.addChild(gNodeC); gNodeC.addChild(gNodeG); gNodeC.addChild(gNodeH); gNodeC.addChild(gNodeI); // Nodes A -> D gNodeA.addChild(gNodeD); DoWorkGNode doWorkGNode = new DoWorkGNode(); // get path from starting Node List<List<GNode>> pathsResult = doWorkGNode.paths(gNodeA); System.out.println(pathsResult); List<GNode> walkResult = doWorkGNode.walkGraph(gNodeB); System.out.println(walkResult); } } <file_sep>package test.cisco.java.challenge; import cisco.java.challenge.GNode; import cisco.java.challenge.Impl.GNodeImpl; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.util.List; import static org.junit.Assert.*; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class DoWorkGNodeTest { private GNode gNodeA; private GNode gNodeB; private GNode gNodeC; private GNode gNodeD; private DoWorkGNode doWorkGNode; public DoWorkGNodeTest() { doWorkGNode = new DoWorkGNode(); } @Before public void setUp() throws Exception { gNodeA = new GNodeImpl("A"); gNodeB = new GNodeImpl("B"); gNodeC = new GNodeImpl("C"); gNodeD = new GNodeImpl("D"); gNodeA.addChild(gNodeB); gNodeA.addChild(gNodeC); gNodeA.addChild(gNodeD); } @Test public void paths() throws Exception { List<List<GNode>> list = doWorkGNode.paths(gNodeA); assertEquals(3, list.size()); assertEquals("A", list.get(0).get(0).getName()); assertEquals("B", list.get(0).get(1).getName()); assertEquals("C", list.get(1).get(1).getName()); assertEquals("A", list.get(2).get(0).getName()); assertEquals("D", list.get(2).get(1).getName()); } @Test public void walkGraph() throws Exception { List<GNode> list = doWorkGNode.walkGraph(gNodeA); assertEquals("A", list.get(0).getName()); assertEquals("B", list.get(1).getName()); assertEquals("C", list.get(2).getName()); assertEquals("D", list.get(3).getName()); assertEquals(4, list.size()); } }<file_sep>package test.cisco.java.challenge; import cisco.java.challenge.GNode; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; public class DoWorkGNode { public List<GNode> walkGraph(GNode gNode) { List<List<GNode>> list = paths(gNode); Set<GNode> set = new TreeSet<>(); for (List<GNode> nList : list) { set.addAll(nList); } return new ArrayList<>(set); } public List<List<GNode>> paths(GNode gNode) { List<List<GNode>> pathsAll = new ArrayList<>(); for (GNode child : gNode.getChildren()) { try { List<GNode> path; if (child.getChildren().length > 0) { for (int j = 0; j < child.getChildren().length; j++) { path = new ArrayList<>(); path.add(gNode); path.add(child); // child node path.add(child.getChildren()[j]); pathsAll.add(path); } } else { path = new ArrayList<>(); path.add(gNode); path.add(child); // child node pathsAll.add(path); } } catch (Exception ex) { ex.printStackTrace(); } } return pathsAll; } } <file_sep>package cisco.java.challenge.Impl; import cisco.java.challenge.GNode; import java.util.Arrays; public class GNodeImpl implements GNode, Comparable<GNode> { private String name; private GNode[] child = new GNode[0]; public GNodeImpl(String name) { this.name = name; } @Override public String getName() { return name; } @Override public void addChild(GNode gNode) { child = Arrays.copyOf(child, child.length + 1); child[child.length - 1] = gNode; } @Override public GNode[] getChildren() { return child; } @Override public String toString() { return getName(); } @Override public int compareTo(GNode o) { return this.getName().compareToIgnoreCase(o.getName()); } }
968b7eb7acfd8af5457cb97d76e9d46fc096618c
[ "Java" ]
4
Java
andrZav/GNodeTask
9129995d4aaa802325ced508c772604ca1f128e8
b9b8cae835d03481c78dd30a19d7f9c5fdfba118
refs/heads/master
<repo_name>CarlosEReis/Curso-Spring-MVC-Alura<file_sep>/m2aula06casadocodigo/src/main/java/br/com/alura/casadocodigo/configurations/SpringSecurityFilterConfiguration.java package br.com.alura.casadocodigo.configurations; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; public class SpringSecurityFilterConfiguration extends AbstractSecurityWebApplicationInitializer{ } <file_sep>/m2aula06casadocodigo/src/main/webapp/WEB-INF/message.properties field.required = Campo é obrigatório field.required.produto.titulo = O Campo título é obrigatório field.required.produto.qtdePaginas = Informe o número de páginas field.required.produto.descricao = O Campo descrição é obrigatório typeMismatch = O tipo de dado foi inválido typeMismatch.produtos.qtdePaginas = O tipo de dado foi inválido navegacao.categoria.home = Home navegacao.categoria.agile = Agilidade navegacao.categoria.front_end = Front End navegacao.categoria.games = Jogos navegacao.categoria.java = Java navegacao.categoria.mobile = Mobile navegacao.categoria.web = Web navegacao.categoria.outros = Outros menu.carrinho = Seu carrinho ({0}) menu.sobre = Sobre nós menu.pt = Português menu.en = English<file_sep>/m2aula04casadocodigo/src/main/webapp/WEB-INF/message.properties field.required = Campo é obrigatório field.required.produto.titulo = O Campo título é obrigatório field.required.produto.qtdePaginas = Informe o número de páginas field.required.produto.descricao = O Campo descrição é obrigatório typeMismatch = O tipo de dado foi inválido typeMismatch.produtos.qtdePaginas = O tipo de dado foi inválido<file_sep>/m2aula06casadocodigo/src/main/java/br/com/alura/casadocodigo/controllers/HomeController.java package br.com.alura.casadocodigo.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import br.com.alura.casadocodigo.daos.ProdutoDAO; @Controller public class HomeController { @Autowired private ProdutoDAO produtoDao; @Cacheable(value="produtosHome") @RequestMapping("/") public ModelAndView home() { ModelAndView mv = new ModelAndView("home"); mv.addObject("produtos", produtoDao.lista()); System.out.println("Acessando a Home da CDC"); return mv; } }
92487fb7cdb744e00928b0b56c23f03e8b7128ba
[ "Java", "INI" ]
4
Java
CarlosEReis/Curso-Spring-MVC-Alura
b91658a6a8db18cfe0692dcd534eb1364009993c
98fb4c17757e2ae57ef357ffe984022999ce2986
refs/heads/master
<repo_name>lauraGasca/Simple-Box_Wordpress<file_sep>/header.php <!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <title><?php wp_title('|', true, 'right');?> <?php bloginfo('name'); ?></title> <meta charset="<?php bloginfo('charset');?>"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <link rel="shortcut icon" type="image/x-icon" href="<?php echo get_stylesheet_directory_uri(); ?>/favicon.png"> <!-- Cargando la Hoja de Estilos --> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" > <!--================================= Style Sheets =================================--> <link href='http://fonts.googleapis.com/css?family=Lato:400,700,300' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,600,700,300' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_directory_uri(); ?>/assets/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_directory_uri(); ?>/assets/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_directory_uri(); ?>/assets/css/animate.css"> <link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_directory_uri(); ?>/assets/css/owl.theme.css"> <link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_directory_uri(); ?>/assets/css/owl.carousel.css"> <link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_directory_uri(); ?>/assets/css/jquery.vegas.css"> <link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri(); ?>/assets/css/main.css"> <script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/modernizr-2.6.2-respond-1.1.0.min.js"></script> <!-- Pingbacks --> <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" /> <?php if ( is_singular() ) wp_enqueue_script( "comment-reply" ); ?> <?php wp_head(); ?> </head> <body <?php body_class(); ?> data-spy="scroll" data-target="#sticktop" data-offset="70"> <!--========================= Header ===========================--> <header> <nav id="sticktop" class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"><?php bloginfo('name');?></a> </div> <?php wp_nav_menu(array( 'theme_location' => 'menu-principal', 'container' => 'div', 'container_class' => 'navbar-collapse collapse', 'menu_class' => 'nav navbar-nav', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>' )); ?> <!--/.nav-collapse --> </div> </nav> </header> <!--========================= Head ===========================--> <div class="page-head"> <div class="container"> <h3><?php if ( is_category() ): single_cat_title(); elseif ( is_tag() ) : single_tag_title(); elseif ( is_day() ) : _e('Archivo', 'amk');?>: <?php the_date(); elseif ( is_month() ) : _e('Archivo', 'amk');?>: <?php the_date('F Y'); elseif ( is_year() ) : _e('Archivo', 'amk');?>: <?php the_date('Y'); elseif ( is_search() ) : _e('Resultados para', 'amk');?>: <?php echo the_search_query(); elseif ( is_author() ) : _e('Artículos por', 'amk');?>: <?php $curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author)); echo $curauth->display_name; elseif ( is_404() ) : _e('Error 404', 'amk');?>: <?php _e('Página no encontrada', 'amk'); else: bloginfo('name'); endif; ?></h3> </div><!--container--> </div><!--head--> <file_sep>/page.php <?php get_header(); ?> <div class="container"> <div class="row"> <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12"> <div class="sidebar"> <?php get_sidebar(); ?> </div><!--sidebar--> </div><!--col--> <div class="col-lg-8 col-md-8 col-sm-8 col-xs-12"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <article class="blog-post"> <figure> <?php the_post_thumbnail();?> </figure> <div class="post-head"> <h3><?php the_title(); ?></h3> <div class="clearfix"></div> </div><!--post-head--> <?php the_content(); ?> </article> <?php endwhile; else : ?> <article class="blog-post"> <p><em>No se encontraron articulos</em></p> </article> <?php endif; ?> </div><!--col--> </div><!--row--> </div> <?php get_footer(); ?><file_sep>/single.php <?php get_header(); ?> <div class="container"> <div class="row"> <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12"> <div class="sidebar"> <?php get_sidebar(); ?> </div><!--sidebar--> </div><!--col--> <div class="col-lg-8 col-md-8 col-sm-8 col-xs-12"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <article class="blog-post"> <figure> <?php the_post_thumbnail();?> </figure> <div class="post-head"> <div class="date-stamp"> <span class="date"><?php echo get_the_date('d'); ?></span> <span class="month"><?php echo get_the_date('M'); ?></span> </div><!--date--> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <ul> <li><span>Por:</span> <?php echo get_the_author(); ?> </li> <li><span>Fecha:</span> <?php echo get_the_date(); ?></li> <li><span>Comentarios:</span> <?php comments_number(); ?> </li> </ul> <div class="clearfix"></div> </div><!--post-head--> <?php the_content(); ?> </article> <div class="comments"> <br/><br/> <?php comments_template(); ?> </div><!--comments--> <?php endwhile; else : ?> <article class="blog-post"> <p><em>No se encontraron articulos</em></p> </article> <?php endif; ?> </div><!--col--> </div><!--row--> </div> <?php get_footer(); ?><file_sep>/footer.php <!--=========socials==========--> <div class="socials"> <div class="container"> <div class="section-head style1"> <h2>Siguenos</h2> </div> <ul> <li><a href="https://www.facebook.com/InTic-412488632280555/"><span class="fa fa-facebook"></span></a><h5 class="animated">facebook</h5></li> <li><a href="https://www.facebook.com/InTic-412488632280555/"><span class="fa fa-twitter"></span></a><h5 class="animated">twitter</h5></li> <li><a href="https://www.youtube.com/channel/UCipMZEt2YM-99jF2cG-wOSA/"><span class="fa fa-youtube"></span></a><h5 class="animated">youtube</h5></li> </ul> </div> </div><!--socials--> <footer> <div class="container"> <?php wp_nav_menu(array( 'theme_location' => 'menu-abajo', 'container' => 'div', 'container_class' => 'row', 'menu_class' => 'site_map', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>' )); ?> <div class="row copyrights"> <div class="col-xs-12 col-sm-6"> Copyright © 2016 <span class="simple"><?php echo bloginfo('name');?></span> - All rights reserved. </div> <div class="col-xs-12 col-sm-6 text-right">Diseñado por <a href="http://elnahual.com.mx" class="simple">El Nahual</a></div> </div> </div> <a class="fa fa-chevron-up toTop" href="#"></a> </footer> <!--==========================================--> <script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/jquery-1.11.1.min.js"></script> <script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/bootstrap.min.js"></script> <script src="http://maps.googleapis.com/maps/api/js"></script> <script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/owl.carousel.min.js"></script> <script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/jquery.sticky.js"></script> <script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/masonry.pkgd.min.js"></script> <script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/jquery.waitforimages.js"></script> <script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/jquery.carouFredSel-6.2.1-packed.js"></script> <script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/jquery.vegas.min.js"></script> <script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/parallax.js"></script> <script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/main.js"></script> <?php wp_footer(); ?> </body> </html>
f043cb31ce108e8961bd145ff3a5dbd5cecaf9fd
[ "PHP" ]
4
PHP
lauraGasca/Simple-Box_Wordpress
2c74f859eec04040de39bb003704577bfb09e632
58299eb75229e1f4bcbf86ea07be3a94a60b1e22
refs/heads/master
<file_sep># Roadmap for regression problems A roadmap for regressions problems including [feature selection, linear regressions, decission trees, Support Vector Regressor, XGBoost, NN, PCA y NN, Kernel PCA (iteration over sigma) y NN, CNN (1D, 2D), synthetic data generation with VAE's and Synthetic minority oversampling technique (SMOTE), custom loss functions, customs activation functions, tensorflow tunner (random search) to find the best architectures of neural nets, etc.)] <file_sep>import warnings warnings.filterwarnings("ignore") # Preprocessing from datetime import timedelta import pandas as pd from tqdm import tqdm import numpy as np import io import boto3 import pytz import pickle import time import os from os import listdir import seaborn as sns # Stats models import statsmodels.api as sm import pandas as pd import numpy as np # Machine learning import xgboost from xgboost import plot_importance from matplotlib import pyplot from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.svm import SVR from sklearn.linear_model import LinearRegression # from sklearn.externals import joblib from sklearn.preprocessing import LabelEncoder from imblearn.over_sampling import SMOTE, RandomOverSampler import joblib # Deep learning # import keras import tensorflow as tf from tensorflow import keras # tf.enable_eager_execution() from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization from sklearn.metrics import mean_squared_error,mean_absolute_error from keras.callbacks import ReduceLROnPlateau, EarlyStopping import keras.backend as K # Visualization import matplotlib.pyplot as plt def crear_dos_clases(cantidad, punto_corte): """ Crea las variables con las que se podría predecir en los sectores Parameters ---------- cantidad : Int Entero que hay que sobre muestrear. Returns ------- clase : TYPE La clase a la que pertenece en la distribución. """ if cantidad > punto_corte: clase = 0 if cantidad <= punto_corte: clase = 1 return clase def crear_tres_clases(cantidad, punto_corte1, punto_corte2): """ Crea las variables con las que se podría predecir en los sectores Parameters ---------- cantidad : Int Entero que hay que sobre muestrear. Returns ------- clase : TYPE La clase a la que pertenece en la distribución. """ if cantidad <= punto_corte1: clase = 0 elif (cantidad > punto_corte1) & (cantidad <= punto_corte2): clase = 1 elif cantidad > punto_corte2: clase = 2 return clase def crear_n_clases(cantidad, n, max_, min_): """ Función bacán para crear las clases considerando tratando de formar una distribución lo más parecida a la uniforme Parameters ---------- cantidad : Int Entero que hay que sobre muestrear. n : int Número de subdivisiones en la data que se quiere crear max_ : TYPE máx del array min_ : TYPE min del array Returns ------- None. """ delta = max_ - min_ delta_n = int(delta / n) + 1 num = cantidad - min_ clase = int(num / delta_n) return clase def read_pkl_s3(bucket, ruta): """ La funcion lee un archivo pkl desde s3 Parameters ---------- bucket : Nombre del bucket ruta : Ruta del archivo Returns ------- data : Dataframe con los datos """ s3 = boto3.client("s3") obj = s3.get_object(Bucket=bucket, Key=ruta) body = obj["Body"].read() data = pickle.loads(body) # data.reset_index(inplace=True, drop=True) return data def get_data_operator(bucket, fecha_actual, dias, dataframe): """ La funcion busca los archivos .pickle que cumplen un rango de fechas Parameters ---------- s3: Conexion a servicio s3 fecha_actual : Ultima fecha desde la que se analiza dias : Dias hacia atras que se quiere buscar dataframe: nombre del dataframe Returns ------- data_final : dataframe con los datos """ # Data final data_final = pd.DataFrame() # Lista de fechas en el rango rutas = [] # Calculamos los dias anteriores for i in range(dias): # print(i) d = (fecha_actual-timedelta(i)).day m = (fecha_actual-timedelta(i)).month y = (fecha_actual-timedelta(i)).year ruta = "indicadores/" + str(y) + "/" + str(m) + "/" + dataframe + f"_{d}-{m}-{y}.pkl" # print(prefijo) rutas.append(ruta) # Para cada dia for ruta in tqdm(rutas): try: s3 = boto3.client("s3") obj = s3.get_object(Bucket=bucket, Key=ruta) body = obj["Body"].read() data = pickle.loads(body) data_final = pd.concat([data_final, data], axis=0) except: pass return data_final def load_ads_s3(fecha_inicio, fecha_final): dias = fecha_final - fecha_inicio dias = int(dias.total_seconds() / (24*60*60)) + 1 # Dataframes a analizar estadisticas = get_data_operator("cosmos-amsa-salida", fecha_final, dias, "ads_modelo") estadisticas = estadisticas.drop_duplicates().reset_index(drop=True) return estadisticas def analisis_variables(X): """ Realiza el análisis estadístico de las columnas con las que se están trabajando antes y después del sobremuestreo Parameters ---------- X : Dataframe ADS. Returns ------- Análsis estadístico de la muestra """ analisis = pd.DataFrame() for columna in X.columns.to_list(): mean = X[columna].mean() std = X[columna].std() min_ = X[columna].min() max_ = X[columna].max() list_ = [columna, mean, std, min_, max_] df_ = pd.DataFrame(list_).transpose() analisis = pd.concat([analisis, df_], axis=0) analisis.columns = ['columna', 'media', 'desviacion', 'min', 'max'] analisis = analisis.reset_index(drop=True) return analisis def selection_by_correlation(dataset, threshold): """ Selecciona solo una de las columnas altamente correlacionadas Parameters ---------- dataset : TYPE DESCRIPTION. threshold : TYPE DESCRIPTION. Returns ------- dataset : TYPE DESCRIPTION. TYPE DESCRIPTION. """ col_corr = set() # Set of all the names of deleted columns corr_matrix = dataset.corr() for i in range(len(corr_matrix.columns)): for j in range(i): if (corr_matrix.iloc[i, j] >= threshold) and (corr_matrix.columns[j] not in col_corr): colname = corr_matrix.columns[i] # getting the name of column col_corr.add(colname) if colname in dataset.columns: del dataset[colname] # deleting the column from the dataset dataset = dataset.reset_index(drop=True) return dataset, dataset.columns.to_list() def xgboost_processing(X_train, X_test, y_train, y_test, early_stopping_rounds, columns_dataset): """ Parameters ---------- X_train : TYPE DESCRIPTION. X_test : TYPE DESCRIPTION. y_train : TYPE DESCRIPTION. y_test : TYPE DESCRIPTION. early_stopping_rounds : TYPE DESCRIPTION. columns_dataset : TYPE DESCRIPTION. Returns ------- y_pred : TYPE DESCRIPTION. data : TYPE DESCRIPTION. regressor : TYPE DESCRIPTION. """ columns_X = columns_dataset # Reordenar en la forma (algo,) y_train = np.ravel(y_train) y_test = np.ravel(y_test) # Conjunto de testeo eval_set = [(X_test, y_test)] # XGBRegressor MODEL regressor = xgboost.XGBRegressor() # Entrenar el modelo regressor.fit(X_train, y_train, eval_set = [(X_test, y_test)], early_stopping_rounds = 40) # Generar predicciones y_pred = regressor.predict(X_test) feature_importance =\ regressor.get_booster().get_score(importance_type="weight") keys = list(feature_importance.keys()) values = list(feature_importance.values()) data = pd.DataFrame(data=values, index=keys, columns=["score"]).sort_values(by = "score", ascending=False) list_feature_importance = [] # Get the feature importance on a dataframe by column name for col,score in zip(columns_X,regressor.feature_importances_): list_feature_importance.append([col, score]) data =pd.DataFrame(list_feature_importance, columns=["feature", "importance_score"]) data = data.sort_values(by="importance_score", ascending=False).reset_index(drop=True) pickle.dump(regressor, open("xgboost.pickle.dat", "wb")) # # Plot importance # plt.figure(figsize=(40,20)) # plot_importance(regressor) # pyplot.show() # plt.show() return y_pred, data, regressor def neural_net_processing(model, X_train, X_test, y_train, y_test, batch_size, epochs, patience, min_delta, model_name, filename): """ Parameters ---------- model : TYPE DESCRIPTION. X_train : TYPE DESCRIPTION. X_test : TYPE DESCRIPTION. y_train : TYPE DESCRIPTION. y_test : TYPE DESCRIPTION. batch_size : TYPE DESCRIPTION. epochs : TYPE DESCRIPTION. patience : TYPE DESCRIPTION. min_delta : TYPE DESCRIPTION. model_name : TYPE DESCRIPTION. filename : TYPE DESCRIPTION. Returns ------- None. """ penalization = False # Agregar las función de costo a keras keras.losses.handler_loss_function = handler_loss_function # Compile optimizer model.compile(loss=handler_loss_function(batch_size, penalization), optimizer='nadam') keras.callbacks.Callback() stop_condition = keras.callbacks.EarlyStopping(monitor='val_loss', mode ='min', patience=patience, verbose=1, min_delta=min_delta, restore_best_weights=True) learning_rate_schedule = ReduceLROnPlateau(monitor="val_loss", factor=0.5, patience=25, verbose=1, mode="auto", cooldown=0, min_lr=5E-3) callbacks = [stop_condition, learning_rate_schedule] history = model.fit(X_train, y_train,validation_split=0.2, batch_size=batch_size, epochs=epochs, shuffle=False, verbose=1, callbacks=callbacks) size_training = len(history.history['val_loss']) fig = training_history(history, size_training, model_name, filename + "_ultimas:"+ str(size_training)+"epocas") fig =training_history(history, int(1.5 * size_training / 2), model_name, filename + "_ultimas:"+\ str(1.5 * size_training / 2) + "epocas") fig =training_history(history, int(size_training / 2), model_name, filename + "_ultimas:"+ str(size_training / 2) +\ "epocas") fig =training_history(history, int(size_training / 3), model_name, filename + "_ultimas:"+ str(size_training / 3) +\ "epocas") fig =training_history(history, int(size_training / 4), model_name, filename + "_ultimas:"+ str(size_training / 4) +\ "epocas") # Score del modelo entrenado scores = model.evaluate(X_test, y_test, batch_size=batch_size) print('Mean squared error, Test:', scores) # Predictions on y_test y_pred = model.predict(X_test) # Metricas de evaluación mae_acum = abs(y_pred-y_test) mae = mae_acum.mean() std = mae_acum.std() print("=================================") print("MAE -----> " + str(mae)) print("DEVEST --> " + str(std)) print("=================================") time.sleep(5) diff = y_pred - y_test diff = np.reshape(diff, -1) negative_values = np.count_nonzero(diff<0) print("Porcentaje de errores por debajo:", negative_values/y_pred.shape[0]*100) # Save the model as .h5 model.save(f"models_checkpoint/{filename}_{model_name}.h5") return y_pred, model def training_history(history, epocas_hacia_atras, model_name, filename): # x_labels # Hist training largo = len(history.history['loss']) x_labels = np.arange(largo-epocas_hacia_atras, largo) x_labels = list(x_labels) loss_training = history.history['loss'][-epocas_hacia_atras:] loss_validation = history.history['val_loss'][-epocas_hacia_atras:] fig,ax = plt.subplots(1,figsize=(16, 8)) ax.plot(x_labels, loss_training,'b', linewidth=2) ax.plot(x_labels, loss_validation,'r', linewidth=2) ax.set_xlabel('Epochs', fontname="Arial", fontsize=14) ax.set_ylabel('Cosmos loss function', fontname="Arial", fontsize=14) ax.set_title(f"{model_name}", fontname="Arial", fontsize=20) ax.legend(['Training', 'Validation'], loc='upper left',prop={'size': 14}) for tick in ax.get_xticklabels(): tick.set_fontsize(14) for tick in ax.get_yticklabels(): tick.set_fontsize(14) plt.show() fig.savefig(f"training_results/{model_name}.png") def handler_loss_function(batch_size, penalization): if penalization==True: # Retorna la función de costos de cosmos con penalización def cosmos_loss_function(y_true, y_pred): # Covertir a tensor de tensorflow con keras como backend y_true=K.cast(y_true, dtype='float32') y_pred=K.cast(y_pred, dtype='float32') # Reshape como vector y_true = K.reshape(y_true, (-1, 1)) y_pred = K.reshape(y_pred, (-1, 1)) # Vector de error mae diff_error = y_pred - y_true # Cuenta el número de veces que se equivo por abajo negative_values = K.cast(tf.math.count_nonzero(diff_error > 0), dtype='float32') size_train = K.shape(y_pred)[0] size_train = K.reshape(size_train, (-1, 1)) loss = K.square(y_pred - y_true) loss = K.sum(loss, axis=1) loss = K.mean(loss) loss = loss * (0.1 + negative_values / batch_size) return loss elif penalization==False: # Retorna el error cuadratico medio def cosmos_loss_function(y_true, y_pred): y_true=K.cast(y_true, dtype='float32') y_pred=K.cast(y_pred, dtype='float32') y_true = K.reshape(y_true, (-1, 1)) y_pred = K.reshape(y_pred, (-1, 1)) size_train = K.shape(y_pred)[0] size_train = K.reshape(size_train, (-1, 1)) loss = K.square(y_pred - y_true) loss = K.sum(loss, axis=1) loss = K.mean(loss) return loss return cosmos_loss_function def get_model_summary(model): """ Retorna el sumary de los modelos Parameters ---------- model : TYPE DESCRIPTION. Returns ------- summary_string : TYPE DESCRIPTION. """ stream = io.StringIO() model.summary(print_fn=lambda x: stream.write(x + '\n')) summary_string = stream.getvalue() stream.close() return summary_string def read_pkl_files(path): files = os.listdir(path) data = pd.DataFrame() for file in files: root = path +"/" + file data_i = pd.read_pickle(root) data = pd.concat([data, data_i], axis=0) return data def oversampling_smote_selection(X, target, n_max_clases): """ Función que ayuda a determinar la evolución de la distribución de los datos en función del oversampling Parameters ---------- X : TYPE DESCRIPTION. target : TYPE DESCRIPTION. n_max_clases : TYPE DESCRIPTION. Returns ------- None. """ for i in range(2, n_max_clases +1): num_classes = int(i) # Calculo del máximo y mínimo de las cantidades que se quiere crear max_ = X[target].max() min_ = X[target].min() Y_classes = X[target].apply(lambda x: crear_n_clases(x, num_classes, max_, min_)) smote = SMOTE(random_state=27) random_os = SMOTE(random_state=27) # Pass the entire data, including the target variable new_data, _ = random_os.fit_resample(X, Y_classes) porcentaje = new_data.shape[0] / X.shape[0] porcentaje = round(porcentaje, 2) filas_nuevas = new_data.shape[0] fig,ax = plt.subplots(1,figsize=(16, 8)) sns.set_context("paper", rc={"font.size":20, "axes.titlesize":20, "axes.labelsize":20}) x0 = new_data['Cantidad'] x1 = X['Cantidad'] sns.distplot(x1,color='r') sns.distplot(x0,color='b') ax.set_title(f'Sobre muestreo: clases = {num_classes}, ratio = {porcentaje}, filas = {filas_nuevas}' , fontname="Arial", fontsize=25) plt.legend(labels=['Distribución original', 'Distribución sobre muestreada'], ncol=1, loc='upper left', fontsize=20) for tick in ax.get_xticklabels(): tick.set_fontsize(16) for tick in ax.get_yticklabels(): tick.set_fontsize(16) fig.savefig(f'synthetic_data/{num_classes}.png', dpi=fig.dpi) <file_sep>import pandas as pd import numpy as np import warnings warnings.filterwarnings("ignore") import os from os import listdir from library_training import * import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import LabelEncoder from imblearn.over_sampling import SMOTE, RandomOverSampler ads = read_pkl_files('dataset/data_2') ads.drop_duplicates(subset=["Date", "Equipo"], inplace=True) ads = ads.sort_values(by=['Date']).reset_index() ads = ads[ads["diff hrs"]>3] ads = ads[(ads["Cantidad"]>300) & (ads['Cantidad'] < 5300)] ads = ads[ads['t_cargado'] >= 0] ads = ads[ads['tiempo_ciclo_mean'] >= 0] ads = ads[ads["suma toneladas"]>300] ads = ads[ads["diff hrs"]<48] # features variables = ads.columns.to_list() X = ads[variables] # # Reemplazamos carga normal por valores 0 y 1 X['carga_normal'] = X['carga_normal'].apply(str) X["carga_normal"] = X["carga_normal"].replace(["True", "False"], [1,0]) # Buscamos obtener las estadisticas de la carga anterior X.sort_values(by=["Equipo", "Date"], inplace=True) for variable in variables: if variable in ["Cantidad", "carga_normal"]: new_parametro = variable + "_A" X[new_parametro] = X.groupby(by=["Equipo"]).shift()[variable] # Eliminamos las cargas anomalas X = X[(X["Cantidad"] / X["diff hrs"]) < 240] X = X[['Cantidad','t_encendido', 'Cantidad_A', 'suma toneladas', 't_final', 'distancia_gps', 'd_gps_sc', 'num_cargado', 'diff hrs', 'num_registros', 'num_cargado_subiendo', 'diff_cota_sub', 'diff_cota', 'tiempo', 't_apagado', 'distancia_gps_c', 'd_gps_sv', 'd_gps_bc', 'd_gps_bv', 'carga_normal', 't_cargado', 'numero_cargas', 'vel_mean', 'vel025', 'vel075', 'tiempo_ciclo_mean', 'distancia_pendiente', 'carga_normal_A']] X = X.reset_index(drop=True) # borrar esta columna después # X = X.fillna(X.mean()) X = X.dropna() df = X.copy() fig,ax = plt.subplots(1,figsize=(16, 8)) sns.set_context("paper", rc={"font.size":20,"axes.titlesize":20,"axes.labelsize":20}) x1 = X['Cantidad'] sns.distplot(x1,color='r') ax.set_title('Distribución Datos', fontname="Arial", fontsize=25) plt.legend(labels=['Data'], ncol=1, loc='upper left', fontsize=20) for tick in ax.get_xticklabels(): tick.set_fontsize(16) for tick in ax.get_yticklabels(): tick.set_fontsize(16) X.to_pickle('dataset/preprocessed_ads.pkl') # realizar un análsis estadístico de las columnas para ver el antes y el # después del sobremuestreo analisis_antes = analisis_variables(X) # Comenzar el proceso de generación de data sintetica target = 'Cantidad' # El número de clases debe ser menor al mínimo número de vecinos que tiene cada # tiene cada punto en las subdivisiones por clase oversampling_smote_selection(X, target, n_max_clases=35) num_classes = 25 # Calculo del máximo y mínimo de las cantidades que se quiere crear max_ = X[target].max() min_ = X[target].min() Y_classes = X[target].apply(lambda x: crear_n_clases(x, num_classes, max_, min_)) smote = SMOTE(random_state=27) random_os = SMOTE(random_state=27) # Pass the entire data, including the target variable new_data, _ = random_os.fit_resample(X, Y_classes) analisis_despues = analisis_variables(new_data) new_data.to_pickle('dataset/oversampling_ads.pkl') <file_sep>import warnings warnings.filterwarnings("ignore") import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.externals import joblib from library_training import * # Preparamos la data ads = pd.read_pickle("dataset/preprocessed_ads.pkl") X = ads y = X[["Cantidad"]] del X["Cantidad"] columns_dataset = X.columns.to_list() # ======================================================================= # Data preparation # ======================================================================= # Para cargar el scaler en cualquier otro file # scaler_filename = "scaler" # scaler = joblib.load(scaler_filename) # Crear objecto scaler scaler = MinMaxScaler(feature_range=(0, 1)) # Normalizar X = scaler.fit_transform(X) # # Guardar objeto scaler scaler_filename = "scaler_dataset/scaler_xgboost.save" joblib.dump(scaler, scaler_filename) # Dividir los conjuntos de datos X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=20) y_train = np.ravel(y_train) y_test = np.ravel(y_test) # Suport vector machines regressor regressor = SVR(kernel='rbf') # regressor = SVR(kernel='linear') # Entrenar el modelo regressor.fit(X_train,y_train) # Generar predicciones y_pred = regressor.predict(X_test) diff = y_pred - y_test mae = abs(diff).mean() print(mae) <file_sep>import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.model_selection import train_test_split import keras import tensorflow as tf from tensorflow.compat.v1 import ConfigProto from tensorflow.compat.v1 import InteractiveSession config = ConfigProto() config.gpu_options.allow_growth = True session = InteractiveSession(config=config) from keras.models import Sequential from keras.layers import Dense, Dropout, BatchNormalization from keras.callbacks import ReduceLROnPlateau import matplotlib.pyplot as plt import joblib from keras.layers import Conv1D, Conv2D, MaxPooling2D import time from library_training import * filename = "CNN_final_model" # Preparamos la data ads = pd.read_pickle("dataset/oversampling_ads.pkl") features = ads.columns.to_list() X = ads[features] y = X[["Cantidad"]] del X["Cantidad"] columns_dataset = X.columns.to_list() # ======================================================================= # Data preparation # ======================================================================= # Crear objecto scaler # scaler = MinMaxScaler(feature_range=(0, 1)) scaler = StandardScaler() # Normalizar X = scaler.fit_transform(X) # # Guardar objeto scaler scaler_filename = f"scaler_dataset/{filename}_scaler.save" joblib.dump(scaler, scaler_filename) print(X.shape) # transformar el feature vetor to matrix X = np.reshape(X, (-1, 9, 3, 1)) print(X.shape) # Dividir los conjuntos de datos X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=20) # Si penalization es True, ocupa la función de costos que penaliza errores <0 penalization = False # Elección de hiperparámetros según la penalización que se utiliza if penalization==True: # Hiperparámetros de la red batch_size = 1024 epochs = 1200 # Hiperparámetros de los callbacks patience = 25 min_delta = 500 elif penalization==False: # Hiperparámetros de la red batch_size = 1024 epochs = 1200 # Hiperparámetros de los callbacks patience = 25 min_delta = 500 model_name = f"CNN: {filename}" model = Sequential() model.add(Conv2D(32, input_shape = X_train.shape[1:], kernel_size = (2, 1), padding="same", activation="relu")) model.add(Conv2D(64, (2, 1), padding="same", activation="relu")) model.add(Flatten()) model.add(Dense(1024, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.3)) model.add(Dense(512, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.3)) model.add(Dense(128, activation='relu')) model.add(BatchNormalization()) model.add(Dense(1, activation='relu')) model.summary() # Agregar las función de costo a keras keras.losses.handler_loss_function = handler_loss_function # Compile optimizer model.compile(loss=handler_loss_function(batch_size, penalization), optimizer='nadam') keras.callbacks.Callback() stop_condition = keras.callbacks.EarlyStopping(monitor='val_loss', mode ='min', patience=patience, verbose=1, min_delta=min_delta, restore_best_weights=True) learning_rate_schedule = ReduceLROnPlateau(monitor="val_loss", factor=0.5, patience=25, verbose=1, mode="auto", cooldown=0, min_lr=5E-4) callbacks = [stop_condition, learning_rate_schedule] history = model.fit(X_train, y_train,validation_split=0.2, batch_size=batch_size, epochs=epochs, shuffle=False, verbose=1, callbacks=callbacks) size_training = len(history.history['val_loss']) fig = training_history(history, size_training, model_name, filename + "_ultimas:"+ str(size_training)+"epocas") fig =training_history(history, int(1.5 * size_training / 2), model_name, filename + "_ultimas:"+\ str(1.5 * size_training / 2) + "epocas") fig =training_history(history, int(size_training / 2), model_name, filename + "_ultimas:"+ str(size_training / 2) +\ "epocas") fig =training_history(history, int(size_training / 3), model_name, filename + "_ultimas:"+ str(size_training / 3) +\ "epocas") fig =training_history(history, int(size_training / 4), model_name, filename + "_ultimas:"+ str(size_training / 4) +\ "epocas") # Score del modelo entrenado scores = model.evaluate(X_test, y_test, batch_size=batch_size) print('Mean squared error, Test:', scores) # Predictions on y_test y_pred = model.predict(X_test) # Metricas de evaluación mae_acum = abs(y_pred-y_test) mae = int(mae_acum.mean()) std = int(mae_acum.std()) q95 = int(mae_acum.quantile(0.95)) print("=================================") print("MAE -----> " + str(mae)) print("DEVEST --> " + str(std)) print("=================================") # Save the model as .h5 # model.save(f"models_checkpoint/{filename}_{model_name}.h5") diff = y_pred - y_test diff = np.reshape(diff, -1) negative_values = np.count_nonzero(diff<0) print("Porcentaje de errores por debajo:", negative_values/y_pred.shape[0]*100) fig,ax = plt.subplots(1,figsize=(22, 12)) plt.scatter(y_test, y_pred, color = 'blue') plt.scatter(y_test, y_pred, color = 'blue') plt.scatter(y_test, y_test, color = 'red') titulo = f'CNN oversampling + originales' +\ f'| Data original: {y_test.shape[0]} filas' +'\n'+\ f'MAE: {str(mae)} [lts] --- STD: {str(std)} [lts] --- Q95: {str(q95)} [lts]' plt.title(titulo, fontsize=30) plt.xlabel('Cantidades reales de combustible', fontsize=30) plt.ylabel('Predicción CNN de combustible', fontsize=30) ax.tick_params(axis='both', which='major', labelsize=20) plt.legend(["Predicciones", "Cantidades reales"], fontsize=30, loc = "lower right") plt.ylim(0, 4600) plt.xlim(0, 4600) plt.show() model.save(f"models_checkpoint/{filename}_{model_name}.h5") # data_original = pd.read_pickle("dataset/preprocessed_ads.pkl").reset_index(drop=True) # # features # features = data_original.columns.to_list() # X_original = data_original[features] # y_original = X_original[["Cantidad"]] # del X_original["Cantidad"] # X_original = scaler.transform(X_original) # # Transformar a dataframe # X_original = pd.DataFrame(X_original) # X_original.columns = columns_dataset # # transformar a dataframe el test # X_test = np.reshape(X_test, (-1, 27)) # print(X_test.shape) # X_test = pd.DataFrame(X_test) # X_test.columns = columns_dataset # y_test = pd.DataFrame(y_test) # y_test.columns = ['Cantidad'] # X_original = X_original.reset_index(drop=True) # y_original = y_original.reset_index(drop=True) # # obtengo la data de testo y la data original # data_original = pd.concat([y_original, X_original], axis=1) # data_test = pd.concat([y_test, X_test], axis=1) # # de la data de testeo saco solamente la que esta en el conjunto de datos # # original # alpha = data_test.merge(data_original, how = 'inner' ,indicator=False) # y_original = alpha[["Cantidad"]] # del alpha["Cantidad"] # # X_original = X_original.to_numpy() # # print(X_original.shape) # # X_original = np.reshape(X_original, (-1, 9, 3, 1)) # # print(X_original.shape) # # saco la matriz de datos original # X_original = alpha.copy() # y_pred_original = model.predict(X_original) # y_pred_original = pd.DataFrame(y_pred_original, columns=['Cantidad']) # mae_original = abs(y_pred_original-y_original) # mae = int(mae_original.mean()) # std = int(mae_original.std()) # q95 = int(mae_original.quantile(0.95)) # max_original = max(y_original.max()) # fig,ax = plt.subplots(1,figsize=(22, 12)) # plt.scatter(y_test, y_pred, color = 'blue') # plt.scatter(y_original, y_pred_original, color = 'green') # plt.scatter(y_original, y_original, color = 'red') # titulo = f'NN oversampling + originales' +\ # f'| Data original: {alpha.shape[0]} filas' +'\n'+\ # f'MAE: {str(mae)} [lts] --- STD: {str(std)} [lts] --- Q95: {str(q95)} [lts]' # plt.title(titulo, fontsize=30) # plt.xlabel('Cantidades reales de combustible', fontsize=30) # plt.ylabel('Predicción NN de combustible', fontsize=30) # ax.tick_params(axis='both', which='major', labelsize=20) # plt.legend(["Predicciones oversampling", # "Predicciones que estan en la data de testeo y data original", # "Cantidades reales", ""], fontsize=20, # loc = "lower right") # plt.ylim(0, 4600) # plt.xlim(0, 4600) # plt.show() # print("=================================") # print("MAE -----> " + str(mae)) # print("DEVEST --> " + str(std)) # print("QUANTILE 0.95-->" + str(q95)) # print("=================================") <file_sep>import warnings warnings.filterwarnings("ignore") # Preprocessing import pandas as pd from sklearn.preprocessing import StandardScaler # Machine learning from sklearn.model_selection import train_test_split from sklearn.externals import joblib # Libreria de fine tuning from fine_tuning_cosmos_library import * from library_training import * # deep learning from tensorflow import keras from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping from tensorflow.keras.models import model_from_json # Visualization import io filename = "Final_model" # Preparamos la data ads = pd.read_pickle("dataset/preprocessed_ads.pkl").reset_index(drop=True) dataset = ads features = ads.columns.to_list() X = ads[features] y = X[["Cantidad"]] del X["Cantidad"] columns_dataset = X.columns.to_list() # ======================================================================= # Data preparation # ======================================================================= # Crear objecto scaler # scaler = MinMaxScaler(feature_range=(0, 1)) scaler = StandardScaler() # Normalizar X = scaler.fit_transform(X) # # Guardar objeto scaler scaler_filename = f"scaler_dataset/{filename}_scaler.save" joblib.dump(scaler, scaler_filename) # Dividir los conjuntos de datos # Hacer la división por indices para ir a buscar los datos anomalos X = pd.DataFrame(X, columns=columns_dataset).reset_index(drop=True) y = y.reset_index(drop=True) X = X.to_numpy(dtype="float64") y = y.to_numpy(dtype="float64") # Dividir los conjuntos de datos X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=20) # Libreria deep learning tesseracto filename = "Fine_tunning_model" batch_size = 60 epochs = 150 patience = 25 min_delta = 500 input_shape = (X_train.shape[1],) hypermodel = CosmosHyperModel(input_shape) tuner_rs = RandomSearch( hypermodel, objective='mse', seed=20, max_trials=150, executions_per_trial=3, directory='fine_tuning/') tuner_rs.search_space_summary() keras.callbacks.Callback() stop_condition = keras.callbacks.EarlyStopping(monitor='val_loss', mode ='min', patience=patience, verbose=1, min_delta=min_delta, restore_best_weights=True) learning_rate_schedule = ReduceLROnPlateau(monitor="val_loss", factor=0.5, patience=25, verbose=1, mode="auto", cooldown=0, min_lr=5E-3) callbacks = [stop_condition, learning_rate_schedule] tuner_rs.search(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2, callbacks=callbacks, verbose=1) # Se guarda en un txt las 10 mejores arquitecturas models = tuner_rs.get_best_models(num_models=10) idx = 0 with open('fine_tuning/Best_Architectures.txt','w') as ff: for model in models: ss = get_model_summary(model) ff.write('\n') ff.write(ss) ff.write(str(model.get_config())) best_model = tuner_rs.get_best_models(num_models=1)[0] loss, mse = best_model.evaluate(X_test, y_test) print(best_model.summary()) model_json = best_model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 best_model.save_weights("fine_tuning_model.h5") print("Se guardo el mejor modelo de la búsqueda") # Guardar el json para saber la arquitectura json_file = open('model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # Cargar los pesos loaded_model.load_weights("fine_tuning_model.h5") print("Modelo cargado") # Evaluar el modelo loaded_model.compile(loss='mse', optimizer='adam') score = loaded_model.evaluate(X_test, y_test, verbose=1) print("El error del modelo es:", score) # # Borrar la carpeta donde se guardan los archivos # os.rmdir("fine_tuning/untitled_project") y_pred = loaded_model.predict(X_test) mae = abs(y_pred - y_test).mean() std_mae = abs(y_pred - y_test).std() max_mae = abs(y_pred - y_test).max() error = y_pred - y_test print(mae)<file_sep>import boto3 import tensorflow as tf import tempfile import numpy as np import decimal import os import json def predict_estanque(event, context): """ La funcion recibe los parametros actuales y predice el combustible gastado por los camiones """ print(event) s3 = boto3.resource('s3') # Datos del camion camion = event[1][0] cantidad = event[1][1] carga_normal = event[1][2] real_time_param = event[1][3] parametros = np.array([event[0]]) trainbucket = os.environ["buckettrain"] # Traemos el modelo de s3 with tempfile.TemporaryFile() as f: # Cargamos el modelo s3.meta.client.download_fileobj(trainbucket, f"Modelos/all.h5", f) model = tf.keras.models.load_model(f, compile=False) # Prediccion if p >= 0: print(model.predict(parametros).flatten()) p = model.predict(parametros).flatten()[0] else: p = 0 if real_time_param == "True": # Nuevos datos capacidad_inicial = set_capacidad(cantidad, carga_normal) estanque_actual = capacidad_inicial - p estanque_actual = max(estanque_actual, 0) # ADS actualmente cargado dynamodb_r = boto3.resource("dynamodb") adsdynamodb = os.environ["dynamodbads"] tabla = dynamodb_r.Table(adsdynamodb) # Datos a actualizar en el ADS prediccion = round_float_to_decimal(float(p)) estanque_actual = round_float_to_decimal(estanque_actual) capacidad_inicial = round_float_to_decimal(capacidad_inicial) response = tabla.\ update_item(Key={"Equipo": camion}, UpdateExpression="set prediccion = :r ", ExpressionAttributeValues={':r': prediccion}, ReturnValues="UPDATED_NEW") response = tabla.\ update_item(Key={"Equipo": camion}, UpdateExpression="set estanque_actual = :r ", ExpressionAttributeValues={':r': estanque_actual}, ReturnValues="UPDATED_NEW") response = tabla.\ update_item(Key={"Equipo": camion}, UpdateExpression="set capacidad = :r ", ExpressionAttributeValues={':r': capacidad_inicial}, ReturnValues="UPDATED_NEW") print(f"El equipo {camion} ha consumido {p} litros comenzo el" f" ciclo con {capacidad_inicial} litros, por ende solo le " f"quedan {estanque_actual}") return json.dumps(str(p)) def set_capacidad(cantidad, carga_normal, min_estanque=300, max_estanque=4500): """ """ if ((carga_normal == "True") | (carga_normal == True)): return float(max_estanque) else: return float(min_estanque) + float(cantidad) def round_float_to_decimal(float_value): """ Convert a floating point value to a decimal that DynamoDB can store, and allow rounding. """ # Perform the conversion using a copy of the decimal context that boto3 # uses. Doing so causes this routine to preserve as much precision as # boto3 will allow. with decimal.localcontext(boto3.dynamodb.types.DYNAMODB_CONTEXT) as \ decimalcontext: # Allow rounding. decimalcontext.traps[decimal.Inexact] = 0 decimalcontext.traps[decimal.Rounded] = 0 decimal_value = decimalcontext.create_decimal_from_float(float_value) return decimal_value <file_sep>import warnings warnings.filterwarnings("ignore") # Preprocessing import pandas as pd from sklearn.preprocessing import MinMaxScaler, StandardScaler # Machine learning from sklearn.model_selection import train_test_split # Deep learning import keras import tensorflow as tf # tf.enable_eager_execution() import keras.backend as K from keras.models import Sequential from keras.layers import Dense, Dropout, BatchNormalization from keras.callbacks import ReduceLROnPlateau import matplotlib.pyplot as plt import joblib from sklearn.metrics import mean_absolute_error from sklearn.decomposition import PCA # Libreria deep learning tesseracto from library_training import * filename = "Final_model" # ======================================================================= # Data normalization # ======================================================================= # Preparamos la data # ads = pd.read_pickle("dataset/preprocessed_ads.pkl").reset_index(drop=True) data_oversampling = pd.read_pickle("dataset/oversampling_ads.pkl").reset_index(drop=True) data_original = pd.read_pickle("dataset/preprocessed_ads.pkl").reset_index(drop=True) # ads = data_original.merge(data_oversampling, how ='outer', indicator=True).\ # loc[lambda x : x['_merge']=='right_only'] # ads.drop(columns=['_merge'], inplace=True) # ads = ads[ads['Cantidad'] > 0] # ads = ads.reset_index(drop=True) ads = pd.read_pickle("dataset/oversampling_ads.pkl").reset_index(drop=True) dataset = ads.copy() # Eliminar outliers que salieron ads = ads[ads['Cantidad'] < 4500] # features features = ads.columns.to_list() X = ads[features] y = X[["Cantidad"]] del X["Cantidad"] columns_dataset = X.columns.to_list() # ======================================================================= # Data normalization # ======================================================================= # Crear objecto scaler # scaler = MinMaxScaler(feature_range=(0, 1)) scaler = StandardScaler() # Normalizar X = scaler.fit_transform(X) # # Guardar objeto scaler scaler_filename = f"scaler_dataset/{filename}_scaler.save" joblib.dump(scaler, scaler_filename) # Dividir los conjuntos de datos # Hacer la división por indices para ir a buscar los datos anomalos X = pd.DataFrame(X, columns=columns_dataset).reset_index(drop=True) y = y.reset_index(drop=True) X = X.to_numpy(dtype="float64") y = y.to_numpy(dtype="float64") # Dividir los conjuntos de datos X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=20) # Si penalization es True, ocupa la función de costos que penaliza errores <0 penalization = True # Elección de hiperparámetros según la penalización que se utiliza if penalization==True: batch_size = 2048 epochs = 1200 patience = 25*8 min_delta = 500 elif penalization==False: # Ocupo elif por si en el futuro agregamos más funciones de costo batch_size = 120 epochs = 220 patience = 25 min_delta = 500 model_name = f"Arquitectura custom loss function: {filename}" model = Sequential() model.add(Dense(480, input_dim=X_train.shape[1], activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.3)) model.add(Dense(480, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.3)) model.add(Dense(480, activation='relu')) model.add(BatchNormalization()) model.add(Dense(1, activation='linear')) model.summary() # Agregar las función de costo a keras keras.losses.handler_loss_function = handler_loss_function # Compile optimizer model.compile(loss=handler_loss_function(batch_size, penalization), optimizer='nadam') keras.callbacks.Callback() stop_condition = keras.callbacks.EarlyStopping(monitor='val_loss', mode ='min', patience=patience, verbose=1, min_delta=min_delta, restore_best_weights=True) learning_rate_schedule = ReduceLROnPlateau(monitor="val_loss", factor=0.5, patience=25, verbose=1, mode="auto", cooldown=0, min_lr=5E-4) callbacks = [stop_condition, learning_rate_schedule] history = model.fit(X_train, y_train,validation_split=0.2, batch_size=batch_size, epochs=epochs, shuffle=False, verbose=1, callbacks=callbacks) size_training = len(history.history['val_loss']) fig = training_history(history, size_training, model_name, filename + "_ultimas:"+ str(size_training)+"epocas") fig =training_history(history, int(1.5 * size_training / 2), model_name, filename + "_ultimas:"+\ str(1.5 * size_training / 2) + "epocas") fig =training_history(history, int(size_training / 2), model_name, filename + "_ultimas:"+ str(size_training / 2) +\ "epocas") fig =training_history(history, int(size_training / 3), model_name, filename + "_ultimas:"+ str(size_training / 3) +\ "epocas") fig =training_history(history, int(size_training / 4), model_name, filename + "_ultimas:"+ str(size_training / 4) +\ "epocas") # Score del modelo entrenado scores = model.evaluate(X_test, y_test, batch_size=batch_size) print('Mean squared error, Test:', scores) # Predictions on y_test y_pred = model.predict(X_test) # Metricas de evaluación mae_acum = abs(y_pred-y_test) mae = mae_acum.mean() std = mae_acum.std() print("=================================") print("MAE -----> " + str(mae)) print("DEVEST --> " + str(std)) print("=================================") # Save the model as .h5 # model.save(f"models_checkpoint/{filename}_{model_name}.h5") diff = y_pred - y_test diff = np.reshape(diff, -1) negative_values = np.count_nonzero(diff<0) print("Porcentaje de errores por debajo:", negative_values/y_pred.shape[0]*100) print("Porcentaje de errores por arriba:", 100 - negative_values/y_pred.shape[0]*100) max_ = max(y_pred.max(), y_test.max()) fig,ax = plt.subplots(1,figsize=(20, 10)) plt.scatter(y_test, y_pred, color = 'blue') plt.scatter(y_test, y_test, color = 'red') plt.title(f'Modelo: Red neuronal (Penalización={penalization})', fontsize=30) plt.xlabel('Cantidades reales de combustible', fontsize=30) plt.ylabel('Predicción NN de combustible', fontsize=30) ax.tick_params(axis='both', which='major', labelsize=20) plt.legend(["Predicciones", "Cantidades reales"], fontsize=30, loc = "lower right") plt.ylim(0, 4600) plt.xlim(0, 4600) plt.show() model.save(f"models_checkpoint/{model_name}.h5") # Análisis con los datos post testeo # Eliminar outliers que salieron data_original = data_original[data_original['Cantidad'] < 4500].\ reset_index(drop=True) # features features = data_original.columns.to_list() X_original = data_original[features] y_original = X_original[["Cantidad"]] del X_original["Cantidad"] X_original = scaler.transform(X_original) # Transformar a dataframe X_original = pd.DataFrame(X_original) X_original.columns = columns_dataset # transformar a dataframe el test X_test = pd.DataFrame(X_test) X_test.columns = columns_dataset y_test = pd.DataFrame(y_test) y_test.columns = ['Cantidad'] # obtengo la data de testo y la data original data_original = pd.concat([y_original, X_original], axis=1) data_test = pd.concat([y_test, X_test], axis=1) # de la data de testeo saco solamente la que esta en el conjunto de datos # original alpha = data_test.merge(data_original, how = 'inner' ,indicator=False) y_original = alpha[["Cantidad"]] del alpha["Cantidad"] # saco la matriz de datos original X_original = alpha.copy() y_pred_original = model.predict(X_original) y_pred_original = pd.DataFrame(y_pred_original, columns=['Cantidad']) mae_original = abs(y_pred_original-y_original) mae = int(mae_original.mean()) std = int(mae_original.std()) q95 = int(mae_original.quantile(0.95)) max_original = max(y_original.max()) fig,ax = plt.subplots(1,figsize=(22, 12)) plt.scatter(y_test, y_pred, color = 'blue') plt.scatter(y_original, y_pred_original, color = 'green') plt.scatter(y_original, y_original, color = 'red') titulo = f'NN oversampling + originales' +\ f'| Data original: {alpha.shape[0]} filas' +'\n'+\ f'MAE: {str(mae)} [lts] --- STD: {str(std)} [lts] --- Q95: {str(q95)} [lts]' plt.title(titulo, fontsize=30) plt.xlabel('Cantidades reales de combustible', fontsize=30) plt.ylabel('Predicción NN de combustible', fontsize=30) ax.tick_params(axis='both', which='major', labelsize=20) plt.legend(["Predicciones oversampling", "Predicciones que estan en la data de testeo y data original", "Cantidades reales", ""], fontsize=20, loc = "lower right") plt.ylim(0, 4600) plt.xlim(0, 4600) plt.show() print("=================================") print("MAE -----> " + str(mae)) print("DEVEST --> " + str(std)) print("QUANTILE 0.95-->" + str(q95)) print("=================================") <file_sep>import warnings warnings.filterwarnings("ignore") import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.externals import joblib from library_training import * # Preparamos la data ads = pd.read_pickle("dataset/preprocessed_ads.pkl") X = ads y = X[["Cantidad"]] del X["Cantidad"] columns_dataset = X.columns.to_list() # ======================================================================= # Data preparation # ======================================================================= # Para cargar el scaler en cualquier otro file # scaler_filename = "scaler" # scaler = joblib.load(scaler_filename) # Crear objecto scaler scaler = MinMaxScaler(feature_range=(0, 1)) # Normalizar X = scaler.fit_transform(X) # # Guardar objeto scaler scaler_filename = "scaler_dataset/scaler_xgboost.save" joblib.dump(scaler, scaler_filename) # Dividir los conjuntos de datos X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=20) early_stopping_rounds = 200 y_pred, feature_importance, xgboost =\ xgboost_processing(X_train, X_test, y_train, y_test, early_stopping_rounds, columns_dataset) y_test = y_test.to_numpy() y_test = np.reshape(y_test, (-1,)) mae_xgboost = mean_absolute_error(y_test, y_pred) print(mae_xgboost) # ======================================================================= # Feature selection # ======================================================================= feature_selected = feature_importance["feature"].to_list() # feature_selected = feature_importance["feature"].iloc[0:8].to_list() dataset = ads[feature_selected] correlation_columns =\ dataset.corr().unstack().sort_values().\ drop_duplicates().reset_index(drop=False) correlation_columns.columns = ["var1", "var2", "correlation"] correlation_columns = correlation_columns.sort_values(by=["correlation"], ascending=False).\ iloc[1:].reset_index(drop=True) # High correlation columns high_correlated_columns =\ correlation_columns[(correlation_columns['correlation'] > 0.5) | (correlation_columns['correlation'] < -0.5)] threshold = 0.5 dataset_final, final_columns = selection_by_correlation(dataset, threshold) total_ = feature_importance['importance_score'].sum() feature_importance['importance_score'] =\ feature_importance['importance_score']*100 feature_importance.to_csv('feature_importance.csv', index=False)<file_sep>import warnings warnings.filterwarnings("ignore") import pandas as pd from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.model_selection import train_test_split import keras import tensorflow as tf from keras.models import Sequential from keras.layers import Dense, Dropout, BatchNormalization from keras.callbacks import ReduceLROnPlateau import matplotlib.pyplot as plt import joblib from sklearn.decomposition import PCA import time from library_training import * filename = "PCA_NN_models" # Preparamos la data ads = pd.read_pickle("dataset/oversampling_ads.pkl") features = ads.columns.to_list() X = ads[features] y = X[["Cantidad"]] del X["Cantidad"] columns_dataset = X.columns.to_list() # ======================================================================= # Data preparation # ======================================================================= # Crear objecto scaler scaler = MinMaxScaler(feature_range=(0, 1)) scaler = StandardScaler() # Para cargar el scaler en cualquier otro file # scaler_filename = "scaler" # scaler = joblib.load(scaler_filename) # Normalizar X = scaler.fit_transform(X) # # Guardar objeto scaler scaler_filename = f"scaler_dataset/{filename}_scaler.save" joblib.dump(scaler, scaler_filename) # ======================================================================= # PCA - Preprocessing # ======================================================================= print(X.shape) pca = PCA(n_components=18) principalComponents = pca.fit_transform(X) principalComponents = pd.DataFrame(principalComponents) print(pca.explained_variance_ratio_.sum()) # Dividir los conjuntos de datos X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=69) # Guardar resultados del modelo resultados_modelos = [] # ======================================================================= # Arquitectura 1 # ======================================================================= # Hiperparámetros de la red batch_size = 60 epochs = 150 # Hiperparámetros de los callbacks patience = 25 min_delta = 500 model_name = f"Arquitectura 1: {filename}" model = Sequential() model.add(Dense(128, input_dim=X_train.shape[1], activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(64, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(32, activation='relu')) model.add(BatchNormalization()) model.add(Dense(1, activation='relu')) model.summary() y_pred1, model1 = neural_net_processing(model, X_train, X_test, y_train, y_test, batch_size, epochs, patience, min_delta, model_name, filename) mae1 = mean_absolute_error(y_test, y_pred1) mae_acum1 = abs(y_pred1-y_test) std1 = mae_acum1.std()[0] resultados_modelos.append([model_name, mae1, std1]) # ======================================================================= # Arquitectura 2 (ocupar esta arquitectura con PCA antes) # ======================================================================= # Hiperparámetros de la red batch_size = 60 epochs = 110 # Hiperparámetros de los callbacks patience = 25 min_delta = 500 model_name = f"Arquitectura 2: {filename}" model = Sequential() model.add(Dense(128, input_dim=X_train.shape[1], activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(64, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(32, activation='relu')) model.add(BatchNormalization()) model.add(Dense(1, activation='relu')) model.summary() y_pred2, model2 = neural_net_processing(model, X_train, X_test, y_train, y_test, batch_size, epochs, patience, min_delta, model_name, filename) mae2 = mean_absolute_error(y_test, y_pred2) mae_acum2 = abs(y_pred2-y_test) std2 = mae_acum2.std()[0] resultados_modelos.append([model_name, mae2, std2]) # ======================================================================= # Arquitectura 3 # ======================================================================= # Hiperparámetros batch_size = 60 epochs = 110 patience = 25 min_delta = 500 model_name = f"Arquitectura 3: {filename}" model = Sequential() model.add(Dense(256, input_dim=X_train.shape[1], activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(128, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(64, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(32, activation='relu')) model.add(BatchNormalization()) model.add(Dense(1, activation='relu')) model.summary() y_pred3, model3 = neural_net_processing(model, X_train, X_test, y_train, y_test, batch_size, epochs, patience, min_delta, model_name, filename) mae3 = mean_absolute_error(y_test, y_pred3) mae_acum3 = abs(y_pred3-y_test) std3 = mae_acum3.std()[0] resultados_modelos.append([model_name, mae3, std3]) # ======================================================================= # Arquitectura 4 # ======================================================================= # Hiperparámetros de la red batch_size = 60 epochs = 110 # Hiperparámetros de los callbacks patience = 25 min_delta = 500 model_name = f"Arquitectura 4: {filename}" model = Sequential() model.add(Dense(128, input_dim=X_train.shape[1], activation='linear')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(64, activation='linear')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(32, activation='linear')) model.add(BatchNormalization()) model.add(Dense(1, activation='relu')) model.summary() y_pred4, model4 = neural_net_processing(model, X_train, X_test, y_train, y_test, batch_size, epochs, patience, min_delta, model_name, filename) mae4 = mean_absolute_error(y_test, y_pred4) mae_acum4 = abs(y_pred4-y_test) std4 = mae_acum4.std()[0] resultados_modelos.append([model_name, mae4, std4]) # ======================================================================= # Arquitectura 5 # ======================================================================= # Hiperparámetros de la red batch_size = 60 epochs = 110 # Hiperparámetros de los callbacks patience = 25 min_delta = 500 model_name = f"Arquitectura 5: {filename}" model = Sequential() model.add(Dense(256, input_dim=X_train.shape[1], activation='linear')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(128, activation='linear')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(64, activation='linear')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(32, activation='linear')) model.add(BatchNormalization()) model.add(Dense(1, activation='relu')) model.summary() y_pred5, model5 = neural_net_processing(model, X_train, X_test, y_train, y_test, batch_size, epochs, patience, min_delta, model_name, filename) mae5 = mean_absolute_error(y_test, y_pred5) mae_acum5 = abs(y_pred5-y_test) std5 = mae_acum5.std()[0] resultados_modelos.append([model_name, mae5, std5]) # ======================================================================= # Guardar resultados # ======================================================================= resultados_modelos = pd.DataFrame(resultados_modelos) resultados_modelos.columns = ['Arquitectura', 'Error absoluto medio (MAE)', 'Desviación estandar error'] resultados_modelos.to_csv(f"training_results/{filename}_results.csv") mae_acum1 = pd.DataFrame(mae_acum1).reset_index(drop=True) mae_acum2 = pd.DataFrame(mae_acum2).reset_index(drop=True) mae_acum3 = pd.DataFrame(mae_acum3).reset_index(drop=True) mae_acum4 = pd.DataFrame(mae_acum4).reset_index(drop=True) mae_acum5 = pd.DataFrame(mae_acum5).reset_index(drop=True) mae_results = pd.concat([mae_acum1, mae_acum2, mae_acum3, mae_acum4, mae_acum5], axis=1) mae_results.columns = ['Arquitectura 1', 'Arquitectura 2', 'Arquitectura 3', 'Arquitectura 4', 'Arquitectura 5'] mae_results.to_csv(f"training_results/{filename}_mae_test.csv") columnas = mae_results.columns.to_list() errors = [] for i in range(5): columna = mae_results.iloc[:,i] column = columnas[i] # print(columna.shape) errors.append([column, columna.mean(), columna.max(), columna.std(), columna.quantile(0.05), columna.quantile(0.95), columna.quantile(0.1), columna.quantile(0.9), columna.median()]) errors = pd.DataFrame(errors) errors.columns = ["Arquitectura", "MAE", "MAX error", "STD mae", "Quantile 5%", "Quantile 95%", "Quantile 10%", "Quantile 90%", "Mediana"] errors[['MAE', 'MAX error', 'STD mae', 'Quantile 5%', 'Quantile 95%', 'Quantile 10%', 'Quantile 90%', 'Mediana']] = errors[['MAE', 'MAX error', 'STD mae', 'Quantile 5%', 'Quantile 95%', 'Quantile 10%', 'Quantile 90%', 'Mediana']].apply(lambda x: round(x,2)) errors.columns = ["Arquitectura", "MAE", "MAX error", "STD mae", "Quantile 5%", "Quantile 95%", "Quantile 10%", "Quantile 90%", "Mediana"] errors.to_csv(f"training_results/summary_{filename}.csv") # errors = pd.read_csv('training_results/summary_PCA_NN_models.csv') # errors.drop(columns='Unnamed: 0', inplace=True) # errors[['MAE', 'MAX error', 'STD mae', 'Quantile 5%', # 'Quantile 95%', 'Quantile 10%', # 'Quantile 90%', 'Mediana']] = errors[['MAE', 'MAX error', 'STD mae', # 'Quantile 5%', 'Quantile 95%', # 'Quantile 10%', 'Quantile 90%', # 'Mediana']].apply(lambda x: round(x,2)) # errors.to_csv('training_results/summary_PCA_NN_models.csv')<file_sep>import pandas as pd dataset = pd.read_pickle('dataset/FINAL.pkl') columns_data = dataset.columns.to_list() data_s_camniones = dataset[['Cantidad', 'Con_Max', 'Consumo_Encendido', 'Date', 'Equipo', 'ID', 'Operador', 'Station Name', 'anomalia', 'crew', 'd_gps_bc', 'd_gps_bv', 'd_gps_sc', 'd_gps_sv', 'des_v1', 'des_v2', 'diff hrs', 'diff_cota', 'diff_cota_sub', 'distancia_gps', 'distancia_gps_c', 'distancia_total1', 'distancia_total2', 'lt_an', 'lt_extra', 'lt_sc', 'mean toneladas', 'num_cargado', 'num_cargado_subiendo', 'num_registros', 'suma toneladas', 't_apagado', 't_final', 'temperatura', 'tiempo', 'tiempo_c', 'v1_max', 'v1_mean', 'v2_max', 'v2_mean']] data_s_camniones = data_s_camniones[data_s_camniones["diff hrs"]>3] data_s_camniones = data_s_camniones[data_s_camniones["Cantidad"]>1000] data_s_camniones = data_s_camniones[data_s_camniones["suma toneladas"]>300] data_s_camniones = data_s_camniones[data_s_camniones["diff hrs"]<48] head = data_s_camniones.head(10000) data_s_camniones = data_s_camniones.sort_values(by="Date") ads = data_s_camniones[['suma toneladas', "t_final", 'distancia_gps', 'd_gps_sc', "num_cargado", "diff hrs", "Cantidad"]] <file_sep>import warnings warnings.filterwarnings("ignore") import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.externals import joblib from library_training import * # Preparamos la data ads = pd.read_pickle("dataset/preprocessed_ads.pkl") ads = ads[ads['Cantidad']<=2000].reset_index(drop=True) import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from keras import backend as K from keras.layers import Input, Dense, Lambda, Layer, Add, Multiply from keras.models import Model, Sequential # Definir el dataset X = ads y = X[["Cantidad"]] del X["Cantidad"] columns_dataset = X.columns.to_list() X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=20) X_train = pd.DataFrame(X_train) X_test = pd.DataFrame(X_test) X_train = pd.concat([y_train, X_train], axis=1).reset_index(drop=True).to_numpy() X_test = pd.concat([y_test, X_test], axis=1).reset_index(drop=True).to_numpy() original_dim = 28 intermediate_dim = 14 latent_dim = 5 batch_size = 100 epochs = 50 epsilon_std = 1.0 def nll(y_true, y_pred): """ Log likelihood (Bernoulli) negativo. """ return K.sum(K.binary_crossentropy(y_true, y_pred), axis=-1) class KLDivergenceLayer(Layer): """ Agregar divergencia KL a el loss del vae """ def __init__(self, *args, **kwargs): self.is_placeholder = True super(KLDivergenceLayer, self).__init__(*args, **kwargs) def call(self, inputs): mu, log_var = inputs kl_batch = - .5 * K.sum(1 + log_var - K.square(mu) - K.exp(log_var), axis=-1) self.add_loss(K.mean(kl_batch), inputs=inputs) return inputs decoder = Sequential([ Dense(intermediate_dim, input_dim=latent_dim, activation='relu'), Dense(original_dim, activation='sigmoid')]) x = Input(shape=(original_dim,)) h = Dense(intermediate_dim, activation='relu')(x) z_mu = Dense(latent_dim)(h) z_log_var = Dense(latent_dim)(h) z_mu, z_log_var = KLDivergenceLayer()([z_mu, z_log_var]) z_sigma = Lambda(lambda t: K.exp(.5*t))(z_log_var) eps = Input(tensor=K.random_normal(stddev=epsilon_std, shape=(K.shape(x)[0], latent_dim))) z_eps = Multiply()([z_sigma, eps]) z = Add()([z_mu, z_eps]) x_pred = decoder(z) vae = Model(inputs=[x, eps], outputs=x_pred) vae.compile(optimizer='adam', loss=nll) vae.fit(X_train, X_train, epochs=epochs, batch_size=batch_size, validation_data=(X_test, X_test)) encoder = Model(x, z_mu) # display a 2D plot of the digit classes in the latent space z_test = encoder.predict(X_test, batch_size=batch_size) plt.figure(figsize=(6, 6)) plt.scatter(z_test[:, 0], z_test[:, 1]) plt.colorbar() plt.show() <file_sep> import warnings warnings.filterwarnings("ignore") from datetime import datetime import boto3 import pandas as pd import numpy as np import pytz from library_training import * import pickle # ======================================================================== # Cargar los datos desde S3 # ======================================================================== # Conexion S3 s3 = boto3.client('s3') # Fecha de incio y termino del procesamiento fecha_inicio1 =\ datetime.strptime("2019-11-01", "%Y-%m-%d") fecha_final1 =\ datetime.strptime("2019-11-30", "%Y-%m-%d") stats1 = load_ads_s3(fecha_inicio1, fecha_final1) fecha_inicio2 =\ datetime.strptime("2019-12-01", "%Y-%m-%d") fecha_final2 =\ datetime.strptime("2019-12-31", "%Y-%m-%d") stats2 = load_ads_s3(fecha_inicio2, fecha_final2) fecha_inicio3 =\ datetime.strptime("2020-01-01", "%Y-%m-%d") fecha_final3 =\ datetime.strptime("2020-01-31", "%Y-%m-%d") stats3 = load_ads_s3(fecha_inicio3, fecha_final3) fecha_inicio4 =\ datetime.strptime("2020-02-01", "%Y-%m-%d") fecha_final4 =\ datetime.strptime("2020-02-28", "%Y-%m-%d") stats4 = load_ads_s3(fecha_inicio4, fecha_final4) fecha_inicio5=\ datetime.strptime("2020-03-01", "%Y-%m-%d") fecha_final5 =\ datetime.strptime("2020-03-31", "%Y-%m-%d") stats5 = load_ads_s3(fecha_inicio5, fecha_final5) fecha_inicio6 =\ datetime.strptime("2020-04-01", "%Y-%m-%d") fecha_final6 =\ datetime.strptime("2020-04-30", "%Y-%m-%d") stats6 = load_ads_s3(fecha_inicio6, fecha_final6) fecha_inicio7 =\ datetime.strptime("2020-05-01", "%Y-%m-%d") fecha_final7 =\ datetime.strptime("2020-05-31", "%Y-%m-%d") stats7 = load_ads_s3(fecha_inicio7, fecha_final7) ads_training = pd.concat([stats1, stats2, stats3, stats4, stats5, stats6, stats7], axis=0).reset_index(drop=True) print(ads_training.shape) ads_training = ads_training.drop_duplicates().reset_index(drop=True) print(ads_training.shape) ads_training.to_pickle('ads_training.pkl')
f09d7a8a3736d9dc18523007b1d1dc84609e4a02
[ "Markdown", "Python" ]
13
Markdown
MatheusGitMhub/Roadmap-for-regression-problems
18f029cbd70e0b5144c20554baa21677b45e97c4
f04a37293f1fb2a45ba9a69cb8a4723bcfdf2100
refs/heads/main
<file_sep>import HeaderComponent from "../components/header"; import React, { useState } from "react"; import { toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import Head from 'next/head'; toast.configure() export default function Browse({ blogsList, setBlogsList }) { React.useEffect(() => { console.log("32323", localStorage.getItem("evbjb")) let initBlogs; if (localStorage.getItem("blogs") === null) { initBlogs = []; } else { initBlogs = JSON.parse(localStorage.getItem("blogs")); } setBlogsList(initBlogs); }, []); const [title, setTitle] = useState(""); const [author, setAuthor] = useState(""); const [body, setBody] = useState(""); const onSubmit = async event => { event.preventDefault(); let sno; if (blogsList.length === 0) { sno = 0; } else { sno = blogsList[blogsList.length - 1].sno + 1; } const temp_blog = { sno: sno, title: title, author: author, body: body }; setBlogsList([...blogsList, temp_blog]) toast('Blog Posted Successfully!'); } React.useEffect(() => { localStorage.setItem("blogs", JSON.stringify(blogsList)); }, [blogsList]); return ( <div> <Head> <title>Blogging App</title> </Head> <HeaderComponent /> <div className="row justify-content-center" style={{ width: "99.99%" }}> <form className="col-sm-4" onSubmit={onSubmit}> <div className="mb-3" style={{ marginTop: "10%" }}> <label className="fs-4 fw-bold form-label" htmlFor="formTitle">Title</label> <input type="text" className="form-control" id="formTitle" required={true} onChange={e => setTitle(e.target.value)} /> </div> <div className="mb-3" style={{ marginTop: "5%" }}> <label className="fs-4 fw-bold form-label" htmlFor="formBody">Content</label> <textarea className="form-control" id="formBody" rows="10" required={true} onChange={e => setBody(e.target.value)} /> </div> <div className="mb-3" style={{ marginTop: "5%" }}> <label className="fs-4 fw-bold form-label" htmlFor="formAuthor">Author</label> <input type="text" className="form-control" id="formAuthor" required={true} onChange={e => setAuthor(e.target.value)} /> </div> <button className="btn btn-primary" style={{ marginTop: "2.5%" }} type="submit">Submit form</button> </form> </div> </div> ) }<file_sep>function HeaderComponent() { return ( <nav className="navbar navbar-expand-lg navbar-light border-bottom border-4"> <ul className="nav container-fluid justify-content-center"> <li className="nav-item" style={{ "marginLeft": "1%", "marginRight": "1%" }}> <a className="nav-link fs-4" href="/">Home</a> </li> <li className="nav-item" style={{ "marginLeft": "1%", "marginRight": "1%" }}> <a className="nav-link fs-4" href="/browse">Browse</a> </li> <li className="nav-item" style={{ "marginLeft": "1%", "marginRight": "1%" }}> <a className="nav-link fs-4" href="/create">Create</a> </li> <li className="nav-item" style={{ "marginLeft": "1%", "marginRight": "1%" }}> <a className="nav-link fs-4" href="/about">About</a> </li> </ul> </nav> ) } export default HeaderComponent<file_sep>import Blog from "../components/blog"; import HeaderComponent from "../components/header"; import React, { useState } from "react"; import {toast} from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import Head from 'next/head'; toast.configure() export default function Browse({ blogsList, setBlogsList }) { React.useEffect(()=>{ let initBlogs; if (localStorage.getItem("blogs") === null) { initBlogs = []; } else { initBlogs = JSON.parse(localStorage.getItem("blogs")); } setBlogsList(initBlogs); }, []); const onDelete = (blog) => { setBlogsList(blogsList.filter((e) => { return e !== blog; })); toast('Blog Deleted Successfully!'); } React.useEffect(()=>{ localStorage.setItem("blogs", JSON.stringify(blogsList)); }, [blogsList]); return ( <div> <Head> <title>Blogging App</title> </Head> <HeaderComponent /> <div className="row justify-content-center" style={{ width: "98%", paddingTop: "7.5%" }}> { blogsList.length == 0 ? "Such empty, much wow. Start blogging now!" : blogsList.map((blog) => { return <Blog blog={blog} key={blog.sno} onDelete={onDelete} /> }) } </div> </div> ) }<file_sep>import React, { useState } from "react"; const [blogsList, setBlogsList] = useState([ { title: "pp", author: "ppp", body: "enfjenfef" }, { title: "eo", author: "yoy", body: "gnkrgjkrn" }, { title: "4p", author: "p5p", body: "enf6enfef" }, { title: "e5", author: "y4y", body: "gnk3gjkrn" } ]); export default [blogsList, setBlogsList]<file_sep>import Head from 'next/head' import HeaderComponent from "../components/header"; export default function Home({ blogsList, setBlogsList }) { return ( <div> <Head> <title>Blogging App</title> </Head> <HeaderComponent /> <div className="row justify-content-center" style={{ width: "99.999%", paddingTop: "5%" }}> <div className="col-sm-8"> <h2> Features </h2> <ul> <li className="fs-5"> Add blogs. </li> <li className="fs-5"> View all blogs. </li> <li className="fs-5"> Delete any blog. </li> <li className="fs-5"> Local Storage. </li> <li className="fs-5"> Edit Blog. </li> <li className="fs-5"> Search Blogs. </li> <li className="fs-5"> Filter search. </li> <li className="fs-5"> Pagination in browsing. </li> <li className="fs-5"> Responsive Design. </li> <li className="fs-5"> Google Sign In. </li> </ul> </div> </div> </div> ) } <file_sep>import '../styles/globals.css' import 'bootstrap/dist/css/bootstrap.min.css' import React, { useState } from "react"; function MyApp({ Component, pageProps }) { const [blogsList, setBlogsList] = useState([]); return <Component {...pageProps} blogsList={blogsList} setBlogsList={setBlogsList} /> } export default MyApp <file_sep>function Blog({ blog, onDelete }) { return ( <div className="col-sm-7"> <div className="border-start border-3"> <div className='row align-items-center justify-content-center' style={{ "marginLeft": "2%" }}> <div className='col-sm-9'> <h2>{blog.title}</h2> <p><em>{blog.author}</em></p> <p className="text-truncated">{blog.body}</p> </div> <div className='col-sm-3 align-items-center justify-content-center'> <div className="align-items-center justify-content-center"> <button className="btn btn-outline-dark" style={{ marginRight: "5%" }}>E</button> <button className="btn btn-outline-dark" onClick={()=>onDelete(blog)}>D</button> </div> </div> </div> </div> </div> ) } export default Blog<file_sep>import HeaderComponent from "../components/header"; import React, { useState } from "react"; import 'react-toastify/dist/ReactToastify.css'; import Head from 'next/head'; export default function About({ blogsList, setBlogsList }) { return ( <div> <Head> <title>Blogs Page</title> </Head> <HeaderComponent /> <div className="row justify-content-center" style={{ width: "99.99%", paddingTop: "7.5%" }}> <p className="col-sm-6 fs-5 justify-content-center">A simple blogging application with minimum features to learn Next.js basics. Check the code repositoy at <a href="https://github.com/himanshuraj18/NextJSTask" target="_blank">GitHub</a>.</p> </div> </div> ) }
e2778767d169e3c21687eee4c280f731227848f7
[ "JavaScript" ]
8
JavaScript
himanshuraj18/NextJSTask
c2af85a6c8d7f438c008478cf9d0fce221c74c72
3fc64924884f3bb6bf6ff061d12f418a65162b73
refs/heads/master
<repo_name>dhanikurnia/pajak<file_sep>/Pajakk/Pajak/result.php <!DOCTYPE html> <html> <head> <title>aaaaaaaaaaaa</title> </head> <body> <center> <?php include 'koneksi.php'; ?> <table border="1"> <tr> <th>No</th> <th>Tanggal</th> <th>Nama Barang</th> <th>Jumlah</th> </tr> <?php $no = 1; if(isset($_GET['tanggal'])){ $tgl = $_GET['tanggal']; $sql = mysqli_query($koneksi,"select * from barang_masuk where tanggal='$tgl'"); }else{ $sql = mysqli_query($koneksi,"select * from barang_masuk"); } while($data = mysqli_fetch_array($sql)){ ?> <tr> <td><?php echo $no++; ?></td> <td><?php echo $data['tanggal']; ?></td> <td><?php echo $data['nama']; ?></td> <td><?php echo $data['jumlah']; ?></td> </tr> <?php } ?> </table> </center> </body> </html><file_sep>/Pajak/index.php <!DOCTYPE html> <html> <head> <title>MENAMPILKAN DATA DARI DATABASE SESUAI TANGGAL DENGAN PHP</title> </head> <body> <center> <?php include 'koneksi.php'; ?> <br/><br/><br/> <form method="post"> <label>PILIH TANGGAL</label> <input type="date" name="TGL_PEMBAYARAN_SPPT"> <a href="result.php"><button class="btn btn-primary">FILTER</button></a> <button>back</button> </form> </center> </body> </html><file_sep>/Pajak/result.php <!DOCTYPE html> <html> <head> <title>aaaaaaaaaaaa</title> </head> <body> <center> <?php include 'koneksi.php'; ?> <table border="5"> <tr> <th>NOMOR</th> <th>KD_PROPINSI</th> <th>THN_PAJAK_SPPT</th> <th>TGL_PEMBAYARAN_SPPT</th> </tr> <?php $no = 1; if(isset($_POST['TGL_PEMBAYARAN_SPPT'])){ $tgl = $_POST['TGL_PEMBAYARAN_SPPT']; $sql = mysqli_query($koneksi,"select * from pembayaran_sppt where TGL_PEMBAYARAN_SPPT='$tgl'"); }else{ $sql = mysqli_query($koneksi,"select * from pembayaran_sppt"); } while($data = mysqli_fetch_array($sql)){ ?> <tr> <td><?php echo $no++?></td> <td><?php echo $data['KD_PROPINSI']; ?> <?php echo $data['KD_DATI2']; ?> <?php echo $data['KD_KECAMATAN']; ?> <?php echo $data['KD_KELURAHAN']; ?> <?php echo $data['KD_BLOK']; ?> <?php echo $data['NO_URUT']; ?> <?php echo $data['KD_JNS_OP']; ?></td> <td><?php echo $data['THN_PAJAK_SPPT']; ?></td> <td><?php echo $data['TGL_PEMBAYARAN_SPPT']; ?></td> </tr> <?php } ?> </table> <table border="5"> <tr> <th>NOMOR</th> <th>KD_KECAMATAN</th> <th>NAMA_KECAMATAN</th> </tr> <?php $no = 1; if(isset($_POST['KD_KECAMATAN'])){ $tgl = $_POST['KD_KECAMATAN']; }else{ $sql = mysqli_query($koneksi,"select * from kecamatan"); } while($data = mysqli_fetch_array($sql)){ ?> <tr> <td><?php echo $no++?></td> <td><?php echo $data['KD_KECAMATAN']; ?> <td><?php echo $data['NM_KECAMATAN']; ?></td> </tr> <?php } ?> </table> </center> </body> </html>
45dfee6adfe422680b0c7cd86c4ba6cbc08ca79b
[ "PHP" ]
3
PHP
dhanikurnia/pajak
a16580f10ec21232590d68fd7f6e660121513f26
c5c74707880d97ec0948de3021059a135eabd9af
refs/heads/master
<file_sep>/** * Events * * @module :: Model * @description :: A short summary of how this model works and what it represents. * @docs :: http://sailsjs.org/#!documentation/models */ module.exports = { attributes: { /* e.g. nickname: 'string' */ }, // Lifecycle Callbacks beforeCreate: function(values, next) { Tags.findOne({'tag': values['tag'].toString()}, function(err, tag) { if (err) return next(err); if (!tag) return next(new Error("No tags with the following parameters were found: {'tag': " + values['tag'] + "}")); Assets.findOne({'tagID': tag.id}, function(err, asset) { if (err) return next(err); if (!asset) return next(new Error("No assets assigned to the following tag were found: {'tag': " + values['tag'] + "}")); Readers.findOne({'reader': values['reader'].toString()}, function(err, reader) { if (err) return next(err); if (!reader) return next(new Error("No readers with the following parameters were found: {'reader': " + values['reader'] + "}")); if (asset.currentReaderId === reader.id) next(); else { asset.currentReaderId = reader.id; asset.save(function(err) { if (err) return next(err); next(); }); } }); }); }); } }; <file_sep># RFID-based Asset Tracking with Node.js and MongoDB As the title states, we are going to discuss how to build an [RFID](http://en.wikipedia.org/wiki/Radio-frequency_identification)-based asset tracking system using popular open source tools like [Node.js](http://nodejs.org/) and [MongoDB](http://www.mongodb.org/). For the sake of simplicity, let's start with a very basic model of a system addressing only a general concern of getting some information from RFID hardware and putting it in the database. Of course, in real life we would have to think about many details and additional components to take into account security, bandwidth consumption, monitoring, etc., but let us forget about it all for now and get back to these aspects in our future posts. ## Overall Architecture Let's take a look at some basic components our RFID asset tracking system needs. ![Overall Architecture](architecture.png) ### RFID Tags RFID tags are compact devices which in our context are physically attached to the asset being tracked. These tags can be active (containing a power source and periodically emitting their ID as a signal), passive (no power source) or semi-passive (have a power source to power internal circuits but use the power from the reader to transmit). Within the scope of this post, the type we are using doesn't really matter since any tag type can provide us with some kind of a tag ID. ### RFID Readers RFID readers are the devices that receive information regarding the positions of RFID tags and transmit it upstream. The type of readers and the way they receive data strongly depends on the type of the tags being used. Once again, let's not focus on the particular hardware so far as we will get back to it later. ### Gateways A gateway is a hub connecting RFID readers with remote modules. It can be a physical device located on the same premises the readers are located on, as well as a remote and / or virtual container. The main purpose of a gateway is gathering messages coming from the readers (or sensors, etc.) and transmitting them to the system backend. Depending on the environment and the complexity of the data, some sort of buffering, caching and pre-processing can also be required to be performed on the gateway. If you are asking yourself whether or not you need some special equipment for an RFID gateway, the answer really depends on the scale and the environment of your project, but in most relatively simple cases a [Raspberry Pi](http://en.wikipedia.org/wiki/Raspberry_Pi) or a [Beaglebone Black](http://en.wikipedia.org/wiki/BeagleBone_Black#BeagleBone_Black) can easily do the job for you. ### API Server In our case, [API](http://en.wikipedia.org/wiki/Application_programming_interface) server is a bridge between the gateways and the database. This server translates the messages from end devices to the database objects. To a certain extent, you could say that it defines what part of your database you want to expose and how you would prefer to do it. There is a lot of ways to design such a server, but if we are talking about some standards, then [REST](http://en.wikipedia.org/wiki/Representational_state_transfer) is, obviously, one of the most advanced and popular. Among other things, it defines a set of actions (e.g. CREATE, READ, UPDATE or DELETE) that can be performed over resources (corresponding to the database collections which are the NoSQL equivalents of tables in [RDBMS](http://en.wikipedia.org/wiki/Relational_database_management_system) and match those actions with the HTTP methods (e.g. POST, GET, PUT or DELETE). Of course, using HTTP and a RESTful API server is only one of many possible approaches, but it can easily give you the idea on how such a system could work in general. ### Database The database, basically, is the place where your RFID data should ultimately land up. At this point it should already be transformed to match the object model of your system, and once the data is received you can easily track the changes through your frontend (e.g. Web, iOS or Android application). ## Software Choices As we agreed earlier, here we are describing a very basic use case of an RFID system without getting in the details. So, you could be curious then, why we are so definitive about Node.js and MongoDB? Let's see some reasoning. ### Node.js and Related Frameworks Obviously, there is a lot of programming environments which could be used in order to implement the solution in question. Node.js and its various frameworks have some important features that could provide considerable help during the implementation, including: - speed: Node.js' V8 engine is much faster than most of the popular languages used for Web development (see https://www.paypal-engineering.com/2013/11/22/node-js-at-paypal/, http://www.appdynamics.com/blog/nodejs/an-example-of-how-node-js-is-faster-than-php/ and http://inkstonehq.com/2013/07/10/node-js-vs-rails-which-is-better/ for some benchmarks); - scalability: a single Node.js process is able to handle thousands of concurrent connections with minimal overhead; - language: JavaScript is extremely popular programming language, which simplifies the task of finding developers for the project; moreover, using JavaScript on both the server and the browser improves communication between system components and offers some opportunities to reuse the server code on the client and vice versa, especially, in case of [isomorphic frameworks](http://venturebeat.com/2013/11/08/the-future-of-web-apps-is-ready-isomorphic-javascript/); - community: Node.js has one of the most strong and active communities nowadays, which makes the processes of code maintenance, debugging and refactoring many times easier and faster; - industry support: [a lot of companies](http://nodejs.org/industry/) from startups to big corporations successfully use Node.js in production; - libraries: more then 70000 different packages are currently accessible via Node Packaged Modules, [npm](https://npmjs.org/), and the total number of packages grows on a faster pace then, for example, even the number of [Ruby gems](http://rubygems.org/stats), that have been around much longer. However, only in very rare cases it makes sense to use pure language implementation for a new Web project, since most of the time some popular features are already implemented with some frameworks. In our case, the following frameworks constitute considerable interest: - [Express.js](http://expressjs.com/) is a server-side web-application framework for Node.js, but a very minimalistic one, which means it provides only some basic functionality, no hidden magic or anything like that. However, Express.js has quickly became a standard in Node.js based Web-development and a base not only for so called [MEAN-stack](http://blog.mongodb.org/post/49262866911/the-mean-stack-mongodb-expressjs-angularjs-and) (MongoDB-Express.js-Angular.js-Node.js), but also for a lot of higher level frameworks; - [Sails.js](http://sailsjs.org/) is one of most popular frameworks (obviously, Ruby on Rails-inspired) using Express.js as a foundation. Some of its key features that can help us to implement our solution include: * automatic RESTful API generation; * built-in database-agnostic [ORM](http://en.wikipedia.org/wiki/Object-relational_mapping); * real-time features support with built-in [Socket.io](http://socket.io/) engine. ### MongoDB Currently, [MongoDB](http://www.mongodb.org/) is probably most popular of the [NoSQL](http://en.wikipedia.org/wiki/NoSQL) database engines. And this is for a reason: it has so many great qualities enhancing previously traditional relational database experience. Namely, for our project the following features are of special interest: - flexibility: storing data in JSON ([BSON](http://en.wikipedia.org/wiki/BSON)) documents, MongoDB is not bounded by such a serious relational database limitation as fixed schema and doesn't need the data to be normalized; for us, it means that we can easily store different class of assets with different specifications and uniquely structured embedded data for every document; - functionality: MongoDB provides most of the traditional RDBMS features including indexes, dynamic queries, sorting, updates, upserts (update if document exists, insert if it doesn’t), etc., adding on top of it all the capacities offered by non-relational model; - speed: keeping related data embedded in documents, we can query results much faster than in case of relational databases where we usually need to join multiple tables in order to achieve similar results; - scalability: scaling the database becomes really easy with MongoDB's [autosharding](http://docs.mongodb.org/manual/sharding/), and that can be really helpful in case of our task, when the number of assets being tracked can grow significantly; - simplicity: easy to install, configure, support, and use, MongoDB works right out of the box, without any excessive configuration or fine-tuning. These features make MongoDB a perfect candidate for the role of the system's main database engine. ## Implementation The basic idea is simple: your gateway is receiving some data from the peripherals (RFID readers in our case) and makes appropriate HTTP-calls to the API server. The latter accepts the information, processes it and updates the database accordingly. Now, let's see how to do it in practice. ### Prerequisites Obviously, in order to run the following examples, you have to install some software first. #### Node.js Download the latest stable Node.js package for your operating system from http://nodejs.org/ or install it via a package manager: https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager. Alternatively, you can use your own build of the desired version, see https://github.com/joyent/node/wiki/Installation for details. #### MongoDB You can download MongoDB binaries from http://www.mongodb.org/downloads, then follow one of the installation guides corresponding to your operating system: http://docs.mongodb.org/manual/installation/. Note, that unless you are using a packaged version, the server doesn't start automatically, so you would need to start it manually as described here: http://docs.mongodb.org/manual/tutorial/manage-mongodb-processes/. #### npm Good news is that npm comes with Node nowadays, so, in general, you don't have to install anything else. Typing npm in the command line should give you a list of available commands (if it doesn't, you can find a bunch of other ways to install npm here: https://www.npmjs.org/doc/README.html#Fancy-Install-Unix or https://www.npmjs.org/doc/README.html#Fancy-Windows-Install). #### Sails.js As simple as `npm install sails@0.9.13 -g` (you may need to prefix it with `sudo` though, depending on your operating system and user privileges). ### Data Structure Keeping it simple, let's define 4 collections that will represent our system's entities: - tags, RFID tags containing: * tag — tag unique identifier (independent from the database, not the database object ID), which can come as an EPC or in any other form allowing to differ a tag unambiguously, - readers, RFID reader objects: * reader — reader unique identifier, in any form the gateway is sending it, - assets, objects corresponding to the assets we are tracking: * name — asset name / title, * tagID — the database object ID (reference) of the tag assigned to this asset, * currentReaderID — the database object ID (reference) of the reader where this asset was seen last time, * note, that here we can also have some custom fields that differ from one asset to another (given the fact that we are using a NoSQL solution, it comes at no cost), since the assets themselves can have completely different nature, - events, containing messages being received from gateways and meaning, in general, that "this tag was seen near this reader": * tag — tag identifier, * reader — reader identifier, * rssi — [RSSI](http://en.wikipedia.org/wiki/Received_signal_strength_indication), an optional field which may or may not be presented depending on your RFID hardware. Let's see how we can create an API server for these models and get it running in 5 minutes. Literally. ### RESTful API with Sails.js A lot of arguments are being conducted on whether it makes sense to extend standard Express' functionality to sort of match higher level Web frameworks or Express itself with its middleware ecosystem already contains everything needed to build a Web application from scratch. The answer, most probably, depends on the project you are developing, but one of the things about Sails.js that looks really impressive is the RESTful API it automatically generates. Indeed, you may not even have to write a single line of code. Let's start by creating a new Sails.js application (Note: the following examples use v0.9.13 of Sails.js, which was the last stable version of the framework as of this writing): sails new rfid-based-asset-tracking-with-nodejs-and-mongodb will create a subfolder named `rfid-based-asset-tracking-with-nodejs-and-mongodb` (or you could use any other name) within your current location and generate base boilerplate code necessary to run the simplest Sails application. Now, in order to create a complete API for the previously described data structure, let's switch to this new folder and type the following: sails g tags sails g readers sails g assets sails g events These commands will generate models and controllers for corresponding entities, so `ls ./api/controllers/` will give you AssetsController.js EventsController.js ReadersController.js TagsController.js and `ls ./api/models/` will display Assets.js Events.js Readers.js Tags.js At this point we don't even care about the code in these files (there's not a lot of it anyway). All we need to see our API server in action is to start the Sails.js application, but first let's make sure it will connect to our MongoDB database. ### Connecting to MongoDB By default, Sails.js comes with a proprietary database adapter called `sails-disk`, which is a simple disk-based storage engine that can be used for development purposes, but not suitable for production (mainly, performance and scalability wise). Let's switch it to Mongo. Open `./config/local.js` and add the following code right after `module.exports = {`: adapters: { default: 'mongo', // MongoDB mongo: { module : 'sails-mongo', host : 'localhost', port : 27017, // user : 'username', // Authentication is supposed to be disabled by default, // password : '<PASSWORD>', // if it's not, put the username / password here database : 'rfid' // Or any other name you want }, }, Since Sails requires a separate module to connect to Mongo, we have to install it: npm install --save sails-mongo Once again, before you proceed, make sure your MongoDB server is running. ### Processing the Data Let's start our server: sails lift By default, Sails application will be listening on port 1337, so if you open `http://localhost:1337/` in your browser, you should get a nice default page (which is useless for us though). Note, that your server must be running during the further experiments. If you open `http://localhost:1337/tags/` now, you will see [], which is a JSON form of an empty array. This simply means we don't have any objects in tags collection of our database. Let's create some. By default, with Sails.js you not only can use a standard RESTful mapping of HTTP methods to CRUD action (e.g. POST to CREATE an object), but you also have so called [developer shortcuts](https://github.com/balderdashy/sails-docs/blob/master/config.controllers.md#shortcuts-boolean) that let you use simple HTTP GET requests for all the actions. So, creating new tags is as simple as opening the following links in your browser: http://localhost:1337/tags/create/?tag=tag1 http://localhost:1337/tags/create/?tag=tag2 http://localhost:1337/tags/create/?tag=tag3 Now, if you go back to `http://localhost:1337/tags/`, you should see something like this: [ { "tag": "tag1", "createdAt": "2014-03-25T15:40:54.995Z", "updatedAt": "2014-03-25T15:40:54.995Z", "id": "5331a38683d14dd59d527277" }, { "tag": "tag2", "createdAt": "2014-03-25T15:41:14.645Z", "updatedAt": "2014-03-25T15:41:14.645Z", "id": "5331a39a83d14dd59d527278" }, { "tag": "tag3", "createdAt": "2014-03-25T15:41:18.731Z", "updatedAt": "2014-03-25T15:41:18.731Z", "id": "5331a39e83d14dd59d527279" } ] Thus, we created three objects that correspond to our RFID tags. Note, that we only needed to provide an identifier to each tag and Sails.js automatically made sure the objects receive additional fields, such as `id` corresponding to the MongoDB `_id` and `createdAt` / `updatedAt` timestamps, similar to the ones Rails provides with its [Active Record](http://guides.rubyonrails.org/active_record_querying.html). Let's create other objects we need in the same manner: http://localhost:1337/readers/create/?reader=reader1 http://localhost:1337/readers/create/?reader=reader2 http://localhost:1337/readers/create?reader=reader3 http://localhost:1337/assets/create?name=asset1 http://localhost:1337/assets/create?name=asset2 http://localhost:1337/assets/create?name=asset3 After that, visiting `http://localhost:1337/readers/` and `http://localhost:1337/assets/` will give you something like [ { "reader": "reader1", "createdAt": "2014-03-25T16:35:13.776Z", "updatedAt": "2014-03-25T16:35:13.776Z", "id": "5331b04183d14dd59d52727a" }, { "reader": "reader2", "createdAt": "2014-03-25T16:35:24.761Z", "updatedAt": "2014-03-25T16:35:24.761Z", "id": "5331b04c83d14dd59d52727b" }, { "reader": "reader3", "createdAt": "2014-03-25T16:35:38.987Z", "updatedAt": "2014-03-25T16:35:38.987Z", "id": "5331b05a83d14dd59d52727c" } ] and [ { "name": "asset1", "createdAt": "2014-03-25T16:36:44.136Z", "updatedAt": "2014-03-25T16:36:44.136Z", "id": "5331b09c83d14dd59d52727d" }, { "name": "asset2", "createdAt": "2014-03-25T16:36:48.303Z", "updatedAt": "2014-03-25T16:36:48.303Z", "id": "5331b0a083d14dd59d52727e" }, { "name": "asset3", "createdAt": "2014-03-25T16:36:59.127Z", "updatedAt": "2014-03-25T16:36:59.127Z", "id": "5331b0ab83d14dd59d52727f" } ] respectively. Now we have to link our assets and our tags (which corresponds to attaching tags to the physical objects). We will use the tagID property of asset objects in order to establish such a link. This operation, once again, can be performed directly in browser, but since MongoDB generates unique object IDs [in a way randomly](http://docs.mongodb.org/manual/reference/object-id/#ObjectIDs-BSONObjectIDSpecification), we can only provide here a template, and you will have to construct your own URLs: http://localhost:1337/assets/update/<id-of-the-asset-object>/?tagID=<id-of-the-tag-object> For example, in our case we got the following URLs: http://localhost:1337/assets/update/5331b09c83d14dd59d52727d/?tagID=5331a38683d14dd59d527277 http://localhost:1337/assets/update/5331b0a083d14dd59d52727e/?tagID=5331a39a83d14dd59d527278 http://localhost:1337/assets/update/5331b0ab83d14dd59d52727f/?tagID=5331a39e83d14dd59d527279 Technically, after that we can already make some API calls to notify our server on the current position (the closest reader) of our assets. The URL template would be http://localhost:1337/assets/update/<id-of-the-asset-object>/?currentReaderID=<id-of-the-tag-object> But there is a couple of problems with this approach. First, the ID of the tag object in this URL is supposed to be the database object ID, which the gateway shouldn't be aware of as we would prefer to keep our peripherals relatively independent from the central server and the database. Second, going this way we will not have any historical information about our assets' locations. That's where we going to need the last class of objects we described in our data structure, events. The idea is pretty simple: instead of updating the location of the asset directly, we are going to create an event each time a new location comes from a gateway. For example: http://localhost:1337/events/create/?tag=tag1&reader=reader1&rssi=128 This will let our server (and the database) know that the tag with the identifier "tag1" was seen near the RFID reader identified as "reader1" and the signal strength was 128 (on a scale from 0 to 255). Perfect. However, it would be much more convenient for us to minimize the number of associations needed whenever we are querying the database trying to get the current location of an asset. Namely, using the `currentReaderID` property of an asset object we could organize our assets collection in an easily queryable way. Here is, probably, the only place (apart from the config file) where you will have to write some code. In order to achieve our goal, we are going to use a feature of Sails.js' [ORM](http://en.wikipedia.org/wiki/Object-relational_mapping) [Waterline](https://github.com/balderdashy/waterline) called lifecycle callbacks (similar to [Rails Active Record callbacks](http://edgeguides.rubyonrails.org/active_record_callbacks.html)), specifically, beforeCreate event. The code we will write goes to `./api/models/Events.js`: module.exports = { attributes: { /* e.g. nickname: 'string' */ }, // Lifecycle Callbacks beforeCreate: function(values, next) { Tags.findOne({'tag': values['tag'].toString()}, function(err, tag) { if (err) return next(err); if (!tag) return next(new Error("No tags with the following parameters were found: {'tag': " + values['tag'] + "}")); Assets.findOne({'tagID': tag.id}, function(err, asset) { if (err) return next(err); if (!asset) return next(new Error("No assets assigned to the following tag were found: {'tag': " + values['tag'] + "}")); Readers.findOne({'reader': values['reader'].toString()}, function(err, reader) { if (err) return next(err); if (!reader) return next(new Error("No readers with the following parameters were found: {'reader': " + values['reader'] + "}")); if (asset.currentReaderId === reader.id) next(); else { asset.currentReaderId = reader.id; asset.save(function(err) { if (err) return next(err); next(); }); } }); }); }); } }; Here is what this code essentially does: - beforeCreate event fires every time a new event object is being created (obviously, before creation); - the handler function receives the values of the event properties; - it finds the tag object corresponding to the identifier sent by the gateway; - it finds the asset to which the found tag is attached; - it finds the reader object corresponding to the identifier sent by the gateway; - it checks whether the asset changed its location, and if it did, the handler set the currentReaderID property of the asset to the new value (object ID of the reader it just found); - finally the handler function calls next() callback to get back to the event loop. Restart your Sails.js application (stop with Ctrl+C and start with `sails lift`). Now, whenever a gateway is sending new data with http://localhost:1337/events/create/?tag=<tag-identifier>&reader=<reader-identifier>&rssi=<rssi-value>, not only corresponding event object (a history log entry) will be saved to the database, but also the currentReaderID property of the tagged asset will be changed accordingly. You can easily do some tests and check the changes via API: `http://localhost:1337/assets` and `http://localhost:1337/readers`. ### Getting Even More So, with only about 50 lines of code we got ourselves an API server that logs movements of our assets and can provide us with up-to-date information on the current location of any of these assets. What could be better? Maybe, the fact that we are actually getting even more with Node.js / Sails.js and MongoDB. These "freebees" include: - though it's very simple, our architecture can easily be scaled horizontally, since the components are relatively independent from each other and we can have, for example, multiple API servers behind a load balancer or use replication and sharding functionalities MongoDB provides out of the box; - one of the main features of Sails.js is Socket.io support built in, so you can have a real-time frontend to your RFID system with minimum effort; - since MongoDB is a schemaless database (or, as they officially say nowadays, "database with dynamic / flexible schema"), we can store with our assets and have ready to be displayed any related information without worrying too much about relational structures, normalization, etc., for example, we can fetch some parameters from our ERP system, store within our Mongo document and display within our asset monitoring frontend; - and so on. ## What's next? Thus, we designed a way our RFID gateways can report the events to the central database. Of course, it is a very simplistic model leaving aside a lot of important aspects (the biggest of which is, probably, security), but it would be somewhat unreasonable to try to cover too many topics within one article, so we will be moving gradually. And the next thing we will look at within our series is the architecture of a simple RFID gateway, its software (and how to write it in Node.js, of course) and connecting RFID peripherals. ## License [The MIT License](http://opensource.org/licenses/MIT) Copyright (c) 2014 [Innobec Technologies Inc.](http://www.innobec.com/)
3001e8f01c858be22461babcd6040301111ab277
[ "JavaScript", "Markdown" ]
2
JavaScript
faridzy/rfid-based-asset-tracking-with-nodejs-and-mongodb
a4fa5dcbf10dccaa74026d1d3a5ceb9eb7ca4970
b669df661e75fb3e17b612f29225f5a2c3d836df
refs/heads/develop
<repo_name>wptechprodigy/decagance<file_sep>/README.md # decagance An online freelance market place. <file_sep>/public/index.js $(function() { // Database url let $dbUrl = 'http://localhost:9000/freelancers'; // Hook point to insert a new freelancer let $cardDeck = $('.card-deck'); // Grab all form inputs let $firstName = $('#first-name'); let $lastName = $('#last-name'); let $joinEmail = $('#join-email'); let $joinPassword = <PASSWORD>'); let $confirmPassword = <PASSWORD>'); // Grab the body let $body = $('#wholeBody'); // Alert messages declaration let $messageContent = { fail: 'Incorrect credentials. Try Again!', success: "Success. You'll be redirected in a moment", blank: 'Fill in all details!', invalid: 'Enter a valid email', notMatch: 'Passwords do not match. Ensure they match!' }; // GET first three freelancers to display on page load $.ajax({ type: 'GET', url: $dbUrl, success: function(freelancers) { for (let i = 0; i <= 2; i++) { $cardDeck.append( ` <div class="card d-flex"> <img src="${freelancers[i].image}" class="card-img-top" alt="${ freelancers[i].name }"> <div class="card-body"> <h5 class="card-title">${freelancers[i].firstName} ${ freelancers[i].lastName }</h5> <p class="card-text">${freelancers[i].description}</p> </div> <div class="card-footer d-flex justify-content-around"> <small class="text-muted"><i class="fas fa-star"></i> ${ freelancers[i].ratings } Ratings</small> <small class="text-muted"><a href="#" id="freelancer-details" data-toggle="modal" data-target="#freelancerDetailsModal"><i class="fas fa-eye"></i></a></i></small> </div> </div> ` ); } } }); // Handles alert function alertHandler(obj, status) { if (status !== 'success') { $('.alert').show('fade'); } else { $('.alert') .removeClass('alert-danger') .addClass('alert-success') .show('fade'); } $('#alert-message-content').html(obj[status]); setTimeout(function() { $('.alert').hide('fade'); }, 3000); } // Handles modal closing function closeModal() { $('.modal').modal('hide'); } function resetModal(modalId) { $(modalId).trigger('reset'); } // View freelancer details // $('#freelancer-details').click(function() { // let $('') // $(this).remove() // }); // Login a freelancer $('#login-btn').click(function() { // Grab incoming credentials let $email = $('#email').val(); let $password = $('#password').val(); // Check if an empty form has been submitted if ( ($email === null || $email === '', $password === null || $password === '') ) { alertHandler($messageContent, 'blank'); } else { // If not... $.ajax({ type: 'GET', url: $dbUrl, success: function(freelancers) { for (let freelancer of freelancers) { if ( freelancer.email === $email && freelancer.password === $password ) { setInterval(function() { resetModal('#login-form'); closeModal(); }, 3200); $body.addClass('bg-light').html($profileBody); // window.location.replace('./profile.html'); } else { alertHandler($messageContent, 'fail'); resetModal('#login-form'); } } }, error: function() { alert('There was an error login in.'); } }); } }); // Prepopulate freelancer dashboard $profileBody = ` <!-- Edit Profile Modal --> <div class="modal fade" id="editProfileModal" tabindex="-1" role="dialog" aria-labelledby="editProfileModalTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="editProfileModalTitle">Update your profile</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="form-row"> <div class="form-group col-md-6"> <label for="first-name">First Name</label> <input type="text" class="form-control" id="first-name" placeholder="Jane"> </div> <div class="form-group col-md-6"> <label for="last-name">Last Name</label> <input type="text" class="form-control" id="last-name" placeholder="Doe"> </div> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" id="email" placeholder="<PASSWORD>"> </div> <div class="form-group"> <label for="description">Description</label> <textarea class="form-control" rows="5" id="description"></textarea> </div> <div class="d-flex justify-content-end"> <button type="submit" class="btn btn-primary">Update</button> <button type="submit" class="btn btn-danger join" data-dismiss="modal" aria-label="Close">Cancel</button> </div> </form> </div> </div> </div> </div> <!-- Navigation --> <nav class="navbar navbar-dark bg-dark"> <a class="navbar-brand mb-0 h1" href="./index.html">Decagance</a> <!-- Nav links --> <div class="nav nav-pills justify-content-end"> <a class="nav-link btn btn-outline-primary" href="./index.html"> Sign Out </a> </div> </nav> <!-- Main content --> <section class="container mt-5"> <div class="row"> <div class="col-4 mx-auto"> <h1>Freelancer Profile</h1> <div class="card border-dark mb-3" style="max-width: 18rem;"> <div class="card-body"> <h5 class="card-title"><NAME></h5> <p class="card-text">I am a nobody.</p> </div> <div class="card-footer bg-transparent border-dark"> <small class="text-muted"><i class="fas fa-star"></i> 4.5 Ratings</small> </div> </div> </div> <div class="col-8"> <form id="freelancer-profile"> <fieldset disabled> <div class="form-group"> <label for="first-name">First Name</label> <input type="text" id="first-name" class="form-control" placeholder="First Name"> </div> <div class="form-group"> <label for="last-name">Last Name</label> <input type="text" id="last-name" class="form-control" placeholder="Last Name"> </div> <div class="form-group"> <label for="email">Email</label> <input type="text" id="email" class="form-control" placeholder="Email"> </div> <div class="form-group"> <label for="description">Description</label> <textarea class="form-control" rows="5" id="description"></textarea> </div> <div class="form-group"> <label for="services">Services</label> <input type="text" id="services" class="form-control" placeholder="Services"> </div> </fieldset> </form> <div class="nav nav-pills justify-content-end mb-5 mt-5"> <button class="nav-link btn btn-outline-primary btn-sm" data-toggle="modal" data-target="#editProfileModal" href="#"><i class="fas fa-pen"></i> Edit</button> <button class="nav-link btn btn-outline-danger join btn-sm" href="#"><i class="fas fa-trash"></i> Delete</button> </div> </div> </div> </section> `; // Register a new freelancer $('#join-btn').click(function(event) { event.preventDefault(); // Make AJAX call to add freelancer to the database let newData = { firstName: $firstName.val(), lastName: $lastName.val(), email: $joinEmail.val(), password: $join<PASSWORD>.val(), location: '', description: '', ratings: 0, services: [], role: 'freelancer', image: '' }; // Grab confirm password value for comparison $confirmPassword = $confirmPassword.val(); if ( newData.firstName === '' || newData.lastName === '' || newData.email === '' || newData.password === '' || $confirmPassword === '' ) { alertHandler($messageContent, 'blank'); } else if (newData.password !== $confirmPassword) { alertHandler($messageContent, 'notMatch'); resetModal('#join-form'); } else { $.ajax({ type: 'POST', url: $dbUrl, data: newData, // This is included for POST method dataType: 'JSON', success: function(newFreelancer) { console.log(newFreelancer); $('#join-form').trigger('reset'); closeModal(); let newFreelancerData = { firstName: newFreelancer.firstName, lastName: $lastName.val(), email: $joinEmail.val(), description: '', ratings: 0, services: [], role: 'freelancer', image: '' }; $body.addClass('bg-light').html($profileBody); // window.location.replace('./profile.html'); }, error: function() { alert('Something went wrong!'); } }); } }); });
ce572c6146e3ecb970e32f52a4605dd0917cbd0f
[ "Markdown", "JavaScript" ]
2
Markdown
wptechprodigy/decagance
9867c4bf209560816c0a4a73655f511fcfaaae61
fb315ea55485886f14db27f5859b0453e8e3a2ae
refs/heads/master
<repo_name>murtonen/IRC<file_sep>/src/irc/IRCModel.java /* * Modelissa huolehditaan jarjestelmaan liittyvan datan hallinnasta ja sailytyksesta * Lisaksi modeli vastaa kaikesta tiedonvalityksesta pircbot apia extendaavan MyServer luokan toteutuksesta */ package irc; import java.io.IOException; import java.util.ArrayList; import java.util.Observable; import java.util.logging.Level; import java.util.logging.Logger; import org.jibble.pircbot.IrcException; import org.jibble.pircbot.NickAlreadyInUseException; import org.jibble.pircbot.User; /** * * @author <NAME> */ public class IRCModel extends Observable { // Muuttujat teksteille private final String userChange = "userChange"; private final String newText = "newText"; private final String newTopic = "newTopic"; private final String nickInUse = "nickInUse"; private final String newLogLine = "newLogLine"; private final String newChanMode = "newChanMode"; private final String newMode = "newMode"; private final String disconnected = "disconnected"; private final String privMessage = "privateMessage"; private final String joinPart = "joinPart"; private final String noServer = "noServer"; private final String connectOK = "connectOK"; // Debuggausta varten MyServer ircnet; // Connected? boolean connected; boolean connectedOnce; // Strings String topic; String channel; String activeChannel; String logline; String response; String topicChannel; String privateSender; String privateMessage; String privateServer; String joinPartChannel; String fromChannel; String fromSender; String fromMessage; String fromServer; String modeServer; // ServerLista ja servereiden määrä sekä muut integerit MyServer[] serverList; Server[] Servers; int serverAmount; int activeServer; int disconnectedServer; // Rakentaja public IRCModel() throws Exception { // Muuttujien alustukset serverAmount = 0; activeServer = 0; // Ei kukaan voi kayttaa yli 10 serveria! serverList = new MyServer[10]; Servers = new Server[10]; // Alustukset jatkuu logline = ""; activeChannel = "Default"; channel = ""; topic = ""; response = ""; topicChannel= ""; disconnectedServer=0; joinPartChannel=""; fromChannel = ""; fromSender = ""; fromMessage = ""; connected = false; modeServer = ""; fromServer = ""; connectedOnce = false; } // Palautetaan tieto siita onko connectoiduttu // Tahan voisi kayttaa myos MyServerin metodia... public boolean isConnected() { return connected; } // Asetetaan aktiivisen serveirn indeksi public void setActiveServer(int index) { activeServer = index; } // Hihkaistaan observereille että kayttajalista kaipaa paivitysta public void updateUserList() { setChanged(); notifyObservers(userChange); } // Saatu uuden tekstirivin tiedot MyServerilta // Otetaan ne ylos ja ilmoitetaan observereille etta uutta tekstia saatavilla public void newText(String ser,String c, String s, String m) { fromServer = ser; fromChannel = c; fromSender = s; fromMessage = m; setChanged(); notifyObservers(newText); } // Metodi jolla valitetaan aktiivisen serverin myserverille tieto siita // mille kanavalle pitaa lahettaa tekstirivi public void sendLine(String channel,String line) { serverList[activeServer].sendMessage(channel,line); } // Metodi kanavalle liittymiseksi, syotteena kanavan nimi ja indeksitieto public void joinChannel (String nimi, int index) { if (serverAmount > 0) { activeChannel = nimi; serverList[activeServer].joinChannel(nimi); serverList[activeServer].sendRawLine("MODE " + nimi); Servers[activeServer].addChannel(index); } else { // Jos palvelinyhteytta ei ole, ilmoitetaan tasta observoijia setChanged(); notifyObservers(noServer); } } // Haetaan aktiivisen palvelimen viimeisin saama tekstirivi public String getLine() { return serverList[activeServer].lastText; } // Haetaan aktiivisen palvelimen kayttajat aktiiviselta kanavalta public User[] getUsers() { return serverList[activeServer].getUsers(activeChannel); } // Haetaan aktiivisen palvelimen kayttajat parametrina saadulta kanavalta public User[] getUsersChannel(String channel) { return serverList[activeServer].getUsers(channel); } // Haetaan parametrina saadun palvelimen parametrina saadun kanavan kayttajat public User[] getUserChan(String Channel,String server) { String serverName=""; User[] paluu = null; for (int i=0;i < serverAmount;i++) { serverName = serverList[i].getServer(); System.out.println(serverName+" vs "+server); if (serverName.equals(server)) { paluu = serverList[i].getUsers(Channel); } } return paluu; } // Haetaan parametrina saadun palvelimen parametrina saadun kanavan kayttajat // Hieman erilainen vertailu yllaolevaan, equals vs. contains public User[] getUsersChannel(String channel,String server) { String serverName=""; User[] paluu = null; for (int i=0;i < serverAmount;i++) { serverName = serverList[i].getServer(); if (serverName.contains(server)) { paluu = serverList[i].getUsers(channel); } } return paluu; } // Haetaan nickname aktiivisesta palvelimesta public String getCurrentNick() { return serverList[activeServer].getNick(); } // Otetaan ylos saadut tiedot topicista ja kanavasta jolle se asetettiin // Ja ilmoitetaan observoijia etta hakevat ja paivittavat nama tiedot public void updateTopic(String c, String t) { topicChannel = c; topic = t; setChanged(); notifyObservers(newTopic); } // Palautetaan kanava jolla topic muutettiin public String getTopicChannel() { return topicChannel; } // Palautetaan topic public String getTopic() { return topic; } // Palvelimelle yhdistamismetodi, ottaa syotteena palvelimen nimen ja nicknamen // Heittaa IrcExceptionin mikali epaonnistuu public void connectToServer(String server, String n) throws IrcException { // Asetellaan serveri serverList arrayyn serverList[serverAmount] = new MyServer(this); // Logitus verboselle serverList[serverAmount].setVerbose(true); // Asetetaan nick jolla yhdistetaan serverList[serverAmount].newNick(n); // Luodaan serveri sailomaan kanavatietoja Servers[serverAmount] = new Server(); // Yritetaan yhdistamista try { serverList[serverAmount].connect(server); activeServer=serverAmount; serverAmount++; connected=true; connectedOnce=true; setChanged(); notifyObservers(connectOK); } catch (IOException ex) { Logger.getLogger(IRCModel.class.getName()).log(Level.SEVERE, null, ex); // Jos nick kaytossa, ilmoitetaan observoijia tasta } catch (NickAlreadyInUseException ex) { setChanged(); notifyObservers(nickInUse); } } // Asetetaan uusi nickName public void changeNick(String newnick) { serverList[activeServer].newNick(newnick); } // Metodi jolla voidaan yrittaa reconnectia aktiivisella serverilla public void reconnect() throws IrcException { try { serverList[activeServer].reconnect(); connected = true; } catch (IOException ex) { Logger.getLogger(IRCModel.class.getName()).log(Level.SEVERE, null, ex); } catch (NickAlreadyInUseException ex) { Logger.getLogger(IRCModel.class.getName()).log(Level.SEVERE, null, ex); } } // Metodi jolla voidaan potkia henkilo pois aktiiviselta serverilta aktiivisella kanavalla public void kickTarget(String nick) { nick = nick.replace("+",""); nick = nick.replace("@",""); serverList[activeServer].kick(activeChannel, nick); } // Asetetaan aktiivinen kanava public void setActiveChannel(String string) { activeChannel = string; } // Otetaan logline talteen ja ilmoitetaan observoijille etta hakevat ko. tiedon public void sendLogLine(String line) { logline = line; setChanged(); notifyObservers(newLogLine); } // Palautetaan logline public String getLogLine() { return logline; } // Ilmoitetaan etta on saatu uusi kanavamode, parametreina palaute ja serveri jolta tieto saatu public void channelModeNotify(String r,String s) { response = r; modeServer = s; setChanged(); notifyObservers(newChanMode); } // Palautetaan ko. modetieto public String getResponse() { return response; } // Palautetaan serveri jolla mode tehtiin public String getModeServer() { return modeServer; } // Metodi jolla asetetaan nicknamelle Operator status, tai poistetaan se jos arvo on jo // Parametrina kyseinen nickname public void opOrDeop(String n) { n = n.replace("+",""); n = n.replace("@",""); User[] users = serverList[activeServer].getUsers(activeChannel); for (int i = 0;i<users.length;i++) { if (users[i].getNick().equals(n)) { if (users[i].isOp()) { serverList[activeServer].deOp(activeChannel, n); } else { serverList[activeServer].op(activeChannel, n); } } } } // Vastaava metodi jolla asetetaan voice tai poistetaan se jos kyseinen arvo on jo public void voiceOrDevoice(String n) { n = n.replace("+",""); n = n.replace("@",""); User[] users = serverList[activeServer].getUsers(activeChannel); for (int i = 0;i<users.length;i++) { if (users[i].getNick().equals(n)) if (users[i].hasVoice()) { serverList[activeServer].deVoice(activeChannel, n); } else { serverList[activeServer].voice(activeChannel, n); } } } // Valitetaan tieto bannausmaskista myserverille public void ban(String mask) { serverList[activeServer].ban(activeChannel, mask); } // Valietaan tieto unbanmaskista myserverille public void unban(String mask) { serverList[activeServer].unBan(activeChannel, mask); } // Palautetaan aktiivinen kanava public String getActiveChannel() { return activeChannel; } // Metodi kanavalta poistumiseksi, parametrina tieto palvelimesta ja kanavasta // seka indeksitieto // Kay serverarrayn lapi ja etsii oikean palvelimen ja ilmoittaa sille kanavan jolta poistuttiin public void partChannel(String channelToPart, int index) { String server = "Default"; String channel = "Default"; String serverB = "-1"; try { String[] splitted = channelToPart.split(":"); server = splitted[0]; channel = splitted[1]; } catch (Exception ex) { } for (int i = 0;i < serverAmount;i++) { if (serverList[i].getServer() != null ) { try { String[] splitmore = serverList[i].getServer().split("\\."); serverB = splitmore[1]; } catch (Exception ez) { } if (server.equals(serverB)) { serverList[i].partChannel(channel); Servers[i].removeChannel(index); } } } } // Metodi jolla disconnectoidutaan palvelimelta, saa syotteena indeksiarvon // Disconnectaa ko. serverin ja disposee ilmentyman // Ja ilmoittaa observoijille etta on disconnectoiduttu public void disconnectServer(int selectedServer) { disconnectedServer = selectedServer; serverList[selectedServer].disconnect(); serverList[selectedServer].dispose(); serverAmount--; if ( serverAmount == 0) { connected = false; } setChanged(); notifyObservers(disconnected); } // Palauttaa ko. palvelimen kanavat public ArrayList getServerChannels(int selectedServer) { return Servers[selectedServer].Channels(); } // Paivittaa viimeisimman palvelimen aktiiviseksi public void updateActiveServer() { activeServer=serverAmount; } // Ottaa privaattiviestin tiedot ylos ja ilmoittaa observoijia etta hakevat ko. tiedot public void privateMessage(String ser, String sender, String message) { privateSender = sender; privateMessage = message; privateServer = ser; setChanged(); notifyObservers(privMessage); } // Palauttaa tiedon milta kanavalta viesti oli public String fromChannel() { return fromChannel; } // Palauttaa tiedon kenelta viesti oli public String fromSender() { return fromSender; } // Palauttaa viestin public String fromMessage() { return fromMessage; } // Palauttaa palvelimen jolta viesit oli public String fromServer() { return fromServer; } // Palauttaa privaattiviestin lahettajan public String getSender() { return privateSender; } // Palauttaa privaattiviestin public String getMessage() { return privateMessage; } // Ottaa ylos kanavan joka tulee paivittaa ja ilmoittaa observoijaa tasta public void updateUserListOnJP(String c) { joinPartChannel=c; setChanged(); notifyObservers(joinPart); } // Palauttaa kanavan jolta partattiin public String getJoinPartChannel() { return joinPartChannel; } // Metodi jolla paatellaan voiko reconnectoida public boolean canReconnect() { boolean paluu; if ( serverAmount > 0 && connectedOnce == true) { paluu = true; } else { paluu = false; } return paluu; } // Quit metodi disconnectaa ja disposee kaikki myserver oliot public void quit() { if ( isConnected() ) { for (int i=0;i<serverList.length;i++) { try { serverList[i].disconnect(); } catch (Exception e) { } serverList[i].dispose(); } } } // Otetaan ylos palvelin ja kanava jolla usermode muutos tapahtui // Ja ilmoitetaan observerille etta hakee ko. tiedot public void updateUserListOnMode(String server, String channel, String mode) { fromServer = server; fromChannel = channel; setChanged(); notifyObservers(newMode); } // Palauttaa privaattimessagen palvelimen osoitteen public String getPServer() { return privateServer; } } <file_sep>/src/irc/IRCController.java /* * Controller luokassa toteutetaan ohjelman "aly", eli viestien valitys * ja niiden kasittely viewin ja modelin valilla */ package irc; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.jibble.pircbot.IrcException; /** * * @author <NAME> */ public class IRCController implements ActionListener,ChangeListener { // Maaritellaan kayttoon Model ja View IRCModel model; IRCView view; public IRCController (final IRCModel m, final IRCView v) { // Asetetaan paaohjelmasta saadut model ja view paikalleen model = m; view = v; // Connectorit on toteutettu inject tyyppisesti, eli view toteuttaa metodit // listenerin lisaamiseksi ja controllerissa ne asetetaan, jotta actionperformed saadaan tanne // Connect Listener v.setConnectListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String nick = v.getNick(); String server = v.getServer(); if (server != null && !server.equals("")) { try { m.connectToServer(server,nick); v.addToServerMenu(server); v.setServerItemListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m.setActiveServer(v.getIndex()); } }); v.setFocus(); } catch (IrcException ex) { Logger.getLogger(IRCController.class.getName()).log(Level.SEVERE, null, ex); } } } }); // DiscConnect Listener v.setDisconnectListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m.isConnected()) { m.disconnectServer(v.getSelectedServer()); m.updateActiveServer(); } else { v.cannotDisconnect(); } } }); // ReConnect Listener v.setReconnectListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m.canReconnect()) { try { m.reconnect(); } catch (IrcException ex) { Logger.getLogger(IRCController.class.getName()).log(Level.SEVERE, null, ex); } } else { v.cannotReconnect(); } } }); // chanListListener v.setChanListListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // Get current tab int sel = v.getSelectedPaneIndex(); v.setActiveTab(sel); v.clearListModel(); v.channelChange(sel); } }); // Connect Listener v.setPreferencesListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { v.getPreferences(); } }); // Join Button Listener v.setJoinButtonListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m.isConnected()) { String channelToJoin; int index; channelToJoin = v.getJoinChannel(); index = v.joinChannel(channelToJoin); m.joinChannel(channelToJoin,index); v.setFocus(); } else { v.noServer(); } } }); // Part Button Listener v.setPartButtonListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m.isConnected()) { int indexPart = v.partChannelIndex(); m.partChannel(v.partChannel(),indexPart); } else { v.noServer(); } } }); // Kick Button Listener v.setKickListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String nick = v.getTarget(); m.kickTarget(nick); m.updateUserList(); } }); // Op/Deop Button Listener v.setOpListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String nick = v.getTarget(); m.opOrDeop(nick); } }); // Voice/DeVoice Button Listener v.setVoiceListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String nick = v.getTarget(); m.voiceOrDevoice(nick); } }); // Ban Button Listener v.setBanListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String mask = v.getMask(); m.ban(mask); } }); // UnBan Button Listener v.setUnBanListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String mask = v.getMask(); m.unban(mask); } }); // Input Area Listener v.setInputAreaListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String input=""; String channel=""; String[] splitted; input = v.getInput(); int index; if ( input.startsWith("/join")) { splitted = input.split(" "); index = v.joinChannel(splitted[1]); m.joinChannel(splitted[1], index); } else { channel = v.getActiveChannel(); m.sendLine(channel,input); v.sendLine(input); } } }); // UnBan Button Listener v.setQuitListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { m.quit(); } catch (Exception ex) { } try { v.quit(); } catch (Exception ex) { } System.exit(0); } }); } // Should not be used! Debugging. (Yes, left it here.) public void getUserList() { //return model.getUserList(); } // No need but netbeans wanted these @Override public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); } // No need but netbeans wanted these @Override public void stateChanged(ChangeEvent e) { throw new UnsupportedOperationException("Not supported yet."); } } <file_sep>/src/irc/IRC.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package irc; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingUtilities; /** * * @author <NAME> */ public class IRC { /** * @param args the command line arguments */ // Ohjelman starttaaminen public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { IRCModel m; try { m = new IRCModel(); IRCView v = new IRCView(m); IRCController c = new IRCController(m, v); } catch (Exception ex) { } } }); } } <file_sep>/src/irc/IRCView.java /* * View toteuttaa ohjelman näkymän ja siihen liittyvät toiminnot kuten painikkeet * */ package irc; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.*; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeListener; import org.jibble.pircbot.IrcException; import org.jibble.pircbot.User; /** * * @author <NAME> */ public class IRCView extends JPanel implements MouseListener,Observer { // Paalayoutti JFrame frame; JTabbedPane chanList; // JTextFieldit JTextField topic,input; final JTextField nickN, altN, userN, realN; // nickList ja modeli sita varten DefaultListModel listModel; JList nickPanel; // JmenuBar ja itemit JMenuBar menuBar; JMenu File,Server,Options; JMenuItem Connect,Disconnect,Reconnect,Quit,Preferences; // Panels JPanel northPanel; JPanel eastPanel; JPanel southPanel; JPanel defaultti; JPanel westPanel; // PopUpMenu JPopupMenu popup; JMenuItem kick,ban,unban,op,voice; // Model IRCModel m; // Jbutton JButton Join,Part,ConnectB,DisconnectB,ReconnectB,QuitB; // Lists for Channels JTextArea[] channels; String[] channelNames; String[] channelTopics; // Counts int activeTab; int chanAmount; int serverAmount; int selectedServer; // Other int int partChannelIndex; // ScrollPane JScrollPane nickScrollPane,defaultScrollPane; // MenuButtonGroup ButtonGroup serverGroup; // JButtonGroup JRadioButtonMenuItem[] buttonList; // Strings String server, nick, altnick; public IRCView(IRCModel model) { // Framen luominen frame = new JFrame("(A)wesome irc (C)lient (E)xperience"); frame.setSize(450,150); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Serveramount serverAmount = 0; // Asetetaan Observer m = model; m.addObserver(this); // JTextFieldit topic = new JTextField(40); input = new JTextField(40); input.setActionCommand("input"); topic.setEditable(false); topic.setText("Welcome to ACE!"); // Nick listing listModel = new DefaultListModel(); nickPanel = new JList(listModel); nickPanel.setBackground(topic.getBackground()); nickPanel.addMouseListener(this); nickScrollPane = new JScrollPane(nickPanel); // JTextArea chanAmount = 0; channels = new JTextArea[30]; channelNames = new String[30]; channels[chanAmount] = new JTextArea(30,30); channelNames[chanAmount] = new String("Default"); channelTopics = new String[30]; channelTopics[0] = "Default"; // Lisätään vähän tervetuloa defaulttiin. channels[0].append("Welcome to Awesome irc Client Experience!\n"); channels[0].append("Help is not available.\n"); channels[0].append("But don't panic!\n"); channels[0].append("Because with such an intuitive UI,\n"); channels[0].append("no help is needed!\n"); // JPanelit, niiden layoutit ja koot northPanel = new JPanel(new BorderLayout()); eastPanel = new JPanel(new BorderLayout()); eastPanel.setPreferredSize(new Dimension(200,100)); southPanel = new JPanel(new BorderLayout()); westPanel = new JPanel(); westPanel.setLayout(new BoxLayout(westPanel,BoxLayout.Y_AXIS)); // JTabbedPane ja Defaultpane logitusta varten chanList = new JTabbedPane(); defaultti = new JPanel(new BorderLayout()); defaultti.add(channels[chanAmount]); defaultScrollPane = new JScrollPane(defaultti); chanList.addTab("Default",defaultScrollPane); // Asetetaan defaulttab aktiiviseksi activeTab = 0; // Asetetaan default arvoja nickN = new JTextField(12); altN = new JTextField(12); userN = new JTextField(12); realN = new JTextField(12); nickN.setText("Anonymous123"); altN.setText("Anonymous234"); userN.setText("Anonymous"); realN.setText("<NAME>"); // Borderit layouteille TitledBorder topicBorder; topicBorder = BorderFactory.createTitledBorder("Topic"); topic.setBorder(topicBorder); TitledBorder inputBorder; inputBorder = BorderFactory.createTitledBorder("Input"); input.setBorder(inputBorder); TitledBorder nickListBorder; nickListBorder = BorderFactory.createTitledBorder("Names"); nickPanel.setBorder(nickListBorder); // Lisataan JPaneliin northPanel.add(topic); eastPanel.add(nickScrollPane); southPanel.add(input); // Luodaan Menubar menuBar = new JMenuBar(); // Asetetaan siihen otsikot File = new JMenu("File"); Server = new JMenu("Server"); Options = new JMenu("Options"); menuBar.add(File); menuBar.add(Server); menuBar.add(Options); // Ja niihin sisalto Connect = new JMenuItem("Connect"); Disconnect = new JMenuItem("Disconnect"); Reconnect = new JMenuItem("Reconnect"); Quit = new JMenuItem("Quit"); Preferences = new JMenuItem("Preferences"); // ButtonGroup serverGroup = new ButtonGroup(); buttonList = new JRadioButtonMenuItem[10]; // Ja laitetaan menuun File.add(Connect); File.add(Disconnect); File.add(Reconnect); File.add(Quit); Options.add(Preferences); // PopUpMenu popup = new JPopupMenu(); kick = new JMenuItem("Kick"); ban = new JMenuItem("Ban"); unban = new JMenuItem("UnBan"); op = new JMenuItem("Op/DeOp"); voice = new JMenuItem("Voice/DeVoice"); // Lisaykset popupvalikkoon popup.add(kick); popup.add(ban); popup.add(unban); popup.add(op); popup.add(voice); // Jbuttonit ja koon pakotukset Join = new JButton("Join"); Join.setPreferredSize(new Dimension(100,25)); Join.setMinimumSize(new Dimension(100,25)); Join.setMaximumSize(new Dimension(100,25)); Part = new JButton("Part"); Part.setPreferredSize(new Dimension(100,25)); Part.setMinimumSize(new Dimension(100,25)); Part.setMaximumSize(new Dimension(100,25)); ConnectB = new JButton("Connect"); ConnectB.setPreferredSize(new Dimension(100,25)); ConnectB.setMinimumSize(new Dimension(100,25)); ConnectB.setMaximumSize(new Dimension(100,25)); DisconnectB = new JButton("Disconnect"); DisconnectB.setPreferredSize(new Dimension(100,25)); DisconnectB.setMinimumSize(new Dimension(100,25)); DisconnectB.setMaximumSize(new Dimension(100,25)); ReconnectB = new JButton("Reconnect"); ReconnectB.setPreferredSize(new Dimension(100,25)); ReconnectB.setMinimumSize(new Dimension(100,25)); ReconnectB.setMaximumSize(new Dimension(100,25)); QuitB = new JButton("Quit"); QuitB.setPreferredSize(new Dimension(100,25)); QuitB.setMinimumSize(new Dimension(100,25)); QuitB.setMaximumSize(new Dimension(100,25)); // Lisataan ne paneliin westPanel.add(ConnectB); westPanel.add(DisconnectB); westPanel.add(ReconnectB); westPanel.add(QuitB); westPanel.add(Join); westPanel.add(Part); // Laitetaan frameen Jpanelit frame.setJMenuBar(menuBar); frame.add(northPanel,BorderLayout.NORTH); frame.add(eastPanel,BorderLayout.EAST); frame.add(southPanel,BorderLayout.SOUTH); frame.add(chanList,BorderLayout.CENTER); frame.add(westPanel,BorderLayout.WEST); // Naytetaan sisalto frame.pack(); frame.setVisible(true); } // Mouseeventteja, ide tahtoi nama public void mousePressed(MouseEvent e) { if ( e.getButton() == MouseEvent.BUTTON3) { popup.show( e.getComponent(), e.getX(), e.getY() ); } } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } // Update metodissa otetaan observable mallin mukaisesti viesti modelilta // Ja toimitaan riippuen viestin arvosta public void update(Observable o, Object arg) { String msg = (String)arg; String channel; String topicChannel; String topik; String newnick; // Haetaan modelilta teksti ja syotetaan se nakymaan if ( msg.equals("newText")) { addToChannel(m.fromServer(),m.fromChannel(),m.fromSender(),m.fromMessage()); } else if (msg.equals("userChange")) { // Paivitetaan kayttajalistaus listModel.clear(); changeUsers(m.getUsers()); } else if (msg.equals("newTopic")) { // Haetaan modelista topic ja topickanava ja paivetaan nakyma topicChannel = m.getTopicChannel(); topik = m.getTopic(); String verrattava = null; String verrattavaActive = null; for ( int i = 0;i <= chanAmount;i++) { if ( channelNames[i] != null ) { try { String[] splitted = channelNames[i].split(" "); verrattava = splitted[1]; } catch (Exception ex) { } if (verrattava != null ) { if (verrattava.contains(topicChannel)) { channelTopics[i] = topik; } } try { String[] splitted = channelNames[activeTab].split(" "); verrattavaActive = splitted[1]; } catch (Exception ex) { } if (verrattavaActive.contains(topicChannel)) { channelTopics[activeTab]=topik; topic.setText(topik); } } } } else if (msg.equals("nickInUse")) { //Nickname oli kaytossa, kysytaan uusi nick ja reconnectoidaan newnick = nickUsed(); m.changeNick(newnick); try { m.reconnect(); } catch (IrcException ex) { Logger.getLogger(IRCView.class.getName()).log(Level.SEVERE, null, ex); } } else if (msg.equals("newLogLine")) { // Uusi logirivi, haetaan se ja syotetaan nakymaan channels[0].append(m.getLogLine()+"\n"); } else if (msg.equals("newChanMode")) { // Uusi mode kanavalla, haetaan sen tiedot ja syotetaan nakymaan String response = m.getResponse(); String tempServer = m.getModeServer(); String modeServer=null; try { String[] splitserver = tempServer.split("\\."); modeServer = splitserver[1]; } catch (Exception ex) { } String splitted[] = response.split(" "); channel = splitted[1]; String mode = splitted[2]; String kanava = "-1"; String palvelin = "-1"; for ( int j = 0;j <= chanAmount;j++) { if (channelNames[j] != null ) { try { String[] split = channelNames[j].split(" "); kanava = split[1]; palvelin = split[0]; } catch (Exception ex) { } if (kanava.contains(channel) && palvelin.contains(modeServer)) { String[] splitmore = chanList.getTitleAt(j).split(" "); String newTopic = splitmore[0]+" "+splitmore[1]+" "+mode; chanList.setTitleAt(j,newTopic); } } } // disconnectoiduttu serverilta, poistetaan kaikki ko serverin tabit } else if (msg.equals("disconnected")) { serverAmount--; int index; int remove = this.getSelectedServer(); ArrayList toBeRemoved=m.getServerChannels(selectedServer); for (int k = 0;k < toBeRemoved.size();k++) { index = (Integer)toBeRemoved.get(k); chanList.remove(index); } Server.remove(buttonList[remove]); JOptionPane.showMessageDialog(frame, "Disconnected from Server!"); if ( serverAmount != 0 ) buttonList[serverAmount].setSelected(true); } else if ( msg.equals("privateMessage")) { // Privatemessage, haetaan tiedot ja viesti modelista String serverP = m.getPServer(); String serverPr = "Default"; try { String[] splitP = serverP.split("\\."); serverPr = splitP[1]; } catch (Exception ex) { } String sender = m.getSender(); String message = m.getMessage(); String vertailtava = "["+serverPr+"]"+" "+sender; boolean found = false; for (int l = 0;l <= chanAmount;l++) { if ( channelNames[l] != null ) { if ( channelNames[l].equals(vertailtava)) { channels[l].append(sender+": "+message+"\n"); found = true; } } } if (found == false) { this.joinChannel(sender); channels[chanAmount].append(sender+": "+message+"\n"); } // Joku joinasi tai parttasi kanavalta, paivitetaan kayttajalistaus modelilta } else if ( msg.equals("joinPart")) { listModel.clear(); changeUsers(m.getUsersChannel(m.getJoinPartChannel())); } else if ( msg.equals("connectOK")) { // Connect mennyt oikein annetaan siita popup ilmoitus JOptionPane.showMessageDialog(frame, "Connected to Server!"); } else if ( msg.equals("newMode")) { // Uusi mode, paivitetaan kayttajalistaus listModel.clear(); changeUsers(m.getUserChan(m.fromChannel(),m.fromServer())); } else { } } // Metodi viestin lisaamiseksi kanavalle, ottaa argumenteiksi palvelimen, kanavan // lahettajan ja viestin ja parsee tabit lapi etsien oikean tabin ja syottaen sen jalkeen // viestin oikein muotoiltuna ko. tabiin public void addToChannel(String ser, String c, String s, String m) { String kanava = "Default"; String palvelin = "Default"; String palvelinB = ""; try { String[] splittwo = ser.split("\\."); palvelinB = splittwo[1]; } catch (Exception ex) { } for ( int i = 0;i <= chanList.getTabCount();i++) { if (chanList.getTitleAt(i) != null) { try { String[] splitone = chanList.getTitleAt(i).split(" "); palvelin = splitone[0]; kanava = splitone[1]; palvelin = palvelin.replace("[",""); palvelin = palvelin.replace("]",""); } catch (Exception ez) { } if (palvelin.equals(palvelinB) && kanava.equals(c)) { channels[i].append(s+": "+m+"\n"); } } } } // Yksinkertainen addline jos halutaan vain lisata aktiiviseen tabiin public void addLine(String rivi) { channels[activeTab].append(rivi+"\n"); } // ChangeUsers metodi joka saa syotteena User[] arrayn jonka pohjalta // syottaa listModeltiin tavaraa addNick metodilla, muotoiltuaan ensiksi // nicknamen eteen tarpeelliset prefixit kuten + tai @ public void changeUsers(User[] users) { if ( users != null ) { int koko = users.length; String prefix = ""; for (int i = 0;i<koko;i++) { if (users[i].isOp()) { prefix = "@"; } else if ( users[i].hasVoice()) { prefix = "+"; } else { prefix = ""; } addNick(users[i].getNick(),prefix); } } } // Lisaa nicknamen listmodeliin public void addNick(String nick,String prefix) { String element = prefix+nick; listModel.addElement((String)element); } // Listenerit kaikille tarpeellisille, controller injektoi naihin actionlistenerit public void setServerItemListener(ActionListener l) { buttonList[serverAmount-1].addActionListener(l); } public void setPreferencesListener(ActionListener l) { Preferences.addActionListener(l); } public void setJoinButtonListener(ActionListener l) { Join.addActionListener(l); } public void setPartButtonListener(ActionListener l) { Part.addActionListener(l); } public void setInputAreaListener(ActionListener l) { input.addActionListener(l); } public void setConnectListener(ActionListener l) { Connect.addActionListener(l); ConnectB.addActionListener(l); } public void setDisconnectListener(ActionListener l) { Disconnect.addActionListener(l); DisconnectB.addActionListener(l); } public void setReconnectListener(ActionListener l) { Reconnect.addActionListener(l); ReconnectB.addActionListener(l); } public void setQuitListener(ActionListener l) { Quit.addActionListener(l); QuitB.addActionListener(l); } public void setKickListener(ActionListener l) { kick.addActionListener(l); } public void setBanListener(ActionListener l) { ban.addActionListener(l); } public void setUnBanListener(ActionListener l) { unban.addActionListener(l); } public void setOpListener(ActionListener l) { op.addActionListener(l); } public void setVoiceListener(ActionListener l) { voice.addActionListener(l); } public void setChanListListener(ChangeListener c) { chanList.addChangeListener(c); } public int getSelectedPaneIndex() { return chanList.getSelectedIndex(); } // Palautetaan inputin teksti ja tyhjataan inputalue public String getInput() { String paluu = input.getText(); input.setText(""); return paluu; } // Metodi kanavatabin luomiseksi, ottaa parametriksi kanavan nimen // ja luo taman pohjalta tabin jonka nimi on "[server] #kanava" public int joinChannel(String n) { String server = "Default"; int i = this.getSelectedServer(); String temp = (String)buttonList[i].getText(); try { String[] splitted = temp.split("\\."); server = splitted[1]; } catch (Exception ex) { } String nimi = "["+server+"] "+n; chanAmount++; channelNames[chanAmount]=new String(nimi); chanList.add(nimi,addPanel()); chanList.setSelectedIndex(chanAmount); channels[chanAmount].append("Joined channel: "+nimi+"\n"); return chanAmount; } // Metodi joka lisaa palauttaa JTextArean sisaltavan JPanelin public JPanel addPanel() { channels[chanAmount] = new JTextArea(30,30); JScrollPane tempScrollPane = new JScrollPane(channels[chanAmount]); JPanel temp = new JPanel(new BorderLayout()); temp.add(tempScrollPane); return temp; } // Palautetaan aktiivinen tabi, miksi sita ei haeta vaan JPanel.getSelectedIndex? // en muista enaa syyta... public int activeTab() { return activeTab; } // Palautetaan aktiivisen tabin kanavan nimi public String getActiveChannel() { return channelNames[activeTab]; } // Lahetetaan aktiiviselle kanavalle syotetty rivi public void sendLine(String input) { String nick = m.getCurrentNick(); channels[activeTab].append(nick+": "+input+"\n"); } // Kysytaan palvelin JDialogilla public String getServer() { String s = (String)JOptionPane.showInputDialog( frame, "Enter server to connect to: ","Connect to Server", 1); return s; } // Kysytaan nicname JDialogilla public String getNick() { String n = (String)JOptionPane.showInputDialog( frame, "Enter nickname: ","Set Up Nickname", 1); return n; } // Kysytaan uusi nickname jos edellinen oli kaytetty public String nickUsed() { String n = (String)JOptionPane.showInputDialog( frame, "Enter new nickname: ","Nickname already in use", 1); return n; } // Lisataan nappi servermenuun ja linkitetaan se buttongrouppiin public void addToServerMenu(String server) { buttonList[serverAmount] = new JRadioButtonMenuItem(server); serverGroup.add(buttonList[serverAmount]); buttonList[serverAmount].setSelected(true); Server.add(buttonList[serverAmount]); serverAmount++; } // Metodi jolla palautetaan listModelista elementti public String getTarget() { return (String)listModel.getElementAt(nickPanel.getSelectedIndex()); } // Tyhjataan listModel public void clearListModel() { listModel.clear(); } // Vaihdettu tabia joten paivitetaan kayttajalistaus nickListiin ko. kanavan osalta public void channelChange(int sel) { String channel = "Default"; String server = "Default"; if (channelTopics[sel] != null ) { topic.setText(channelTopics[sel]); } else { topic.setText(""); } try { String[] splitted = channelNames[sel].split(" "); server = splitted[0]; server = server.replace("[",""); server = server.replace("]",""); channel = splitted[1]; } catch (Exception ex) { } changeUsers(m.getUsersChannel(channel,server)); } // Paivitetaan ko. kanavan kayttajalistaus hakemalla kayttaja modelista public void updateUsers(int sel) { changeUsers(m.getUsersChannel(channelNames[sel])); } // Kysytaan netmaski bannausta/unbannausta varten public String getMask() { String n = (String)JOptionPane.showInputDialog( frame, "Enter netmask","Enter netmask:", 1); return n; } // Kysytaan kanava jolle halutaan liittya JDialogilla public String getJoinChannel() { String n = (String)JOptionPane.showInputDialog( frame, "Enter channel to join: ","Join new channel", 1); return n; } // Asetetaan aktiivinen tabi public void setActiveTab(int sel) { activeTab=sel; } // On poistuttu kanavalta joten poistetaan ko. tabi ja palautetaan mikä serveri ja kanava oli kyseessa public String partChannel() { String serveR = "Default"; String channeL = "Default"; String title = chanList.getTitleAt(chanList.getSelectedIndex()); try { String[] splitted = title.split(" "); serveR = splitted[0]; serveR = serveR.replace("[",""); serveR = serveR.replace("]",""); channeL = splitted[1]; } catch (Exception ex) { } chanList.removeTabAt(chanList.getSelectedIndex()); chanAmount--; if (chanAmount > 0) { for (int j = 1;j<channelNames.length-1;j++) { channelNames[j] = channelNames[j+1]; } } String paluu = serveR+":"+channeL; return paluu; } // Haetaan buttongroupista valittu palvelin public int getSelectedServer() { int buttons = serverGroup.getButtonCount(); int paluu = -1; for (int i = 0; i <= buttons; i++) { if (buttonList[i] != null ) { if (buttonList[i].isSelected()) { selectedServer = i; paluu = i; } } } return paluu; } // Asetetaan focus inputkentaan public void setFocus() { input.requestFocusInWindow(); } // Metodi jolla JDialogia hyvaksikayttaen kysytaan kayttajalta preferenssit // Ja serializoidaan ne tiedostosta kentiksi ja vastaavasti takaisin tiedostoon public void getPreferences() { // Jbuttonit JButton Save = new JButton("Save"); JButton Cancel = new JButton("Cancel"); // JPanel JPanel main = new JPanel(new BorderLayout()); JPanel buttonPanel = new JPanel(); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel,BoxLayout.Y_AXIS)); // Paneeliin lisaykset buttonPanel.add(Save); buttonPanel.add(Cancel); // Yritetaan ladata talletettuja arvoja try { ObjectInputStream ois = new ObjectInputStream( new FileInputStream("prefs.obj")); Preferences p = (Preferences)ois.readObject(); ois.close(); // Asetetaan arvot nickN.setText(p.getNick()); altN.setText(p.getAlt()); userN.setText(p.getUser()); realN.setText(p.getReal()); } catch ( ClassCastException cce ) { } catch (Exception e ) { } final JDialog dialog = new JDialog(frame, true); // Tallennetaan tiedot objektiin ja kirjoitetaan objekti fileen Save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Preferences myPrefs = new Preferences(); if (nickN.getText() != null ) myPrefs.setNick(nickN.getText()); if (altN.getText() != null) myPrefs.setAlt(altN.getText()); if (realN.getText() != null) myPrefs.setReal(realN.getText()); if (userN.getText() != null) myPrefs.setUser(userN.getText()); serializeInformation(myPrefs); dialog.dispose(); } }); Cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dialog.dispose(); } }); // Borderit // Borderit layouteille TitledBorder nickNBorder; nickNBorder = BorderFactory.createTitledBorder("Nickname"); nickN.setBorder(nickNBorder); TitledBorder altNBorder; altNBorder = BorderFactory.createTitledBorder("Alternative nick"); altN.setBorder(altNBorder); TitledBorder userNBorder; userNBorder = BorderFactory.createTitledBorder("Username"); userN.setBorder(userNBorder); TitledBorder realNBorder; realNBorder = BorderFactory.createTitledBorder("Realname"); realN.setBorder(realNBorder); // Asetellaan ja paketoidaan mainPanel.add(nickN); mainPanel.add(altN); mainPanel.add(userN); mainPanel.add(realN); main.add(mainPanel,BorderLayout.NORTH); main.add(buttonPanel,BorderLayout.SOUTH); dialog.setName("Input preferences"); dialog.getContentPane().add(main); dialog.pack(); dialog.setLocation(525,200); dialog.setVisible(true); } // Serializoidaan tiedostoon, syotteena Pferenssiobjekti private void serializeInformation(Preferences p) { try { ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("prefs.obj") ); oos.writeObject( p ); oos.close(); } catch (Exception e ) { e.printStackTrace();} } // Errormessage siita ettei yhteytta ole public void noServer() { JOptionPane.showMessageDialog(frame, "Connect to a server before joining or parting a channel!"); } // Errormessage siita etta ei voitu reconnectaa public void cannotReconnect() { JOptionPane.showMessageDialog(frame, "Connect to a server atleast once and disconnect atleast once before attempting to reconnect!"); } // Errormessage siita etta ei voitu disconnectaa public void cannotDisconnect() { JOptionPane.showMessageDialog(frame, "Connect to a server before attempting to discconnect!"); } // Disposetaan frame quitin yhteydessa public void quit() { frame.dispose(); } // Palautetaan indeksiarvo public int getIndex() { return serverAmount-1; } // Palautetaan chanlistin valitun tabin indeksi public int partChannelIndex() { return chanList.getSelectedIndex(); } } <file_sep>/src/irc/Preferences.java /* * Olio jonka avulla voidaan serializee ohjelman preferenssit * Toteuttaa getterit ja setterit preferenssien arvoille */ package irc; import java.io.Serializable; /** * * @author <NAME> */ public class Preferences implements Serializable { // Muuttujat private String nick; private String alt; private String user; private String real; // Rakentaja public Preferences() { } // Getterit ja Setterit public String getNick() { return nick; } public String getAlt() { return alt; } public String getUser() { return user; } public String getReal() { return real; } public void setNick(String n) { nick = n; } public void setAlt(String a) { alt = a; } public void setUser(String u) { user = u; } public void setReal(String r) { real = r; } }
e07876d056ee0d85fd1cc406397c6fe492c4f204
[ "Java" ]
5
Java
murtonen/IRC
77025fdcca117f73147dc05e728a15be2a75ae86
b226b4de2def45cbacd2878f43481a42b6e2f569
refs/heads/master
<file_sep>''' @author: <EMAIL> This script tries to crop images from Alvin's dataset such that only objects of interest are visible. Since as input to keras we use 32x32x3 (similar to cifar-10), reducing our images to small size means the features are too small to be detected. ''' from __future__ import print_function import cv2 as cv import argparse #import cv import numpy as np import os import glob PATH_DATA = "../image_dataset-master/" PATH_WRITE = "../image_dataset-master-cropped/" max_value = 255 max_value_H = 360//2 low_H = 0 low_S = 0 low_V = 0 high_H = max_value_H high_S = max_value high_V = max_value window_capture_name = 'Video Capture' window_detection_name = 'Object Detection' low_H_name = 'Low H' low_S_name = 'Low S' low_V_name = 'Low V' high_H_name = 'High H' high_S_name = 'High S' high_V_name = 'High V' ## [low] def on_low_H_thresh_trackbar(val): global low_H global high_H low_H = val low_H = min(high_H-1, low_H) cv.setTrackbarPos(low_H_name, window_detection_name, low_H) ## [low] ## [high] def on_high_H_thresh_trackbar(val): global low_H global high_H high_H = val high_H = max(high_H, low_H+1) cv.setTrackbarPos(high_H_name, window_detection_name, high_H) ## [high] def on_low_S_thresh_trackbar(val): global low_S global high_S low_S = val low_S = min(high_S-1, low_S) cv.setTrackbarPos(low_S_name, window_detection_name, low_S) def on_high_S_thresh_trackbar(val): global low_S global high_S high_S = val high_S = max(high_S, low_S+1) cv.setTrackbarPos(high_S_name, window_detection_name, high_S) def on_low_V_thresh_trackbar(val): global low_V global high_V low_V = val low_V = min(high_V-1, low_V) cv.setTrackbarPos(low_V_name, window_detection_name, low_V) def on_high_V_thresh_trackbar(val): global low_V global high_V high_V = val high_V = max(high_V, low_V+1) cv.setTrackbarPos(high_V_name, window_detection_name, high_V) parser = argparse.ArgumentParser(description='Code for Thresholding Operations using inRange tutorial.') parser.add_argument('--camera', help='Camera devide number.', default=0, type=int) args = parser.parse_args() ## [cap] cap = cv.VideoCapture(args.camera) ## [cap] ## [window] cv.namedWindow(window_capture_name) cv.namedWindow(window_detection_name) ## [window] ## [trackbar] cv.createTrackbar(low_H_name, window_detection_name , low_H, max_value_H, on_low_H_thresh_trackbar) cv.createTrackbar(high_H_name, window_detection_name , high_H, max_value_H, on_high_H_thresh_trackbar) cv.createTrackbar(low_S_name, window_detection_name , low_S, max_value, on_low_S_thresh_trackbar) cv.createTrackbar(high_S_name, window_detection_name , high_S, max_value, on_high_S_thresh_trackbar) cv.createTrackbar(low_V_name, window_detection_name , low_V, max_value, on_low_V_thresh_trackbar) cv.createTrackbar(high_V_name, window_detection_name , high_V, max_value, on_high_V_thresh_trackbar) ## [trackbar] def morphOpen(image): # define structuring element # take 5% of least dimension of image as kernel size kernel_size = min(5, int(min(image.shape[0],image.shape[1])*0.05)) kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE,(kernel_size,kernel_size)) #kernel = cv.getStructuringElement(cv.MORPH_RECT,(5,5)) opening = cv.morphologyEx(image, cv.MORPH_OPEN, kernel) return opening for dirname in os.listdir(PATH_DATA): #if dirname == 'Blue Cube': count = 0 hsv_data = [] image_name_data =[] if dirname == 'Blue Cube': continue if dirname == 'Red Cylinder': continue if dirname == 'Yellow Ball': continue if dirname == 'Yellow Cube': continue if dirname == 'Purple Cross': continue if dirname == 'Blue Triangle': continue for file in glob.glob(PATH_DATA + dirname + "/*.jpg"): if count <=100: count = count +1 else: f1 = open(PATH_WRITE + dirname+'/hsv_data_1.txt', 'w+') f1.write('%s'%hsv_data) f1.close() print('wrote color data for '+dirname) f2 = open(PATH_WRITE + dirname+'/image_name_data_1.txt', 'w+') f2.write('%s'%image_name_data) f2.close() break image = cv.imread(file) # cv.imshow('Image', image) # if cv.waitKey(0) & 0xFF == ord('y'): # print('CROP IT') # elif cv.waitKey(0) & 0xFF == ord('n'): # print('DONT TOUCH!') #frame = cv.imread('../ras_objects.jpg') while True: ## [while] #ret, frame = cap.read() if image is None: break else: frame = np.copy(image) frame_HSV = cv.cvtColor(frame, cv.COLOR_BGR2HSV) frame_threshold = cv.inRange(frame_HSV, (low_H, low_S, low_V), (high_H, high_S, high_V)) ## [while] frame_morph = morphOpen(frame_threshold) # find contours _, contours, _ = cv.findContours(frame_morph, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) if contours.__len__() == 0: count = count -1 print('NO CONTOURS FOUND, GETTING NEXT IMAGE!') break else: #find the biggest area c = max(contours, key = cv.contourArea) #bounding rect xx,yy,w,h = cv.boundingRect(c) #expand Bounding box increment_param = 0.1 tl_x = max(0, int(xx - increment_param*w)) tl_y = max(0, int(yy - increment_param*h)) br_x = min(image.shape[1], int(xx + w + increment_param*w)) br_y = min(image.shape[0], int(yy + h + increment_param*h)) # draw the book contour (in green) cv.rectangle(frame,(tl_x,tl_y),(br_x,br_y),(0,255,0),2) # Extract ROI with expanded Bounding box bBox_img = image[tl_y:tl_y+(br_y-tl_y), tl_x:tl_x+(br_x-tl_x)] ## [show] cv.imshow(window_capture_name, cv.resize(frame, (640,480))) cv.imshow(window_detection_name, cv.resize(frame_threshold, (640,480))) ## [show] key = cv.waitKey(30) if key == ord('y') or key == 27: cv.imwrite(PATH_WRITE + dirname + '/'+file.split('/')[-1], bBox_img) print(str(count) + ': CROPPED AND SAVED!') # Extract hsv and image name data (for future use) hsv_data.append([low_H,low_S,low_V,high_H,high_S,high_V]) image_name_data.append(file.split('/')[-1]) break elif key == ord('n'): count = count -1 print('DONt TOUCH!!!!!!!') # Extract hsv and image name data (for future use) hsv_data.append([low_H,low_S,low_V,high_H,high_S,high_V]) image_name_data.append(file.split('/')[-1]) break <file_sep># Robotics Project Course Submission The main goal of this project was to make a robot which can: 1. Explore and map its environment 2. Grip and rescue/ bring back the most valuable object it found during 1. The robot is equipped with an RGBD camera, a 2-D RP Lidar and among other things, wheel encoders, speaker, arduino (for gripping). It is powered by an intel NUC computer. The robot successfully achieves above goals through following pipelines: - Object (small colorful shapes) detection using image based deep learning. - Obstacle (heavy batteries and missing walls) detection using image analysis. - whenever it finds an object/obstacle it speaks out. - Localization using particle filter. - Path planning and control using A star to traverse from point A to B. - Integration is done using a state machine (smach package in ROS) If you're interested to know more on how these pipelines are integrated in ROS, check out our [Project page](https://github.com/RAS-2018-grp-4). ## Videos Autonomous Exploration | What Robot sees during Exploration :-------------------------:|:-------------------------: [![IMAGE ALT TEXT HERE](http://img.youtube.com/vi/khB9kPSdTlk/0.jpg)](https://youtu.be/khB9kPSdTlk) | [![IMAGE ALT TEXT HERE](http://img.youtube.com/vi/7GNrhhASpx8/0.jpg)](https://youtu.be/7GNrhhASpx8) ## Contributors: - [<NAME>](https://www.linkedin.com/in/viktor-tuul-827ab7162/) - [<NAME>](https://www.linkedin.com/in/shuo-zheng) - [<NAME>](https://www.linkedin.com/in/davidvillagra/) - [<NAME>](https://www.linkedin.com/in/ajinkyakhoche/) <file_sep>from matplotlib import pyplot # from scipy.misc import toimage from keras.datasets import cifar10 import cv2 import glob import os from sklearn.utils import shuffle from sklearn.model_selection import train_test_split def show_imgs(X): pyplot.figure(1) k = 0 for i in range(0,6): for j in range(0,6): pyplot.subplot2grid((6,6),(i,j)) # pyplot.imshow(toimage(X[k])) pyplot.imshow(X[k]) k = k+1 # show the plot pyplot.show() # (x_train, y_train), (x_test, y_test) = cifar10.load_data() # show_imgs(x_test[:16]) shape_class = ['Ball', 'Cube', 'Cylinder', 'Hollow Cube', 'Cross', 'Triangle', 'Star' ] PATH_DATA = "/media/ajinkya/My Passport/RAS/ras_perception/DL_training/image_dataset_keras_shape" def load_custom_data(): x_list = [] y_list = [] # x_test_list = [] # y_test_list = [] ### LOAD Training DATA ### print('########## LOADING DATA ##########') for dirname in os.listdir(PATH_DATA): if dirname == 'Ball': label = 0 elif dirname == 'Cube': label = 1 elif dirname == 'Cylinder': label = 2 elif dirname == 'Hollow Cube': label = 3 elif dirname == 'Cross': label = 4 elif dirname == 'Triangle': label = 5 elif dirname == 'Star': label = 6 print('########## ' + dirname + ' , Label : ' + str(label) + ' ##########') for file in glob.glob(os.path.join(PATH_DATA, dirname, "*.jpg")): image = cv2.imread(file) x_list.append(cv2.resize(image, (32,32))) y_list.append(label) x_arr = np.array(x_list) y_arr = np.reshape(np.array(y_list), (-1,1)) x_train, x_test, y_train, y_test = train_test_split(x_arr, y_arr, test_size=0.3, random_state=0) return (x_train, y_train), (x_test, y_test) import keras from keras.models import Sequential from keras.utils import np_utils from keras.preprocessing.image import ImageDataGenerator from keras.layers import Dense, Activation, Flatten, Dropout, BatchNormalization from keras.layers import Conv2D, MaxPooling2D from keras.datasets import cifar10 from keras import regularizers from keras.callbacks import LearningRateScheduler import numpy as np def lr_schedule(epoch): lrate = 0.001 if epoch > 75: lrate = 0.0005 elif epoch > 100: lrate = 0.0003 return lrate (x_train, y_train), (x_test, y_test) = load_custom_data() x_train = x_train.astype('float32') x_test = x_test.astype('float32') from keras.preprocessing.image import ImageDataGenerator datagen = ImageDataGenerator( rotation_range=90, width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True) datagen.fit(x_train) #z-score mean = np.mean(x_train,axis=(0,1,2,3)) std = np.std(x_train,axis=(0,1,2,3)) x_train = (x_train-mean)/(std+1e-7) x_test = (x_test-mean)/(std+1e-7) num_classes = 7 y_train = np_utils.to_categorical(y_train,num_classes) y_test = np_utils.to_categorical(y_test,num_classes) weight_decay = 1e-4 model = Sequential() model.add(Conv2D(32, (3,3), padding='same', kernel_regularizer=regularizers.l2(weight_decay), input_shape=x_train.shape[1:])) model.add(Activation('elu')) model.add(BatchNormalization()) model.add(Conv2D(32, (3,3), padding='same', kernel_regularizer=regularizers.l2(weight_decay))) model.add(Activation('elu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Dropout(0.2)) model.add(Conv2D(64, (3,3), padding='same', kernel_regularizer=regularizers.l2(weight_decay))) model.add(Activation('elu')) model.add(BatchNormalization()) model.add(Conv2D(64, (3,3), padding='same', kernel_regularizer=regularizers.l2(weight_decay))) model.add(Activation('elu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Dropout(0.3)) model.add(Conv2D(128, (3,3), padding='same', kernel_regularizer=regularizers.l2(weight_decay))) model.add(Activation('elu')) model.add(BatchNormalization()) model.add(Conv2D(128, (3,3), padding='same', kernel_regularizer=regularizers.l2(weight_decay))) model.add(Activation('elu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Dropout(0.4)) model.add(Flatten()) model.add(Dense(num_classes, activation='softmax')) model.summary() #data augmentation datagen = ImageDataGenerator( rotation_range=15, width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True, ) datagen.fit(x_train) #training batch_size = 64 opt_rms = keras.optimizers.rmsprop(lr=0.001,decay=1e-6) model.compile(loss='categorical_crossentropy', optimizer=opt_rms, metrics=['accuracy']) model.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size),\ steps_per_epoch=x_train.shape[0] // batch_size,epochs=125,\ verbose=1,validation_data=(x_test,y_test),callbacks=[LearningRateScheduler(lr_schedule)]) #save to disk model_json = model.to_json() with open('model.json', 'w') as json_file: json_file.write(model_json) model.save_weights('model.h5') #testing scores = model.evaluate(x_test, y_test, batch_size=128, verbose=1) print('\nTest result: %.3f loss: %.3f' % (scores[1]*100,scores[0])) ### Test indices = np.argmax(model.predict(x_test[:36]),1) print( [shape_class[kk] for kk in indices]) show_imgs(x_test[:36])<file_sep># Object-Detection-on-CPU This work covers the perception pipeline of our submission for the Robotics and Autonomous Systems Project course [DD2425](https://www.kth.se/student/kurser/kurs/DD2425?l=en). The course involved constructing a mobile robot from scratch to carry out mock search and rescue. The goal was to detect and localize the objects in a scene on an intel NUC platform, **without a GPU**. The objects were multi-colored toy blocks shown below: <p align="center"> <img src="./docs/ras_objects.jpg" width="400" height="300"> </p> There are two ways to go about it. One can either use traditional image analysis (like thresholding, morphing, contour detection etc.). Although the approach sounds good on paper, it will never generalize well and be free of outliers. The thresholding parameters may change with the lighting. The shape detection (for instance between a *cube* and a *hollow cube*) is non-trivial. Another approach is training a neural network/ machine learning model. We started by looking at the excellent fork of yolov2 by [AlexeyAB](https://github.com/AlexeyAB/yolo2_light). It was observed that even the lightest object detector network gave a measely 0.2 FPS with poor detection accuracy on a CPU. ## Approach The key is to breakdown the problem of object detection into object localization and image classification (which many deep learning methods like R-CNN do). Using traditional image analysis, the algorithm can generate many regions of interest, which can be fed to an image recognition network for accurate detection. Moreover, a separate CNN was used for color and shape detection for increased robustness. The pipeline is shown below: <p align="center"> <img src="./docs/pipeline.png" width="900" height="300"> </p> ## Steps 1. **Creating a Dataset**: This involved recording videos capturing the scene experienced by the robot, and sampling images from it to create a dataset of objects. Thankfully, one of our seniors (<NAME>) created this dataset an year before. But this dataset was suitable for object detection, not image recognition. So, I wrote a script [keras_crop_dataset.py](./keras_crop_dataset.py), which provides a simple GUI to quickly crop, annotate objects from a scene and store them, utilizing the image analysis pipeline shown above. This way I was quickly able to create datasets for **both color and shape** with ~1300 samples per object. You can [download these datasets](https://drive.google.com/open?id=1MMKEmKiMA-hvhDsqLiFjRVLTiX7THz5C) for reproducibility. 2. **Training the CNN**: The number of shapes and colors to be recognized are 7 and 6 respectively. Since the problem is similar to CIFAR-10 image recognition, I used the architecture provided by Keras in their excellent [documentation](https://github.com/keras-team/keras/blob/master/examples/cifar10_cnn.py). These are provided in the [saved_models_1](./saved_models_1) folder along with their training summaries. 3. **Bringing it all together**: check [keras_object_detection.py](./keras_object_detection.py) ## Results/ Videos **Object Detection on running Robot (~25-30 FPS on CPU)**: The blue box is a region of interest generated by using traditional image analysis and the green box contains the actual detection. The algorithm also uses depth provided by RGBD camera and [camera intrinsics](http://docs.ros.org/kinetic/api/sensor_msgs/html/msg/CameraInfo.html) to compute distances to the object. Object detection on Robot | :-------------------------:| [![IMAGE ALT TEXT HERE](http://img.youtube.com/vi/kYFFCXGbXrY/0.jpg)](https://youtu.be/kYFFCXGbXrY) | ## Bonus: Obstacle Detection In addition to valuable objects, the perception system also needed to detect obstacles (grey batteries) and avoid them. The following videos demonstrate the logic behind obstacle detection algorithm. A side-by-side comparison to object detection is also shown to prove robustness. Obstacle detection | Object Detection v/s Obstacle detection :-------------------------:|:-------------------------: [![IMAGE ALT TEXT HERE](http://img.youtube.com/vi/H6HnhnuMGn4/0.jpg)](https://youtu.be/H6HnhnuMGn4) | [![IMAGE ALT TEXT HERE](http://img.youtube.com/vi/6hN6UD0YFjo/0.jpg)](https://youtu.be/6hN6UD0YFjo) ## Robotics Project Course Submission For more information/videos on our submission for the Robotics Project course, see [Robotics-Project-Info.md](./Robotics-Project-Info.md) ## License MIT License <file_sep>import cv2 import numpy as np import keras.models from keras.models import model_from_json import glob from datetime import datetime ''' @author:<NAME> model_shape: A CNN which detects shape ----------- Class Labels: SHAPE ----- 0: Ball 1: Cube 2: Cylinder 3: Hollow Cube 4: Cross 5: Triangle 6: Star ######################################## model_color: A CNN which detects color ----------- Class Labels: COLOR ------ 0: Yellow 1: Green 2: Orange 3: Red 4: Blue 5: Purple ''' # Load SHAPE CNN # model_shape = keras.models.load_model('./saved_models/keras_RAS_model_shape_1.h5') json_file = open('./saved_models/cropped_shape_3.json', 'r') loaded_model_json = json_file.read() json_file.close() model_shape = model_from_json(loaded_model_json) model_shape.load_weights('./saved_models/cropped_shape_3.h5') # Load COLOR CNN model_color = keras.models.load_model('./saved_models/keras_cropped_color_2.h5') shape_class = ['Ball', 'Cube', 'Cylinder', 'Hollow Cube', 'Cross', 'Triangle', 'Star' ] color_class = ['Yellow', 'Green', 'Orange', 'Red', 'Blue', 'Purple'] VIDEO_INFERENCE = 1 IMG_INFERNECE = 0 N_SHAPES = 7 N_COLORS = 6 DEBUG = 1 def morphOpen(image): # define structuring element # take 5% of least dimension of image as kernel size kernel_size = min(5, int(min(image.shape[0],image.shape[1])*0.05)) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(kernel_size,kernel_size)) #kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5)) opening = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) return opening def detect_object(image, color_label): hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) if color_label == 0: #YELLOW mask = cv2.inRange(hsv, np.array([17,128,0]), np.array([32,255,255])) elif color_label == 1: #GREEN mask = cv2.inRange(hsv, np.array([32,129,0]), np.array([66,255,255])) elif color_label == 2: #ORANGE # mask1 = cv2.inRange(hsv, np.array([0,40,120]), np.array([8,255,255])) # mask2 = cv2.inRange(hsv, np.array([160,40,120]), np.array([179,255,255])) # mask = mask1 + mask2 mask = cv2.inRange(hsv, np.array([0,175,188]), np.array([23,255,255])) elif color_label == 3: #RED # mask1 = cv2.inRange(hsv, np.array([0,50,50]), np.array([15,255,255])) # mask2 = cv2.inRange(hsv, np.array([170,50,50]), np.array([180,255,255])) # mask = mask1 + mask2 mask = cv2.inRange(hsv, np.array([0,150,0]), np.array([4,255,200])) elif color_label == 4: #BLUE mask = cv2.inRange(hsv, np.array([68,0,0]), np.array([110,255,255])) elif color_label == 5: #PURPLE mask = cv2.inRange(hsv, np.array([116,100,8]), np.array([179,166,173])) if DEBUG: cv2.imshow('mask', mask) cv2.waitKey(0) # blur image #mask_blur = cv2.GaussianBlur(mask,(2,2),0) mask_morph = morphOpen(mask) if DEBUG: cv2.imshow('mask_blur_morph', mask_morph) cv2.waitKey(0) # find contours # _, contours, _ = cv2.findContours(mask_morph, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours, _ = cv2.findContours(mask_morph, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for k in range(contours.__len__()): xx, yy, w, h = cv2.boundingRect(contours[k]) #print(box[2]*box[3]) if w/h > 0.5 and w/h<2: if w*h > 2000: # we need to give slightly bigger image to detector to get a clear detection tl_x = max(0, int(xx - 0.25*w)) tl_y = max(0, int(yy - 0.25*h)) br_x = min(image.shape[1], int(xx + w + 0.25*w)) br_y = min(image.shape[0], int(yy + h + 0.25*h)) #bBox_img = image[yy:yy+h, xx:xx+w] bBox_img = image[tl_y:tl_y+(br_y-tl_y), tl_x:tl_x+(br_x-tl_x)] input_img = [] input_img.append(cv2.resize(bBox_img, (32,32))) input_img = np.array(input_img) pred_shape = model_shape.predict(input_img) pred_color = model_color.predict(input_img) draw_result([xx,yy,w,h], image, pred_shape, pred_color) # draw_result([xx,yy,w,h], image) # draw_result([tl_x,tl_y,tl_x+(br_x-tl_x),tl_y+(br_y-tl_y)], image) print(color_class[np.argmax(pred_color)]+ ' ' +shape_class[np.argmax(pred_shape)]) def draw_result(box, image, pred_shape, pred_color): # def draw_result(box, image): cv2.rectangle(image, (box[0], box[1]), (box[0]+box[2], box[1]+box[3]), (0,255,0), 2) '''Both shape and color on bounding box''' cv2.putText(image, color_class[np.argmax(pred_color)]+ ' ' +shape_class[np.argmax(pred_shape)], (box[0],box[1]-15), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0), 2, cv2.LINE_AA) '''only color on bounding box''' # cv2.putText(image, color_class[np.argmax(pred_color)], (box[0],box[1]-15), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0), 2, # cv2.LINE_AA) '''Only shape on bounding box''' # cv2.putText(image, shape_class[np.argmax(pred_shape)], (box[0],box[1]-15), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0), 2, # cv2.LINE_AA) if VIDEO_INFERENCE: cap = cv2.VideoCapture('../ras_labeling/vid2.mp4') #cap = cv2.VideoCapture(0) while cap.isOpened(): a = datetime.now() ret, image = cap.read() image = cv2.resize(image, (0,0), fx=0.33, fy=0.33) for i in range(N_COLORS): detect_object(image, i) cv2.imshow('result', image) cv2.waitKey(1) b = datetime.now() c = b - a fps = 1.0/(c.total_seconds()) print('## FPS: ' + str(fps)) print('') elif IMG_INFERNECE: try: while True: for file in glob.glob('../RAS_DATASET' + "/*.jpg"): image = cv2.imread(file) for i in range(N_COLORS): detect_object(image, i) cv2.imshow('result', image) cv2.waitKey(0) except KeyboardInterrupt: pass # image = cv2.imread('./1001.jpg') # image = cv2.resize(image, (0,0), fx=0.33, fy=0.33) # for i in range(N_COLORS): # detect_object(image, i) # cv2.imshow('result', image) # cv2.waitKey(0)
b2d3cb80489a5aaf027fb23fb5fa6373959621cc
[ "Markdown", "Python" ]
5
Python
ajinkyakhoche/Object-Detection-on-CPU
e06f07b56b6536f18a6a1878adb389ea54dfb6db
aadc8832812cd35dee92cb6c89573d92968a21f9
refs/heads/master
<repo_name>ZSY000/myNotes<file_sep>/html_css/youxuan/index.js var slices = $('.sliceBox li') var page = $('.pagination li') var width = $('.sliceBox li:first img').eq(0).width() var index = 0 var timer = null var flag = true // 自动轮播控制 function autoMove(flag) { if(flag){ timer = setInterval(function() { index++ selectImg(index) },3000) }else{ clearInterval(timer) } } // 轮播动画 function selectImg(num) { page.eq(num).addClass('active').siblings().removeClass('active') $('.sliceBox').animate({ left: -num*width },1000,function() { // 检查是否是最后一张 if(index == slices.length-1){ index = 0 $('.sliceBox').css('left','0px') page.eq(0).addClass('active').siblings().removeClass('active') } }) } autoMove(flag) <file_sep>/vue/vue-practice/src/store/state/state.js // 存储状态 export default { count: 0, num1: 1, num2: 3 } <file_sep>/webpack-vue/config/webpack.dev.js // development 开发环境的配置 // 导入公共配置 const base = require('./webpack.base.js') // 导入webpack-merge用于配置合并,是一个方法 const merge = require('webpack-merge') // 导出开发环境的配置 // merge可以传入多个参数,会将多个参数合并成一个对象 // 如果有重复的属性名,后面的对象属性会覆盖前面的 module.exports = merge(base, { // 打包模式mode,development不压缩,production压缩 mode: 'development', // 配置开发服务器 devServer: { port: 3333, //配置端口 open: true // 自动打开浏览器 } })<file_sep>/vue/vue-practice/src/router/routes.js // 封装所有路由 // import HelloWorld from '../components/HelloWorld' export default [ // { // path: '/', // name: 'HelloWorld', // component: HelloWorld // } ] <file_sep>/vue/vue-practice/src/store/mutations/mutations.js // 对数据进行同步操作 export default { updateNum (state, num) { state.num1 = num.num1 state.num2 = num.num2 } } <file_sep>/react-demo/redux-demo/src/components/PostForm.js import React, { Component } from 'react' import './PostForm.css' import PropTypes from 'prop-types' import { connect } from 'react-redux'; import { createPost } from '../actions/postAction' class PostForm extends Component { constructor (props) { super(props) this.state = { title: '', body: '' } this.titleChange = (e) => { this.setState({ title: e.target.value }) } this.bodyChange = (e) => { this.setState({ body: e.target.value }) } this.submitFn = (e) => { e.preventDefault() // 阻止默认行为 const data = { title: this.state.title, body: this.state.body } // 触发action this.props.createPost(data) } } render() { return ( <form className="formStyle"> <label>Title: </label> <input type="text" name="title" onChange={this.titleChange}/> <br/> <label>Content: </label> <textarea name="body" onChange={this.bodyChange}/> <br/> <input type="submit" value="Submit" onSubmit={this.submitFn}/> </form> ) } } PostForm.propTypes = { createPost: PropTypes.func.isRequired } // View不需要改变,所以第一个参数为null export default connect(null, { createPost })(PostForm)<file_sep>/webpack-vue/src/main.js import App from './App.vue' import Vue from 'vue' import VueRouter from 'vue-router' import createRouter from './router/index' Vue.use(VueRouter) const router = createRouter() new Vue({ el: '#app', // 模板index.html中的#app元素 router, render: h => h(App) })<file_sep>/react-demo/react-basic/src/App.js import React from 'react' import './App.css' import Persons from './components/Persons/Persons' import Header from './components/Header/Header' class App extends React.Component { constructor (props) { super(props) this.state = { person: [ { id:1, name:"Crazy", age:23 }, { id:2, name:"Lucy", age:20 }, { id:3, name:"Sherry", age:18 } ], showPerson: true } } // 更改名称 changeName = (event, id) => { const personIndex = this.state.person.findIndex((p) => { return p.id === id }) const person = this.state.person person[personIndex].name = event.target.value this.setState({ person: person }) } // 按钮切换 toggleBtn = () => { let flag = this.state.showPerson this.setState({showPerson: !flag}) } // 点击删除 deleteItem = (index) => { // const leftPerson = this.state.person const leftPerson = [...this.state.person] leftPerson.splice(index, 1) this.setState({ person: leftPerson }) } render () { // 定义按钮的行内样式 const style = { background: 'none', border: '1px solid #bbb', padding: '5px 10px' } const timeStyle = [] if (this.state.person.length<2) { timeStyle.push('red') } if(this.state.person.length<1) { timeStyle.push('bold') } let showContent = null if(this.state.showPerson){ showContent = <Persons person={this.state.person} deleteItem={this.deleteItem} changeName={this.changeName} /> } return ( <div className="App"> <Header btnStyle={style} btnClick={this.toggleBtn} pStyle={timeStyle}/> {/* 点击切换内容 */} {showContent} </div> ) } } export default App; <file_sep>/webpack-vue/config/webpack.base.js // 公共配置 const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') // 自动打包html const MiniCssExtractPlugin = require('mini-css-extract-plugin') // 分离css插件 const { CleanWebpackPlugin } = require('clean-webpack-plugin') // 清除dist目录插件 const VueLoaderPlugin = require('vue-loader/lib/plugin') // 处理vue module.exports = { // 入口entry,从哪个文件开始打包 entry: './src/main.js', // 出口output,打包到哪里 output: { // 打包输出的目录(必须是绝对路径) path: path.join(__dirname, '../dist'), // 打包后生成的文件名 filename: 'js/bundle.js' //把放入js文件中 }, // 配置模块加载规则 // 默认webpack只认识json和js,不认识其他文件,如果需要打包其他文件,需要配置对应loader module: { rules: [ // 处理vue { test: /\.vue$/, loader: 'vue-loader' }, { test: /\.css$/, // 正则表达式,用来匹配 // css-loader让webpack能够识别解析css文件 // style-loader通过动态创建style标签的方式让解析后的css内容作用在页面上 // use: ['style-loader', 'css-loader'] // 处理顺序:从后往前处理 use: [ { loader: MiniCssExtractPlugin.loader, options: { publicPath: '../' } }, 'css-loader' ] }, { test: /\.less$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { publicPath: '../' } }, 'css-loader', 'less-loader' ] // less-loader将less转换为css }, { test: /\.(png|jpg|jpeg|gif)$/i, // i忽视大小写 use: [ { // 如果不配置url-loader,默认会将文件转成base64字符串格式 loader: 'url-loader', options: { limit: 8*1024, // 8k以内,转成base64,减少请求次数;大于8k,会请求图片 name: '[name].[ext]', // 配置输出的文件名 publicPath: '../images/', // 配置静态资源的引用路径(相对于index.html) outputPath: 'images/' // 配置输出的文件目录 } } ] }, // 处理js高级语法 { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, // 引入插件 plugins: [ new HtmlWebpackPlugin({template: './public/index.html'}), new MiniCssExtractPlugin({ filename: 'css/index.css' // 定义打包好的文件的存放路径和文件名(dist/css/index.css) }), new CleanWebpackPlugin(), new VueLoaderPlugin() ], // 提取公共模块 optimization: { splitChunks: { chunks: 'all' } } }<file_sep>/vue/vue-practice/src/store/getters/getters.js // 可以认为是 store 的计算属性 // 就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来, // 且只有当它的依赖值发生了改变才会被重新计算 // 可以接受其他 getter 作为第二个参数 export default { res (state) { return state.num1 + state.num2 } } <file_sep>/webpack-demo/src/main.js require('./css/style.css') require('./css/base.css') let fn = () => { console.log('000') } fn() console.log('111')<file_sep>/html_css/projectList/projectList.js $(function() {     var data = [         {id:0,name:'智能汽车',unit:'小鹏汽车',date:'18/12/3',state:'已完成'},         {id:1,name:'旅游路线规划',unit:'去哪儿',date:'19/6/13',state:'进行中'},         {id:2,name:'旅游官网',unit:'小红书',date:'19/3/5',state:'已完成'},         {id:3,name:'水泥厂智能一体化',unit:'娲石水泥',date:'18/4/4',state:'已完成'},         {id:4,name:'汽车中控UI',unit:'特斯拉',date:'19/12/6',state:'进行中'},         {id:5,name:'物流公司官网',unit:'中通快递',date:'20/1/21',state:'未开始'},         {id:6,name:'湖北地铁管理平台',unit:'武汉市政府',date:'20/1/3',state:'未开始'},         {id:7,name:'湖北高速管理平台',unit:'湖北省政府',date:'19/7/30',state:'已完成'},         {id:8,name:'物流管理平台',unit:'菜鸟驿站',date:'18/11/21',state:'已完成'},         {id:9,name:'海关管理平台',unit:'物通公司',date:'19/6/8',state:'已完成'},         {id:10,name:'智能管理系统',unit:'中国银行',date:'20/2/1',state:'未开始'}     ] var tmp = template('list',{ data:data }) $('.dataList').append(tmp) for(let i=0;i<data.length;i++){ var text = $('.dataList .row:eq('+i+') div:last').text() var row = $('.dataList .row:eq('+i+')') switch (text){ case '未开始':row.css('backgroundColor','#FAE0E0');break; case '进行中':row.css('backgroundColor','#FCF0CB');break; case '已完成':row.css('backgroundColor','#D8FCD8');break; } } }) <file_sep>/webpack-vue/src/router/routes.js import Home from '../views/Home.vue' import Login from '../views/Login.vue' export default [ { path: '/', redirect: '/home' }, { path: '/home', redirect: Home }, { path: '/login', component: Login } ]
7bd55ad2391f6b9e6ed73131b4a64cf9d1cdae7c
[ "JavaScript" ]
13
JavaScript
ZSY000/myNotes
2c7d2665cb5ad9521c93f115e3d30a29d230662c
0e274e3720e4a715be8516ffba2984e6ac6389ec
refs/heads/master
<file_sep>from .people import * from .salary import *<file_sep>def get_employees(): return "<NAME>", "<NAME>", "<NAME>" <file_sep>from application import salary from application import people import datetime from datetime import date if __name__ == '__main__': today = date.today() print(f"Today is the {today}") f = salary.calculate_salary(23000) print(f) W = people.get_employees() print (W) <file_sep>def calculate_salary(amount_in_a_year): amount_you_get_in_a_year = (amount_in_a_year * 12) return f"This is your salary in a year: {amount_you_get_in_a_year}" <file_sep>from application.people import * from application.salary import * if __name__ == '__main__': f = calculate_salary(23000) print(f) W = get_employees() print (W)
e0133765ff171c7f97d67f47a972e6db52536973
[ "Python" ]
5
Python
UP-Polina-97/Python-HM-2.1
d2842a659c116afa12bf4021609ff2fa78e35f3e
bf14c6c665853679d8d9607a4f11568bca907ed8
refs/heads/master
<repo_name>pugovka/task-tracker<file_sep>/TaskTracker.WebAPI/Controllers/TasksController.cs using System.Linq; using System.Net; using TaskTracker.WebAPI.Models; using System.Net.Http; using System.Web.Http; using System.Web.Http.Cors; namespace TaskTracker.WebAPI.Controllers { [EnableCors(origins: "http://localhost:8333", headers: "*", methods: "*")] public class TasksController : ApiController { private TaskDBContext db = new TaskDBContext(); public HttpResponseMessage Get() { var tasks = db.Tasks.ToList(); return Request.CreateResponse( HttpStatusCode.OK, tasks); } public HttpResponseMessage Post(Task task) { if (task == null || !ModelState.IsValid) { return Request.CreateErrorResponse( HttpStatusCode.BadRequest, "Invalid input"); } db.Tasks.Add(task); db.SaveChanges(); return Request.CreateResponse(HttpStatusCode.Created); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>/TaskTracker.UI/app/components/TaskForm/index.js import React from 'react'; import { connect } from 'react-redux'; import TaskForm from './presenter'; function mapStateToProps(state) { const tasks = state.task; return { tasks }; } export default connect(mapStateToProps)(TaskForm); <file_sep>/TaskTracker.UI/app/actions/index.js 'use strict'; import { setTasks } from './task'; import { addTask } from './task'; export { setTasks, addTask }; <file_sep>/TaskTracker.UI/app/index.js 'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import configureStore from './stores/configureStore'; import * as actions from './actions'; import * as constants from './constants'; import TaskTracker from './components/TaskTracker'; import TaskForm from './components/TaskForm'; import { httpRequest } from './functions'; // Set initial state - get tasks from db and display them httpRequest('GET', constants.SERVER_URL) .then( response => { const tasks = JSON.parse(response); const store = configureStore(); store.dispatch(actions.setTasks(tasks)); const TaskTrackerApp = () => ( <div> <TaskTracker /> <TaskForm /> </div> ); ReactDOM.render( <Provider store={store}> <TaskTrackerApp /> </Provider>, document.getElementById('app') ); }, error => { console.log(error) } ); <file_sep>/TaskTracker.WebAPI/Models/Task.cs using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; namespace TaskTracker.WebAPI.Models { public class Task { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] public string Title { get; set; } public string Description { get; set; } } public class TaskDBContext : DbContext { public DbSet<Task> Tasks { get; set; } } } <file_sep>/TaskTracker.UI/app/functions/index.js 'use strict'; export function createCORSRequest(method, url) { let xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // Check if the XMLHttpRequest object has a "withCredentials" property. // "withCredentials" only exists on XMLHTTPRequest2 objects. xhr.open(method, url, true); } else if (typeof XDomainRequest != "undefined") { // Otherwise, check if XDomainRequest. // XDomainRequest only exists in IE, and is IE's way of making CORS requests. xhr = new XDomainRequest(); xhr.open(method, url); } else { // Otherwise, CORS is not supported by the browser. xhr = null; } return xhr; } export function httpRequest(method, url, data = {}) { return new Promise(function(resolve, reject) { const xhr = createCORSRequest(method, url); if (!xhr) { reject(new Error('CORS not supported')); } xhr.onerror = () => { reject(new Error('Error in request')); }; xhr.onload = function() { if (this.status == 200) { resolve(this.response); } else if (this.status == 201) { resolve(this.response); } else { const error = new Error(this.statusText); error.code = this.status; reject(error); } }; xhr.withCredentials = ''; if (method === 'GET') { xhr.send(); } else if (method === 'POST') { xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(data)); } else { reject(new Error('Method is not supported')); } }); } <file_sep>/TaskTracker.UI/app/components/TaskTracker/index.js 'use strict'; import React from 'react'; import { connect } from 'react-redux'; import TaskTracker from './presenter'; function mapStateToProps(state) { const tasks = state.task; return { tasks }; } export default connect(mapStateToProps)(TaskTracker); <file_sep>/README.md # React Task Tracker Lightweight web task tracker. - `./TaskTracker.UI` - front end. Written in js ES6 using react and redux - `./TaskTracker.WebAPI` - back end. Written in C# using ASP.NET <file_sep>/TaskTracker.UI/app/reducers/task.js 'use strict'; import * as actionTypes from '../constants/actionTypes'; const initialState = []; const taskReducer = (state, action) => { switch (action.type) { case actionTypes.ADD_TASK: return { Title: action.task.title, Description: action.task.description }; } return state; } export default function(state = initialState, action) { console.log(action); switch (action.type) { case actionTypes.TASKS_SET: return setTasks(state, action); case actionTypes.ADD_TASK: return addTask(state, action); } return state; } function setTasks(state, action) { const { tasks } = action; return [ ...state, ...tasks ]; } function addTask(state, action) { return [ ...state, taskReducer(undefined, action) ] } <file_sep>/TaskTracker.UI/app/constants/actionTypes.js 'use strict'; export const TASKS_SET = 'TASKS_SET'; export const ADD_TASK = 'ADD_TASK';
9b2681970ee6fdd578d75694421955845e7ad9cf
[ "JavaScript", "C#", "Markdown" ]
10
C#
pugovka/task-tracker
317dfddb10e30c5e4bf734c00a32fdbbb09064d6
3d6bad865bd7fba5b04e0e69734df46822fdeb52
refs/heads/master
<repo_name>filipw-trafikbyran/Pivo<file_sep>/saver.php <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .manuel-edit-beer { display: block; padding-top: 10px; } </style> <script src="https://www.gstatic.com/firebasejs/5.7.0/firebase.js"></script> <script> // Initialize Firebase var config = { apiKey: "<KEY>", authDomain: "pivo-225207.firebaseapp.com", databaseURL: "https://pivo-225207.firebaseio.com", projectId: "pivo-225207", storageBucket: "", messagingSenderId: "110860684342" }; firebase.initializeApp(config); </script> <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script> <?php $xml = new SimpleXMLElement(file_get_contents('https://www.systembolaget.se/api/assortment/products/xml')); $beer = []; foreach ($xml->artikel as $key => $value) { if($value->Varugrupp == 'Öl' && $value->Utgått == '0') { // echo '<pre>'; // print_r($value); // echo '</pre>'; // if($value->Sortiment == 'FS'){ // $beer[] = $value; // } if($value->Sortiment == 'BS' /* or $value->Sortiment == 'TSLS' */ or $value->Sortiment == 'TSE'){ $lanuched = strtotime($value->Saljstart); $monthago = time()-60 * 60 * 24; $monthsago = time()-60 * 60 * 24 * 6; $yearago = time()-60 * 60 * 24 * 12; $yearsago = time()-60 * 60 * 24 * 24; if($lanuched > $yearsago){ $beer[] = $value; } } } } ?> <script> const database = firebase.database(); // database.ref('beers/').remove(); var i = 0; function searchString(name){ var output = JSON.stringify({query: `{ beerSearch(query: "` + name + `",first: 1){ items: items { name, averageRating, abv, brewer { name }, ratingCount, style { name }, imageUrl } } }`}); return output } function rateBeerCall(beer,querys,x,callback){ console.log('query'); console.log(querys[x]); if(querys[x]){ $.ajax({ url: 'https://api.ratebeer.com/v1/api/graphql/', method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'access-control-allow-origin' : 'https://pivo-225207.firebaseapp.com/', 'Access-Control-allow-credentials': true, 'x-api-key': '<KEY>' }, data: querys[x], dataType: 'json', success: function(response) { // console.log(response); callback(beer,querys,x,response); }, error: function (response) { console.log(response); } }); } } function matcher(systemet,apibeer){ var systemetAbv = parseFloat(systemet.alch); var apibeerAbv = apibeer.abv; var diff; if (systemetAbv > apibeerAbv){ diff = systemetAbv-apibeerAbv; } else { diff = apibeerAbv-systemetAbv; } return diff; } function switcher(systemet,querys,x,value){ console.log('switcher in:'); var apibeer = value.data.beerSearch.items[0]; if(apibeer) { console.log(systemet); console.log(apibeer); var match = matcher(systemet,apibeer); if(match < 1){ console.log('good match'); saveToDB(systemet,apibeer); } else { console.log('no match'); console.log(match); console.log(querys.length); console.log(x); if(querys.length > x + 1){ x++ i = i + 4000; setTimeout(function(){ rateBeerCall(systemet,querys,x,switcher), i }); } else { saveToDBNocomplete(systemet); } } } else { console.log('no results'); if(querys.length > x + 1){ x++ i = i + 4000; setTimeout(function(){ rateBeerCall(systemet,querys,x,switcher), i }); } else { saveToDBNocomplete(systemet); } } console.log('switcher out!'); } function saveToDB(systemet,apibeer){ database.ref('beers/' + systemet.id).update({ "name": systemet.name, "subline": systemet.subline, "art": systemet.art, "date": systemet.date, "brewery": systemet.brewery, "type": systemet.type, "style": systemet.style, "pris": systemet.pris, "volym": systemet.volym, "packing": systemet.packing, "origin": systemet.origin, "alch": systemet.alch, "sort": systemet.sort, "avgrate": apibeer.averageRating, "ratecount": apibeer.ratingCount, "image": apibeer.imageUrl, "ratebeername": apibeer.name, "updated": true, "new" : false }); console.log('saved to DB'); } function saveToDBNocomplete(systemet){ database.ref('beers/' + systemet.id).update({ "name": systemet.name, "subline": systemet.subline, "art": systemet.art, "date": systemet.date, "brewery": systemet.brewery, "type": systemet.type, "style": systemet.style, "pris": systemet.pris, "volym": systemet.volym, "packing": systemet.packing, "origin": systemet.origin, "alch": systemet.alch, "sort": systemet.sort, "avgrate": '', "ratecount": '', "image": '', "ratebeername": '', "updated": false, "new" : false }); console.log('saved to DB - not complete'); } function saveer(){ i = 0; var y = $('.amount').val()*4500; var savedBeers = Array(); var phpxml = JSON.parse('<?php echo json_encode($beer,JSON_HEX_APOS|JSON_HEX_QUOT); ?>'); console.log(phpxml.length); console.log('started'); database.ref('beers/').once('value').then(function(snapshot) { $.each(snapshot.val(), function(key, value){ savedBeers[key] = value; }); $.each(phpxml,function(key,value){ if(typeof value.Namn2 != 'string'){ value.Namn2 = ''; } var beer = { id: value.Artikelid, name: value.Namn, subline: value.Namn2, brewery: value.Producent, art: value.Varnummer, date: new Date(value.Saljstart), type: value.Typ, style: value.Stil, pris: value.Prisinklmoms, volym: value.Volymiml, packing: value.Forpackning, origin: value.Ursprunglandnamn, alch: value.Alkoholhalt, sort: value.Sortiment, } var querys = []; if(!savedBeers[parseInt(beer.id)] /*|| !savedBeers[parseInt(beer.id)]['updated']*/){ i = i + 4500; if(i > y){ // console.log('amount left'); return; } setTimeout(function(){ console.log('--------------------------------------------'); if(beer.subline){ querys = [ searchString(beer.name + ' ' + beer.subline + ' ' + beer.brewery), searchString(beer.name + ' ' + beer.subline), searchString(beer.brewery + ' ' + beer.subline), searchString(beer.name + ' ' + beer.brewery), searchString(beer.subline), searchString(beer.name), ] }else { querys = [ searchString(beer.name + ' ' + beer.brewery), searchString(beer.name), ] } rateBeerCall(beer,querys,0,switcher); },i); } else { console.log('already saved'); if(!savedBeers[parseInt(beer.id)]['updated']){ if(savedBeers[parseInt(beer.id)]['ratebeername']){ if(savedBeers[parseInt(beer.id)]['ratebeername'] != 'unavailable') { querys = [ searchString(savedBeers[parseInt(beer.id)]['ratebeername']) ] rateBeerCall(beer,querys,0,switcher); } }else { var output = '<a class="manuel-edit-beer" target="_blank" href="https://console.firebase.google.com/project/pivo-225207/database/pivo-225207/data/beers/' + parseInt(beer.id) + '">' + savedBeers[parseInt(beer.id)]['name'] + ' Needs atention!</a>'; $('#main').append(output); } } } }) }); }; $( document ).ready(function() { }); </script> <meta charset="UTF-8"> <title>Pivo - saver</title> </head> <body> <button onclick="saveer()">Spara</button> <input type="text" class="amount" value="3"> <span class="date"></span> <ul id="main"> </ul> </body> </html>
8064f325a58f61b8f4674c9c5184044b460a6256
[ "PHP" ]
1
PHP
filipw-trafikbyran/Pivo
7d937942a8ffe326d07838cf0b067d5118a57af6
32d49d411584de0412b6ff0c95d65ea6f477b17d
refs/heads/main
<file_sep>class DashboardController < ApplicationController before_action :authenticate_user! def index end def all_articles end end <file_sep>console.log("hello custom js") <file_sep>Rails.application.routes.draw do devise_for :users devise_scope :user do get 'sign_up', to: 'devise/registrations#new' post 'sign_up', to: 'devise/registrations#create' get 'login', to: 'devise/sessions#new' post 'login', to: 'devise/sessions#create' delete 'logout', to: 'devise/sessions#destroy' end get 'all_articles', to: 'articles#all_articles' get 'about', to: 'home#about' get 'contact', to: 'home#contact' get 'users/:id', to: 'users#show' get 'users_all', to: 'users#index' get 'dashboard', to: 'dashboard#index' resources :articles root 'home#index' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
3f88a4074e2df89410bcba102c5b353bba3a6779
[ "JavaScript", "Ruby" ]
3
Ruby
alexohre/blog
82ae1f81e1147a452397365ee4f537b13210b630
1071a6d056d8f3e9a47cc500501ab3e6c5ae98c2
refs/heads/master
<repo_name>rushabhj-hub/PrimaThink-Library-Management-System<file_sep>/library.sql -- phpMyAdmin SQL Dump -- version 4.8.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jul 20, 2018 at 01:54 PM -- Server version: 10.1.31-MariaDB -- PHP Version: 7.2.4 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `library` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE `admin` ( `id` int(11) NOT NULL, `FullName` varchar(100) DEFAULT NULL, `AdminEmail` varchar(120) DEFAULT NULL, `UserName` varchar(100) NOT NULL, `Password` varchar(100) NOT NULL, `updationDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`id`, `FullName`, `AdminEmail`, `UserName`, `Password`, `updationDate`) VALUES (1, '<NAME>', '<EMAIL>', 'admin', '<PASSWORD>', '2020-08-16 18:11:42'); -- -------------------------------------------------------- -- -- Table structure for table `overdue` -- CREATE TABLE `overdue` ( `StudentID` varchar(11) NOT NULL, `StudentName` varchar(40) NOT NULL, `MobNumber` varchar(11) NOT NULL, `Fine` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `tblauthors` -- CREATE TABLE `tblauthors` ( `id` int(11) NOT NULL, `AuthorName` varchar(159) DEFAULT NULL, `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `UpdationDate` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tblauthors` -- INSERT INTO `tblauthors` (`id`, `AuthorName`, `creationDate`, `UpdationDate`) VALUES (2, '<NAME>', '2020-07-08 14:30:23', NULL), (3, '<NAME>', '2020-07-08 14:35:08', NULL), (4, '<NAME>', '2020-07-08 14:35:21', NULL), (5, 'DC Pande', '2020-07-08 14:30:23', NULL), (6, '<NAME>', '2020-07-08 14:35:08', NULL), (7, '<NAME>', '2020-07-08 14:35:21', NULL); -- -------------------------------------------------------- -- -- Table structure for table `tblbooks` -- CREATE TABLE `tblbooks` ( `id` int(11) NOT NULL, `BookName` varchar(255) DEFAULT NULL, `Copies` int(3) NOT NULL, `IssuedCopies` int(3) NOT NULL, `CatId` int(11) DEFAULT NULL, `AuthorId` int(11) DEFAULT NULL, `ISBNNumber` int(11) DEFAULT NULL, `BookPrice` int(11) DEFAULT NULL, `RegDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `UpdationDate` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tblbooks` -- INSERT INTO `tblbooks` (`id`, `BookName`, `Copies`, `IssuedCopies`, `CatId`, `AuthorId`, `ISBNNumber`, `BookPrice`, `RegDate`, `UpdationDate`) VALUES (3, 'Wings of Fire', 10, 7, 6, 4, 1111, 15, '2020-08-08 20:17:31', '2020-08-20 09:40:40'), (4, 'half girlfriend', 5, 3, 4, 5, 20, 100, '2020-08-06 22:52:21', '2020-09-13 08:51:41'), (5, '<NAME>', 3, 1, 5, 3, 111, 200, '2020-06-11 17:48:02', '2020-07-20 09:37:04'), (6, 'How to win Friends', 3, 0, 4, 2, 456, 500, '2020-08-11 17:49:10', '2020-09-13 21:35:31'), (7, 'Subconsious Mind', 11, 7, 6, 4, 1111, 15, '2020-08-18 20:17:31', '2020-08-20 09:40:40'), (8, 'Mindset', 5, 3, 4, 5, 20, 100, '2020-08-16 22:52:21', '2020-09-13 08:51:41'), (9, '<NAME>', 3, 1, 5, 3, 111, 200, '2020-06-11 17:48:02', '2020-07-20 09:37:04'), (10, '<NAME>', 10, 7, 6, 4, 1111, 15, '2020-08-08 20:17:31', '2020-08-20 09:40:40'), (11, 'Tale of two cities', 5, 3, 4, 5, 20, 100, '2020-08-06 22:52:21', '2020-09-13 08:51:41'), (12, 'Around The world in 80 Days', 3, 1, 5, 3, 111, 200, '2020-06-11 17:48:02', '2020-07-20 09:37:04'), (13, '<NAME>', 3, 0, 4, 2, 456, 500, '2020-06-11 17:49:10', '2018-06-13 21:35:31'); -- -------------------------------------------------------- -- -- Table structure for table `tblcategory` -- CREATE TABLE `tblcategory` ( `id` int(11) NOT NULL, `CategoryName` varchar(150) DEFAULT NULL, `Status` int(1) DEFAULT NULL, `CreationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `UpdationDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tblcategory` -- INSERT INTO `tblcategory` (`id`, `CategoryName`, `Status`, `CreationDate`, `UpdationDate`) VALUES (4, 'Knowledge', 1, '2017-07-04 18:35:25', '2018-06-07 18:55:37'), (5, 'Technology', 1, '2017-07-04 18:35:39', '2017-07-08 17:13:03'), (6, 'Science', 1, '2017-07-04 18:35:55', '0000-00-00 00:00:00'), (7, 'Management', 1, '2017-07-04 18:36:16', '2018-06-06 18:46:41'), (8, 'physics', 1, '2018-06-11 17:31:43', '2018-06-11 17:36:56'), (9, 'history', 1, '2018-06-11 18:24:53', '2018-06-13 00:29:15'), (14, 'LifeStyle', 1, '2018-07-13 05:17:16', '0000-00-00 00:00:00'); -- -------------------------------------------------------- -- -- Table structure for table `tblfine` -- CREATE TABLE `tblfine` ( `fine` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tblfine` -- INSERT INTO `tblfine` (`fine`) VALUES (10); -- -------------------------------------------------------- -- -- Table structure for table `tblissuedbookdetails` -- CREATE TABLE `tblissuedbookdetails` ( `id` int(11) NOT NULL, `BookId` int(11) DEFAULT NULL, `StudentID` varchar(150) DEFAULT NULL, `IssuesDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `ReturnDate` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `ReturnStatus` int(1) NOT NULL, `fine` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tblissuedbookdetails` -- INSERT INTO `tblissuedbookdetails` (`id`, `BookId`, `StudentID`, `IssuesDate`, `ReturnDate`, `ReturnStatus`, `fine`) VALUES (6, 4, 'SID009', '2018-06-12 20:52:10', '2018-06-13 20:44:28', 1, 20), (7, 5, 'SID009', '2018-06-12 20:55:24', '2018-06-12 23:46:08', 1, 200), (8, 3, 'SID009', '2018-06-12 23:27:23', NULL, 0, NULL), (9, 5, 'SID009', '2018-06-13 21:24:38', NULL, 0, NULL), (10, 5, 'SID009', '2018-06-13 21:44:50', NULL, 0, NULL), (11, 10, 'SID002', '2018-07-11 18:30:00', '2018-07-18 07:47:46', 1, 10), (12, 10, 'SID005', '2018-07-18 07:59:30', '2018-07-18 07:59:41', 1, NULL), (13, 5, 'SID005', '2018-07-18 08:00:25', '2018-07-18 08:00:41', 1, NULL), (14, 5, 'SID009', '2018-07-20 09:37:03', NULL, 0, NULL), (15, 5, 'SID009', '2018-07-20 09:40:40', NULL, 0, NULL); -- -------------------------------------------------------- -- -- Table structure for table `tblrequestedbookdetails` -- CREATE TABLE `tblrequestedbookdetails` ( `StudentID` varchar(20) NOT NULL, `StudName` varchar(40) NOT NULL, `BookName` varchar(50) NOT NULL, `CategoryName` varchar(20) NOT NULL, `AuthorName` varchar(50) NOT NULL, `ISBNNumber` int(11) NOT NULL, `BookPrice` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `tblstudents` -- CREATE TABLE `tblstudents` ( `id` int(11) NOT NULL, `StudentId` varchar(100) DEFAULT NULL, `FullName` varchar(120) DEFAULT NULL, `EmailId` varchar(120) DEFAULT NULL, `MobileNumber` char(11) DEFAULT NULL, `Password` varchar(120) DEFAULT NULL, `Status` int(1) DEFAULT NULL, `RegDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `UpdationDate` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tblstudents` -- INSERT INTO `tblstudents` (`id`, `StudentId`, `FullName`, `EmailId`, `MobileNumber`, `Password`, `Status`, `RegDate`, `UpdationDate`) VALUES (1, 'SID002', '<NAME>', '<EMAIL>', '9865472555', 'f925916e2754e5e03f75dd58a5733251', 1, '2020-07-11 15:37:05', '2020-07-30 08:49:22'), (4, 'SID005', '<NAME>', '<EMAIL>', '8569710025', 'f925916e2754e5e03f75dd58a5733251', 1, '2020-08-15 15:41:27', '2020-09-11 18:26:20'), (8, 'SID009', '<NAME>', '<EMAIL>', '8329629259', 'f925916e2754e5e03f75dd58a5733251', 1, '2020-08-15 15:58:28', '2020-09-18 05:17:54'), (9, 'SID010', '<NAME>', '<EMAIL>', '8585856224', 'f925916e2754e5e03f75dd58a5733251', 1, '2020-08-17 13:40:30', NULL), (10, 'SID011', '<NAME>', '<EMAIL>', '4672423754', 'f925916e2754e5e03f75dd58a5733251', 1, '2020-09-15 18:00:59', NULL), (11, 'SID012', '<NAME>', '<EMAIL>', '1234567890', 'f925916e2754e5e03f75dd58a5733251', 1, '2020-07-11 17:55:21', '2020-07-18 05:18:49'); -- -- Indexes for dumped tables -- -- -- Indexes for table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`id`); -- -- Indexes for table `tblauthors` -- ALTER TABLE `tblauthors` ADD PRIMARY KEY (`id`); -- -- Indexes for table `tblbooks` -- ALTER TABLE `tblbooks` ADD PRIMARY KEY (`id`); -- -- Indexes for table `tblcategory` -- ALTER TABLE `tblcategory` ADD PRIMARY KEY (`id`); -- -- Indexes for table `tblissuedbookdetails` -- ALTER TABLE `tblissuedbookdetails` ADD PRIMARY KEY (`id`); -- -- Indexes for table `tblstudents` -- ALTER TABLE `tblstudents` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `StudentId` (`StudentId`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `admin` -- ALTER TABLE `admin` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `tblauthors` -- ALTER TABLE `tblauthors` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `tblbooks` -- ALTER TABLE `tblbooks` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT for table `tblcategory` -- ALTER TABLE `tblcategory` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- AUTO_INCREMENT for table `tblissuedbookdetails` -- ALTER TABLE `tblissuedbookdetails` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16; -- -- AUTO_INCREMENT for table `tblstudents` -- ALTER TABLE `tblstudents` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; COMMIT; /*!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 */; <file_sep>/admin/dashboard.php <?php session_start(); error_reporting(0); include('includes/config.php'); if(strlen($_SESSION['alogin'])==0) { header('location:index.php'); } else{?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> <meta name="description" content="" /> <meta name="author" content="" /> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <![endif]--> <title>Online Library Management System | Admin Dash Board</title> <!-- BOOTSTRAP CORE STYLE --> <link href="assets/css/bootstrap.css" rel="stylesheet" /> <!-- FONT AWESOME STYLE --> <link href="assets/css/font-awesome.css" rel="stylesheet" /> <!-- CUSTOM STYLE --> <link href="assets/css/style.css" rel="stylesheet" /> <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css"> <!-- GOOGLE FONT --> <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' /> </head> <body> <!------MENU SECTION START--> <?php include('includes/header.php'); include('bgwork.php');?> <!-- MENU SECTION END--> <div class="content-wrapper"> <div class="container"> <div class="row pad-botm"> <div class="heading-line" style="width:90%; padding: 5px 30px 10px 30px; margin-left:20px;"> <h4 class="header-line ">ADMIN DASHBOARD</h4> </div> </div> <div class="row" style="width:70%;background-color : #FEEAF7;padding:7px 7px 7px 7px;border-radius:20px;margin : 10px; "> <div class="col-md-3 col-sm-3 col-xs-6"> <div class="alert alert-success back-widget-set text-center" style="background-color:#FECFF8;"> <i class="fa fa-book fa-5x" aria-hidden="true" style="color:black"></i> <?php $sql ="SELECT id from tblbooks "; $query = $dbh -> prepare($sql); $query->execute(); $results=$query->fetchAll(PDO::FETCH_OBJ); $listdbooks=$query->rowCount(); ?> <h3><?php echo htmlentities($listdbooks);?></h3> <h3> Listed Books</h3> </div> </div> <div class="col-md-3 col-sm-2 col-xs-6"> <div class="alert alert-info back-widget-set text-center" style="background-color:#FECFF8;"> <i class="fa fa-bar-chart fa-5x" aria-hidden="true" style="color:black"></i> <?php $sql1 ="SELECT id from tblissuedbookdetails "; $query1 = $dbh -> prepare($sql1); $query1->execute(); $results1=$query1->fetchAll(PDO::FETCH_OBJ); $issuedbooks=$query1->rowCount(); ?> <h3><?php echo htmlentities($issuedbooks);?> </h3> <h3>Book Issue Frequency</h3> </div> </div> <div class="col-md-3 col-sm-2 col-xs-6"> <div class="alert alert-warning back-widget-set text-center" style="background-color:#FECFF8;"> <i class="fa fa-area-chart fa-5x" aria-hidden="true" style="color:black;"></i> <?php $status=1; $sql2 ="SELECT id from tblissuedbookdetails where ReturnStatus=:status"; $query2 = $dbh -> prepare($sql2); $query2->bindParam(':status',$status,PDO::PARAM_STR); $query2->execute(); $results2=$query2->fetchAll(PDO::FETCH_OBJ); $returnedbooks=$query2->rowCount(); ?> <h3><?php echo htmlentities($returnedbooks);?></h3> <h3>Book Return Frequency</h3> </div> </div> <div class="col-md-3 col-sm-2 col-xs-6"> <div class="alert alert-danger back-widget-set text-center" style="background-color:#FECFF8;"> <i class="fa fa-users fa-4x" style="color:black;"></i> <?php $sql3 ="SELECT id from tblstudents "; $query3 = $dbh -> prepare($sql3); $query3->execute(); $results3=$query3->fetchAll(PDO::FETCH_OBJ); $regstds=$query3->rowCount(); ?> <h3><?php echo htmlentities($regstds);?></h3> <h3> Registered Users</h3> </div> </div> </div> <div class="row" style="width:70%;background-color : #FEEAF7;padding:7px 7px 7px 7px;border-radius:20px;margin : 10px; "> <div class="col-md-4 col-sm-2 col-xs-6"> <div class="alert alert-success back-widget-set text-center"style="background-color:#FECFF8;"> <i class="fa fa-user fa-5x" style="color:black;"></i> <?php $sql4 ="SELECT id from tblauthors "; $query4 = $dbh -> prepare($sql4); $query4->execute(); $results4=$query4->fetchAll(PDO::FETCH_OBJ); $listdathrs=$query4->rowCount(); ?> <h3><?php echo htmlentities($listdathrs);?></h3> <h3>Listed Publications</h3> </div> </div> <div class="col-md-4 col-sm-2 rscol-xs-6"> <div class="alert alert-info back-widget-set text-center" style="background-color:#FECFF8;"> <i class="fa fa-bookmark fa-5x" style="color:black;"></i> <?php $sql5 ="SELECT id from tblcategory "; $query5 = $dbh -> prepare($sql5); $query5->execute(); $results5=$query5->fetchAll(PDO::FETCH_OBJ); $listdcats=$query5->rowCount(); ?> <h3><?php echo htmlentities($listdcats);?> </h3> <h3>Listed Categories</h3> </div> </div> <div class="col-md-4 col-sm-2 rscol-xs-6"> <div class="alert alert-info back-widget-set text-center" style="background-color:#FECFF8;"> <i class="fa fa-money fa-5x" style="color:black;"></i> <?php $ret="select * from tblfine where 1"; $query= $dbh -> prepare($ret); $query-> execute(); $results=$query->fetchAll(PDO::FETCH_OBJ); if($query->rowCount() > 0) { foreach($results as $result) { $fine=$result->fine; } } ?> <h3><?php echo htmlentities($fine);?> </h3> <h3>Current Fine Per Day</h3> </div> </div> </div> </div> </div> <script src="assets/js/jquery-1.10.2.js"></script> <!-- BOOTSTRAP SCRIPTS --> <script src="assets/js/bootstrap.js"></script> <!-- CUSTOM SCRIPTS --> <script src="assets/js/custom.js"></script> <!---Footer--> <footer class="text-center text-white foot"> <h3 style="color:white"> <center><strong> PrimaThink : Library Management System </strong> </center> </h3> <div id="contact" >Contact Our Toll Free Number : 180X 40XX 30XX for more Information. </div> <!-- Copyright--> <div class="text-center p-3" style="background-color: rgba(0, 0, 0, 0.2);"> © 2021 Copyright: <a class="text-white" style="color:white;text-decoration" href="https://primathink.com/">PrimaThink (All Rights Reserved) </a> </div> </footer> </body> </html> <?php } ?> <file_sep>/admin/1.php <?php include('includes/config.php'); $ret="select * from tblfine where 1"; $query= $dbh -> prepare($ret); $query-> execute(); $results=$query->fetchAll(PDO::FETCH_OBJ); if($query->rowCount() > 0) { foreach($results as $result) { $fine=$result->fine; echo"<script>alert('".$fine."')</script>"; } } ?><file_sep>/temp.php <?php session_start(); error_reporting(0); include('includes/config.php'); if(strlen($_SESSION['login'])==0) { header('location:index.php'); } else{ $StudentID=$_GET['StudentID']; $StudName=$_GET['StudName']; $ISBNNumber=$_GET['ISBNNumber']; $BookName=$_GET['BookName']; $AuthorName=$_GET['AuthorName']; $CategoryName=$_GET['CategoryName']; $BookPrice=$_GET['BookPrice']; $sql = "SELECT * from tblrequestedbookdetails where StudentID=:StudentID and ISBNNumber=:ISBNNumber"; $query = $dbh -> prepare($sql); $query->bindParam(':StudentID',$StudentID,PDO::PARAM_STR); $query->bindParam(':ISBNNumber',$ISBNNumber,PDO::PARAM_STR); $query->execute(); $results=$query->fetchAll(PDO::FETCH_OBJ); $cnt=1; if($query->rowCount() > 0) { $_SESSION['msg']="You have already requested this book"; header('location:request-a-book.php'); } else{ $sql = "SELECT * from tblrequestedbookdetails where StudentID=:StudentID"; $query = $dbh -> prepare($sql); $query->bindParam(':StudentID',$StudentID,PDO::PARAM_STR); $query->execute(); $results=$query->fetchAll(PDO::FETCH_OBJ); $cnt=1; if($query->rowCount() == 2) { $_SESSION['msg']="You cannot request more than 2 books at a time"; header('location:request-a-book.php'); } else { $sql="INSERT INTO tblrequestedbookdetails(StudentID,StudName,BookName,CategoryName,AuthorName,ISBNNumber,BookPrice) VALUES(:StudentID,:StudName,:BookName,:CategoryName,:AuthorName,:ISBNNumber,:BookPrice)"; $query = $dbh->prepare($sql); $query->bindParam(':StudentID',$StudentID,PDO::PARAM_STR); $query->bindParam(':StudName',$StudName,PDO::PARAM_STR); $query->bindParam(':BookName',$BookName,PDO::PARAM_STR); $query->bindParam(':CategoryName',$CategoryName,PDO::PARAM_STR); $query->bindParam(':AuthorName',$AuthorName,PDO::PARAM_STR); $query->bindParam(':ISBNNumber',$ISBNNumber,PDO::PARAM_STR); $query->bindParam(':BookPrice',$BookPrice,PDO::PARAM_STR); $query->execute(); $lastInsertId = $dbh->lastInsertId(); $_SESSION['msg']="Book requested successfully"; header('location:request-a-book.php'); } } }?> <file_sep>/admin/overduereport.php <?php //require_once 'core.php'; require_once 'includes/config.php'; $sql = "SELECT * from overdue"; $query = $dbh -> prepare($sql); $query->execute(); $results=$query->fetchAll(PDO::FETCH_OBJ); $table = ' <table border="1" cellspacing="0" cellpadding="0" style="width:100%;"> <tr> <th>Sr No</th> <th>Student Name</th> <th>Student ID</th> <th>Phone Number</th> <th>Fine</th> </tr> <tr>'; $cnt=1; $totalcredit=0; if($query->rowCount() > 0) { foreach($results as $result) { //echo"<script>alert('".$result->FullName."')</script>"; $table .= '<tr> <td><center>'.$cnt.'</center></td> <td><center>'.$result->StudentName.'</center></td> <td><center>'.$result->StudentID.'</center></td> <td><center>'.$result->MobNumber.'</center></td> <td><center>'.$result->Fine.'</center></td> </tr>'; $cnt+=1; $totalcredit+=$result->Fine; } } $table .= ' </tr> </table> <div align="right">Total Credit:'.$totalcredit.'</div> <br> <button onClick="window.print()">Print this page</button> '; echo $table; ?><file_sep>/admin/bgwork.php <?php if($_SESSION['thread1']==0) { include('includes/config.php'); $date=Date('Y/m/d'); $ret="select * from tblfine where 1"; $query= $dbh -> prepare($ret); $query-> execute(); $results=$query->fetchAll(PDO::FETCH_OBJ); if($query->rowCount() > 0) { foreach($results as $result) { $_SESSION['fine']=$result->fine; } } $ret="select BookId,StudentID,IssuesDate from tblissuedbookdetails where ReturnStatus=0"; $query= $dbh -> prepare($ret); $query-> execute(); $results=$query->fetchAll(PDO::FETCH_OBJ); if($query->rowCount() > 0) { foreach($results as $result) { $date2=Date("Y/m/d",strtotime($result->IssuesDate)); $diff=strtotime($date)- strtotime($date2); $days=floor($diff/86400); if($days>7){ $days=$days-7; //echo"<script>alert('".$days."')</script>"; $totalfine=$days*$_SESSION['fine']; $ret1="select * from overdue where StudentID=:id"; $query1= $dbh -> prepare($ret1); $query1 -> bindParam(':id',$result->StudentID, PDO::PARAM_STR); $query1-> execute(); $res=$query1->fetchAll(PDO::FETCH_OBJ); if($query1->rowCount()<=0){ $sql="INSERT INTO overdue(StudentID,Fine,StudentName,MobNumber) VALUES(:studentid,:fine,:name,:number)"; $query2 = $dbh->prepare($sql); $sq="select FullName,MobileNumber from tblstudents where StudentId=:studentid"; $query4 = $dbh->prepare($sq); $query4->bindParam(':studentid',$result->StudentID,PDO::PARAM_STR); $query4->execute(); $res1=$query4->fetch(PDO::FETCH_OBJ); $query2->bindParam(':studentid',$result->StudentID,PDO::PARAM_STR); $query2->bindParam(':fine',$totalfine,PDO::PARAM_STR); $query2->bindParam(':name',$res1->FullName,PDO::PARAM_STR); $query2->bindParam(':number',$res1->MobileNumber,PDO::PARAM_STR); $query2->execute(); $lastInsertId = $dbh->lastInsertId(); } else{ $sql1="update overdue set Fine=Fine+:fine where StudentID=:studentid"; $query3 = $dbh->prepare($sql1); $query3->bindParam(':fine',$totalfine,PDO::PARAM_STR); $query3->bindParam(':studentid',$result->StudentID,PDO::PARAM_STR); $query3->execute(); } } } } $_SESSION['thread1']=1; } ?><file_sep>/admin/report.php <?php session_start(); error_reporting(0); include('includes/config.php'); if(strlen($_SESSION['alogin'])==0) { header('location:index.php'); } else{ if(isset($_POST['view'])) { $type=$_POST['type']; if($type=="userwise"){ header('location:Clientreport.php'); } if($type=="overdue"){ header('location:overduereport.php'); } } ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>Online Library Management System | Add Categories</title> <!-- BOOTSTRAP CORE STYLE --> <link href="assets/css/bootstrap.css" rel="stylesheet" /> <!-- FONT AWESOME STYLE --> <link href="assets/css/font-awesome.css" rel="stylesheet" /> <!-- CUSTOM STYLE --> <link href="assets/css/style.css" rel="stylesheet" /> <!-- GOOGLE FONT --> <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' /> </head> <body> <!------MENU SECTION START--> <?php include('includes/header.php');?> <div class="content-wrapper"> <div class="container"> <div class="row pad-botm"> <div class="heading-line" style="width:90%; padding: 5px 30px 10px 30px; margin-left:20px;"> <h4 class="header-line ">Report Issues</h4> </div> </div> </div> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3""> <div class="panel panel-info"> <div class="panel-heading" style=" background-color:#FE46A8;"> <h2 style=" color: white; font-size: 40px;">Reports</h2> </div> <div class="panel-body"> <form role="form" method="post"> <div class="form-group"> <label>Report Type</label> <select name="type" class="form-control"> <option value="">Select</option> <option value="userwise">User-Wise</option> <option value="overdue">Over-Due</option> </select> </div> <button type="submit" name="view" class="btn btn-info" style="width:100px">View</button> </form> </div> </div> </div> </div> </div> </div> <script src="assets/js/jquery-1.10.2.js"></script> <!-- BOOTSTRAP SCRIPTS --> <script src="assets/js/bootstrap.js"></script> <!-- CUSTOM SCRIPTS --> <script src="assets/js/custom.js"></script> <!---Footer--> <footer class="text-center text-white foot"> <h3 style="color:white"> <center><strong> PrimaThink : Library Management System </strong> </center> </h3> <div id="contact" >Contact Our Toll Free Number : 180X 40XX 30XX for more Information. </div> <!-- Copyright--> <div class="text-center p-3" style="background-color: rgba(0, 0, 0, 0.2);"> © 2021 Copyright: <a class="text-white" style="color:white;text-decoration" href="https://primathink.com/">PrimaThink (All Rights Reserved) </a> </div> </footer> </body> </html> <?php } ?> <file_sep>/admin/Clientreport.php <?php //require_once 'core.php'; require_once 'includes/config.php'; $sql = "SELECT tblstudents.FullName,tblbooks.BookName,tblbooks.ISBNNumber,tblbooks.id,tblissuedbookdetails.IssuesDate,tblissuedbookdetails.ReturnDate,tblissuedbookdetails.id as rid from tblissuedbookdetails join tblstudents on tblstudents.StudentId=tblissuedbookdetails.StudentId join tblbooks on tblbooks.id=tblissuedbookdetails.BookId order by tblissuedbookdetails.id desc"; $query = $dbh -> prepare($sql); $query->execute(); $results=$query->fetchAll(PDO::FETCH_OBJ); $table = ' <table border="1" cellspacing="0" cellpadding="0" style="width:100%;"> <tr> <th>Student Name</th> <th>Book Name</th> <th>Book ID</th> <th>ISBN Number</th> <th>Issued Date</th> <th>Return Date</th> </tr> <tr>'; $cnt=1; if($query->rowCount() > 0) { foreach($results as $result) { //echo"<script>alert('".$result->FullName."')</script>"; $table .= '<tr> <td><center>'.$result->FullName.'</center></td> <td><center>'.$result->BookName.'</center></td> <td><center>'.$result->id.'</center></td> <td><center>'.$result->ISBNNumber.'</center></td> <td><center>'.$result->IssuesDate.'</center></td> <td><center>'.$result->ReturnDate.'</center></td> </tr>'; } } $table .= ' </tr> </table> <button onClick="window.print()">Print this page</button> '; echo $table; ?>
1a7d230ded56cb94121c8d7027ad6170cefab557
[ "SQL", "PHP" ]
8
SQL
rushabhj-hub/PrimaThink-Library-Management-System
7c443f1f3cbbdffab198dea7c7f7514b4c0c77e8
e3295ad1f326775044425c904d1f0002ac5c15f1
refs/heads/master
<file_sep>using Google.Apis.Drive.v2.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GoogleDrive.Model { public class GoogleDriveFile { public GoogleDriveFile() { } public GoogleDriveFile(File file) { CreatedDate = Convert.ToDateTime(file.CreatedDate); IconLink = file.IconLink; Id = file.Id; Labels = new GoogleDriveFileLabel { Hidden = file.Labels.Hidden.Value, Restricted = file.Labels.Restricted.Value, Starred = file.Labels.Starred.Value, Trashed = file.Labels.Trashed.Value, Viewed = file.Labels.Viewed.Value }; ModifiedDate = Convert.ToDateTime(file.ModifiedDate); OriginalFilename = file.OriginalFilename; ThumbnailLink = file.ThumbnailLink; Title = file.Title; WebContentLink = file.WebContentLink; } public string Id { get; set; } public string Title { get; set; } public string OriginalFilename { get; set; } public string ThumbnailLink { get; set; } public string IconLink { get; set; } public string WebContentLink { get; set; } internal DateTime createdDate; public DateTime CreatedDate { get { var istDate = TimeZoneInfo.ConvertTime(this.createdDate,TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id)); return istDate; } set { this.createdDate = value; } } private DateTime modifiedDate; public DateTime ModifiedDate { get { var istDate = TimeZoneInfo.ConvertTime(this.modifiedDate, TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id)); return istDate; } set { this.modifiedDate = value; } } public GoogleDriveFileLabel Labels { get; set; } } public class GoogleDriveFileLabel { public bool Starred { get; set; } public bool Hidden { get; set; } public bool Trashed { get; set; } public bool Restricted { get; set; } public bool Viewed { get; set; } } } <file_sep>using Google.Apis.Drive.v2.Data; using GoogleDrive.Model; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web; namespace GoogleDrive.MVC.UtilityMethods { public class WebApiCall { public async Task<GoogleDriveFile> PostToGoogleDrive(HttpPostedFileBase file) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:16184/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //converting byte to array byte[] byteArray = new byte[file.ContentLength]; file.InputStream.Read(byteArray, 0, file.ContentLength); //converting HttpPostedfileBase to json string jsonConvertedFile = JsonConvert.SerializeObject(byteArray); StringContent content = new StringContent(jsonConvertedFile, Encoding.UTF8, "application/json"); //sends file name along with querystring HttpResponseMessage message = await client.PostAsync("api/FileToDrive/SaveFile?fileName=" + file.FileName, content); if (message.StatusCode == HttpStatusCode.OK) { //Problem Arise Here as Some extra chareters added to id string responseContent = await message.Content.ReadAsStringAsync(); //Removing the slashes from both the end e.g. "\"0B2pC99R_P4taZlFPRnJEbENVbTA\"" GoogleDriveFile uploadedFile = JsonConvert.DeserializeObject<GoogleDriveFile>(responseContent); return uploadedFile; } return null; } } public async Task<GoogleDriveFile> GetFile(string fileId) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:16184/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string url = string.Format($"api/FileToDrive/GetFile?fileId={fileId}"); HttpResponseMessage message = await client.GetAsync(url); if (message.StatusCode == HttpStatusCode.OK) { var file = JsonConvert.DeserializeObject<GoogleDriveFile>(await message.Content.ReadAsStringAsync()); return file; } return null; } } public async Task<HttpResponseMessage> GetAllFiles() { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:16184/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage message = await client.GetAsync("api/FileToDrive/GetAllFiles").ConfigureAwait(false); if (message.StatusCode == HttpStatusCode.OK) { return message; } return null; } } public async Task<string> DeleteFile(string fileId) { using (var Client = new HttpClient()) { Client.BaseAddress = new Uri("http://localhost:16184/"); Client.DefaultRequestHeaders.Accept.Clear(); Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var result = Client.DeleteAsync($"api/FileToDrive/Delete/{fileId}").Result; if (result.StatusCode == HttpStatusCode.OK) return "deleted"; else if (result.StatusCode == HttpStatusCode.InternalServerError) return "internal server error"; return "error"; } } public async Task<string> EditFile(string fileId, string Title, string OriginalFileName, string Description) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:16184/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage message = await client.PostAsync($"api/EditFile/SaveEdited/{fileId}/{Description}/{OriginalFileName}/{Title}", null); if (message.StatusCode == HttpStatusCode.OK) { return "success"; } return null; } } } } //String fileId, String newTitle, // String newDescription, String newMimeType, String newFilename<file_sep>using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v2; using Google.Apis.Drive.v2.Data; using Google.Apis.Services; using Google.Apis.Util.Store; using System; using System.IO; using System.Threading; namespace GoogleDrive.WebApi.GoogleDrive { public class GoogleUtility { //Getting google credential with OAuth2 public UserCredential GetCredential() { UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = "1095883481859-uqkb7r66vth2402p0dn8dpel8g2ptidm.apps.googleusercontent.com", ClientSecret = "<KEY>" }, new[] { DriveService.Scope.Drive}, "user", CancellationToken.None ).Result; return credential; } public bool SearchFolder(DriveService service, string folderId) { ChildrenResource.ListRequest request = service.Children.List("root"); //to search only folder and nontrashed area request.Q = "mimeType='application/vnd.google-apps.folder' and trashed=false"; do { try { ChildList childern = request.Execute(); foreach (ChildReference item in childern.Items) { if (item.Id == folderId) return true; } //reffers to next page of data request.PageToken = childern.NextPageToken; ; } catch (Exception ex) { request.PageToken = null; } } while (!string.IsNullOrEmpty(request.PageToken)); return false; } } }<file_sep>using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v2; using Google.Apis.Services; using GoogleDrive.Model; using GoogleDrive.MVC.UtilityMethods; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; namespace GoogleDrive.MVC.Controllers { public class FIleUploadController : Controller { // GET: FIleUpload public ActionResult Index() { return View(); } public async Task<ActionResult> PostFile(HttpPostedFileBase file) { if (file == null) { ModelState.AddModelError("File", "Please Upload Your file"); } else if (file.ContentLength > 0) { int MaxContentLength = 1024 * 1024 * 4; //4 MB string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf", ".jpeg" }; if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.')))) { ModelState.AddModelError("File", "Please upload file of type: " + string.Join(", ", AllowedFileExtensions)); } else if (file.ContentLength > MaxContentLength) { ModelState.AddModelError("File", $"Your file is too large, maximum allowed size is: { MaxContentLength } MB"); } else { ModelState.Clear(); #region Transferd to WebApi //UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( // new ClientSecrets // { // ClientId = "1095883481859-uqkb7r66vth2402p0dn8dpel8g2ptidm.apps.googleusercontent.com", // ClientSecret = "<KEY>" // }, // new[] { DriveService.Scope.Drive }, // "user", // CancellationToken.None // ).Result; //var service = new DriveService(new BaseClientService.Initializer() //{ // HttpClientInitializer = credential, // ApplicationName = "DriveApiFileUpload"///Can be changed //}); //Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); //body.Title = "Candidates Document-" + System.IO.Path.GetFileNameWithoutExtension(file.FileName); //body.Description = "Carrer document"; //body.MimeType = "image/jpeg"; //byte[] byteArray = new byte[file.ContentLength];// System.IO.File.ReadAllBytes(path); //file.InputStream.Read(byteArray, 0, file.ContentLength); //MemoryStream stream = new MemoryStream(byteArray); //FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "image/jpeg"); //request.Upload(); //var driveFile = request.ResponseBody; #endregion //calling to api to upload file to dirve //http://localhost:16184/api/FileUpload/PostToGoogleDrive WebApiCall call = new WebApiCall(); //string fileId = await call.PostToGoogleDrive(file); GoogleDriveFile uploadedFile = await call.PostToGoogleDrive(file); if (uploadedFile != null) { ViewBag.Message = "File uploaded successfully"; return View("ViewFile", uploadedFile); } else { ViewBag.Message = "Failed to upload"; } } } return View(); } public async Task<ActionResult> GetFile(string id) { //check for null to fileId WebApiCall call = new UtilityMethods.WebApiCall(); var file = await call.GetFile(id); return View("ViewFile", file); } public async Task<ActionResult> GetAllFile() { WebApiCall call = new WebApiCall(); var message = await call.GetAllFiles(); string result = await message.Content.ReadAsStringAsync(); // GoogleDriveFile files = new JavaScriptSerializer().Deserialize<GoogleDriveFile>(result); object files = JsonConvert.DeserializeObject<IList<GoogleDriveFile>>(result); //return Json(files, JsonRequestBehavior.AllowGet); return View(files); } [HttpGet] public async Task<ActionResult> EditFile(string fileId) { WebApiCall call = new WebApiCall(); TempData["id"] = fileId; return View(await call.GetFile(fileId)); } [HttpPost] public async Task<ActionResult> EditFile(string Title, string OriginalFileName, string Description) { WebApiCall call = new WebApiCall(); if (TempData["id"] != null) { var message = await call.EditFile(TempData["id"].ToString(), Title, OriginalFileName, Description); if (message == "success") ViewBag.Message = "Saved Successfully"; else ViewBag.Message = "Error in editing"; } return View("Index"); } public async Task<ActionResult> Delete(string id) { WebApiCall call = new WebApiCall(); string result = await call.DeleteFile(id); if (result.Equals("deleted", StringComparison.Ordinal)) { ViewBag.Message = "File deleted successfully"; } else if (result.Equals("error", StringComparison.Ordinal)) ViewBag.Message = "Error in deleting"; return View("Index"); } public async Task<string> FileName(HttpPostedFileBase file) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:16184/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var message = await client.GetAsync("api/FileUpload/Demo"); return message.Content.ToString(); } } } }<file_sep>using Google; using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v2; using Google.Apis.Drive.v2.Data; using Google.Apis.Services; using GoogleDrive.Model; using GoogleDrive.WebApi.GoogleDrive; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Web; using System.Web.Http; namespace GoogleDrive.WebApi.Controllers { public class FileToDriveController : ApiController { [HttpPost] public IHttpActionResult SaveFile([FromBody] byte[] byteArray, [FromUri] string fileName) { //Gets credentials GoogleUtility googleUtility = new GoogleUtility(); UserCredential credential = googleUtility.GetCredential(); //byte array to HttpPostedFileBase HttpPostedFileBase file = new ByteArrayToHttpPostedFileBase(byteArray, fileName); var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "DriveApiFileUpload" }); //Folder id can be retrived from database which is user specific var folderId = "0B2pC99R_P4taZHdQeU9ScDJoSWs"; bool folderExists = googleUtility.SearchFolder(service, folderId); //check wheather the folder exists or not if (!folderExists) { //folder Creation var folder = new Google.Apis.Drive.v2.Data.File { Title = "Photos", MimeType = "application/vnd.google-apps.folder" }; var result = service.Files.Insert(folder).Execute(); folderId = result.Id; } Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File() { Title = Path.GetFileNameWithoutExtension(file.FileName), Description = "Uploaded from WebApi", MimeType = MimeMapping.GetMimeMapping(fileName), //Maps the file MIME type Parents = new List<ParentReference>() { new ParentReference() { Id = folderId } } }; MemoryStream stream = new MemoryStream(byteArray); FilesResource.InsertMediaUpload requestToUpload = service.Files.Insert(body, stream, body.MimeType); requestToUpload.Upload(); var response = requestToUpload.ResponseBody; GoogleDriveFile outputFile = new GoogleDriveFile(response); return Ok(outputFile); } [HttpGet] public IHttpActionResult GetFile(string fileId) { GoogleUtility googleUtility = new GoogleUtility(); UserCredential credential = googleUtility.GetCredential(); var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "DriveApiFileUpload", }); try { Google.Apis.Drive.v2.Data.File file = service.Files.Get(fileId).Execute(); if (file == null) { return NotFound(); } return Ok(file); } catch (GoogleApiException ex) { return InternalServerError(ex); } catch (Exception ex) { return InternalServerError(ex); } } [HttpGet] public IHttpActionResult GetAllFiles() { //Gets credentials GoogleUtility googleUtility = new GoogleUtility(); UserCredential credential = googleUtility.GetCredential(); var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "DriveApiFileUpload" }); var listRequest = service.Files.List(); listRequest.MaxResults = 120; listRequest.Q = "mimeType!='application/vnd.google-apps.folder' and trashed=false"; IList<Google.Apis.Drive.v2.Data.File> files = listRequest.Execute().Items; if (files != null) { return Ok(files); } return InternalServerError(); } [HttpDelete] [Route("api/FileToDrive/Delete/{id}")] public IHttpActionResult DeleteFile(string id) { try { GoogleUtility utility = new GoogleUtility(); var credential = utility.GetCredential(); DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "DriveApiFileUpload" }); var value= service.Files.Delete(id).Execute(); return Ok(value); } catch (Exception ex) { return InternalServerError(ex); } } [HttpPut] public IHttpActionResult Put(string fileId, string Title, string OriginalFileName, string Description) { try { GoogleUtility utility = new GoogleUtility(); var credential = utility.GetCredential(); var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "DriveApiFileUpload" }); Google.Apis.Drive.v2.Data.File fileMetaData = service.Files.Get(fileId).Execute(); HttpWebRequest fileRequest = (HttpWebRequest)WebRequest.Create(fileMetaData.WebContentLink); HttpWebResponse response = (HttpWebResponse)fileRequest.GetResponse(); var responseStream = response.GetResponseStream(); // File's new content. //byte[] byteArray = System.IO.File.ReadAllBytes(responseStream); //System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); Google.Apis.Drive.v2.Data.File GoogleFile = new Google.Apis.Drive.v2.Data.File { Id = fileId, Title = Title, Description = Description, }; FilesResource.UpdateMediaUpload request = service.Files.Update(GoogleFile, fileId, responseStream, "image/jpeg"); request.Upload(); Google.Apis.Drive.v2.Data.File updatedFile = request.ResponseBody; return Ok(updatedFile); } catch (Exception ex) { return InternalServerError(ex); } } } }<file_sep>using Google; using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v2; using Google.Apis.Drive.v2.Data; using Google.Apis.Services; using GoogleDrive.Model; using GoogleDrive.WebApi.GoogleDrive; using System; using System.Net; using System.Web.Http; namespace GoogleDrive.WebApi.Controllers { public class EditFileController : ApiController { [HttpPost] [Route("api/EditFile/SaveEdited/{fileId}/{Title}/{OriginalFileName}/{Description}")] public IHttpActionResult SaveEdited([FromUri]string fileId, [FromUri] string Title, [FromUri]string OriginalFileName, [FromUri]string Description) { try { GoogleUtility utility = new GoogleUtility(); var credential = utility.GetCredential(); var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "DriveApiFileUpload" }); Google.Apis.Drive.v2.Data.File fileMetaData = service.Files.Get(fileId).Execute(); //getting file content from web as downloaded WebClient client = new WebClient(); Uri uri = new Uri(fileMetaData.WebContentLink); byte[] ar = client.DownloadData(uri); //// File's new content. System.IO.MemoryStream stream = new System.IO.MemoryStream(ar); Google.Apis.Drive.v2.Data.File GoogleFile = new Google.Apis.Drive.v2.Data.File { Id = fileId, Title = Title, Description = Description, }; FilesResource.UpdateMediaUpload request = service.Files.Update(GoogleFile, fileId, stream, GoogleFile.MimeType); request.Upload(); Google.Apis.Drive.v2.Data.File updatedFile = request.ResponseBody; return Ok(updatedFile); } catch (Exception ex) { return InternalServerError(ex); } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace GoogleDrive.WebApi.GoogleDrive { public class ByteArrayToHttpPostedFileBase: HttpPostedFileBase { private readonly byte[] fileBytes; private Stream inputStream; public ByteArrayToHttpPostedFileBase(byte[] byteArray, string fileName=null) { this.fileBytes = byteArray; this.FileName = fileName; this.InputStream = new MemoryStream(byteArray); } public override int ContentLength => fileBytes.Length; public override string FileName { get; } public override Stream InputStream { get; } } }<file_sep>using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v2; using Google.Apis.Drive.v2.Data; using Google.Apis.Services; using Google.Apis.Util.Store; using GoogleDrive.WebApi.GoogleDrive; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Web; using System.Web.Http; namespace GoogleDrive.WebApi.Controllers { public class FileUploadController : ApiController { [HttpPost] [Route("Drive")] public IHttpActionResult PostToGoogleDrive([FromBody] byte[] byteArray, [FromUri] string fileName) { //Gets credentials UserCredential credential = new GoogleUtility().GetCredential(); var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "DriveApiFileUpload" }); Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File() { Title = Path.GetFileNameWithoutExtension(fileName), Description = "Uploaded from WebApi", MimeType = "image/jpeg" //Maps the file MIME type }; //byte[] byteArray = new byte[file.ContentLength]; //file.InputStream.Read(byteArray, 0, file.ContentLength); MemoryStream stream = new MemoryStream(byteArray); FilesResource.InsertMediaUpload requestToUpload = service.Files.Insert(body, stream, body.MimeType); requestToUpload.Upload(); var response = requestToUpload.ResponseBody; return Ok(response.Id); } [HttpGet] public IHttpActionResult Demo() { return Ok("This is demo method"); } } }
2c08489b57b561c9af8c1c801a37dbfcc18fff56
[ "C#" ]
8
C#
keshari1arya/GoogleDrive
c27aa22110cd2b6f83f8c12b8ff4db7cebc884a2
20d83f0293e6b341ebc06b9bc6a16f8e6f19b9a9
refs/heads/master
<file_sep>package database; import java.sql.Timestamp; import java.util.List; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.criterion.Example; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A data access object (DAO) providing persistence and search support for * Cargout entities. Transaction control of the save(), update() and delete() * operations can directly support Spring container-managed transactions or they * can be augmented to handle user-managed Spring transactions. Each of these * methods provides additional information for how to configure it for the * desired type of transaction control. * * @see database.Cargout * @author MyEclipse Persistence Tools */ public class CargoutDAO extends BaseHibernateDAO { private static final Logger log = LoggerFactory.getLogger(CargoutDAO.class); // property constants public static final String CARGO_OUTERID = "cargoOuterid"; public static final String CARGO_CHECKERID = "cargoCheckerid"; public void save(Cargout transientInstance) { log.debug("saving Cargout instance"); try { getSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(Cargout persistentInstance) { log.debug("deleting Cargout instance"); try { getSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Cargout findById(java.lang.String id) { log.debug("getting Cargout instance with id: " + id); try { Cargout instance = (Cargout) getSession().get("database.Cargout", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(Cargout instance) { log.debug("finding Cargout instance by example"); try { List results = getSession().createCriteria("database.Cargout").add( Example.create(instance)).list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding Cargout instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Cargout as model where model." + propertyName + "= ?"; Query queryObject = getSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByCargoOuterid(Object cargoOuterid) { return findByProperty(CARGO_OUTERID, cargoOuterid); } public List findByCargoCheckerid(Object cargoCheckerid) { return findByProperty(CARGO_CHECKERID, cargoCheckerid); } public List findAll() { log.debug("finding all Cargout instances"); try { String queryString = "from Cargout"; Query queryObject = getSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public Cargout merge(Cargout detachedInstance) { log.debug("merging Cargout instance"); try { Cargout result = (Cargout) getSession().merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Cargout instance) { log.debug("attaching dirty Cargout instance"); try { getSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Cargout instance) { log.debug("attaching clean Cargout instance"); try { getSession().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } }<file_sep>package operation; import java.util.List; import database.Viewer; public interface I_Find<T> { T findById(Object id);//根据主键查找 List<Viewer> findBycolumns(String[] columns,String[] values);//多条件查找 List<T> findBycolumn(String column,Object value);//单条件查找 List<T> findAll();//通过所有列查找 } <file_sep>package support; public class Savecargorecord { } <file_sep>package operation; import java.util.List; import database.Viewer; //create cargorecord xls public class BuildCargoRecord implements I_Build{ public void buildXLS(String tablename) { CreateXLS create=new CreateXLS(tablename); Find<Viewer> find=new Find<Viewer>("cargorecord"); List<Viewer> data=find.findAll(); create.create(data); for(int i=0;i<data.size();i++){ if(data.get(i).getColumn(9).equals("1")){ find=new Find<Viewer>("cargomoving"); List<Viewer> movrecord=find.findBycolumn("cargo_id",data.get(i).getColumn(0)); create=new CreateXLS(data.get(i).getColumn(0)+"movrecord"); create.create(movrecord); } } } } <file_sep>package servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import database.CargoDAO; import database.Cargoin; import database.CargoinDAO; import database.Cargorecord; import database.CargorecordDAO; public class Cargoreadyservlet extends HttpServlet { /** * Constructor of the object. */ public Cargoreadyservlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SimpleDateFormat df = new SimpleDateFormat("yyyymmddhhmmss"), df2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date now=new Date(); Timestamp ts=Timestamp.valueOf(df2.format(now)); String time=df.format(now); String trackingno=request.getParameter("trackingno"), checkerid=request.getParameter("username"), kg=request.getParameter("kg"), isintact=request.getParameter("isintact"), state="΄ύΘλ", remark=request.getParameter("remark"), cargoId=trackingno.substring(0,2)+time+"00"; response.setContentType("text/html"); Cargorecord record=new Cargorecord(); CargorecordDAO crdao=new CargorecordDAO(); record.setCargoId(cargoId); record.setCargoIsintact(Integer.parseInt(isintact)); record.setCargoKg(Double.parseDouble(kg)); record.setCargoRemark(remark); record.setCargoState(state); crdao.save(record); Cargoin cargo=new Cargoin(); CargoinDAO cdao=new CargoinDAO(); cargo.setCargoId(cargoId); cargo.setCargoCheckerid(checkerid); cargo.setCargoGetime(ts); cargo.setCargoTrackingno(trackingno); cdao.save(cargo); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } } <file_sep>package operation; import java.util.List; import support.GetSQL; import support.RunSQL; import database.*; //To find tble Cargo public class FindCargo<T> implements I_Find<Cargo>{ RunSQL runsql=new RunSQL(); Turn turn=new Turn(); String sql=""; public List<Cargo> findAll() { sql="select * from cargo;"; return turn.turnToCargo(runsql.selectSQL(sql)); } public Cargo findById(Object id) { sql="select * from cargo where cargo_trackingno="+id+";"; return turn.turnToCargo(runsql.selectSQL(sql).get(0)); } public List<Cargo> findBycolumn(String column, Object value) { sql="select * from cargo where "+column+"="+value+";"; return turn.turnToCargo(runsql.selectSQL(sql)); } public List<Viewer> findBycolumns(List<String> columns,List<String> values){ GetSQL getsql=new GetSQL("cargo"); String sql=getsql.columnsLimit(columns, values); return runsql.selectSQL(sql); } } <file_sep>package support; public class GetSQL { String table=""; public GetSQL(String table){ this.table=table; } public String columnsLimit(String[] columns,String[] values){ String sql="select * from "+table+" where "+columns[0]+"='"+values[0]+"'"; for(int i=1;i<columns.length;i++)//若有多个条件,则进入for循环 sql+=" and "+columns[i]+"='"+values[i]+"'"; sql+=";"; return sql; } } <file_sep>package support; import java.sql.*; import java.util.*; import database.Viewer; //running sql by jdbc,return in List public class RunSQL { String name="YaaMe", password="<PASSWORD>", jdbc="jdbc:sqlserver://localhost:1433;DatabaseName=WMS", driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"; public RunSQL(){} public RunSQL(String name,String password){ this.name=name;this.password=password; } public RunSQL(String driver,String jdbc,String name,String password){ this.driver=driver;this.jdbc=jdbc;this.name=name;this.password=<PASSWORD>; } public List<Viewer> selectSQL(String sql){//通过传递sql语句作为参数进行查询 Connection con = null; Statement stmt = null; ResultSet rs = null; Viewer entity;//Viewer的实体 List<Viewer> data=new ArrayList<Viewer>();//List是一个接口,没法new;ArrayList则是一个类 try { Class.forName(driver); con = DriverManager.getConnection(jdbc, name,password); stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); rs=stmt.executeQuery(sql); while(rs.next()){ int counts=rs.getMetaData().getColumnCount(); String[] columnames=new String[counts]; for(int i=0;i<counts;i++) columnames[i]=rs.getMetaData().getColumnName(i+1); entity=new Viewer(counts,columnames);//获取表格中列的标题名称的列数 for(int i=0;i<counts;i++){ entity.setColumn(i,rs.getString(i+1)); } data.add(entity); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException s) { s.printStackTrace(); } finally { try { if (rs != null) { rs.close(); rs = null; } if (stmt != null) { stmt.close(); stmt = null; } if (con != null) { con.close(); con = null; } } catch (SQLException se) { se.printStackTrace(); } } return data; } public int insertSQL(String sql){//以sql语句为参数进行插入操作 Connection con = null; Statement stmt = null; ResultSet rs = null; int num=0; try { Class.forName(driver); con = DriverManager.getConnection(jdbc, name,password); stmt = con.createStatement(); num=stmt.executeUpdate(sql); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException s) { s.printStackTrace(); } finally { try { if (rs != null) { rs.close(); rs = null; } if (stmt != null) { stmt.close(); stmt = null; } if (con != null) { con.close(); con = null; } } catch (SQLException se) { se.printStackTrace(); } } return num; } } <file_sep>package operation; import java.sql.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import support.RunSQL; import database.*; public class Test { public static void main(String[] args) throws SQLException { String sql="select * from warehousestate;"; RunSQL runsql=new RunSQL(); List<Viewer> data=runsql.selectSQL(sql); System.out.println(data.get(0).getColumnCounts()); System.out.println(data.get(0).getColumn(4).equals("")); // System.out.println(data.get(0).getColumn(i)); // SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Date now=new Date(); // Timestamp time=Timestamp.valueOf(df.format(now)); // System.out.println(time); // for(int i=0;i<4;i++) // System.out.print("view.getColumn("+i+"),"); // RunSQL runsql=new RunSQL(); // String sql="select * from cargout;"; // List<Viewer> data=runsql.selectSQL(sql); // System.out.println(data.get(0)); // Timestamp time=Timestamp.valueOf(data.get(0).getColumn(3)); // System.out.println(time); // String[] values={"00220140209","123456","admin","Fiona","ÄÐ"}; // Viewer a=new Viewer(5, values); // a.setColumn(0, values[0]);a.setColumn(1, values[1]);a.setColumn(2, values[2]); // a.setColumn(3, values[3]);a.setColumn(4, values[4]); // Find<Viewer> find = new Find<Viewer>("users"); // List<Viewer> list=find.findAll(); // System.out.println(list.get(0).getColumn(0)); // System.out.println(list.get(0).getColumnName(0)); // System.out.println(list.get(0).getColumnName().length); // CreateXLS cre=new CreateXLS("users"); //String[][] str={{"c1","c2","c3"},{"1","2","3"}}; // cre.create(list); // String[] column={"u_type","u_gender"}; // String[] values={"admin","Å®"}; // List<Viewer> data=find.findBycolumns(column, values); // for(int i=0;i<data.size();i++,System.out.println()) // for(int j=0;j<data.get(i).getColumnCounts();j++) // System.out.print(data.get(i).getColumn(j)+"||"); // Find<User> find=new Find<User>("user"); // User user=find.findById("00120110327"); // List<User> users=find.findAll(); // System.out.print(user.getUName()); // GetSQL getsql=new GetSQL("users"); // String[] column={"u_name","u_gender"}; // String[] values={"aaa","male"}; // System.out.println(getsql.columnsLimit(column, values)); // Find<Viewer> find = new Find<Viewer>("warehousestate"); // // List<Viewer> data=find.findBycolumn("cargo_area", "A1"); // System.out.println(data.size()); // String sql="select * from users;"; // // RunSQL runner=new RunSQL(); // List<Viewer> data=runner.selectSQL(sql); // // System.out.println("success:"+data.get(0).toString()); // Find<Viewer> find=new Find<Viewer>("users"); // List<Viewer> da=find.findBycolumn("u_id", "00120110327"); // System.out.println(da.get(0).getColumn(3)); // Test test=new Test(); // System.out.println(test.SQL('B', 2, 3, 4, 20)); // System.out.println("cargo_mov".hashCode()); // System.out.println("cargo".hashCode()); } public String SQL(char b,int alimit,int rows,int shelfs,int seats){ String sql=""; char a='A'; String area="",row="",shelf="",seat=""; while(a<=b){ for(int areaid=1;areaid<alimit;areaid++){ area=a+""+areaid; for(int rowid=1;rowid<=rows;rowid++){ row=rowid+""; for(int shelfid=1;shelfid<=shelfs;shelfid++){ shelf=area+"R0"+shelfid+"-"+rows+"-0"+seats; for(int seatid=1;seatid<=seats;seatid++){ sql+=oneSQL(area,row,shelf,seatid); sql+="\n"; } } } } a++; } return sql; } public String oneSQL(String area,String row,String shelf,int seat){ return "insert into Warehousestate values("+"'"+area+"',"+"'"+row+"',"+"'"+shelf+"',"+"'"+seat+"','');"; } } <file_sep>package database; import java.sql.Timestamp; /** * Cargout entity. @author MyEclipse Persistence Tools */ public class Cargout implements java.io.Serializable { // Fields private String cargoId; private Timestamp cargoOutime; private String cargoOuterid; private String cargoCheckerid; // Constructors /** default constructor */ public Cargout() { } /** minimal constructor */ public Cargout(String cargoId) { this.cargoId = cargoId; } /** full constructor */ public Cargout(String cargoId, Timestamp cargoOutime, String cargoOuterid, String cargoCheckerid) { this.cargoId = cargoId; this.cargoOutime = cargoOutime; this.cargoOuterid = cargoOuterid; this.cargoCheckerid = cargoCheckerid; } // Property accessors public String getCargoId() { return this.cargoId; } public void setCargoId(String cargoId) { this.cargoId = cargoId; } public Timestamp getCargoOutime() { return this.cargoOutime; } public void setCargoOutime(Timestamp cargoOutime) { this.cargoOutime = cargoOutime; } public String getCargoOuterid() { return this.cargoOuterid; } public void setCargoOuterid(String cargoOuterid) { this.cargoOuterid = cargoOuterid; } public String getCargoCheckerid() { return this.cargoCheckerid; } public void setCargoCheckerid(String cargoCheckerid) { this.cargoCheckerid = cargoCheckerid; } }<file_sep>package operation; import java.util.List; import support.GetSQL; import support.RunSQL; import database.Cargoin; import database.Cargout; import database.CargoutDAO; import database.Viewer; //To find table cargout public class FindCargout<T> implements I_Find<Cargout>{ RunSQL runsql=new RunSQL(); Turn turn=new Turn(); String sql=""; public List<Cargout> findAll() { sql="select * from cargout;"; return turn.turnToCargout(runsql.selectSQL(sql)); } public Cargout findById(Object id) { sql="select * from cargout where cargo_id="+id+";"; return turn.turnToCargout(runsql.selectSQL(sql).get(0)); } public List<Cargout> findBycolumn(String column, Object value) { sql="select * from cargout where "+column+"="+value+";"; return turn.turnToCargout(runsql.selectSQL(sql)); } public List<Viewer> findBycolumns(String[] columns, String[] values) { RunSQL runsql=new RunSQL(); GetSQL getsql=new GetSQL("cargout"); String sql=getsql.columnsLimit(columns, values); return runsql.selectSQL(sql); } } <file_sep>package database; import java.sql.Timestamp; import java.util.List; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.criterion.Example; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A data access object (DAO) providing persistence and search support for * Cargomoving entities. Transaction control of the save(), update() and * delete() operations can directly support Spring container-managed * transactions or they can be augmented to handle user-managed Spring * transactions. Each of these methods provides additional information for how * to configure it for the desired type of transaction control. * * @see database.Cargomoving * @author MyEclipse Persistence Tools */ public class CargomovingDAO extends BaseHibernateDAO { private static final Logger log = LoggerFactory .getLogger(CargomovingDAO.class); // property constants public static final String CARGO_ID = "cargoId"; public static final String CARGO_MOVERID = "cargoMoverid"; public static final String CARGO_OLDAREA = "cargoOldarea"; public static final String CARGO_OLDROW = "cargoOldrow"; public static final String CARGO_OLDSHELF = "cargoOldshelf"; public static final String CARGO_OLDSEAT = "cargoOldseat"; public static final String CARGO_NEWAREA = "cargoNewarea"; public static final String CARGO_NEWROW = "cargoNewrow"; public static final String CARGO_NEWSHELF = "cargoNewshelf"; public static final String CARGO_NEWSEAT = "cargoNewseat"; public void save(Cargomoving transientInstance) { log.debug("saving Cargomoving instance"); try { getSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(Cargomoving persistentInstance) { log.debug("deleting Cargomoving instance"); try { getSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Cargomoving findById(java.lang.Integer id) { log.debug("getting Cargomoving instance with id: " + id); try { Cargomoving instance = (Cargomoving) getSession().get( "database.Cargomoving", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(Cargomoving instance) { log.debug("finding Cargomoving instance by example"); try { List results = getSession().createCriteria("database.Cargomoving") .add(Example.create(instance)).list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding Cargomoving instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Cargomoving as model where model." + propertyName + "= ?"; Query queryObject = getSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByCargoId(Object cargoId) { return findByProperty(CARGO_ID, cargoId); } public List findByCargoMoverid(Object cargoMoverid) { return findByProperty(CARGO_MOVERID, cargoMoverid); } public List findByCargoOldarea(Object cargoOldarea) { return findByProperty(CARGO_OLDAREA, cargoOldarea); } public List findByCargoOldrow(Object cargoOldrow) { return findByProperty(CARGO_OLDROW, cargoOldrow); } public List findByCargoOldshelf(Object cargoOldshelf) { return findByProperty(CARGO_OLDSHELF, cargoOldshelf); } public List findByCargoOldseat(Object cargoOldseat) { return findByProperty(CARGO_OLDSEAT, cargoOldseat); } public List findByCargoNewarea(Object cargoNewarea) { return findByProperty(CARGO_NEWAREA, cargoNewarea); } public List findByCargoNewrow(Object cargoNewrow) { return findByProperty(CARGO_NEWROW, cargoNewrow); } public List findByCargoNewshelf(Object cargoNewshelf) { return findByProperty(CARGO_NEWSHELF, cargoNewshelf); } public List findByCargoNewseat(Object cargoNewseat) { return findByProperty(CARGO_NEWSEAT, cargoNewseat); } public List findAll() { log.debug("finding all Cargomoving instances"); try { String queryString = "from Cargomoving"; Query queryObject = getSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public Cargomoving merge(Cargomoving detachedInstance) { log.debug("merging Cargomoving instance"); try { Cargomoving result = (Cargomoving) getSession().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Cargomoving instance) { log.debug("attaching dirty Cargomoving instance"); try { getSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Cargomoving instance) { log.debug("attaching clean Cargomoving instance"); try { getSession().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } }
287d6e8d54776941d15def7bb2aad8091bffadb6
[ "Java" ]
12
Java
YaaMe/WMS
b151442a318f29f73cd703207a6d357945afd129
ff82159614e83a40e03e711831e3cdc5252bb7f3
refs/heads/master
<file_sep>#include <iostream> #include <vector> #include <algorithm> #include <queue> #include <stack> using namespace std; int V, E; int input[1000][2]; double dinput[1000]; /*Begin Edge class */ class Edge { int v, w; public: double weight; Edge(int iv, int iw, double iweight) { v = iv; w = iw; weight = iweight; }; int either() { return v; }; int other(int vertex) { if (vertex == v) return w; else return v; }; static int cmp(Edge me, Edge that) { if (me.weight < that.weight) return -1; else if (me.weight > that.weight) return 1; else return 0; }; bool operator<(const Edge &that) const { return weight > that.weight; }; /*bool operator()(const Edge &e1, const Edge &e2) const{ return e1.weight > e2.weight; };*/ bool operator()(const Edge &lhs, const Edge &rhs) const { return lhs.weight > rhs.weight; } void printE() { cout << v << " " << w << " " << weight << endl; }; }; /*End Edge class*/ /*Begin EWGraph class*/ class EWGraph { int V; public: vector<Edge> adj[1000]; vector<Edge> edges; EWGraph(int iV) { V = iV; edges.clear(); for (int i=0; i<V; i++) { vector<Edge> tmp; adj[i] = tmp; } }; void addEdge(Edge e) { int v = e.either(); int w = e.other(v); adj[v].push_back(e); adj[w].push_back(e); edges.push_back(e); }; int getV() { return V; }; }; /*End EWGraph*/ /*Union Find class*/ class UF { int id[100001]; int N; int uF_root(int p); int sz[100001]; public: UF(int n); void uF_union(int p, int q); bool uF_find(int p, int q); }; UF::UF(int n) { memset(id,0, sizeof(id)); memset(sz,0, sizeof(id)); N = n; for (int i=0; i<N; i++) { id[i] = i; } }; int UF::uF_root(int x) { while (x != id[x]) { id[x] = id[id[x]]; x = id[x]; } return x; }; bool UF::uF_find(int p, int q) { return uF_root(p) == uF_root(q) ; }; void UF::uF_union(int p, int q) { int qr = uF_root(q); int pr = uF_root(p); if (qr==pr) return; if(sz[qr] < sz[pr]) { id[qr] = pr; sz[pr]+=sz[qr]; } else { id[pr] = qr; sz[qr]+=sz[pr]; } //id[pr] = qr; } /*End Union Find*/ struct Node { int v, w, weight; }; struct comp { bool operator()(const Node &lhs, const Node &rhs) const { return lhs.weight > rhs.weight; } }; /*Begin Kruskal*/ class KruskalMST { public: queue<Edge> mst; KruskalMST(EWGraph G) { while(!mst.empty()) { mst.pop(); } priority_queue<Edge> pq; for (vector<Edge>::iterator it = G.edges.begin(); it!=G.edges.end(); it++) { pq.push(*it); } UF uf(G.getV()); while (!pq.empty() && mst.size() < G.getV()-1) { Edge e = pq.top(); pq.pop(); int v = e.either(); int w = e.other(v); if (!uf.uF_find(v,w)) { uf.uF_union(v,w); mst.push(e); } } } }; /*End Kruskal*/ /*Begin Lazy Prim*/ class LazyPrimMST { bool marked[1000]; priority_queue<Edge> pq; void visit(EWGraph G, int v) { marked[v] = true; for (int i=0; i< G.adj[v].size(); i++) { if (!marked[G.adj[v][i].other(v)]) { pq.push(G.adj[v][i]); } } }; public: queue<Edge> mst; LazyPrimMST(EWGraph G) { while(!pq.empty()) pq.pop(); while(!mst.empty()) mst.pop(); memset(marked, false, sizeof(marked)); visit(G,0); while (!pq.empty()) { Edge e = pq.top(); pq.pop(); int v = e.either(); int w = e.other(v); if (!marked[v] && !marked[w]) continue; mst.push(e); if (!marked[v]) visit(G, v); if (!marked[w]) visit(G, w); } } }; /*End Lazy Prim*/ int main() { scanf_s("%d %d", &V, &E); for (int i=0; i<E; i++) { scanf_s("%d %d", &input[i][0], &input[i][1]); scanf_s("%lf", &dinput[i]); } EWGraph G(V); for (int i=0; i< E; i++) { Edge e(input[i][0], input[i][1], dinput[i]); G.addEdge(e); } cout << "Kruskal MST:" << endl; KruskalMST KMST(G); while (!KMST.mst.empty()) { Edge tmp = KMST.mst.front(); KMST.mst.pop(); tmp.printE(); }; cout << "Prim lazy MST:" << endl; LazyPrimMST LPMST(G); while (!LPMST.mst.empty()) { Edge tmp = LPMST.mst.front(); LPMST.mst.pop(); tmp.printE(); } return 0; }<file_sep>#include <iostream> #include <time.h> #include <set> #include <stack> using namespace std; int N, M, Q, T, test_case, Answer, tf, tps, tp, tq, tmp; int ufA[100001][2], PQ[100001][3]; set<int> s; stack<int> res; /*Union Find class*/ class UF { int id[100001]; int N; int uF_root(int p); int sz[100001]; public: UF(int n); void uF_union(int p, int q); int uF_find(int p, int q); }; UF::UF(int n) { memset(id,0, sizeof(id)); memset(sz,0, sizeof(id)); N = n; for (int i=0; i<N; i++) { id[i] = i; } }; int UF::uF_root(int x) { while (x != id[x]) { id[x] = id[id[x]]; x = id[x]; } return x; }; int UF::uF_find(int p, int q) { return uF_root(p) == uF_root(q) ? 1 : 0 ; }; void UF::uF_union(int p, int q) { int qr = uF_root(q); int pr = uF_root(p); if (qr==pr) return; if(sz[qr] < sz[pr]) { id[qr] = pr; sz[pr]+=sz[qr]; } else { id[pr] = qr; sz[qr]+=sz[pr]; } //id[pr] = qr; } int main(){ scanf("%d", &T); clock_t tStart = clock(); for (test_case = 1; test_case<= T; test_case++) { scanf("%d %d", &N, &M); memset(ufA,0,sizeof(ufA)); memset(PQ, 0, sizeof(PQ)); for (int i=0; i<M; i++) { scanf("%d %d", &ufA[i][0], &ufA[i][1]); ufA[i][0]--; ufA[i][1]--; } scanf("%d", &Q); for (int i=0; i<Q; i++) { scanf("%d", &tf); if (tf==1) { scanf("%d", &tps); PQ[i][0] = tf; PQ[i][1] = --tps; s.insert(PQ[i][1]); } else if (tf==2) { scanf("%d %d", &tp, &tq); PQ[i][0] = tf; PQ[i][1] = --tp; PQ[i][2] = --tq; } } UF uf(N); for (int i=0; i< M; i++) { if(s.find(i) == s.end()){ uf.uF_union(ufA[i][0], ufA[i][1]); } } cout << "#" << test_case << " "; for (int i=Q-1; i>=0; i--) { if (PQ[i][0] == 2) { res.push(uf.uF_find(PQ[i][1], PQ[i][2])); } else if (PQ[i][0] == 1) { uf.uF_union(ufA[PQ[i][1]][0], ufA[PQ[i][1]][1]); } } /*for (int i = 0; i< Q; i++) { if (PQ[i][0] == 2) { uf.uF_find(PQ[i][1], PQ[i][2]); } }*/ while (!res.empty()) { tmp = res.top(); cout << tmp; res.pop(); } cout << endl; } printf("Time taken: %.2fs\n", (double)(clock() - tStart) / CLOCKS_PER_SEC); return 0; }<file_sep>https://www.geeksforgeeks.org/implement-min-heap-using-stl/ https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-using-priority_queue-stl/ https://www.techiedelight.com/single-source-shortest-paths-dijkstras-algorithm/ https://medium.com/@codingfreak/data-structures-and-algorithms-problems-in-c-using-stl-7900a6ddb1d4 https://stackoverflow.com/questions/16111337/declaring-a-priority-queue-in-c-with-a-custom-comparator/48587737 <file_sep>#include <iostream> #include <vector> #include <algorithm> #include <queue> using namespace std; int V, E; int input[1000][2]; /*BEGIN Graph class */ class UGraph { int V; int E; public: vector<int> adj[1000]; UGraph(int Vx); void addEdge(int v, int w); void printUG(); int getV() { return V; } }; UGraph::UGraph(int Vx) { V = Vx; E=0; for (int i=0; i<V; i++) { vector<int> tmp; adj[i] = tmp; } } void UGraph::addEdge(int v, int w) { E++; adj[v].push_back(w); adj[w].push_back(v); } void UGraph::printUG() { for (int i=0; i< V; i++) { for (vector<int>::iterator it = adj[i].begin(); it != adj[i].end(); it++) { cout << i << " " << *it << endl; } } } /*END Graph class */ /*BEGIN DFS */ class DFSPaths { int s; bool marked[1000]; int edgeTo[1000]; void dfs(UGraph G, int v); public: DFSPaths(UGraph G, int v); bool hasPathTo(int v); vector<int> pathTo(int v); }; bool DFSPaths::hasPathTo(int v) { return marked[v]; } vector<int> DFSPaths::pathTo(int v) { vector<int> path; if (!hasPathTo(v)) return path; for (int x = v; x!=s; x = edgeTo[x]) { path.push_back(x); } path.push_back(s); reverse(path.begin(), path.end()); return path; } DFSPaths::DFSPaths(UGraph G, int v) { s = v; memset(marked, false, sizeof(marked)); memset(edgeTo, -1, sizeof(edgeTo)); dfs(G, s); } void DFSPaths::dfs(UGraph G, int v) { marked[v] = true; for (vector<int>::iterator it=G.adj[v].begin(); it != G.adj[v].end(); it++) { if (!marked[*it]) { dfs(G, *it); edgeTo[*it] = v; } } } /*END DFS*/ /*BEGIN BFS*/ class BFSPaths{ int s; bool marked[1000]; int edgeTo[1000]; void bfs(UGraph G, int v); public: BFSPaths(UGraph G, int v); bool hasPathTo(int v); vector<int> pathTo(int v); }; BFSPaths::BFSPaths(UGraph G, int v) { s = v; memset(marked, false, sizeof(marked)); memset(edgeTo, -1, sizeof(edgeTo)); bfs(G, s); } void BFSPaths::bfs(UGraph G, int v) { queue<int> bfsq; marked[v] = true; bfsq.push(v); while (!bfsq.empty()) { int tmp = bfsq.front(); bfsq.pop(); for (vector<int>::iterator it=G.adj[tmp].begin(); it!=G.adj[tmp].end(); it++) { if(!marked[*it]) { bfsq.push(*it); edgeTo[*it] = tmp; marked[*it] = true; } } } } bool BFSPaths::hasPathTo(int v) { return marked[v]; } vector<int> BFSPaths::pathTo(int v) { vector<int> path; if (!hasPathTo(v)) return path; for (int i= v; i != s; i = edgeTo[i]) { path.push_back(i); } path.push_back(s); reverse(path.begin(), path.end()); return path; } /*END BFS */ /*bool isBipartite(vector<int> adj[], int v, vector<bool>& visited, vector<int>& color) { for (int u : adj[v]) { // if vertex u is not explored before if (visited[u] == false) { // mark present vertic as visited visited[u] = true; // mark its color opposite to its parent color[u] = !color[v]; // if the subtree rooted at vertex v is not bipartite if (!isBipartite(adj, u, visited, color)) return false; } // if two adjacent are colored with same color then // the graph is not bipartite else if (color[u] == color[v]) return false; } return true; } */ class CC { bool marked[1000]; int id[1000]; int count; public: CC(UGraph G) { memset(marked, false, sizeof(marked)); memset(id, 0, sizeof(id)); count =0; for (int v=0; v<G.getV(); v++) { if (!marked[v]) { dfs(G, v); count ++; } } }; void dfs(UGraph G, int v) { marked[v] = true; id[v]= count; for (vector<int>::iterator it = G.adj[v].begin(); it != G.adj[v].end(); it++) { if (!marked[*it]) { dfs(G, *it); } } }; bool isConnected(int v, int w) { return id[v]==id[w]; }; }; int main() { scanf_s("%d %d", &V, &E); for (int i=0; i<E; i++) { scanf_s("%d %d", &input[i][0], &input[i][1]); } UGraph G(V); for (int i=0; i<E; i++) { G.addEdge(input[i][0], input[i][1]); } // G.printUG(); /*DFSPaths DFS(G, 0); BFSPaths BFS(G,0); vector<int> tmp = DFS.pathTo(6); vector<int> tmp1 = BFS.pathTo(6); cout << "DFS:" ; for (vector<int>::iterator it = tmp.begin(); it!=tmp.end(); it++) { cout << *it << " "; } cout << endl; cout << "BFS:" ; for (vector<int>::iterator it = tmp1.begin(); it!=tmp1.end(); it++) { cout << *it << " "; }*/ CC c(G); cout << c.isConnected(0,11); cout << endl; //G.printUG(); return 0; }<file_sep>#include <iostream> #include <vector> #include <algorithm> #include <queue> #include <stack> using namespace std; int V, E; int input[1000][2]; /*BEGIN Graph class */ class DGraph { int V; int E; public: vector<int> adj[1000]; DGraph(int Vx); void addEdge(int v, int w); void printDG(); DGraph reverse(); bool isCycle(); int getV(){ return V; } }; DGraph DGraph::reverse() { DGraph G(V); for (int i=0; i < V; i++) { for (vector<int>::iterator it= adj[i].begin(); it != adj[i].end(); it++) { G.addEdge(*it,i); } } return G; } bool DGraph::isCycle(){ // Create a vector to store indegrees of all // vertices. Initialize all indegrees as 0. vector<int> in_degree(V, 0); vector<int>::iterator it; // Traverse adjacency lists to fill indegrees of // vertices. This step takes O(V+E) time for (int u = 0; u < V; u++) { for (it = adj[u].begin(); it!=adj[u].end(); it++) in_degree[*it]++; } // Create an queue and enqueue all vertices with // indegree 0 queue<int> q; for (int i = 0; i < V; i++) if (in_degree[i] == 0) q.push(i); // Initialize count of visited vertices int cnt = 0; // Create a vector to store result (A topological // ordering of the vertices) vector<int> top_order; // One by one dequeue vertices from queue and enqueue // adjacents if indegree of adjacent becomes 0 while (!q.empty()) { // Extract front of queue (or perform dequeue) // and add it to topological order int u = q.front(); q.pop(); top_order.push_back(u); // Iterate through all its neighbouring nodes // of dequeued node u and decrease their in-degree // by 1 vector<int>::iterator itr; for (itr = adj[u].begin(); itr != adj[u].end(); itr++) // If in-degree becomes zero, add it to queue if (--in_degree[*itr] == 0) q.push(*itr); cnt++; } // Check if there was a cycle if (cnt != V) return true; else return false; } DGraph::DGraph(int Vx) { V = Vx; E=0; for (int i=0; i<V; i++) { vector<int> tmp; adj[i] = tmp; } } void DGraph::addEdge(int v, int w) { E++; adj[v].push_back(w); } void DGraph::printDG() { for (int i=0; i< V; i++) { for (vector<int>::iterator it = adj[i].begin(); it != adj[i].end(); it++) { cout << i << " " << *it << endl; } } } /*END Graph class */ /*BEGIN DFS */ class DFSPaths { int s; bool marked[1000]; int edgeTo[1000]; void dfs(DGraph G, int v); public: DFSPaths(DGraph G, int v); bool hasPathTo(int v); vector<int> pathTo(int v); }; bool DFSPaths::hasPathTo(int v) { return marked[v]; } vector<int> DFSPaths::pathTo(int v) { vector<int> path; if (!hasPathTo(v)) return path; for (int x = v; x!=s; x = edgeTo[x]) { path.push_back(x); } path.push_back(s); reverse(path.begin(), path.end()); return path; } DFSPaths::DFSPaths(DGraph G, int v) { s = v; memset(marked, false, sizeof(marked)); memset(edgeTo, -1, sizeof(edgeTo)); dfs(G, s); } void DFSPaths::dfs(DGraph G, int v) { marked[v] = true; for (vector<int>::iterator it=G.adj[v].begin(); it != G.adj[v].end(); it++) { if (!marked[*it]) { dfs(G, *it); edgeTo[*it] = v; } } } /*END DFS*/ /*BEGIN BFS*/ class BFSPaths{ int s; bool marked[1000]; int edgeTo[1000]; void bfs(DGraph G, int v); public: BFSPaths(DGraph G, int v); bool hasPathTo(int v); vector<int> pathTo(int v); }; BFSPaths::BFSPaths(DGraph G, int v) { s = v; memset(marked, false, sizeof(marked)); memset(edgeTo, -1, sizeof(edgeTo)); bfs(G, s); } void BFSPaths::bfs(DGraph G, int v) { queue<int> bfsq; marked[v] = true; bfsq.push(v); while (!bfsq.empty()) { int tmp = bfsq.front(); bfsq.pop(); for (vector<int>::iterator it=G.adj[tmp].begin(); it!=G.adj[tmp].end(); it++) { if(!marked[*it]) { bfsq.push(*it); edgeTo[*it] = tmp; marked[*it] = true; } } } } bool BFSPaths::hasPathTo(int v) { return marked[v]; } vector<int> BFSPaths::pathTo(int v) { vector<int> path; if (!hasPathTo(v)) return path; for (int i= v; i != s; i = edgeTo[i]) { path.push_back(i); } path.push_back(s); reverse(path.begin(), path.end()); return path; } /*END BFS */ /*BEGIN Topo sort*/ class DFOrder { bool marked[1000]; public: stack<int> reversePost; DFOrder(DGraph G) { while(!reversePost.empty()) { reversePost.pop(); } memset(marked, false, sizeof(marked)); for (int v = 0; v< G.getV(); v++) if (!marked[v]) dfs(G,v); }; void dfs(DGraph G, int v) { marked[v] = true; for (vector<int>::iterator it=G.adj[v].begin(); it != G.adj[v].end(); it++) if (!marked[*it]) dfs(G, *it); reversePost.push(v); } void printTO() { while (!reversePost.empty()) { int tmp = reversePost.top(); reversePost.pop(); cout << tmp << " "; } cout << endl; } }; /* END topo sort*/ /* BEGIN Connected component */ class CC { bool marked[1000]; int id[1000]; int count; public: CC(DGraph G) { memset(marked, false, sizeof(marked)); memset(id, 0, sizeof(id)); count =0; DFOrder DFO(G.reverse()); while (!DFO.reversePost.empty()) { int tmp = DFO.reversePost.top(); DFO.reversePost.pop(); if (!marked[tmp]) { dfs(G,tmp); count++; } } }; void dfs(DGraph G, int v) { marked[v] = true; id[v]= count; for (vector<int>::iterator it = G.adj[v].begin(); it != G.adj[v].end(); it++) { if (!marked[*it]) { dfs(G, *it); } } }; bool isConnected(int v, int w) { return id[v]==id[w]; }; }; /* END Connected component*/ int main() { scanf_s("%d %d", &V, &E); for (int i=0; i<E; i++) { scanf_s("%d %d", &input[i][0], &input[i][1]); } DGraph G(V); for (int i=0; i<E; i++) { G.addEdge(input[i][0], input[i][1]); } G.printDG(); DFSPaths DFS(G, 0); BFSPaths BFS(G,0); vector<int> tmp = DFS.pathTo(2); vector<int> tmp1 = BFS.pathTo(2); cout << "DFS:" ; for (vector<int>::iterator it = tmp.begin(); it!=tmp.end(); it++) { cout << *it << " "; } cout << endl; cout << "BFS:" ; for (vector<int>::iterator it = tmp1.begin(); it!=tmp1.end(); it++) { cout << *it << " "; } cout << endl; cout << G.isCycle(); cout << endl; //DFOrder DFO(G); //DFO.printTO(); CC c(G); cout << c.isConnected(0,1); cout << endl; //G.printUG(); return 0; }<file_sep>#include <iostream> #include <vector> #include <algorithm> #include <stack> #include <time.h> using namespace std; int T, test_case, N, Q, P, Answer, tmp; long long int Input[1001][2], Qs[101][2]; class Point2D { public: long long int x; long long int y; Point2D(long long int a, long long int b); void setP(long long int a, long long int b); static bool ccv(Point2D a, Point2D b, Point2D c); static bool cp_Yc(Point2D a, Point2D b); static bool cp_Polar(Point2D a, Point2D b); void print() { cout << x << " " << y << endl; } }; Point2D p(0,0); vector <Point2D> vPoints; stack <Point2D> CH; vector <Point2D> tmp1; bool Point2D::cp_Polar(Point2D a, Point2D b) { long long int dy1 = a.y - p.y; long long int dy2 = b.y - p.y; if (dy1==0 && dy2==0) return false; else if (dy1>=0 && dy2<0) return false; else if (dy2>=0 && dy1<0) return true; return ccv(p,a,b); } bool Point2D::cp_Yc(Point2D a, Point2D b) { return (a.y < b.y); } bool Point2D::ccv(Point2D a, Point2D b, Point2D c) { long long int area2 = (b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x); if (area2 <= 0) return false; //clockwise return true; //counter-clockwise //else return 0; //collinear } Point2D::Point2D(long long int a, long long int b) { x = a; y = b; }; void Point2D::setP(long long int a, long long int b) { x = a; y = b; } int main(){ Point2D pTmp(0,0); scanf_s("%d", &T); clock_t tStart = clock(); for (test_case = 1; test_case <= T; test_case++) { scanf_s("%d", &N); memset(Input,0, sizeof(Input)); memset(Qs,0, sizeof(Qs)); vPoints.clear(); for (int i=0; i< N; i++) { scanf_s("%lld %lld", &Input[i][0], &Input[i][1]); pTmp.setP(Input[i][0], Input[i][1]); //cout << Input[i][0] << " " << Input[i][1] << endl; //cout << pTmp.x << " " << pTmp.y << endl; vPoints.push_back(pTmp); } scanf_s("%d", &Q); for (int i=0; i<Q; i++) { scanf_s("%lld %lld", &Qs[i][0], &Qs[i][1]); } sort(vPoints.begin(), vPoints.end(), Point2D::cp_Yc); p.setP(vPoints[0].x, vPoints[0].y); sort(vPoints.begin(), vPoints.end(), Point2D::cp_Polar); CH.push(vPoints[0]); CH.push(vPoints[1]); for (int i=2; i<N; i++) { Point2D top = CH.top(); CH.pop(); while (!CH.empty() && !Point2D::ccv(CH.top(),top, vPoints[i]) ){ top = CH.top(); CH.pop(); } CH.push(top); CH.push(vPoints[i]); } tmp1.empty(); while (!CH.empty()) { tmp1.push_back(CH.top()); CH.pop(); } Answer = 0; for (int i=0; i< Q; i++) { Point2D qNode(Qs[i][0], Qs[i][1]); if (qNode.y>=p.y) { vector <Point2D> tmp2(tmp1); reverse(tmp2.begin(), tmp2.end()); tmp2.push_back(qNode); //sort(tmp2.begin(),tmp2.end(), Point2D::cp_Yc); sort(tmp2.begin(), tmp2.end(), Point2D::cp_Polar); if (tmp2.rbegin()->x != qNode.x || tmp2.rbegin()->x != qNode.x) { for (int j=0; j<tmp2.size()-1; j++) { if (tmp2[j].x == qNode.x && tmp2[j].y == qNode.y) { if (Point2D::ccv(tmp2[j-1],tmp2[j], tmp2[j+1])) Answer++; } } } else { Answer++; } } else { Answer++; } } cout << "#" << test_case << " " << Answer << endl; //for (vector <Point2D>::iterator it = vPoints.begin(); it!=vPoints.end(); it++) { // //cout << it->x << " " << it->y << endl; // it->print(); //} } printf("Time taken: %.2fs\n", (double)(clock() - tStart) / CLOCKS_PER_SEC); return 0; }
7eecbc24f04acb3c976f9ebd2e958c6e4d70ff28
[ "Markdown", "C++" ]
6
C++
Cypherman1/SWTPro
3c28ef4a541ab96fed9c01b27304fb4e92a530c8
1a829f64adbaa2fd0bfc012c9be5d5b5986b80c8
refs/heads/master
<repo_name>bluedoctor/Asura<file_sep>/Asura/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Asura.Database; using Microsoft.AspNetCore.Mvc; using Asura.Models; using Asura.Service; using Microsoft.ApplicationInsights.AspNetCore.Extensions; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Options; namespace Asura.Controllers { public class HomeController : Controller { private SiteConfig Config; private AsuraContext db; public HomeController(IOptions<SiteConfig> option, AsuraContext context) { Config = option.Value; db = context; } [Route("")] [Route("index")] [Route("page/{page}")] [Route("page/{page}.{ext}")] public async Task<IActionResult> Index(int page, string ext) { if (!string.IsNullOrEmpty(ext)) { if (ext.ToLower() != "html") return NotFound(); } page = page <= 0 ? 1 : page; ViewData["Blogger"] = Config.Blogger; ViewData["Qiniu"] = Config.QiNiu.Domain; ViewData["Title"] = $"{Config.Blogger.Btitle} | {Config.Blogger.SubTitle}"; ViewData["Description"] = $"博客首页,{Config.Blogger.SubTitle}"; var pageSize = 10; var viewModel = new HomeViewModel(); var startRow = (page - 1) * pageSize; var query = await db.Articles.Where(w => w.IsDraft == false).OrderByDescending(p => p.CreateTime) .Skip(startRow) .Take(pageSize).ToListAsync(); viewModel.Articles = query; viewModel.Prev = page - 1; viewModel.Next = (await db.Articles.Where(w => w.IsDraft == false).CountAsync()) > page * pageSize + 1 ? page + 1 : 0; return View(viewModel); } [Route("p/{slug}")] [Route("p/{slug}.{ext}")] public async Task<IActionResult> Article(string slug, string ext = "html") { if (!string.IsNullOrEmpty(ext)) { ext = ext.ToLower(); } var article = new Article(); if (ext == "html" || ext == "md") { article = await db.Articles .Include(p => p.SerieArticle).ThenInclude(se => se.Serie) .Include(p => p.TagArticles).ThenInclude(se => se.Tag) .Where(w => (w.IsDraft == false && w.Slug == slug)) .SingleOrDefaultAsync(); } if (article == null) return NotFound(); // 请求html页面 if (ext == "html") { ViewData["Title"] = $"{article.Title} | {Config.Blogger.Btitle}"; ViewData["Blogger"] = Config.Blogger; ViewData["Qiniu"] = Config.QiNiu.Domain; ViewData["Description"] = $"{article.Desc},{Config.Blogger.SubTitle}"; var viewModel = new ArticleViewModel(); List<SerieViewModel> series = new List<SerieViewModel>(); foreach (var sa in article.SerieArticle) { var svm = new SerieViewModel { Name = sa.Serie.Name, SerieId = sa.SerieId, Articles = await db.SerieArticles .Include(p => p.Article) .Where(pt => pt.SerieId == sa.SerieId) .Select(pt => new ArticleSlugViewModel { Slug = pt.Article.Slug, Title = pt.Article.Title, CreateTime = pt.Article.CreateTime, }) .ToListAsync() }; series.Add(svm); } viewModel.Series = series; viewModel.Article = article; viewModel.Tags = article.TagArticles.Select(s => s.Tag).ToList(); viewModel.Prev = await db.Articles .Where(w => (w.IsDraft == false && w.ArticleId == article.ArticleId - 1)) .Select(ar => new ArticleSlugViewModel { Slug = ar.Slug, Title = ar.Title, CreateTime = ar.CreateTime, }) .SingleOrDefaultAsync(); viewModel.Next = await db.Articles .Where(w => (w.IsDraft == false && w.ArticleId == article.ArticleId + 1)) .Select(ar => new ArticleSlugViewModel { Slug = ar.Slug, Title = ar.Title }) .SingleOrDefaultAsync(); return View(viewModel); } return NotFound(); } [Route("series")] [Route("series.{ext}")] public async Task<IActionResult> Series(string ext = "html") { if (!string.IsNullOrEmpty(ext)) { if (ext.ToLower() != "html") return NotFound(); } ViewData["Blogger"] = Config.Blogger; ViewData["Qiniu"] = Config.QiNiu.Domain; ViewData["Title"] = $"专题 | {Config.Blogger.Btitle}"; ViewData["Description"] = $"专题列表,,{Config.Blogger.SubTitle}"; ViewData["SeriesSubTitle"] = Config.Blogger.SeriesSubTitle; List<SerieViewModel> viewModels = new List<SerieViewModel>(); var series = await db.Series .Include(i => i.SerieArticle) .ToListAsync(); foreach (var serie in series) { var svm = new SerieViewModel { Desc = serie.Desc, Name = serie.Name, SerieId = serie.SerieId, Articles = await db.SerieArticles .Include(p => p.Article) .Where(pt => pt.SerieId == serie.SerieId) .Select(pt => new ArticleSlugViewModel { Slug = pt.Article.Slug, Title = pt.Article.Title, CreateTime = pt.Article.CreateTime, }) .ToListAsync() }; viewModels.Add(svm); } return View(viewModels); } public IActionResult Error() { return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier}); } } }<file_sep>/Asura/Comm/CustomTagHelper.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Markdig; using Markdig.Extensions.AutoIdentifiers; using Markdig.Renderers; using Markdig.Renderers.Html; using Markdig.Syntax; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; namespace Asura.TagHelpers { [HtmlTargetElement("markdown")] public class MarkdownTagHelper : TagHelper { [HtmlAttributeName("text")] public string Text { get; set; } [HtmlAttributeName("source")] public ModelExpression Source { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { if (Source != null) { Text = Source.Model.ToString(); } var pipeline = new MarkdownPipelineBuilder() .UseNoFollowLinks() .UseMediaLinks() .UseAutoIdentifiers(AutoIdentifierOptions.GitHub) .Build(); var doc = Markdown.Parse(Text, pipeline); var headings = doc.Descendants<HeadingBlock>().ToList(); var lastLevel = 1; foreach (var heading in headings) { if (heading.Level == lastLevel + 1) { } // writer.Write($"](#{heading.GetAttributes().Id})"); } var html = string.Empty; using (var writer = new StringWriter()) { var htmlWriter = new HtmlRenderer(writer) {EnableHtmlForInline = true}; htmlWriter.Render((MarkdownObject) doc); html = writer.ToString(); } output.TagName = "div"; output.Content.SetHtmlContent(html); output.TagMode = TagMode.StartTagAndEndTag; } public static void Render<T>(T model, Func<Action<T>, Action<T>> f) { Fix(f)(model); } public static Action<T> Fix<T>(Func<Action<T>, Action<T>> f) { return x => f(Fix(f))(x); } } [HtmlTargetElement("markplain")] public class String2HtmlTagHelper : TagHelper { [HtmlAttributeName("text")] public string Text { get; set; } [HtmlAttributeName("source")] public ModelExpression Source { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { if (Source != null) { Text = Source.Model.ToString(); } var result = Markdown.ToPlainText(Text); output.TagName = "p"; output.Content.SetHtmlContent(result); output.TagMode = TagMode.StartTagAndEndTag; } } }<file_sep>/Asura/Startup.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Asura.Database; using Asura.Service; using WilderMinds.MetaWeblog; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; namespace Asura { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMetaWeblog<AsuraMetaWeblogService>(); services.AddDbContext<AsuraContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); //添加options services.AddOptions(); services.Configure<SiteConfig>(Configuration.GetSection("SiteConfig")); // 增加内存中的缓存 services.AddMemoryCache(); //添加MVC services.AddMvc(); // 压缩 services.AddResponseCompression(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // if (env.IsDevelopment()) // { // app.UseDeveloperExceptionPage(); // } // else // { // app.UseExceptionHandler("/Home/Error"); // } app.UseDeveloperExceptionPage(); app.UseStaticFiles(); app.UseMetaWeblog("/api/xmlrpc"); app.UseMvcWithDefaultRoute(); //压缩 app.UseResponseCompression(); } } }<file_sep>/README.MD # Asura 这是个.net core mvc 和entityframeworkcore 用 sqlite数据库写的单人博客 DEMO: [https://dev.luodaoyi.com](https://dev.luodaoyi.com) >正在慢慢完成中。 感谢[https://imququ.com/](https://imququ.com/)和[https://deepzz.com/](https://deepzz.com/) 两位大佬 他们的博客几乎是瞬间打开 所以我也想用 .net core实现一遍。以便于熟悉和巩固asp.net core的和entityframeworkcore相关的知识,并且拥有一个速度非常非常快的博客系统 ## 开发调试 ``` dotnet watch run ``` ## 发布部署 ``` dotnet publish -c Release -o Publish --runtime ubuntu.16.04-x64 ``` 此方式发布后目标操作系统无需安装运行时 支持的系统 ### windows - 可移植 - `win-x86` - `win-x64` - Windows 7 / Windows Server 2008 R2 - `win7-x64` - `win7-x86` - Windows 8 / Windows Server 2012 - `win8-x64` - `win8-x86` - `win8-arm` - Windows 8.1 / Windows Server 2012 R2 - `win81-x64` - `win81-x86` - `win81-arm` - Windows 10 / Windows Server 2016 - `win10-x64` - `win10-x86` - `win10-arm` - `win10-arm64` ### Linux - 可移植 - `linux-x64` - CentOS - `centos-x64` - `centos.7-x64` - Debian - `debian-x64` - `debian.8-x64` - Fedora - `fedora-x64` - `fedora.24-x64` - `fedora.25-x64`(.NET Core 2.0 或更高版本) - `fedora.26-x64`(.NET Core 2.0 或更高版本) - Gentoo(.NET Core 2.0 或更高版本) - `gentoo-x64` - openSUSE - `opensuse-x64` - `opensuse.42.1-x64` - Oracle Linux - `ol-x64` - `ol.7-x64` - `ol.7.0-x64` - `ol.7.1-x64` - `ol.7.2-x64` - Red Hat Enterprise Linux - `rhel-x64` - `rhel.6-x64`(.NET Core 2.0 或更高版本) - `rhel.7-x64` - `rhel.7.1-x64` - `rhel.7.2-x64` - `rhel.7.3-x64`(.NET Core 2.0 或更高版本) - `rhel.7.4-x64`(.NET Core 2.0 或更高版本) - Tizen(.NET Core 2.0 或更高版本) - `tizen` - Ubuntu - `ubuntu-x64` - `ubuntu.14.04-x64` - `ubuntu.14.10-x64` - `ubuntu.15.04-x64` - `ubuntu.15.10-x64` - `ubuntu.16.04-x64` - `ubuntu.16.10-x64` - Ubuntu 衍生内容 - `linuxmint.17-x64` - `linuxmint.17.1-x64` - `linuxmint.17.2-x64` - `linuxmint.17.3-x64` - `linuxmint.18-x64` - `linuxmint.18.1-x64`(.NET Core 2.0 或更高版本) ## macos - `osx-x64`(.NET 核心 2.0 或更高版本,最低版本是`osx.10.12-x64`) - `osx.10.10-x64` - `osx.10.11-x64` - `osx.10.12-x64`(.NET Core 1.1 或更高版本) - `osx.10.13-x64` <file_sep>/Asura/Models/PageViewModel.cs using System; using System.Collections.Generic; using Asura.Database; namespace Asura.Models { public class HomeViewModel { public List<Article> Articles { get; set; } public int Prev { get; set; } public int Next { get; set; } } public class ArticleViewModel { public Article Article { get; set; } public List<SerieViewModel> Series { get; set; } public List<Tag> Tags { get; set; } public ArticleSlugViewModel Prev { get; set; } public ArticleSlugViewModel Next { get; set; } } public class ArticleSlugViewModel { public string Slug { get; set; } public string Title { get; set; } public DateTime CreateTime { get; set; } } public class SerieViewModel { public List<ArticleSlugViewModel> Articles { get; set; } public int SerieId { get; set; } public string Name { get; set; } public string Desc { get; set; } } }
14c4335141790a0ae83b637aa857172d8e060687
[ "Markdown", "C#" ]
5
C#
bluedoctor/Asura
53d1b5de50e550818fd52720e0468aad44ff873f
2aa6baa9988ec94ae94670b9996c501e3b567901
refs/heads/master
<file_sep>package powtorka.dziedziczenie; public interface Sprinter { void sprint(); } <file_sep>package funkcyjne; @FunctionalInterface public interface Checker { boolean check(Czlowiek czlowiek); } <file_sep>package enumy; public enum Rozmiar { S(50,100), M(55,110), L(60,120), XL(100,200); private int dlugosc; private int szerokosc; Rozmiar(int dlugosc, int szerokosc) { this.dlugosc = dlugosc; this.szerokosc = szerokosc; } public int getDlugosc() { return dlugosc; } public int getSzerokosc() { return szerokosc; } } <file_sep>package powtorka.dziedziczenie; public class Kalkulator { public int potegowanie(int podstawa, int potega) { int wynik = podstawa; for (int i = 0; i < potega; i++) { wynik = mnozenie(wynik,podstawa); } return wynik; } private int mnozenie(int a, int b) { return a * b; } } <file_sep>package wyjatki; public class SdaException extends Exception{ } <file_sep>package enumy.zadanie; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class ProductServiceTest { private ProductService productService; @BeforeEach void setUp() { Product product = new Product("jablko", 50.0, 1, ProductType.OWOCE); Product product1 = new Product("gruszka", 50.0, 1, ProductType.OWOCE); Product product2 = new Product("kurczak", 50.0, 1, ProductType.MIESO); Product product3 = new Product("marchewka", 50.0, 1, ProductType.WARZYWA); List<Product> products = Arrays.asList(product, product1, product2, product3); productService = new ProductService(products); } @Test void testWhenRetrievingFruitsThenGetFruits() { List<Product> owoce = productService.retrieveFruits(); for (Product product : owoce) { // System.out.println(product.getProductType() + " " +product.getName()); assertEquals(ProductType.OWOCE, product.getProductType()); } } } <file_sep>package enumy.calculator; public enum Operation { PLUS, MINUS, DODATKOWA_OPERACJA; double calculate(double x, double y) { switch (this) { case PLUS: return x + y; case MINUS: return x - y; default: throw new AssertionError("Nieznana operacja: " + this); } } } <file_sep>package powtorka2; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.*; class MeetingTest { private Meeting meeting; @BeforeEach void setUp() { meeting = new Meeting("opis", "adres"); } @Test void testIfDefaultDateIsNow() { LocalDate now = LocalDate.now(); LocalDate date = meeting.getDate(); if (now.equals(date)) { //test przeszedl } else { //test nie przeszedl } assertEquals(LocalDate.now(), meeting.getDate(), "Domyslna data powinna być dzisiejsza!"); // assertTrue(now.equals(date)); // assertFalse(!now.equals(date)); } @Test void testIfDefaultRoomCapacityIs18() { assertEquals(18, meeting.getSize(), "Domyslny rozmiar sali to 18!"); } @Test void testWhenDelayingMeetingThenMeetingIsPostponed() { meeting.delayMeeting(5); assertEquals(LocalDate.now().plusDays(5), meeting.getDate()); } //dodaj test ktory sprawdza czy przy opoznienia spotkania o 0 dni data spotkania sie nie zmienia } <file_sep>package wyjatki.zadanie; public class Shop { private int iloscVodki; public void sellVodka(Person person) throws InvalidAgeException, NoVodkaException { if (person.getAge() < 18) { throw new InvalidAgeException("koles nie masz 18 lat"); } if (iloscVodki == 0) { throw new NoVodkaException("brak wodki"); } iloscVodki--; // iloscVodki = iloscVodki - 1; System.out.println("sold"); } public Shop(int iloscVodki) { this.iloscVodki = iloscVodki; } } <file_sep>package wyjatki.zadanie; public class Test { public static void main(String[] args) { Shop shop = new Shop(2); Person pelnoletni = new Person(20); Person niepelnoletni = new Person(15); try { shop.sellVodka(pelnoletni); shop.sellVodka(niepelnoletni); // // shop.sellVodka(pelnoletni); shop.sellVodka(pelnoletni); } catch (InvalidAgeException e) { System.out.println("Wykop ze sklepu"); } catch (NoVodkaException e) { System.out.println("Przepraszamy, dostawa niedlugo"); } } } <file_sep>package funkcyjne; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; public class Test { public static void main(String[] args) { Czlowiek czlowiek = new Czlowiek(20, "Mateusz"); Czlowiek czlowiek1 = new Czlowiek(15, "Adam"); Czlowiek czlowiek2 = new Czlowiek(19, "JakiesImie"); Checker checker = czl -> { return true; }; List<Czlowiek> czlowieki = Arrays.asList(czlowiek, czlowiek1, czlowiek2); List<String> listaImion = czlowieki.stream().map(czl1 -> { return czl1.getImie(); }).collect(Collectors.toList()); List<String> listaImion2 = czlowieki.stream().map(Czlowiek::getImie).collect(Collectors.toList()); listaImion.forEach(imie -> System.out.println(imie)); // // System.out.println(listaImion); czlowieki.forEach(p -> System.out.println(p.getImie())); czlowieki.forEach(System.out::println); for (Czlowiek czlowiek3 : czlowieki) { System.out.println(czlowiek3.getImie()); } // drukuj(czlowieki, czl -> { // return czl.getAge() >= 18; // }); // // czlowieki.stream() // .filter(p -> p.getAge() >= 18) // .filter(p -> p.getAge() < 30).map(p-> p.getImie()) // .forEach(p -> System.out.println(p)); // a -> { } // // Checker ageChecker = czlowiek4 -> {return true;}; // // drukuj(czlowieki, czlowiek3 -> {return false;}); // // // // // drukuj(czlowieki, czlowiek4 -> {System.out.println(czlowiek4); return czlowiek4.getAge() > 18;}); Optional<Czlowiek> mateusz = czlowieki.stream().filter(czlowiek3 -> czlowiek3.getImie().equals("Mateusz")).findFirst(); if (mateusz.isPresent()) { System.out.println(mateusz.get()); } mateusz.orElse(new Czlowiek(1, "Mateusz")); } public static void drukuj(List<Czlowiek> czlowieki, Predicate<Czlowiek> checker) { for (Czlowiek czlowiek : czlowieki) { if (checker.test(czlowiek)) { System.out.println(czlowiek.getImie()); } } } } <file_sep>package funkcyjne; public class StringProcessor { private StringOperation stringOperation; public String process(String input) { return stringOperation.operation(input); } public StringProcessor() { stringOperation = input -> input; //input -> { return input;}; } public void setStringOperation(StringOperation stringOperation) { this.stringOperation = stringOperation; } } // (a,b) -> {}; <file_sep>package generyki; public class Gdanszczanin extends Mieszkaniec { public void spacerujPoStarowce() { System.out.println("spaceruje po starowce"); } } <file_sep>package enumy; public class Koszulka { private Rozmiar rozmiar; public Rozmiar getRozmiar() { return rozmiar; } public void setRozmiar(Rozmiar rozmiar) { this.rozmiar = rozmiar; } } <file_sep>package generyki; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { List lista = new ArrayList(); lista.add("napis"); lista.add(123); for (Object element : lista) { System.out.println(((String) element).length()); } List<String> listaZGenerykiem = new ArrayList<String>(); listaZGenerykiem.add("napis"); // listaZGenerykiem.add(123); for (String element : listaZGenerykiem) { System.out.println(element.length()); } } } <file_sep>package powtorka.dziedziczenie; public abstract class Zawodnik { private int numer; private String imie; public void biegaj() { System.out.println("biegam"); } public abstract void kopnij(); public int getNumer() { return numer; } public void setNumer(int numer) { this.numer = numer; } public String getImie() { return imie; } public void setImie(String imie) { this.imie = imie; } // private void prywatnaMetoda() { // // } // // public void publicznaMetoda() { // prywatnaMetoda(); // } } <file_sep>package generyki; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class TestMieszkancow { public static void main(String[] args) { // Miasto miasto = new Miasto("cokolwiek"); // List<Mieszkaniec> mieszkaniecList = new ArrayList<>(); // Mieszkaniec mieszkaniec = new Mieszkaniec(); // mieszkaniec.setId(1); // mieszkaniec.setImie("Mateusz"); // Mieszkaniec mieszkaniec1 = new Mieszkaniec(); // mieszkaniec1.setId(2); // mieszkaniec1.setImie("Adam"); // mieszkaniecList.add(mieszkaniec); // mieszkaniecList.add(mieszkaniec1); // miasto.setMieszkancy(mieszkaniecList); // // //// Miasto gdansk = new Miasto("Gdansk"); //// Miasto gdynia = new Miasto("Gdynia"); // // Gdanszczanin gdanszczanin = new Gdanszczanin(); // mieszkaniecList.add(gdanszczanin); // // Miasto<Gdanszczanin> gdansk = new Miasto<Gdanszczanin>("Gdansk"); // // Miasto<Gdynianin> gdynia = new Miasto<Gdynianin>("Gdynia"); // //// Miasto<Object> miastoObiektow = new Miasto<>("Obiekty"); //// //// Miasto<String> miastoString = new Miasto<>("miastoStringow"); // // // // // // List<String> listaStringow = new ArrayList<>(); // List list = new ArrayList(); // // // listaStringow.add("tekst"); //// list. // List<Double> doubles = new ArrayList<>(); doubles.add(1.2); doubles.add(1.3); System.out.println(sum(doubles)); List<Integer> integers = Arrays.asList(1,2,3,4); sum(integers); sum(Arrays.asList(1,2,3,4)); List<Mieszkaniec> lista = new ArrayList<>(); List<Gdanszczanin> gdanszczanins = new ArrayList<>(); test(lista); // test(gdanszczanins); } private static void test(List<? super Mieszkaniec> mieszkancy) { } private static double sum(List<? extends Number> doubles) { double sum = 0.0; for (Number liczba : doubles) { sum+=liczba.doubleValue(); } return sum; } } <file_sep>package wyjatki; import java.io.IOException; public class Testowa { public static void main(String[] args) { boolean zmienna = true; // try { nawiazPolaczenieZBaza(); metodaKtoraRzucaCzasemWyjatek(zmienna); } catch (IOException e) { System.out.println("Polecial wyjatek uzywam innej metody"); metodaBezWyjatku(zmienna); zerwijPolaczenieZBaza(); } finally { zerwijPolaczenieZBaza(); } try (DBConnector connector = new DBConnector()) { metodaKtoraRzucaCzasemWyjatek(zmienna); } catch (Exception e) { System.out.println("Polecial wyjatek uzywam innej metody"); metodaBezWyjatku(zmienna); } } private static void nawiazPolaczenieZBaza() { System.out.println("LACZE Z BAZA"); } private static void zerwijPolaczenieZBaza() { System.out.println("KONCZE POLACZENIE Z BAZA DANYCH"); } private static void metodaBezWyjatku(boolean zmienna) { if (zmienna) { throw new RuntimeException(); } System.out.println("OK"); } private static void metodaKtoraRzucaCzasemWyjatek(boolean zmienna) throws IOException { if (zmienna) { throw new IOException(); } System.out.println("BEZ WYJATKU OK"); } } <file_sep>package pliki; import java.io.*; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Application { public static void main(String[] args) { try { PrintWriter printWriter = new PrintWriter("file.txt"); printWriter.println("<NAME>.."); printWriter.println("<NAME>.."); printWriter.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } File file = new File("file.txt"); try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } // // try { // BufferedReader reader = new BufferedReader(new FileReader("file.txt")); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } System.out.println(file.getName()); System.out.println(file.isFile()); System.out.println(file.isHidden()); System.out.println(file.isDirectory()); System.out.println(file.getAbsolutePath()); List<String> stolice = Arrays.asList("Warszawa", "Berlin", "Praga", "Wiedeń", "Oslo"); try { PrintWriter printWriter = new PrintWriter("capitols.txt"); stolice.forEach(printWriter::println); // stolica -> printWriter.println(stolica); // printWriter.print(stolice); // zapisze toStringa obiektu printWriter.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } <file_sep>package powtorka.dziedziczenie; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Boisko { public static void main(String[] args) { Bramkarz bramkarz = new Bramkarz(); Pilkarz pilkarz = new Pilkarz(); // Zawodnik zawodnik = new Zawodnik(); Zawodnik bramkarz1 = new Bramkarz(); Zawodnik pilkarz1 = new Pilkarz(); // Bramkarz bramkarz2 = (Bramkarz)bramkarz1; // bramkarz2.bron(); // // Bramkarz bramkarz3 = (Bramkarz) pilkarz1; // bramkarz3.bron(); bramkarz1.kopnij(); pilkarz1.kopnij(); Sprinter bramkarzSprinter = new Bramkarz(); Sprinter pilkarzSprinter = new Pilkarz(); niechWszyscySprinterzyBiegajaSprintem(Arrays.asList(bramkarzSprinter, pilkarzSprinter)); List<Bramkarz> bramkarzList = Arrays.asList(bramkarz); // niechWszyscySprinterzyBiegajaSprintem(bramkarzList); // niechWszyscySprinterzyBiegajaSprintem(Arrays.asList(bramkarz)); } public static void niechWszyscySprinterzyBiegajaSprintem(List<Sprinter> sprinterList) { for (Sprinter sprinter : sprinterList) { sprinter.sprint(); } } } <file_sep>package adnotacje; public class Test { private String zmienna; public Test() { zmienna = "tekst"; } public void method1() { System.out.println("To jest tresc zmiennej zmienna: " + zmienna); } private void method2() { System.out.println("Prywatna metoda"); } public void method3(int n) { System.out.println("Metoda z intem : " + n); } } <file_sep>package enumy.zadanie; import java.util.ArrayList; import java.util.List; public class ProductService { private final List<Product> products; public List<Product> retrieveFruits() { List<Product> owoce = new ArrayList<>(); for (Product product : products) { if (ProductType.OWOCE == product.getProductType()) { owoce.add(product); } } return owoce; } public ProductService(List<Product> products) { this.products = products; } } <file_sep>package adnotacje; @SuperKlasa(element = "asd") public class KlasaTestowa { }
bccf58c7ac22798f397944809d46fcf919c30382
[ "Java" ]
23
Java
Javagda40z/gda40
b5cb13dc40c6c786819dc23e16b49690aea41689
368e4b0b40fe2265daf7e97838f815e3b14d24e4
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 18-12-29 下午6:07 # @Author : Gavin # @Site : # @File : douyin.py # @Software: PyCharm import requests from bs4 import BeautifulSoup from tqdm import tqdm import time """ 下载文件参数url和文件的全路径 """ def download_file(src, file_path): # 响应体工作流 r = requests.get(src, stream=True) # 打开文件 f = open(file_path, "wb") # for chunk in r.iter_content(chunk_size=512): # if chunk: # f.write(chunk) for data in tqdm(r.iter_content(chunk_size=512)): # tqdm进度条的使用,for data in tqdm(iterable) f.write(data) return file_path headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' } # 保存路径 save_path = "/zhangkun/PycharmProjects/wangyisong/douyin/" url = "https://kuaiyinshi.com/hot/music/?source=dou-yin&page=1" # 获取响应 res = requests.get(url, headers=headers) # 使用beautifulsoup解析 soup = BeautifulSoup(res.text, 'lxml') # 选择标签获取最大页数 max_page = soup.select('li.page-item > a')[-2].text # 循环请求 song_path = '/zhangkun/PycharmProjects/wangyisong/songs' for page in range(int(max_page)): page_url = "https://kuaiyinshi.com/hot/music/?source=dou-yin&page={}".format(page + 1) page_res = requests.get(page_url, headers=headers) soup = BeautifulSoup(page_res.text, 'lxml') lis = soup.select('li.rankbox-item') singers = soup.select('div.meta') music_names = soup.select('h2.tit > a') for i in range(len(lis)): music_url = "http:" + lis[i].get('data-audio') print("歌名:" + music_names[i].text, singers[i].text, "链接:" + music_url) song_name = music_names[i].text try: download_file(music_url, save_path + music_names[i].text + ' - ' + singers[i].text.replace('/', ' ') + ".mp3") except: pass with open(song_path,'a') as f: f.write(song_name + '\n') exit() print("第{}页完成~~~".format(page + 1)) time.sleep(1)<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 18-12-28 下午6:08 # @Author : Gavin # @Site : # @File : song_id.py # @Software: PyCharm import csv import re import time import urllib import requests, os, json, base64 from bs4 import BeautifulSoup from scrapy.selector import Selector from binascii import hexlify from Crypto.Cipher import AES class Encrypyed(): """ 传入歌曲的ID,加密生成'params'、'encSecKey 返回 """ def __init__(self): self.pub_key = '010001' self.modulus = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7' self.nonce = '0CoJUm6Qyw8W8jud' def create_secret_key(self, size): return hexlify(os.urandom(size))[:16].decode('utf-8') def aes_encrypt(self, text, key): key = key.encode('utf-8') iv = b'0102030405060708' pad = 16 - len(text) % 16 text = text + pad * chr(pad) text = text.encode('utf-8') encryptor = AES.new(key, AES.MODE_CBC, iv) result = encryptor.encrypt(text) result_str = base64.b64encode(result).decode('utf-8') return result_str def rsa_encrpt(self, text, pubKey, modulus): text = text[::-1] rs = pow(int(hexlify(text.encode('utf-8')), 16), int(pubKey, 16), int(modulus, 16)) return format(rs, 'x').zfill(256) def work(self, ids, br=128000): text = {'ids': [ids], 'br': br, 'csrf_token': ''} text = json.dumps(text) i = self.create_secret_key(16) encText = self.aes_encrypt(text, self.nonce) encText = self.aes_encrypt(encText, i) encSecKey = self.rsa_encrpt(i, self.pub_key, self.modulus) data = {'params': encText, 'encSecKey': encSecKey} return data def search(self, text): text = json.dumps(text) i = self.create_secret_key(16) encText = self.aes_encrypt(text, self.nonce) encText = self.aes_encrypt(encText, i) encSecKey = self.rsa_encrpt(i, self.pub_key, self.modulus) data = {'params': encText, 'encSecKey': encSecKey} return data class search(): ''' 跟歌单直接下载的不同之处,1.就是headers的referer 2.加密的text内容不一样! 3.搜索的URL也是不一样的 输入搜索内容,可以根据歌曲ID进行下载,大家可以看我根据跟单下载那章,自行组合 ''' def __init__(self): self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Host': 'music.163.com', 'Referer': 'http://music.163.com/search/'} ###!!注意,搜索跟歌单的不同之处!! self.main_url = 'http://music.163.com/' self.session = requests.Session() self.session.headers = self.headers self.ep = Encrypyed() def search_song(self, search_content, search_type=1, limit=1): """ :param search_content: 音乐名 :param search_type: 不知 :param limit: 返回结果数量 :return: 可以得到id 再进去歌曲具体的url """ url = 'http://music.163.com/weapi/cloudsearch/get/web?csrf_token=' song_id_li = [] song_name_li = [] singer_li = [] alia_li = [] text = {'s': search_content, 'type': search_type, 'offset': 0, 'sub': 'false', 'limit': limit} data = self.ep.search(text) resp = self.session.post(url, data=data) result = resp.json() if result.get('result') is None: print('搜不到!!') elif result.get('result').get('songCount') <= 0: print('搜不到!!') else: songs = result['result']['songs'] for song in songs: song_id, song_name, singer, alia = song['id'], song['name'], song['ar'][0]['name'], song['al']['name'] song_id_li.append(song_id) song_name_li.append(song_name) singer_li.append(singer) alia_li.append(alia) return zip(song_id_li,song_name_li,singer_li,alia_li) class singer_songs(): def __init__(self): self.singername = 'no' self.alia = '默认' def get_html(self,singerid): proxy_addr = {'http': '172.16.31.10:80'} # 用的代理 ip,如果被封或者失效,在http://www.xicidaili.com/换一个 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'} url = 'https://music.163.com/artist?id={}'.format(singerid) try: html = requests.get(url, headers=headers, proxies=proxy_addr).text return html except BaseException: print('request error') pass def get_top50(self,singerid): """ 根据歌手id获取歌曲id和歌曲名称 :param singerid: :return: """ html = self.get_html(singerid) soup = BeautifulSoup(html, 'lxml') info = soup.select('.f-hide #song-list-pre-cache a') songname = [] songids = [] singer = [] alia = [] for sn in info: songnames = sn.getText() songname.append(songnames) singer.append(self.singername) alia.append(self.alia) for si in info: songid = str(re.findall('href="(.*?)"', str(si))).strip().split('=')[-1].split('\'')[ 0] # 用re查找,查找对象一定要是str类型 songids.append(songid) return zip(songids,songname,singer,alia) class download(): def __init__(self): self.headers = { 'Referer': 'https://music.163.com/', "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.89 " "Safari/537.36" } def get_data(self,result): data = [] for songid, songname, singer, alia in result: info = {} info.setdefault('歌曲ID', songid) info.setdefault('歌曲名字', songname.replace('/','')) info.setdefault('歌手名字', singer) info.setdefault('alia', alia) data.append(info) return data def save_song_new(self,songurl, path, songname): with open(path, 'wb') as f: try: respo = requests.get(songurl, headers=self.headers) f.write(respo.content) print('歌曲下载完成:' + songname) except BaseException: print('下载失败:' + songname) pass def song_download(self,songid, songname,downloadpath): songurl = 'http://music.163.com/song/media/outer/url?id={}'.format(songid) path = '{}/{}.mp3'.format(downloadpath,songname) self.save_song_new(songurl, path, songname) time.sleep(5) def get_lyrics(self,songids): url = 'http://music.163.com/api/song/lyric?id={}&lv=-1&kv=-1&tv=-1'.format( songids) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'} html = requests.get(url, headers=headers).text json_obj = json.loads(html) initial_lyric = json_obj['lrc']['lyric'] reg = re.compile(r'\[.*\]') lyric = re.sub(reg, '', initial_lyric).strip() return lyric def lyrics_download(self,songname,path, songids): lyric = self.get_lyrics(songids) songname = songname.replace('/', '') print('正在保存歌曲:{}'.format(songname)) with open('{}/{}.txt'.format(path,songname), 'a', encoding='utf-8')as f: f.write(lyric) #######根据歌曲名称下载 def songnamedown(): song_name_path = '/zhangkun/PycharmProjects/wangyisong/songs' song_down_path = '/zhangkun/PycharmProjects/wangyisong/ss' lyric_path = '/zhangkun/PycharmProjects/wangyisong/lyrics' d = search() down = download() with open(song_name_path,'r') as p: songname_c = p.readlines() for i in songname_c: print(i) result = list(d.search_song(i)) # print((result)) data = down.get_data(result) # save2csv(data) if data: alone_song = data[0] songid = alone_song.get('歌曲ID') songname = alone_song.get('歌曲名字') path = '/zhangkun/PycharmProjects/wangyisong/song' down.song_download(songid,songname,path) down.lyrics_download(songname,lyric_path,songid) with open(song_down_path,'a') as f: f.write('\n' + i) ########根据歌手id下载 def singerdown(): lyric_path = '/zhangkun/PycharmProjects/wangyisong/lyrics' singer_so = singer_songs() down = download() singer_id = '4721'####歌手的id在热门歌手信息new.csv中查看 result = list(singer_so.get_top50(singer_id)) data = down.get_data(result) if data: for alone_song in data: songid = alone_song.get('歌曲ID') songname = alone_song.get('歌曲名字') path = '/zhangkun/PycharmProjects/wangyisong/songss' down.song_download(songid, songname, path) down.lyrics_download(songname, lyric_path,songid) if __name__ == '__main__': songnamedown() # singerdown()
1e667ec5b0d89d60121be57b648e01f8b849b360
[ "Python" ]
2
Python
gavin199006/wangyisongnew
330233899c08f70216c57a3a2f27cbd3da3aa154
720fc657a6403cb811c123338ca2de1d376df1f8
refs/heads/master
<file_sep>#pragma once // Gives main cpp access to the other cpp files void story1(); void story2(); void story3();<file_sep>#include <string> #include <iostream> #include "Header.h" #include <cstdlib> using namespace std; // Global Variables int sanity = 3; int amount_of_sanity_potion = 0; int win = 0; int main() // Main function { string player_name; // Stores player name into a string cout << "Hello! What is your name? "; cin >> player_name; rerun: system("cls"); cout << "Welcome " << player_name << " to Insanity!" << endl; system("pause"); system("cls"); cout << "Insanity is a text based horror game.\n"; system("cls"); cout << "In this game you will have something called sanity if your sanity reaches 0 you will die. \n"; cout << "You will lose sanity throughout the game.\n"; system("pause"); system("cls"); cout << "Good luck and don't die!\n"; system("pause"); story1(); // Call story1 function if (sanity > 0) // Check to make sure player has sanity before continuing to story function 2 { story2(); // Go to story function 2 } if (sanity > 0) // Check to make sure player has sanity before continuing to story function 3 { story3(); // Go to story function 2 } if (sanity <= 0) // if sanity is less than or equal to 0 tell user they died { string answer; // Stores player name in a string system("cls"); cout << "Your sanity reached 0" << " you died!\n"; cout << "Would you like to try again? y/n\n"; cin >> answer; if (answer == "y" || answer == "Y") // If user input y rerun code { system("cls"); ++sanity; // Add one to sanity ++sanity; // Add one to sanity ++sanity; // Add one to sanity goto rerun; // Go to rerun } else if (answer == "n" || answer == "N") // if user inputs n quite game { system("cls"); cout << "Thank you for playing " << player_name << endl; cout << "\nPress enter to quit the game.\n"; exit(0); // closes application } } if (win == 1) // if win variable = 1 congratulate the user on winning the game { system("cls"); cout << "Congratulations " << player_name << " you won the game!"; cout << "\nPress enter to quit the game.\n"; system("pause"); exit(0); // closes application } }
0d15abd0f8b28132bed37896823391f6f0197d03
[ "C", "C++" ]
2
C
sudo-Jake/Header-and-Source-Code-files-for-Projects
be57380e54d7032f70052d10f0b42e40857b002d
23429ff90ccb0b5219ccaebe3c96eb4cbf1cce2f
refs/heads/master
<file_sep>package com.eckstein.paige.knittingcompanion.Projects; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.text.InputType; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.eckstein.paige.knittingcompanion.BaseClasses.BaseActivity; import com.eckstein.paige.knittingcompanion.DatabaseHelpers.ProjectDBHelper; import com.eckstein.paige.knittingcompanion.MainActivity; import com.eckstein.paige.knittingcompanion.R; /** * Activity to create new Project */ public class CreateProjectActivity extends BaseActivity { private String startDate, endDate; private String patternName, yarnName, projectName; private int totalYardage, yardageUsed, totalSkeins; private String colorWay, note; private float size; private String yarnWeight, fiber, needleType, needleLength; float needleSize; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout main = findViewById(R.id.mainLayout); LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View contentView = inflater.inflate(R.layout.activity_edit_project, null, false); main.addView(contentView); final EditText projectNameField = findViewById(R.id.projectField); final EditText patternNameField = findViewById(R.id.patternField); final EditText startDateField = findViewById(R.id.startField); final EditText endDateField = findViewById(R.id.endField); final EditText sizeField = findViewById(R.id.sizeField); final EditText yarnNameField = findViewById(R.id.yarnNameField); final EditText yarnWeightField = findViewById(R.id.yarnWeightField); final EditText colorWayField = findViewById(R.id.colorwayField); final EditText totalYardageField = findViewById(R.id.yardUsedField); final EditText fiberField = findViewById(R.id.fiberField); final EditText needleSizeField = findViewById(R.id.needleSizeField); final EditText needleTypeField = findViewById(R.id.needleTypeField); final EditText needleLengthField = findViewById(R.id.needleLengthField); final EditText noteField = findViewById(R.id.noteField); //Done button ============================================================================== Button doneButton = findViewById(R.id.doneButton); doneButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //get data from text fields startDate = startDateField.getText().toString(); endDate = endDateField.getText().toString(); patternName = patternNameField.getText().toString(); yarnName = yarnNameField.getText().toString(); projectName = projectNameField.getText().toString(); colorWay = colorWayField.getText().toString(); note = noteField.getText().toString(); yarnWeight = yarnWeightField.getText().toString(); fiber = fiberField.getText().toString(); needleType = needleTypeField.getText().toString(); needleLength = needleLengthField.getText().toString(); String temp = totalYardageField.getText().toString(); //if any int fields are empty, set to 0 if (!temp.equals("")) { totalYardage = Integer.parseInt(temp); } else { totalYardage = 0; } temp = sizeField.getText().toString(); if (!temp.equals("")) { size = Float.parseFloat(temp); } else { size = 0; } temp = needleSizeField.getText().toString(); if(!temp.equals("")) { needleSize = Float.parseFloat(temp); } else { needleSize = 0; } //create project object and populate with retrieved information Project project = new Project(); project.setStartDate(startDate); project.setEndDate(endDate); project.setPatternName(patternName); project.setYarnName(yarnName, -1); project.setProjectName(projectName); project.setColorWay(colorWay, -1); project.setNote(note); project.setYardageUsed(totalYardage); project.setSize(size); project.setWeight(yarnWeight, -1); project.setFiber(fiber, -1); project.setNeedleSize(needleSize, -1); project.setNeedleType(needleType, -1); project.setNeedleLength(needleLength, -1); //update database with edited Project updateDb(project); //return new project object to View Project Activity Intent projectData = new Intent(CreateProjectActivity.this, MainActivity.class); projectData.putExtra("project", project); setResult(RESULT_OK, projectData); finish(); } }); } /** * add newly created Project to Project database * @param project */ public void updateDb(Project project) { ProjectDBHelper db = new ProjectDBHelper(this); String projectName, patternName, yarnName; String start, end; String totalYards, yardsUsed, colorway; String note, size, skeins; //get project information projectName = project.getProjectName(); patternName = project.getPatternName(); yarnName = project.getYarnName(); start = project.getStartDate(); end = project.getEndDate(); totalYards = String.valueOf(project.getTotalYardage(-1)); yardsUsed = String.valueOf(project.getYardageUsed()); colorway = project.getColorWay(-1); note = project.getNote(0); size = String.valueOf(project.getSize()); skeins = String.valueOf(project.getSkeins(-1)); //insert new row db.insert(projectName, patternName, yarnName, start, end, totalYards, yardsUsed, skeins, colorway, note, size, "test", "test", "0", "test", "test", "test"); } } <file_sep>package com.eckstein.paige.knittingcompanion.Yarn; import android.support.annotation.NonNull; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * Used to create List of Yarn objects returned from Ravelry search * Credit to Sofivanhanen and her code, from which this was edited * From https://github.com/sofivanhanen/Yarnie */ public class YarnList implements List<Yarn> { private Yarn[] yarns; private int firstFreeSpot; /** * Default constructor * create array that can hold 20 Yarn objects */ public YarnList() { yarns = new Yarn[20]; firstFreeSpot = 0; } /** * Returns contained Yarns as an array * * @return The array of objects, null Yarns removed */ // Can't return the 'Yarns' array as it contains empty spaces public Yarn[] returnAsArray() { Yarn[] result = new Yarn[firstFreeSpot]; for (int i = 0; i < firstFreeSpot; i++) { result[i] = yarns[i]; } return result; } /** * Creates a YarnList object out of an array * * @param yarns Array of Yarns * @return A YarnList object */ public static YarnList YarnListFromArray(Yarn[] yarns) { YarnList list = new YarnList(); for (Yarn yarn : yarns) { list.add(yarn); } return list; } /** * Get size of the list * * @return Number of contained Yarns as int */ @Override public int size() { return firstFreeSpot; } /** * Get if empty * * @return True if empty, false if at least one Yarn contained */ @Override public boolean isEmpty() { return firstFreeSpot == 0; } /** * Check if list contains a specific Yarn object * * @param o Yarn we're looking for * @return true if contained, false otherwise */ @Override public boolean contains(Object o) { if (!o.getClass().equals(Yarn.class)) { return false; } else { for (Yarn yarn : yarns) { if (yarn == null) return false; if (yarn.equals(o)) { return true; } } } return false; } /** * Get an iterator of the contained Yarn objects * * @return An iterator of Yarns */ @NonNull @Override public Iterator<Yarn> iterator() { return new Iterator<Yarn>() { private int currentIndex = 0; @Override public boolean hasNext() { if (yarns.length <= currentIndex) return false; else return yarns[currentIndex] != null; } @Override public Yarn next() { Yarn toReturn = yarns[currentIndex]; currentIndex++; return toReturn; } }; } /** * Add a Yarn * * @param yarn Yarn to add * @return Always true */ @Override public boolean add(Yarn yarn) { if (firstFreeSpot == yarns.length) { expandList(); } yarns[firstFreeSpot] = yarn; firstFreeSpot++; return true; } /** * For when array is full */ private void expandList() { Yarn[] newArray = new Yarn[yarns.length * 2]; for (int i = 0; i < firstFreeSpot; i++) { newArray[i] = yarns[i]; } yarns = newArray; } /** * Check if this YarnList contains everything in the given collection * * @param collection Items to check * @return True if all items are contained, false otherwise */ @Override public boolean containsAll(@NonNull Collection<?> collection) { for (Object object : collection) { if (!contains(object)) return false; } return true; } /** * Checks if contains same objects as the defined YarnList * * @param o Object we check * @return True if o is a YarnList containing all the same Yarns, false otherwise */ @Override public boolean equals(Object o) { if (o.getClass() != YarnList.class) return false; else { if (containsAll((YarnList) o)) { return ((YarnList) o).containsAll(YarnList.this); } return false; } } /** * Get Yarn at index * * @param i Index to check * @return Yarn object specified, or possibly null if index not filled */ @Override public Yarn get(int i) { return yarns[i]; } @NonNull @Override public Object[] toArray() { throw new UnsupportedOperationException("Not yet implemented"); } @NonNull @Override public <T> T[] toArray(@NonNull T[] ts) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public boolean addAll(@NonNull Collection<? extends Yarn> collection) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public boolean addAll(int i, @NonNull Collection<? extends Yarn> collection) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public boolean removeAll(@NonNull Collection<?> collection) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public boolean retainAll(@NonNull Collection<?> collection) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public void clear() { throw new UnsupportedOperationException("Not yet implemented"); } @Override public int hashCode() { throw new UnsupportedOperationException("Not yet implemented"); } @Override public Yarn set(int i, Yarn Yarn) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public void add(int i, Yarn Yarn) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public Yarn remove(int i) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public int indexOf(Object o) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public int lastIndexOf(Object o) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public ListIterator<Yarn> listIterator() { throw new UnsupportedOperationException("Not yet implemented"); } @NonNull @Override public ListIterator<Yarn> listIterator(int i) { throw new UnsupportedOperationException("Not yet implemented"); } @NonNull @Override public List<Yarn> subList(int i, int i1) { throw new UnsupportedOperationException("Not yet implemented"); } } <file_sep>package com.eckstein.paige.knittingcompanion.Yarn; import android.os.Parcel; import android.os.Parcelable; /** * Yarn class holds instance of a single yarn * which includes a name, colorway, weight category, fiber, * total yards per skein, total skeins owned, id number, * if it is discontinued or not, weight in grams, its average * rating, wpi, yardage, and company na,e */ public class Yarn implements Parcelable { private String name, colorway, weight, fiber; private int totalYards, totalSkeins, id; private boolean discontinued; private int grams; private float rating_average; private int wpi; private int yardage; private String yarn_company_name; /** * Default constructor * set all values to empty */ public Yarn() { id = 0; name = ""; colorway = ""; weight = ""; fiber = ""; totalYards = 0; totalSkeins = 0; discontinued = false; grams = 0; rating_average = 0; wpi = 0; yardage = 0; yarn_company_name = ""; } /** * Constructor with common fields populated * @param name String: name of yarn * @param colorway String: name of colorway * @param weight String: weight category * @param fiber String: fiber content * @param totalYards int: total yards per skein * @param totalSkeins int: number of skeins owned */ public Yarn(String name, String colorway, String weight, String fiber, int totalYards, int totalSkeins) { this.name = name; this.colorway = colorway; this.weight = weight; this.fiber = fiber; this.totalYards = totalYards; this.totalSkeins = totalSkeins; discontinued = false; grams = 0; rating_average = 0; wpi = 0; yardage = 0; yarn_company_name = ""; } /** * Constructor for use with id * @param id int: yarn id (from Ravelry) * @param name String: yarn name * @param colorway String: yarn colorway * @param weight String: weight category * @param fiber String: fiber content * @param totalYards int: total yards per skein * @param totalSkeins int: total skeins owned */ public Yarn(int id, String name, String colorway, String weight, String fiber, int totalYards, int totalSkeins) { this.id = id; this.name = name; this.colorway = colorway; this.weight = weight; this.fiber = fiber; this.totalYards = totalYards; this.totalSkeins = totalSkeins; discontinued = false; grams = 0; rating_average = 0; wpi = 0; yardage = 0; yarn_company_name = ""; } /** * Constructor for Ravelry search results * @param discontinued boolean: yarn is discontinued or not * @param grams int: yarn weight in grams * @param id int: yarn id (from Ravelry) * @param name String: yarn name * @param rating_average float: yarn's average rating (from Ravelry) * @param wpi int: wpi (wraps per inch) * @param yardage int: total yardage per skein * @param yarn_company_name String: yarn company name */ public Yarn(boolean discontinued, int grams, int id, String name, float rating_average, int wpi, int yardage, String yarn_company_name) { this.discontinued = discontinued; this.grams = grams; this.id = id; this.name = name; this.rating_average = rating_average; this.wpi = wpi; this.yardage = yardage; this.yarn_company_name = yarn_company_name; } /** * getter for yarn name * @return String: yarn name */ public String getName() { return name; } /** * getter for yarn colorway * @return String: yarn colorway */ public String getColorway() { return colorway; } /** * getter for fiber content * @return String: fiber content of yarn */ public String getFiber() { return fiber; } /** * getter for weight category * @return String: weight category (Bulky, worsted, etc.) */ public String getWeight() { return weight; } /** * getter for total skeins owned * @return int: total skeins owned */ public int getTotalSkeins() { return totalSkeins; } /** * getter for total yards per skein * @return int: total yards per skein */ public int getTotalYards() { return totalYards; } /** * getter for yarn id * @return int: id (from ravelry) */ public int getId() { return id; } /** * getter for is discontinued or not * @return boolean: true if discontinued, false otherwise */ public boolean getDiscontinued() { return discontinued; } /** * getter for weight in grams * @return int: weight of yarn in grams */ public int getGrams() { return grams; } /** * getter for average rating (from Ravelry) * @return float: yarn's average rating */ public float getRating_average() { return rating_average; } /** * getter for wpi * @return int: wraps per inch of yarn */ public int getWpi() { return wpi; } /** * getter for yardage * @return int: total yards per skein */ public int getYardage() { return yardage; } /** * getter for company name * @return String: yarn company name */ public String getCompanyName() { return yarn_company_name; } /** * setter for yarn name * @param name String: name of yarn */ public void setName(String name) { this.name = name; } /** * setter for colorway * @param colorway String: colorway of yarn */ public void setColorway(String colorway) { this.colorway = colorway; } /** * setter for fiber * @param fiber String: fiber content of yarn */ public void setFiber(String fiber) { this.fiber = fiber; } /** * setter for weight category * @param weight String: weight category of yarn (ex: bulky, worsted, aran, etc.) */ public void setWeight(String weight) { this.weight = weight; } /** * setter for total skeins * @param totalSkeins int: total number of skeins owned */ public void setTotalSkeins(int totalSkeins) { this.totalSkeins = totalSkeins; } /** * setter for total yards * @param totalYards int: number of yards per skein */ public void setTotalYards(int totalYards) { this.totalYards = totalYards; } /** * setter for id * @param id int: yarn id (from Ravelry) */ public void setId(int id) { this.id = id; } /** * setter for discontinued * @param discontinued boolean: is discontinued */ public void setDiscontinued(boolean discontinued) { this.discontinued = discontinued; } /** * setter for grams * @param grams int: yarn weight in grams */ public void setGrams(int grams) { this.grams = grams; } /** * setter for average rating * @param rating_average float: average rating of yarn (from ravelry) */ public void setRating_average(float rating_average) { this.rating_average = rating_average; } /** * setter for wpi * @param wpi int wraps per inch */ public void setWpi(int wpi) { this.wpi = wpi; } /** * setter for yardage * @param yardage int: total yards per skein */ public void setYardage(int yardage) { this.yardage = yardage; } /** * setter for company name * @param yarn_company_name String: yarn company name (Red Heart, Berroco, etc.) */ public void setCompanyName(String yarn_company_name) { this.yarn_company_name = yarn_company_name; } /** * for parcelable * @return */ @Override public int describeContents() { return 0; } /** * How to save information - for parcelable * @param dest Parcel to save information to * @param flags for parcelable */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(name); dest.writeString(colorway); dest.writeString(weight); dest.writeString(fiber); dest.writeInt(totalYards); dest.writeInt(totalSkeins); dest.writeInt(discontinued ? 1 : 0); dest.writeInt(grams); dest.writeFloat(rating_average); dest.writeInt(wpi); dest.writeInt(yardage); dest.writeString(yarn_company_name); } /** * Constructor used by parcelable * information must be read out in same order it was written in * @param in Parcel to read from */ private Yarn(Parcel in) { this.id = in.readInt(); this.name = in.readString(); this.colorway = in.readString(); this.weight = in.readString(); this.fiber = in.readString(); this.totalYards = in.readInt(); this.totalSkeins = in.readInt(); this.discontinued = in.readInt() != 0; this.grams = in.readInt(); this.rating_average = in.readFloat(); this.wpi = in.readInt(); this.yardage = in.readInt(); this.yarn_company_name = in.readString(); } /** * for parcelable */ public static final Parcelable.Creator<Yarn> CREATOR = new Parcelable.Creator<Yarn>() { @Override public Yarn createFromParcel(Parcel source) { return new Yarn(source); } @Override public Yarn[] newArray(int size) { return new Yarn[size]; } }; } <file_sep>package com.eckstein.paige.knittingcompanion.Stash; import android.content.Intent; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.eckstein.paige.knittingcompanion.BaseClasses.BaseActivity; import com.eckstein.paige.knittingcompanion.R; import com.eckstein.paige.knittingcompanion.Yarn.Yarn; import java.util.ArrayList; import com.eckstein.paige.knittingcompanion.DatabaseHelpers.StashDBHelper; /** * View short form of all yarn saved in stash * shows name and colorway */ public class ViewStashActivity extends BaseActivity { ArrayList<Yarn> stash; LinearLayout main; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //ArrayList to hold all yarn objects in stash stash = new ArrayList<>(); main = findViewById(R.id.mainLayout); StashDBHelper db = new StashDBHelper(this); //get all yarn objects saved in database stash = db.getAllYarn(); //for each yarn object, add it to the UI for (Yarn yarn : stash) { updateUI(yarn); } Button newYarn = new Button(this); newYarn.setText(getResources().getString(R.string.addYarn)); newYarn.setTextColor(ContextCompat.getColor(this, R.color.offWhite)); newYarn.setBackgroundColor(ContextCompat.getColor(this, R.color.darkPink)); newYarn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //go to create stash activity to create a new Yarn object Intent intent = new Intent(ViewStashActivity.this, CreateStashActivity.class); startActivityForResult(intent, 1); } }); main.addView(newYarn); } /** * On result from CreateStashActivity * @param requestCode int: request code (1) * @param resultCode int: resultCode (RESULT_OK) * @param data Intent: hold data returning from Create Stash Activity */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //if all was successful if (requestCode == 1) { if (resultCode == RESULT_OK) { //get bundle from Intent Bundle bundle = data.getExtras(); if (bundle != null) { //get Yarn object from bundle Yarn yarn = bundle.getParcelable("yarn"); //add it to the UI updateUI(yarn); } } } } public void updateUI(Yarn yarn) { final Yarn finalYarn = yarn; RelativeLayout rel = new RelativeLayout(this); TextView yarnName = new TextView(this); yarnName.setTextSize(20); yarnName.setId(View.generateViewId()); yarnName.setText(yarn.getName()); TextView colorway = new TextView(this); colorway.setTextSize(18); colorway.setId(View.generateViewId()); colorway.setText(yarn.getColorway()); //view button set up Button viewProject = new Button(this); viewProject.setTextColor(ContextCompat.getColor(this, R.color.offWhite)); viewProject.setBackgroundColor(ContextCompat.getColor(this, R.color.darkPink)); viewProject.setText(getResources().getString(R.string.view)); viewProject.setId(View.generateViewId()); RelativeLayout.LayoutParams nameParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); nameParams.addRule(RelativeLayout.ALIGN_PARENT_START); nameParams.setMargins(15, 10, 10, 10); yarnName.setLayoutParams(nameParams); RelativeLayout.LayoutParams colorParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); colorParams.addRule(RelativeLayout.BELOW, yarnName.getId()); colorParams.setMargins(15, 10, 10, 10); colorway.setLayoutParams(colorParams); //layout params for button RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); buttonParams.addRule(RelativeLayout.ALIGN_PARENT_END); buttonParams.setMargins(10, 10, 10, 10); viewProject.setLayoutParams(buttonParams); viewProject.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //view in depth yarn information Intent intent = new Intent(ViewStashActivity.this, ViewYarnActivity.class); intent.putExtra("yarn", finalYarn); startActivity(intent); finish(); } }); //draw line between each project View v = new View(this); v.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 5)); v.setBackgroundColor(ContextCompat.getColor(this, R.color.darkPink)); //add text views and button to relative layout rel.addView(yarnName); rel.addView(colorway); rel.addView(viewProject); //add relative layout to main linear layout main.addView(rel); main.addView(v); } } <file_sep>package com.eckstein.paige.knittingcompanion.DatabaseHelpers; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.eckstein.paige.knittingcompanion.Counters.Counter; import java.util.ArrayList; /** * Database helper for Counter objects */ public class CounterDBHelper extends SQLiteOpenHelper { //database information private static final String DATABASE_NAME = "KnittingCompanionCounter.db"; private static final String TABLE_NAME = "counters"; private static final String PROJECT_NAME = "project_name"; private static final String COUNTER_NAME = "counter_name"; private static final String ONES = "ones"; private static final String TENS = "tens"; private static final String HUNDREDS = "hundreds"; /** * Constructor * @param context Context that ProjectDBHelper is being created in */ public CounterDBHelper(Context context) { super(context, DATABASE_NAME, null, 1); } /** * Create Counters table in database * @param db Database to create Counters table in */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + TABLE_NAME + "(id integer primary key, project_name text, counter_name text, ones text, tens text," + " hundreds text)"); } /** * When updating table, drop old one and create new one * @param db Database to update table in * @param oldVersion int old version of table * @param newVersion int new version of table */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } /** * Insert new row into Counters table * @param projectName String: Name of project counter belongs to * @param counterName String: name of counter (ex: rows, repeats, etc.) * @param ones String: string conversion of ones position in counter * @param tens String: string conversion of tens position in counter * @param hundreds String: string conversion of hundreds position in counter * @return */ public boolean insert(String projectName, String counterName, String ones, String tens, String hundreds) { //get database with write permission SQLiteDatabase db = this.getWritableDatabase(); //hold values to insert ContentValues values = new ContentValues(); //add counter variables to values values.put(PROJECT_NAME, projectName); values.put(COUNTER_NAME, counterName); values.put(ONES, ones); values.put(TENS, tens); values.put(HUNDREDS, hundreds); //insert values to Counter table db.insert(TABLE_NAME, null, values); db.close(); return true; } /** * get row from Counter's table where project name matches provided project name * @param projectName project name associated with counter to retrieve * @return Cursor holding query results */ public Cursor getdata(String projectName) { SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery("select * from " + TABLE_NAME + " where project_name=" + projectName + "", null); db.close(); return res; } /** * get total number of rows in Counter table * @return int: total number of rows in Counter table */ public int numberOfRows() { //get database with read permission SQLiteDatabase db = this.getReadableDatabase(); int numRows = ((int) DatabaseUtils.queryNumEntries(db, TABLE_NAME)); db.close(); return numRows; } /** * Update an existing row in Counter table * @param projectName String: name of project associated with counter to be updated * @param counterName String: name of counter to be updated * @param ones String: string version of ones position in counter * @param tens String: string version of tens position in counter * @param hundreds String: string version of hundreds position in counter * @return return true upon updating row */ public boolean updateCounter(String projectName, String counterName, String ones, String tens, String hundreds) { //get database with write permission SQLiteDatabase db = this.getWritableDatabase(); //create values object to hold row information ContentValues values = new ContentValues(); //add new information for row to be updated values.put(PROJECT_NAME, projectName); values.put(COUNTER_NAME, counterName); values.put(ONES, ones); values.put(TENS, tens); values.put(HUNDREDS, hundreds); //update the row in Counter table where project name matches provided and counter name matches provided db.update(TABLE_NAME, values, "project_name = ? AND counter_name = ?", new String[]{projectName, counterName}); db.close(); return true; } /** * delete row from Counter table * @param projectName String project name associated with counter to be deleted * @param counterName String name of counter to be deleted * @return int: number of rows affected */ public Integer deleteCounter(String projectName, String counterName) { //database with write permission SQLiteDatabase db = this.getWritableDatabase(); //delete row where project name and counter name match provided names int delete = db.delete(TABLE_NAME, "project_name = ? AND counter_name = ?", new String[]{projectName, counterName}); db.close(); return delete; } /** * get all rows from database * create Counter objects for each * and add to ArrayList * @return ArrayList of Counter objects created from all rows in the Counter table */ public ArrayList<Counter> getAllCounters() { //holds Counter objects created from db query ArrayList<Counter> counters = new ArrayList<>(); //readable database SQLiteDatabase db = this.getReadableDatabase(); //get all from Counter table Cursor res = db.rawQuery("select * from " + TABLE_NAME + "", null); //move to first row res.moveToFirst(); //Counter object fields String projectName, counterName; int ones, tens, hundreds; //while still rows to go through... while (!res.isAfterLast()) { //get and parse all columns from row projectName = res.getString(res.getColumnIndex(PROJECT_NAME)); counterName = res.getString(res.getColumnIndex(COUNTER_NAME)); ones = Integer.parseInt(res.getString(res.getColumnIndex(ONES))); tens = Integer.parseInt(res.getString(res.getColumnIndex(TENS))); hundreds = Integer.parseInt(res.getString(res.getColumnIndex(HUNDREDS))); //create Counter object with parsed data above Counter counter = new Counter(counterName, projectName, ones, tens, hundreds); //add Counter object to ArrayList counters.add(counter); //go to next row res.moveToNext(); } res.close(); db.close(); return counters; } } <file_sep>package com.eckstein.paige.knittingcompanion.Stash; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.text.InputType; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.eckstein.paige.knittingcompanion.BaseClasses.BaseActivity; import com.eckstein.paige.knittingcompanion.R; import com.eckstein.paige.knittingcompanion.Yarn.Yarn; import com.eckstein.paige.knittingcompanion.DatabaseHelpers.StashDBHelper; public class EditStashActivity extends BaseActivity { private String name, colorWay, weightString, fiberString; private int yardsInt, skeinsInt; private Yarn yarn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout main = findViewById(R.id.mainLayout); LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View contentView = inflater.inflate(R.layout.activity_edit_yarn, null, false); main.addView(contentView); //get Yarn object to edit from View Stash Activity Bundle bundle = getIntent().getExtras(); yarn = bundle.getParcelable("yarn"); final EditText yarnName = findViewById(R.id.yarnNameField); final EditText colorway = findViewById(R.id.colorwayField); final EditText weight = findViewById(R.id.weightField); final EditText fiber = findViewById(R.id.fiberField); final EditText totalYards = findViewById(R.id.yardsField); final EditText totalSkeins = findViewById(R.id.skeinsField); Button doneButton = findViewById(R.id.doneButton); doneButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //get edited yarn information from text fields name = yarnName.getText().toString(); colorWay = colorway.getText().toString(); weightString = weight.getText().toString(); fiberString = fiber.getText().toString(); String temp = totalYards.getText().toString(); //if any int fields are empty, set to 0 if (!temp.equals("")) { yardsInt = Integer.parseInt(temp); } else { yardsInt = 0; } temp = totalSkeins.getText().toString(); if (!temp.equals("")) { skeinsInt = Integer.parseInt(temp); } else { skeinsInt = 0; } //create yarn object from retrieved information Yarn yarn = new Yarn(name, colorWay, weightString, fiberString, yardsInt, skeinsInt); //update Yarn object in database updateDB(yarn); //return edited yarn object to ViewStashActivity Intent projectData = new Intent(EditStashActivity.this, ViewStashActivity.class); projectData.putExtra("yarn", yarn); setResult(RESULT_OK, projectData); finish(); } }); } /** * update edited yarn object in database * @param yarn edited Yarn object to update */ public void updateDB(Yarn yarn) { //yarn fields StashDBHelper db = new StashDBHelper(this); String name, colorway, weight, fiber, yards, skeins; //get yarn fields name = yarn.getName(); colorway = yarn.getColorway(); weight = yarn.getWeight(); fiber = yarn.getFiber(); yards = String.valueOf(yarn.getTotalYards()); skeins = String.valueOf(yarn.getTotalSkeins()); //update row in database db.updateStash(name, colorway, weight, fiber, yards, skeins); } } <file_sep>package com.eckstein.paige.knittingcompanion.DatabaseHelpers; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.eckstein.paige.knittingcompanion.Projects.Needle; import com.eckstein.paige.knittingcompanion.Projects.Project; import com.eckstein.paige.knittingcompanion.Yarn.Yarn; import java.util.ArrayList; /** * Database helper for Projects */ public class ProjectDBHelper extends SQLiteOpenHelper { //Database information private static final String DATABASE_NAME = "KnittingCompanionProject.db"; private static final String TABLE_NAME = "projects"; private static final String PROJECT_NAME = "project_name"; private static final String PATTERN_NAME = "pattern_name"; private static final String YARN_NAME = "yarn_name"; private static final String START_DATE = "start_date"; private static final String END_DATE = "end_date"; private static final String TOTAL_YARDS = "total_yards"; private static final String YARDS_USED = "yards_used"; private static final String TOTAL_SKEINS = "skeins"; private static final String COLORWAY = "colorway"; private static final String NOTE = "note"; private static final String SIZE = "size"; private static final String YARN_WEIGHT = "yarn_weight"; private static final String FIBER = "fiber"; private static final String NEEDLE_SIZE = "needle_size"; private static final String NEEDLE_TYPE = "needle_type"; private static final String NEEDLE_SIZE_TYPE = "needle_size_type"; private static final String NEEDLE_LENGTH = "needle_length"; /** * Constructor - requires Context of calling Activity * @param context Context of Activity database is being created in */ public ProjectDBHelper(Context context) { super(context, DATABASE_NAME, null, 1); } /** * Create table in database * @param db Database to add table to */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + TABLE_NAME + "(id integer primary key, project_name text, pattern_name text, yarn_name text, start_date text," + " end_date text, total_yards text, yards_used text, skeins text, colorway text, note " + "text, size text, yarn_weight text, fiber text, needle_size text, needle_type text, " + "needle_size_type text, needle_length text)"); } /** * On upgrade, delete existing Table and re-create * @param db Database to upgrade table in * @param oldVersion int: old version of table * @param newVersion int: new version of table */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } /** * Insert new row in Projects table * @param projectName String: name of project * @param patternName String: name of pattern * @param yarnName String: yarn name * @param start: String: start date mm/dd/yy * @param end String: end date mm/dd/yy * @param totalYards String: total yards per skein * @param yardsUsed String: yards used in project * @param skeins String: number of skeins of yarn * @param colorway String: yarn colorway name * @param note String: Project notes * @param size String: string conversion of float size * @return */ public boolean insert(String projectName, String patternName, String yarnName, String start, String end, String totalYards, String yardsUsed, String skeins, String colorway, String note, String size, String yarnWeight, String fiber, String needleSize, String needleSizeType, String needleType, String needleLength) { //writable database SQLiteDatabase db = this.getWritableDatabase(); //values object to add row information to ContentValues values = new ContentValues(); //add project information to values values.put(PROJECT_NAME, projectName); values.put(PATTERN_NAME, patternName); values.put(YARN_NAME, yarnName); values.put(START_DATE, start); values.put(END_DATE, end); values.put(TOTAL_YARDS, totalYards); values.put(YARDS_USED, yardsUsed); values.put(TOTAL_SKEINS, skeins); values.put(COLORWAY, colorway); values.put(NOTE, note); values.put(SIZE, size); values.put(YARN_WEIGHT, yarnWeight); values.put(FIBER, fiber); values.put(NEEDLE_SIZE, needleSize); values.put(NEEDLE_TYPE, needleType); values.put(NEEDLE_SIZE_TYPE, needleSizeType); values.put(NEEDLE_LENGTH, needleLength); //insert row into table db.insert(TABLE_NAME, null, values); db.close(); return true; } /** * Get row from Project table * @param projectName String: name of the project to pull information for * @return Cursor res holding query result */ public Cursor getdata(String projectName) { //readable database SQLiteDatabase db = this.getReadableDatabase(); //query to get all information on rows with project name matching provided name Cursor res = db.rawQuery("select * from " + TABLE_NAME + " where project_name=" + projectName + "", null); db.close(); return res; } /** * get total number of rows in Project table * @return int: total number of rows in Project table */ public int numberOfRows() { //readable database SQLiteDatabase db = this.getReadableDatabase(); int numRows = ((int) DatabaseUtils.queryNumEntries(db, TABLE_NAME)); db.close(); return numRows; } /** * Update row in Project table * @param projectName String: name of project to update * @param patternName String: pattern name of project to update * @param yarnName String: yarn name of project to update * @param start String: start date of project to update mm/dd/yy * @param end String: end date of project to update mm/dd/yy * @param totalYards String: conversion of int total yards in skein * @param yardsUsed String: conversion of int total yards used in project * @param skeins String: total number of skeins used in project to update * @param colorway String: colorway name of project * @param note String: note of project to update * @param size String: conversion of float size of project * @return */ public boolean updateProject(String projectName, String patternName, String yarnName, String start, String end, String totalYards, String yardsUsed, String skeins, String colorway, String note, String size, String yarnWeight, String fiber, String needleSize, String needleSizeType, String needleType, String needleLength) { //writable database SQLiteDatabase db = this.getWritableDatabase(); //hold row information ContentValues values = new ContentValues(); //add updated project information to values values.put(PROJECT_NAME, projectName); values.put(PATTERN_NAME, patternName); values.put(YARN_NAME, yarnName); values.put(START_DATE, start); values.put(END_DATE, end); values.put(TOTAL_YARDS, totalYards); values.put(YARDS_USED, yardsUsed); values.put(TOTAL_SKEINS, skeins); values.put(COLORWAY, colorway); values.put(NOTE, note); values.put(SIZE, size); values.put(YARN_WEIGHT, yarnWeight); values.put(FIBER, fiber); values.put(NEEDLE_SIZE, needleSize); values.put(NEEDLE_TYPE, needleType); values.put(NEEDLE_SIZE_TYPE, needleSizeType); values.put(NEEDLE_LENGTH, needleLength); //update row where project name matches provided project name db.update(TABLE_NAME, values, "project_name = ? ", new String[]{projectName}); db.close(); return true; } /** * delete row in table where project name matches provided name * @param projectName String: name of the project to delete * @return int: number of rows affected */ public Integer deleteProject(String projectName) { //writable database SQLiteDatabase db = this.getWritableDatabase(); //delete row where project name matches provided name int delete = db.delete(TABLE_NAME, "project_name = ? ", new String[]{projectName}); db.close(); return delete; } /** * get all rows from Project table * create Project objects from each row * add to ArrayList of Project objects * @return ArrayList of all Project objects created from Project table rows */ public ArrayList<Project> getAllProjects() { //arraylist to hold all Projects created from rows in Project table ArrayList<Project> projects = new ArrayList<>(); //readable database SQLiteDatabase db = this.getReadableDatabase(); //get all rows from Project table Cursor res = db.rawQuery("select * from " + TABLE_NAME + "", null); //move to first row res.moveToFirst(); //Project fields String patternName, projectName, yarnName; String startDate, endDate; int totalYards, yardsUsed, totalSkeins; String colorway, note; float size; String yarnWeight, fiber; float needleSize; String sizeType, type, length; //while there are rows to continue with... while (!res.isAfterLast()) { //get each column field in row patternName = res.getString(res.getColumnIndex(PATTERN_NAME)); projectName = res.getString(res.getColumnIndex(PROJECT_NAME)); yarnName = res.getString(res.getColumnIndex(YARN_NAME)); startDate = res.getString(res.getColumnIndex(START_DATE)); endDate = res.getString(res.getColumnIndex(END_DATE)); totalYards = Integer.parseInt(res.getString(res.getColumnIndex(TOTAL_YARDS))); yardsUsed = Integer.parseInt(res.getString(res.getColumnIndex(YARDS_USED))); totalSkeins = Integer.parseInt(res.getString(res.getColumnIndex(TOTAL_SKEINS))); colorway = res.getString(res.getColumnIndex(COLORWAY)); note = res.getString(res.getColumnIndex(NOTE)); size = Float.parseFloat(res.getString(res.getColumnIndex(SIZE))); yarnWeight = res.getString(res.getColumnIndex(YARN_WEIGHT)); fiber = res.getString(res.getColumnIndex(FIBER)); needleSize = Float.parseFloat(res.getString(res.getColumnIndex(NEEDLE_SIZE))); sizeType = res.getString(res.getColumnIndex(NEEDLE_SIZE_TYPE)); type = res.getString(res.getColumnIndex(NEEDLE_TYPE)); length = res.getString(res.getColumnIndex(NEEDLE_LENGTH)); //create Project object with row information Project project = new Project(startDate, endDate, patternName, projectName, yarnName, totalYards, yardsUsed, colorway, note, size, totalSkeins, yarnWeight, fiber, needleSize, sizeType, type, length); //add Project objected to ArrayList projects.add(project); //move to next row res.moveToNext(); } res.close(); db.close(); return projects; } } <file_sep>package com.eckstein.paige.knittingcompanion.Utilities; import com.eckstein.paige.knittingcompanion.Yarn.Yarn; import com.eckstein.paige.knittingcompanion.Yarn.YarnList; import java.util.HashMap; /** * Get Yarn objects from Ravelry search and add to List * Credit to Sofivanhanen and her code, from which this was edited * From https://github.com/sofivanhanen/Yarnie */ public class FullYarnsResult { private HashMap<Integer, Yarn> yarns; public HashMap<Integer, Yarn> getYarns() { return yarns; } public YarnList getYarnAsList() { YarnList result = new YarnList(); for (Yarn yarn : yarns.values()) { result.add(yarn); } return result; } } <file_sep>package com.eckstein.paige.knittingcompanion.Counters; import android.content.Context; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorManager; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.eckstein.paige.knittingcompanion.BaseClasses.BaseActivity; import com.eckstein.paige.knittingcompanion.R; import com.eckstein.paige.knittingcompanion.Utilities.ShakeDetector; import java.util.ArrayList; import com.eckstein.paige.knittingcompanion.DatabaseHelpers.CounterDBHelper; /** * Activity to view all current counters */ public class ViewCounterActivity extends BaseActivity { ArrayList<Counter> counters; LinearLayout main; // The following are used for the shake detection private SensorManager mSensorManager; private Sensor mAccelerometer; private ShakeDetector mShakeDetector; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); counters = new ArrayList<>(); main = findViewById(R.id.mainLayout); CounterDBHelper db = new CounterDBHelper(this); counters = db.getAllCounters(); for (Counter counter : counters) { updateUI(counter); } Button newCounter = new Button(this); newCounter.setText(getResources().getString(R.string.addCounter)); newCounter.setTextColor(ContextCompat.getColor(this, R.color.offWhite)); newCounter.setBackgroundColor(ContextCompat.getColor(this, R.color.darkPink)); newCounter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent projectData = new Intent(ViewCounterActivity.this, CreateCounterActivity.class); startActivityForResult(projectData, 1); } }); main.addView(newCounter); // ShakeDetector initialization mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mAccelerometer = mSensorManager .getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mShakeDetector = new ShakeDetector(); mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() { @Override public void onShake(int count) { handleShakeEvent(); } }); } /** * what to do when sensor detects shake * (clear all counters) */ public void handleShakeEvent() { for (Counter counter : counters) { counter.reset(); } clearViews(); redraw(); } /** * Add all counters to the UI * @param counter Counter: Individual Counter object to add to UI */ public void updateUI(Counter counter) { final Counter finalCounter = counter; RelativeLayout rel = new RelativeLayout(this); TextView projectName = new TextView(this); projectName.setTextSize(20); projectName.setId(View.generateViewId()); projectName.setText(counter.getProjectName()); TextView counterName = new TextView(this); counterName.setTextSize(20); counterName.setId(View.generateViewId()); counterName.setText(counter.getName()); TextView ones = new TextView(this); ones.setTextSize(20); ones.setId(View.generateViewId()); ones.setTypeface(getResources().getFont(R.font.mahoni)); ones.setText(String.valueOf(counter.getOnes())); TextView tens = new TextView(this); tens.setTextSize(20); tens.setId(View.generateViewId()); tens.setTypeface(getResources().getFont(R.font.mahoni)); tens.setText(String.valueOf(counter.getTens())); TextView hundreds = new TextView(this); hundreds.setTextSize(20); hundreds.setId(View.generateViewId()); hundreds.setTypeface(getResources().getFont(R.font.mahoni)); hundreds.setText(String.valueOf(counter.getHundreds())); //button set up Button increment = new Button(this); increment.setTextColor(ContextCompat.getColor(this, R.color.offWhite)); increment.setBackgroundColor(ContextCompat.getColor(this, R.color.darkPink)); increment.setTextSize(20); increment.setText("+"); increment.setId(View.generateViewId()); Button decrement = new Button(this); decrement.setTextColor(ContextCompat.getColor(this, R.color.offWhite)); decrement.setBackgroundColor(ContextCompat.getColor(this, R.color.darkPink)); decrement.setTextSize(20); decrement.setText("-"); decrement.setId(View.generateViewId()); Button clear = new Button(this); clear.setTextColor(ContextCompat.getColor(this, R.color.offWhite)); clear.setBackgroundColor(ContextCompat.getColor(this, R.color.darkPink)); clear.setTextSize(20); clear.setText(getResources().getString(R.string.clear)); clear.setId(View.generateViewId()); //param set up RelativeLayout.LayoutParams projectParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); projectParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); projectParams.setMargins(15, 10, 10, 10); projectName.setLayoutParams(projectParams); RelativeLayout.LayoutParams counterParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); counterParams.addRule(RelativeLayout.BELOW, projectName.getId()); counterParams.setMargins(15, 10, 10, 10); counterName.setLayoutParams(counterParams); RelativeLayout.LayoutParams incrementParams = new RelativeLayout.LayoutParams(100, 100); incrementParams.addRule(RelativeLayout.BELOW, counterName.getId()); incrementParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); incrementParams.setMargins(15, 10, 10, 10); increment.setLayoutParams(incrementParams); increment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finalCounter.increment(); updateCounterDB(finalCounter); clearViews(); redraw(); } }); RelativeLayout.LayoutParams hundredsParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); hundredsParams.addRule(RelativeLayout.END_OF, increment.getId()); hundredsParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); hundredsParams.setMargins(15, 10, 10, 10); hundreds.setLayoutParams(hundredsParams); RelativeLayout.LayoutParams tensParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); tensParams.addRule(RelativeLayout.END_OF, hundreds.getId()); tensParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); tensParams.setMargins(15, 10, 10, 10); tens.setLayoutParams(tensParams); RelativeLayout.LayoutParams onesParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); onesParams.addRule(RelativeLayout.END_OF, tens.getId()); onesParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); onesParams.setMargins(15, 10, 10, 10); ones.setLayoutParams(onesParams); RelativeLayout.LayoutParams decrementParams = new RelativeLayout.LayoutParams(100, 100); decrementParams.addRule(RelativeLayout.END_OF, ones.getId()); decrementParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); decrementParams.setMargins(15, 10, 10, 10); decrement.setLayoutParams(decrementParams); decrement.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finalCounter.decrement(); updateCounterDB(finalCounter); clearViews(); redraw(); } }); RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); buttonParams.addRule(RelativeLayout.ALIGN_PARENT_END); buttonParams.setMargins(10, 10, 10, 10); clear.setLayoutParams(buttonParams); clear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finalCounter.reset(); updateCounterDB(finalCounter); Intent intent = new Intent(ViewCounterActivity.this, ViewCounterActivity.class); clearViews(); redraw(); } }); //draw line between each project View v = new View(this); v.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 5)); v.setBackgroundColor(ContextCompat.getColor(this, R.color.darkPink)); //add text views and button to relative layout rel.addView(projectName); rel.addView(counterName); rel.addView(increment); rel.addView(hundreds); rel.addView(tens); rel.addView(ones); rel.addView(decrement); rel.addView(clear); //add relative layout to main linear layout main.addView(rel); main.addView(v); } /** * keep database up to date with latest counter values * @param counter Counter: Individual counter object to update in database */ public void updateCounterDB(Counter counter) { CounterDBHelper db = new CounterDBHelper(this); String projectName, counterName, ones, tens, hundreds; projectName = counter.getProjectName(); counterName = counter.getName(); ones = String.valueOf(counter.getOnes()); tens = String.valueOf(counter.getTens()); hundreds = String.valueOf(counter.getHundreds()); db.updateCounter(projectName, counterName, ones, tens, hundreds); } /** * Result from CreateCounterActivity * add newly created Counter object to UI * @param requestCode Activity requestCode (called with 1) * @param resultCode Activity resultCode(OK?) * @param data Bundle data returned from CreateCounterActivity */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { if (resultCode == RESULT_OK) { Bundle bundle = data.getExtras(); if (bundle != null) { Counter counter = bundle.getParcelable("counter"); updateUI(counter); } } } } /** * remove all current views attached to main view */ public void clearViews() { main.removeAllViews(); } /** * redraw UI * get all up to date counters from database * update UI with each one */ public void redraw() { CounterDBHelper db = new CounterDBHelper(this); counters = db.getAllCounters(); for (Counter counter : counters) { updateUI(counter); } Button newCounter = new Button(this); newCounter.setText(getResources().getString(R.string.addCounter)); newCounter.setTextColor(ContextCompat.getColor(this, R.color.offWhite)); newCounter.setBackgroundColor(ContextCompat.getColor(this, R.color.darkPink)); newCounter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent projectData = new Intent(ViewCounterActivity.this, CreateCounterActivity.class); startActivityForResult(projectData, 1); } }); main.addView(newCounter); } /** * for sensor usage */ @Override public void onResume() { super.onResume(); // Add the following line to register the Session Manager Listener onResume mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI); } /** * for sensor usage */ @Override public void onPause() { // Add the following line to unregister the Sensor Manager onPause mSensorManager.unregisterListener(mShakeDetector); super.onPause(); } } <file_sep>package com.eckstein.paige.knittingcompanion.Utilities; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Query; /** * Ravelry API queries * Credit to Sofivanhanen and her code, from which this was edited * From https://github.com/sofivanhanen/Yarnie */ public interface RavAPI { // This query "/yarns/search.json" can be used just like the Ravelry yarn search, // adding in any parameters. This specific call defines name of yarn to search for @GET("/yarns/search.json") Call<YarnSearchResult> getYarns(@Query("query") String yarnName, @Header("Authorization") String authHeader); // This query returns detailed Yarn objects. // ids should be in form "1 2 3 4", here it is parsed to "1+2+3+4" @GET("/yarns.json") Call<FullYarnsResult> getYarnsById(@Query("ids") String ids, @Header("Authorization") String authHeader); }
1f042328b5fcc7ed1da92a508e98490dee28d5a1
[ "Java" ]
10
Java
NotQuiteHeroes/Knitting-Companion
f94d1599a6c2a9161b51a6dd1dadc06bf65afdb2
d0f0e3b39e7e327bfa204ce68964391f2c04166f
refs/heads/master
<repo_name>ducngovan/dayfibonaci<file_sep>/javascript.js arr=[0,1]; for ( let i=2;i<20;i++){ arr[i]=arr[i-1]+arr[i-2] } alert(arr)
c67c096a5c1c2c9947bf89e3022b7b6f68d7c532
[ "JavaScript" ]
1
JavaScript
ducngovan/dayfibonaci
3cabbf5ab833eb3da51fb10f1327589bc8bb119f
aa2bf8ad9b43519a7c337e005ba9579e0e34e17c
refs/heads/master
<file_sep># Sitecore.IdentityServer.ADFS ADFS OpenId connect for Sitecore 9.1 identityserver <file_sep>namespace Sitecore.IdentityServer.ADFS { public class ADFSIdentityProvider { public bool Enabled { get; set; } public string Authority { get; set; } public string ClientId { get; set; } public string AuthenticationScheme { get; set; } public string MetadataAddress { get; set; } public string DisplayName { get; set; } } }<file_sep>namespace Sitecore.IdentityServer.ADFS { public class AppSettings { public static readonly string SectionName = "Sitecore:ExternalIdentityProviders:IdentityProviders:ADFS"; public ADFSIdentityProvider ADFSIdentityProvider { get; set; } = new ADFSIdentityProvider(); } } <file_sep>using System; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using Sitecore.Framework.Runtime.Configuration; namespace Sitecore.IdentityServer.ADFS { public class ConfigureSitecore { private readonly ILogger<ConfigureSitecore> _logger; private readonly AppSettings _appSettings; public ConfigureSitecore(ISitecoreConfiguration scConfig, ILogger<ConfigureSitecore> logger) { this._logger = logger; this._appSettings = new AppSettings(); scConfig.GetSection(AppSettings.SectionName); scConfig.GetSection(AppSettings.SectionName).Bind((object)this._appSettings.ADFSIdentityProvider); } public object IdentityServerConstants { get; private set; } public void ConfigureServices(IServiceCollection services) { ADFSIdentityProvider adfsProvider = this._appSettings.ADFSIdentityProvider; if (!adfsProvider.Enabled) return; _logger.LogDebug($"Adding ADFS clientId {adfsProvider.ClientId} Authority {adfsProvider.Authority} Scheme {adfsProvider.AuthenticationScheme}"); new AuthenticationBuilder(services).AddOpenIdConnect(adfsProvider.AuthenticationScheme, adfsProvider.DisplayName, (Action<OpenIdConnectOptions>)(options => { options.SignInScheme = "idsrv.external"; options.SignOutScheme = "idsrv"; options.RequireHttpsMetadata = false; options.SaveTokens = true; options.Authority = adfsProvider.Authority; options.ClientId = adfsProvider.ClientId; options.ResponseType = "id_token"; options.MetadataAddress = adfsProvider.MetadataAddress; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "roles" }; //Added to enable DEBUG to see all claims //Can be removed in production options.Events = new OpenIdConnectEvents() { OnTokenValidated = (context) => { //This identity include all claims ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity; //ADD break POINT to see all the claims, return Task.FromResult(0); } }; })); } } }
1cfd5a3b59463ec1dd3c2b4d36e13fa744c46994
[ "Markdown", "C#" ]
4
Markdown
istern/Sitecore.IdentityServer.ADFS
886fa61d5095b58c9490e26bd468d83eb10c4389
430b2349c05e759741cdc0ac7a1eafc61497eaa5
refs/heads/master
<repo_name>srikanthtumati/Chatty-Server<file_sep>/src/ChattyServer.java import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ChattyServer { private ServerSocket serverSocket; private Socket client; private HashMap<String, ChattyServerThread> users = new HashMap<>(); private ArrayList<String> admins = new ArrayList<>(); private ArrayList<String> banned_ips = new ArrayList<>(); private ArrayList<String> banned_users = new ArrayList<>(); public ChattyServer(String port) throws ServerException{ try{ this.serverSocket= new ServerSocket(Integer.parseInt(port)); } catch(NumberFormatException ex){ throw new ServerException("Error: Port number must be numerical!"); } catch (IOException ex){ throw new ServerException("Error: Server could not be created!"); } } public Socket acceptIncomingConnections() throws ServerException{ try { client = this.serverSocket.accept(); if (banned_ips.contains(client.getInetAddress().getHostAddress())){ throw new ServerException("IP is banned"); } return client; } catch(IOException ex){ ex.printStackTrace(); } return null; } public static void main(String[] args) throws ServerException{ if (args.length>1){ throw new ServerException("ChattyServer (port #)"); } try{ ChattyServer chattyServer = new ChattyServer(args[0]); chattyServer.init(); } catch(NumberFormatException ex){ throw new ServerException("Error: Port number must be numerical!"); } } public void init(){ loadFile(); while (true){ try { Thread temp = new Thread(new ChattyServerThread(this.acceptIncomingConnections(), this)); temp.start(); } catch (ServerException ex){ try { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); out.write(("You are banned on this server!" + "\n")); out.flush(); } catch (IOException xe) { xe.printStackTrace(); } } } } public void fileParser(BufferedReader fileLoader, String keyword, ArrayList<String> container){ try{ String line; while (true) { line = fileLoader.readLine(); if (line==null || (line = line.toLowerCase()).equals(keyword)) break; container.add(line); } } catch (IOException ex){ ex.printStackTrace(); } } public void loadFile(){ try { BufferedReader fileLoader = new BufferedReader(new FileReader("userData.txt")); fileParser(fileLoader, "banned_ips", admins); fileParser(fileLoader, "banned_users", banned_ips); fileParser(fileLoader, "", banned_users); fileLoader.close(); } catch (FileNotFoundException ex){ try { String template = "admins" + "\n" + "banned_ips" + "\n" + "banned_users"; BufferedWriter fileWriter = new BufferedWriter(new FileWriter("userData.txt")); fileWriter.write(template); fileWriter.close(); } catch (IOException xe){ xe.printStackTrace(); } } catch (IOException ex){ ex.printStackTrace(); } } public void ban(String username, boolean banIP){ banned_users.add(username); updateFile(username, "banned_users"); if (banIP) { banned_ips.add(username); updateFile(username, "banned_ips"); } } public void updateFile(String update, String keyword){ ArrayList<String> temp = new ArrayList<>(); String line; try { BufferedReader fileLoader = new BufferedReader(new FileReader("userData.txt")); Pattern p = Pattern.compile("\\b"+keyword+"\\b", Pattern.CASE_INSENSITIVE); while ( (line = fileLoader.readLine()) != null) { temp.add(line); } for (int i = 0; i < temp.size(); i++) { Matcher m = p.matcher(temp.get(i)); if (m.find()){ temp.add(i, update+"\n"); } } File file = new File("userData.txt"); file.delete(); BufferedWriter fileWriter = new BufferedWriter(new FileWriter("userData.txt")); for (int i = 0; i < temp.size(); i ++){ fileWriter.write(temp.get(i)); } } catch (IOException ex){ ex.printStackTrace(); } } public boolean isAdmin(String username){ return admins.contains(username); } public HashMap<String, ChattyServerThread> getUsers(){ return this.users; } }
ceb69fffc90a32ff849e6380ef19f8ce8d52ea90
[ "Java" ]
1
Java
srikanthtumati/Chatty-Server
f871ccfd791812e162dbb0b8df297d0d8dcc3064
1570038e7fea05fdc69950573e49e75a1f4cd6c7